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
fluentassertions__fluentassertions
Tests/FluentAssertions.Specs/AssemblyInitializer.cs
{ "start": 227, "end": 451 }
public static class ____ { public static void AcknowledgeSoftWarning() { // Suppress the soft warning about the license requirements for commercial use License.Accepted = true; } }
AssemblyInitializer
csharp
NSubstitute__NSubstitute
tests/NSubstitute.Specs/ExtensionsSpecs.cs
{ "start": 2065, "end": 2340 }
public class ____ { [Test] public void Join_strings() { var strings = new[] { "hello", "world" }; Assert.That(strings.Join("; "), Is.EqualTo("hello; world")); } } } }
JoinExtension
csharp
dotnet__efcore
test/EFCore.Relational.Tests/Extensions/RelationalBuilderExtensionsTest.cs
{ "start": 55479, "end": 55513 }
private class ____ : Splot;
Splow
csharp
AutoMapper__AutoMapper
src/UnitTests/CollectionMapping.cs
{ "start": 16265, "end": 16861 }
public class ____ { private IList<string> _myCollection = new List<string>(); public IEnumerable<string> MyCollection => _myCollection; } protected override MapperConfiguration CreateConfiguration() => new(cfg => cfg.CreateMap<Source, Destination>().ForMember(m => m.MyCollection, opt => { opt.MapFrom(src => src.MyCollection); })); [Fact] public void Should_map_ok() { Mapper.Map(new Source(), new Destination()) .MyCollection.SequenceEqual(new[] { "one", "two" }).ShouldBeTrue(); } }
Destination
csharp
dotnet__aspnetcore
src/Http/Routing/test/UnitTests/Template/TemplateMatcherTests.cs
{ "start": 228, "end": 30907 }
public class ____ { [Fact] public void TryMatch_Success() { // Arrange var matcher = CreateMatcher("{controller}/{action}/{id}"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/Bank/DoAction/123", values); // Assert Assert.True(match); Assert.Equal("Bank", values["controller"]); Assert.Equal("DoAction", values["action"]); Assert.Equal("123", values["id"]); } [Fact] public void TryMatch_Fails() { // Arrange var matcher = CreateMatcher("{controller}/{action}/{id}"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/Bank/DoAction", values); // Assert Assert.False(match); } [Fact] public void TryMatch_WithDefaults_Success() { // Arrange var matcher = CreateMatcher("{controller}/{action}/{id}", new { id = "default id" }); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/Bank/DoAction", values); // Assert Assert.True(match); Assert.Equal("Bank", values["controller"]); Assert.Equal("DoAction", values["action"]); Assert.Equal("default id", values["id"]); } [Fact] public void TryMatch_WithDefaults_Fails() { // Arrange var matcher = CreateMatcher("{controller}/{action}/{id}", new { id = "default id" }); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/Bank", values); // Assert Assert.False(match); } [Fact] public void TryMatch_WithLiterals_Success() { // Arrange var matcher = CreateMatcher("moo/{p1}/bar/{p2}", new { p2 = "default p2" }); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/moo/111/bar/222", values); // Assert Assert.True(match); Assert.Equal("111", values["p1"]); Assert.Equal("222", values["p2"]); } [Fact] public void TryMatch_RouteWithLiteralsAndDefaults_Success() { // Arrange var matcher = CreateMatcher("moo/{p1}/bar/{p2}", new { p2 = "default p2" }); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/moo/111/bar/", values); // Assert Assert.True(match); Assert.Equal("111", values["p1"]); Assert.Equal("default p2", values["p2"]); } [Theory] [InlineData(@"{p1:regex(^\d{{3}}-\d{{3}}-\d{{4}}$)}", "/123-456-7890")] // ssn [InlineData(@"{p1:regex(^\w+\@\w+\.\w+)}", "/asd@assds.com")] // email [InlineData(@"{p1:regex(([}}])\w+)}", "/}sda")] // Not balanced } [InlineData(@"{p1:regex(([{{)])\w+)}", "/})sda")] // Not balanced { public void TryMatch_RegularExpressionConstraint_Valid( string template, string path) { // Arrange var matcher = CreateMatcher(template); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch(path, values); // Assert Assert.True(match); } [Theory] [InlineData("moo/{p1}.{p2?}", "/moo/foo.bar", true, "foo", "bar")] [InlineData("moo/{p1?}", "/moo/foo", true, "foo", null)] [InlineData("moo/{p1?}", "/moo", true, null, null)] [InlineData("moo/{p1}.{p2?}", "/moo/foo", true, "foo", null)] [InlineData("moo/{p1}.{p2?}", "/moo/foo..bar", true, "foo.", "bar")] [InlineData("moo/{p1}.{p2?}", "/moo/foo.moo.bar", true, "foo.moo", "bar")] [InlineData("moo/{p1}.{p2}", "/moo/foo.bar", true, "foo", "bar")] [InlineData("moo/foo.{p1}.{p2?}", "/moo/foo.moo.bar", true, "moo", "bar")] [InlineData("moo/foo.{p1}.{p2?}", "/moo/foo.moo", true, "moo", null)] [InlineData("moo/.{p2?}", "/moo/.foo", true, null, "foo")] [InlineData("moo/.{p2?}", "/moo", false, null, null)] [InlineData("moo/{p1}.{p2?}", "/moo/....", true, "..", ".")] [InlineData("moo/{p1}.{p2?}", "/moo/.bar", true, ".bar", null)] public void TryMatch_OptionalParameter_FollowedByPeriod_Valid( string template, string path, bool expectedMatch, string p1, string p2) { // Arrange var matcher = CreateMatcher(template); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch(path, values); // Assert Assert.Equal(expectedMatch, match); if (p1 != null) { Assert.Equal(p1, values["p1"]); } if (p2 != null) { Assert.Equal(p2, values["p2"]); } } [Theory] [InlineData("moo/{p1}.{p2}.{p3?}", "/moo/foo.moo.bar", "foo", "moo", "bar")] [InlineData("moo/{p1}.{p2}.{p3?}", "/moo/foo.moo", "foo", "moo", null)] [InlineData("moo/{p1}.{p2}.{p3}.{p4?}", "/moo/foo.moo.bar", "foo", "moo", "bar")] [InlineData("{p1}.{p2?}/{p3}", "/foo.moo/bar", "foo", "moo", "bar")] [InlineData("{p1}.{p2?}/{p3}", "/foo/bar", "foo", null, "bar")] [InlineData("{p1}.{p2?}/{p3}", "/.foo/bar", ".foo", null, "bar")] [InlineData("{p1}/{p2}/{p3?}", "/foo/bar/baz", "foo", "bar", "baz")] public void TryMatch_OptionalParameter_FollowedByPeriod_3Parameters_Valid( string template, string path, string p1, string p2, string p3) { // Arrange var matcher = CreateMatcher(template); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch(path, values); // Assert Assert.True(match); Assert.Equal(p1, values["p1"]); if (p2 != null) { Assert.Equal(p2, values["p2"]); } if (p3 != null) { Assert.Equal(p3, values["p3"]); } } [Theory] [InlineData("moo/{p1}.{p2?}", "/moo/foo.")] [InlineData("moo/{p1}.{p2?}", "/moo/.")] [InlineData("moo/{p1}.{p2}", "/foo.")] [InlineData("moo/{p1}.{p2}", "/foo")] [InlineData("moo/{p1}.{p2}.{p3?}", "/moo/foo.moo.")] [InlineData("moo/foo.{p2}.{p3?}", "/moo/bar.foo.moo")] [InlineData("moo/foo.{p2}.{p3?}", "/moo/kungfoo.moo.bar")] [InlineData("moo/foo.{p2}.{p3?}", "/moo/kungfoo.moo")] [InlineData("moo/{p1}.{p2}.{p3?}", "/moo/foo")] [InlineData("{p1}.{p2?}/{p3}", "/foo./bar")] [InlineData("moo/.{p2?}", "/moo/.")] [InlineData("{p1}.{p2}/{p3}", "/.foo/bar")] public void TryMatch_OptionalParameter_FollowedByPeriod_Invalid(string template, string path) { // Arrange var matcher = CreateMatcher(template); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch(path, values); // Assert Assert.False(match); } [Fact] public void TryMatch_RouteWithOnlyLiterals_Success() { // Arrange var matcher = CreateMatcher("moo/bar"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/moo/bar", values); // Assert Assert.True(match); Assert.Empty(values); } [Fact] public void TryMatch_RouteWithOnlyLiterals_Fails() { // Arrange var matcher = CreateMatcher("moo/bars"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/moo/bar", values); // Assert Assert.False(match); } [Fact] public void TryMatch_RouteWithExtraSeparators_Success() { // Arrange var matcher = CreateMatcher("moo/bar"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/moo/bar/", values); // Assert Assert.True(match); Assert.Empty(values); } [Fact] public void TryMatch_UrlWithExtraSeparators_Success() { // Arrange var matcher = CreateMatcher("moo/bar/"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/moo/bar", values); // Assert Assert.True(match); Assert.Empty(values); } [Fact] public void TryMatch_RouteWithParametersAndExtraSeparators_Success() { // Arrange var matcher = CreateMatcher("{p1}/{p2}/"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/moo/bar", values); // Assert Assert.True(match); Assert.Equal("moo", values["p1"]); Assert.Equal("bar", values["p2"]); } [Fact] public void TryMatch_RouteWithDifferentLiterals_Fails() { // Arrange var matcher = CreateMatcher("{p1}/{p2}/baz"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/moo/bar/boo", values); // Assert Assert.False(match); } [Fact] public void TryMatch_LongerUrl_Fails() { // Arrange var matcher = CreateMatcher("{p1}"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/moo/bar", values); // Assert Assert.False(match); } [Fact] public void TryMatch_SimpleFilename_Success() { // Arrange var matcher = CreateMatcher("DEFAULT.ASPX"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/default.aspx", values); // Assert Assert.True(match); } [Theory] [InlineData("{prefix}x{suffix}", "/xxxxxxxxxx")] [InlineData("{prefix}xyz{suffix}", "/xxxxyzxyzxxxxxxyz")] [InlineData("{prefix}xyz{suffix}", "/abcxxxxyzxyzxxxxxxyzxx")] [InlineData("{prefix}xyz{suffix}", "/xyzxyzxyzxyzxyz")] [InlineData("{prefix}xyz{suffix}", "/xyzxyzxyzxyzxyz1")] [InlineData("{prefix}xyz{suffix}", "/xyzxyzxyz")] [InlineData("{prefix}aa{suffix}", "/aaaaa")] [InlineData("{prefix}aaa{suffix}", "/aaaaa")] public void TryMatch_RouteWithComplexSegment_Success(string template, string path) { var matcher = CreateMatcher(template); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch(path, values); // Assert Assert.True(match); } [Fact] public void TryMatch_RouteWithExtraDefaultValues_Success() { // Arrange var matcher = CreateMatcher("{p1}/{p2}", new { p2 = (string)null, foo = "bar" }); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/v1", values); // Assert Assert.True(match); Assert.Equal<int>(3, values.Count); Assert.Equal("v1", values["p1"]); Assert.Null(values["p2"]); Assert.Equal("bar", values["foo"]); } [Fact] public void TryMatch_PrettyRouteWithExtraDefaultValues_Success() { // Arrange var matcher = CreateMatcher( "date/{y}/{m}/{d}", new { controller = "blog", action = "showpost", m = (string)null, d = (string)null }); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/date/2007/08", values); // Assert Assert.True(match); Assert.Equal<int>(5, values.Count); Assert.Equal("blog", values["controller"]); Assert.Equal("showpost", values["action"]); Assert.Equal("2007", values["y"]); Assert.Equal("08", values["m"]); Assert.Null(values["d"]); } [Fact] public void TryMatch_WithMultiSegmentParamsOnBothEndsMatches() { RunTest( "language/{lang}-{region}", "/language/en-US", null, new RouteValueDictionary(new { lang = "en", region = "US" })); } [Fact] public void TryMatch_WithMultiSegmentParamsOnLeftEndMatches() { RunTest( "language/{lang}-{region}a", "/language/en-USa", null, new RouteValueDictionary(new { lang = "en", region = "US" })); } [Fact] public void TryMatch_WithMultiSegmentParamsOnRightEndMatches() { RunTest( "language/a{lang}-{region}", "/language/aen-US", null, new RouteValueDictionary(new { lang = "en", region = "US" })); } [Fact] public void TryMatch_WithMultiSegmentParamsOnNeitherEndMatches() { RunTest( "language/a{lang}-{region}a", "/language/aen-USa", null, new RouteValueDictionary(new { lang = "en", region = "US" })); } [Fact] public void TryMatch_WithMultiSegmentParamsOnNeitherEndDoesNotMatch() { RunTest( "language/a{lang}-{region}a", "/language/a-USa", null, null); } [Fact] public void TryMatch_WithMultiSegmentParamsOnNeitherEndDoesNotMatch2() { RunTest( "language/a{lang}-{region}a", "/language/aen-a", null, null); } [Fact] public void TryMatch_WithSimpleMultiSegmentParamsOnBothEndsMatches() { RunTest( "language/{lang}", "/language/en", null, new RouteValueDictionary(new { lang = "en" })); } [Fact] public void TryMatch_WithSimpleMultiSegmentParamsOnBothEndsTrailingSlashDoesNotMatch() { RunTest( "language/{lang}", "/language/", null, null); } [Fact] public void TryMatch_WithSimpleMultiSegmentParamsOnBothEndsDoesNotMatch() { RunTest( "language/{lang}", "/language", null, null); } [Fact] public void TryMatch_WithSimpleMultiSegmentParamsOnLeftEndMatches() { RunTest( "language/{lang}-", "/language/en-", null, new RouteValueDictionary(new { lang = "en" })); } [Fact] public void TryMatch_WithSimpleMultiSegmentParamsOnRightEndMatches() { RunTest( "language/a{lang}", "/language/aen", null, new RouteValueDictionary(new { lang = "en" })); } [Fact] public void TryMatch_WithSimpleMultiSegmentParamsOnNeitherEndMatches() { RunTest( "language/a{lang}a", "/language/aena", null, new RouteValueDictionary(new { lang = "en" })); } [Fact] public void TryMatch_WithMultiSegmentStandamatchMvcRouteMatches() { RunTest( "{controller}.mvc/{action}/{id}", "/home.mvc/index", new RouteValueDictionary(new { action = "Index", id = (string)null }), new RouteValueDictionary(new { controller = "home", action = "index", id = (string)null })); } [Fact] public void TryMatch_WithMultiSegmentParamsOnBothEndsWithDefaultValuesMatches() { RunTest( "language/{lang}-{region}", "/language/-", new RouteValueDictionary(new { lang = "xx", region = "yy" }), null); } [Fact] public void TryMatch_WithUrlWithMultiSegmentWithRepeatedDots() { RunTest( "{Controller}..mvc/{id}/{Param1}", "/Home..mvc/123/p1", null, new RouteValueDictionary(new { Controller = "Home", id = "123", Param1 = "p1" })); } [Fact] public void TryMatch_WithUrlWithTwoRepeatedDots() { RunTest( "{Controller}.mvc/../{action}", "/Home.mvc/../index", null, new RouteValueDictionary(new { Controller = "Home", action = "index" })); } [Fact] public void TryMatch_WithUrlWithThreeRepeatedDots() { RunTest( "{Controller}.mvc/.../{action}", "/Home.mvc/.../index", null, new RouteValueDictionary(new { Controller = "Home", action = "index" })); } [Fact] public void TryMatch_WithUrlWithManyRepeatedDots() { RunTest( "{Controller}.mvc/../../../{action}", "/Home.mvc/../../../index", null, new RouteValueDictionary(new { Controller = "Home", action = "index" })); } [Fact] public void TryMatch_WithUrlWithExclamationPoint() { RunTest( "{Controller}.mvc!/{action}", "/Home.mvc!/index", null, new RouteValueDictionary(new { Controller = "Home", action = "index" })); } [Fact] public void TryMatch_WithUrlWithStartingDotDotSlash() { RunTest( "../{Controller}.mvc", "/../Home.mvc", null, new RouteValueDictionary(new { Controller = "Home" })); } [Fact] public void TryMatch_WithUrlWithStartingBackslash() { RunTest( @"\{Controller}.mvc", @"/\Home.mvc", null, new RouteValueDictionary(new { Controller = "Home" })); } [Fact] public void TryMatch_WithUrlWithBackslashSeparators() { RunTest( @"{Controller}.mvc\{id}\{Param1}", @"/Home.mvc\123\p1", null, new RouteValueDictionary(new { Controller = "Home", id = "123", Param1 = "p1" })); } [Fact] public void TryMatch_WithUrlWithParenthesesLiterals() { RunTest( @"(Controller).mvc", @"/(Controller).mvc", null, new RouteValueDictionary()); } [Fact] public void TryMatch_WithUrlWithTrailingSlashSpace() { RunTest( @"Controller.mvc/ ", @"/Controller.mvc/ ", null, new RouteValueDictionary()); } [Fact] public void TryMatch_WithUrlWithTrailingSpace() { RunTest( @"Controller.mvc ", @"/Controller.mvc ", null, new RouteValueDictionary()); } [Fact] public void TryMatch_WithCatchAllCapturesDots() { // DevDiv Bugs 189892: UrlRouting: Catch all parameter cannot capture url segments that contain the "." RunTest( "Home/ShowPilot/{missionId}/{*name}", "/Home/ShowPilot/777/12345./foobar", new RouteValueDictionary(new { controller = "Home", action = "ShowPilot", missionId = (string)null, name = (string)null }), new RouteValueDictionary(new { controller = "Home", action = "ShowPilot", missionId = "777", name = "12345./foobar" })); } [Fact] public void TryMatch_RouteWithCatchAll_MatchesMultiplePathSegments() { // Arrange var matcher = CreateMatcher("{p1}/{*p2}"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/v1/v2/v3", values); // Assert Assert.True(match); Assert.Equal<int>(2, values.Count); Assert.Equal("v1", values["p1"]); Assert.Equal("v2/v3", values["p2"]); } [Fact] public void TryMatch_RouteWithCatchAll_MatchesTrailingSlash() { // Arrange var matcher = CreateMatcher("{p1}/{*p2}"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/v1/", values); // Assert Assert.True(match); Assert.Equal<int>(2, values.Count); Assert.Equal("v1", values["p1"]); Assert.Null(values["p2"]); } [Fact] public void TryMatch_RouteWithCatchAll_MatchesEmptyContent() { // Arrange var matcher = CreateMatcher("{p1}/{*p2}"); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch("/v1", values); // Assert Assert.True(match); Assert.Equal<int>(2, values.Count); Assert.Equal("v1", values["p1"]); Assert.Null(values["p2"]); } [Fact] public void TryMatch_RouteWithCatchAll_MatchesEmptyContent_DoesNotReplaceExistingRouteValue() { // Arrange var matcher = CreateMatcher("{p1}/{*p2}"); var values = new RouteValueDictionary(new { p2 = "hello" }); // Act var match = matcher.TryMatch("/v1", values); // Assert Assert.True(match); Assert.Equal<int>(2, values.Count); Assert.Equal("v1", values["p1"]); Assert.Equal("hello", values["p2"]); } [Fact] public void TryMatch_RouteWithCatchAll_UsesDefaultValueForEmptyContent() { // Arrange var matcher = CreateMatcher("{p1}/{*p2}", new { p2 = "catchall" }); var values = new RouteValueDictionary(new { p2 = "overridden" }); // Act var match = matcher.TryMatch("/v1", values); // Assert Assert.True(match); Assert.Equal<int>(2, values.Count); Assert.Equal("v1", values["p1"]); Assert.Equal("catchall", values["p2"]); } [Fact] public void TryMatch_RouteWithCatchAll_IgnoresDefaultValueForNonEmptyContent() { // Arrange var matcher = CreateMatcher("{p1}/{*p2}", new { p2 = "catchall" }); var values = new RouteValueDictionary(new { p2 = "overridden" }); // Act var match = matcher.TryMatch("/v1/hello/whatever", values); // Assert Assert.True(match); Assert.Equal<int>(2, values.Count); Assert.Equal("v1", values["p1"]); Assert.Equal("hello/whatever", values["p2"]); } [Fact] public void TryMatch_DoesNotMatchOnlyLeftLiteralMatch() { // DevDiv Bugs 191180: UrlRouting: Wrong template getting matched if a url segment is a substring of the requested url RunTest( "foo", "/fooBAR", null, null); } [Fact] public void TryMatch_DoesNotMatchOnlyRightLiteralMatch() { // DevDiv Bugs 191180: UrlRouting: Wrong template getting matched if a url segment is a substring of the requested url RunTest( "foo", "/BARfoo", null, null); } [Fact] public void TryMatch_DoesNotMatchMiddleLiteralMatch() { // DevDiv Bugs 191180: UrlRouting: Wrong template getting matched if a url segment is a substring of the requested url RunTest( "foo", "/BARfooBAR", null, null); } [Fact] public void TryMatch_DoesMatchesExactLiteralMatch() { // DevDiv Bugs 191180: UrlRouting: Wrong template getting matched if a url segment is a substring of the requested url RunTest( "foo", "/foo", null, new RouteValueDictionary()); } [Fact] public void TryMatch_WithWeimatchParameterNames() { RunTest( "foo/{ }/{.!$%}/{dynamic.data}/{op.tional}", "/foo/space/weimatch/omatcherid", new RouteValueDictionary() { { " ", "not a space" }, { "op.tional", "default value" }, { "ran!dom", "va@lue" } }, new RouteValueDictionary() { { " ", "space" }, { ".!$%", "weimatch" }, { "dynamic.data", "omatcherid" }, { "op.tional", "default value" }, { "ran!dom", "va@lue" } }); } [Fact] public void TryMatch_DoesNotMatchRouteWithLiteralSeparatomatchefaultsButNoValue() { RunTest( "{controller}/{language}-{locale}", "/foo", new RouteValueDictionary(new { language = "en", locale = "US" }), null); } [Fact] public void TryMatch_DoesNotMatchesRouteWithLiteralSeparatomatchefaultsAndLeftValue() { RunTest( "{controller}/{language}-{locale}", "/foo/xx-", new RouteValueDictionary(new { language = "en", locale = "US" }), null); } [Fact] public void TryMatch_DoesNotMatchesRouteWithLiteralSeparatomatchefaultsAndRightValue() { RunTest( "{controller}/{language}-{locale}", "/foo/-yy", new RouteValueDictionary(new { language = "en", locale = "US" }), null); } [Fact] public void TryMatch_MatchesRouteWithLiteralSeparatomatchefaultsAndValue() { RunTest( "{controller}/{language}-{locale}", "/foo/xx-yy", new RouteValueDictionary(new { language = "en", locale = "US" }), new RouteValueDictionary { { "language", "xx" }, { "locale", "yy" }, { "controller", "foo" } }); } [Fact] public void TryMatch_SetsOptionalParameter() { // Arrange var route = CreateMatcher("{controller}/{action?}"); var url = "/Home/Index"; var values = new RouteValueDictionary(); // Act var match = route.TryMatch(url, values); // Assert Assert.True(match); Assert.Equal(2, values.Count); Assert.Equal("Home", values["controller"]); Assert.Equal("Index", values["action"]); } [Fact] public void TryMatch_DoesNotSetOptionalParameter() { // Arrange var route = CreateMatcher("{controller}/{action?}"); var url = "/Home"; var values = new RouteValueDictionary(); // Act var match = route.TryMatch(url, values); // Assert Assert.True(match); Assert.Single(values); Assert.Equal("Home", values["controller"]); Assert.False(values.ContainsKey("action")); } [Fact] public void TryMatch_DoesNotSetOptionalParameter_EmptyString() { // Arrange var route = CreateMatcher("{controller?}"); var url = ""; var values = new RouteValueDictionary(); // Act var match = route.TryMatch(url, values); // Assert Assert.True(match); Assert.Empty(values); Assert.False(values.ContainsKey("controller")); } [Fact] public void TryMatch__EmptyRouteWith_EmptyString() { // Arrange var route = CreateMatcher(""); var url = ""; var values = new RouteValueDictionary(); // Act var match = route.TryMatch(url, values); // Assert Assert.True(match); Assert.Empty(values); } [Fact] public void TryMatch_MultipleOptionalParameters() { // Arrange var route = CreateMatcher("{controller}/{action?}/{id?}"); var url = "/Home/Index"; var values = new RouteValueDictionary(); // Act var match = route.TryMatch(url, values); // Assert Assert.True(match); Assert.Equal(2, values.Count); Assert.Equal("Home", values["controller"]); Assert.Equal("Index", values["action"]); Assert.False(values.ContainsKey("id")); } [Theory] [InlineData("///")] [InlineData("/a//")] [InlineData("/a/b//")] [InlineData("//b//")] [InlineData("///c")] [InlineData("///c/")] public void TryMatch_MultipleOptionalParameters_WithEmptyIntermediateSegmentsDoesNotMatch(string url) { // Arrange var route = CreateMatcher("{controller?}/{action?}/{id?}"); var values = new RouteValueDictionary(); // Act var match = route.TryMatch(url, values); // Assert Assert.False(match); } [Theory] [InlineData("")] [InlineData("/")] [InlineData("/a")] [InlineData("/a/")] [InlineData("/a/b")] [InlineData("/a/b/")] [InlineData("/a/b/c")] [InlineData("/a/b/c/")] public void TryMatch_MultipleOptionalParameters_WithIncrementalOptionalValues(string url) { // Arrange var route = CreateMatcher("{controller?}/{action?}/{id?}"); var values = new RouteValueDictionary(); // Act var match = route.TryMatch(url, values); // Assert Assert.True(match); } [Theory] [InlineData("///")] [InlineData("////")] [InlineData("/a//")] [InlineData("/a///")] [InlineData("//b/")] [InlineData("//b//")] [InlineData("///c")] [InlineData("///c/")] public void TryMatch_MultipleParameters_WithEmptyValues(string url) { // Arrange var route = CreateMatcher("{controller}/{action}/{id}"); var values = new RouteValueDictionary(); // Act var match = route.TryMatch(url, values); // Assert Assert.False(match); } [Theory] [InlineData("/a/b/c//")] [InlineData("/a/b/c/////")] public void TryMatch_CatchAllParameters_WithEmptyValuesAtTheEnd(string url) { // Arrange var route = CreateMatcher("{controller}/{action}/{*id}"); var values = new RouteValueDictionary(); // Act var match = route.TryMatch(url, values); // Assert Assert.True(match); } [Theory] [InlineData("/a/b//")] [InlineData("/a/b///c")] public void TryMatch_CatchAllParameters_WithEmptyValues(string url) { // Arrange var route = CreateMatcher("{controller}/{action}/{*id}"); var values = new RouteValueDictionary(); // Act var match = route.TryMatch(url, values); // Assert Assert.False(match); } private TemplateMatcher CreateMatcher(string template, object defaults = null) { return new TemplateMatcher( TemplateParser.Parse(template), new RouteValueDictionary(defaults)); } private static void RunTest( string template, string path, RouteValueDictionary defaults, IDictionary<string, object> expected) { // Arrange var matcher = new TemplateMatcher( TemplateParser.Parse(template), defaults ?? new RouteValueDictionary()); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch(new PathString(path), values); // Assert if (expected == null) { Assert.False(match); } else { Assert.True(match); Assert.Equal(expected.Count, values.Count); foreach (string key in values.Keys) { Assert.Equal(expected[key], values[key]); } } } }
TemplateMatcherTests
csharp
dotnet__aspnetcore
src/Mvc/Mvc.ViewFeatures/src/IHtmlGenerator.cs
{ "start": 396, "end": 30310 }
public interface ____ { /// <summary> /// Gets the replacement for '.' in an Id attribute. /// </summary> string IdAttributeDotReplacement { get; } /// <summary> /// Encodes a value. /// </summary> /// <param name="value">The value to encode.</param> /// <returns>The encoded value.</returns> string Encode(string value); /// <summary> /// Encodes a value. /// </summary> /// <param name="value">The value to encode.</param> /// <returns>The encoded value.</returns> string Encode(object value); /// <summary> /// Format a value. /// </summary> /// <param name="value">The value to format.</param> /// <param name="format">The format to use.</param> /// <returns>The formatted value.</returns> string FormatValue(object value, string format); /// <summary> /// Generate a &lt;a&gt; element for a link to an action. /// </summary> /// <param name="viewContext">The <see cref="ViewContext"/> instance for the current scope.</param> /// <param name="linkText">The text to insert inside the element.</param> /// <param name="actionName">The name of the action method.</param> /// <param name="controllerName">The name of the controller.</param> /// <param name="protocol">The protocol (scheme) for the generated link.</param> /// <param name="hostname">The hostname for the generated link.</param> /// <param name="fragment">The fragment for the generated link.</param> /// <param name="routeValues"> /// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through /// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically /// created using <see cref="object"/> initializer syntax. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the route parameters. /// </param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes. /// </param> /// <returns> /// A <see cref="TagBuilder"/> instance for the &lt;a&gt; element. /// </returns> TagBuilder GenerateActionLink( ViewContext viewContext, string linkText, string actionName, string controllerName, string protocol, string hostname, string fragment, object routeValues, object htmlAttributes); /// <summary> /// Generate a &lt;a&gt; element for a link to an action. /// </summary> /// <param name="viewContext">The <see cref="ViewContext"/> instance for the current scope.</param> /// <param name="linkText">The text to insert inside the element.</param> /// <param name="pageName">The page name.</param> /// <param name="pageHandler">The page handler.</param> /// <param name="protocol">The protocol (scheme) for the generated link.</param> /// <param name="hostname">The hostname for the generated link.</param> /// <param name="fragment">The fragment for the generated link.</param> /// <param name="routeValues"> /// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through /// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically /// created using <see cref="object"/> initializer syntax. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the route parameters. /// </param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes. /// </param> /// <returns> /// A <see cref="TagBuilder"/> instance for the &lt;a&gt; element. /// </returns> TagBuilder GeneratePageLink( ViewContext viewContext, string linkText, string pageName, string pageHandler, string protocol, string hostname, string fragment, object routeValues, object htmlAttributes); /// <summary> /// Generate an &lt;input type="hidden".../&gt; element containing an antiforgery token. /// </summary> /// <param name="viewContext">The <see cref="ViewContext"/> instance for the current scope.</param> /// <returns> /// An <see cref="IHtmlContent"/> instance for the &lt;input type="hidden".../&gt; element. Intended to be used /// inside a &lt;form&gt; element. /// </returns> IHtmlContent GenerateAntiforgery(ViewContext viewContext); /// <summary> /// Generate a &lt;input type="checkbox".../&gt; element. /// </summary> /// <param name="viewContext">The <see cref="ViewContext"/> instance for the current scope.</param> /// <param name="modelExplorer">The <see cref="ModelExplorer"/> for the <paramref name="expression"/>.</param> /// <param name="expression">Expression name, relative to the current model.</param> /// <param name="isChecked">The initial state of the checkbox element.</param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes. /// </param> /// <returns> /// A <see cref="TagBuilder"/> instance for the &lt;input type="checkbox".../&gt; element. /// </returns> TagBuilder GenerateCheckBox( ViewContext viewContext, ModelExplorer modelExplorer, string expression, bool? isChecked, object htmlAttributes); /// <summary> /// Generate an additional &lt;input type="hidden".../&gt; for checkboxes. This addresses scenarios where /// unchecked checkboxes are not sent in the request. Sending a hidden input makes it possible to know that the /// checkbox was present on the page when the request was submitted. /// </summary> TagBuilder GenerateHiddenForCheckbox( ViewContext viewContext, ModelExplorer modelExplorer, string expression); /// <summary> /// Generate a &lt;form&gt; element. When the user submits the form, the action with name /// <paramref name="actionName"/> will process the request. /// </summary> /// <param name="viewContext">A <see cref="ViewContext"/> instance for the current scope.</param> /// <param name="actionName">The name of the action method.</param> /// <param name="controllerName">The name of the controller.</param> /// <param name="routeValues"> /// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through /// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically /// created using <see cref="object"/> initializer syntax. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the route parameters. /// </param> /// <param name="method">The HTTP method for processing the form, either GET or POST.</param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes. /// </param> /// <returns> /// A <see cref="TagBuilder"/> instance for the &lt;/form&gt; element. /// </returns> TagBuilder GenerateForm( ViewContext viewContext, string actionName, string controllerName, object routeValues, string method, object htmlAttributes); /// <summary> /// Generate a &lt;form&gt; element. When the user submits the form, the page with name /// <paramref name="pageName"/> will process the request. /// </summary> /// <param name="viewContext">A <see cref="ViewContext"/> instance for the current scope.</param> /// <param name="pageName">The name of the page.</param> /// <param name="pageHandler">The page handler to generate a form for.</param> /// <param name="routeValues"> /// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through /// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically /// created using <see cref="object"/> initializer syntax. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the route parameters. /// </param> /// <param name="fragment">The url fragment.</param> /// <param name="method">The HTTP method for processing the form, either GET or POST.</param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes. /// </param> /// <returns> /// A <see cref="TagBuilder"/> instance for the &lt;/form&gt; element. /// </returns> TagBuilder GeneratePageForm( ViewContext viewContext, string pageName, string pageHandler, object routeValues, string fragment, string method, object htmlAttributes); /// <summary> /// Generate a &lt;form&gt; element. The route with name <paramref name="routeName"/> generates the /// &lt;form&gt;'s <c>action</c> attribute value. /// </summary> /// <param name="viewContext">A <see cref="ViewContext"/> instance for the current scope.</param> /// <param name="routeName">The name of the route.</param> /// <param name="routeValues"> /// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through /// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically /// created using <see cref="object"/> initializer syntax. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the route parameters. /// </param> /// <param name="method">The HTTP method for processing the form, either GET or POST.</param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes. /// </param> /// <returns> /// A <see cref="TagBuilder"/> instance for the &lt;/form&gt; element. /// </returns> TagBuilder GenerateRouteForm( ViewContext viewContext, string routeName, object routeValues, string method, object htmlAttributes); /// <summary> /// Generate a &lt;input type="hidden"&gt; element /// </summary> /// <param name="viewContext">A <see cref="ViewContext"/> instance for the current scope.</param> /// <param name="modelExplorer">The <see cref="ModelExplorer"/> for the <paramref name="expression"/>.</param> /// <param name="expression">Expression name, relative to the current model.</param> /// <param name="value">The value which is injected into the element</param> /// <param name="useViewData">Whether to use the ViewData to generate this element</param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through /// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically /// created using <see cref="object"/> initializer syntax. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the route parameters. /// </param> /// <returns></returns> TagBuilder GenerateHidden( ViewContext viewContext, ModelExplorer modelExplorer, string expression, object value, bool useViewData, object htmlAttributes); /// <summary> /// Generate a &lt;label&gt; element /// </summary> /// <param name="viewContext">A <see cref="ViewContext"/> instance for the current scope.</param> /// <param name="modelExplorer">The <see cref="ModelExplorer"/> for the <paramref name="expression"/>.</param> /// <param name="expression">Expression name, relative to the current model. Used to set the target of the label.</param> /// <param name="labelText">Text used to render this label.</param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through /// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically /// created using <see cref="object"/> initializer syntax. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the route parameters. /// </param> /// <returns></returns> TagBuilder GenerateLabel( ViewContext viewContext, ModelExplorer modelExplorer, string expression, string labelText, object htmlAttributes); /// <summary> /// Generate a &lt;input type="password"&gt; element /// </summary> /// <param name="viewContext">A <see cref="ViewContext"/> instance for the current scope.</param> /// <param name="modelExplorer">The <see cref="ModelExplorer"/> for the <paramref name="expression"/>.</param> /// <param name="expression">Expression name, relative to the current model.</param> /// <param name="value">Value used to prefill the checkbox</param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through /// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically /// created using <see cref="object"/> initializer syntax. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the route parameters. /// </param> /// <returns></returns> TagBuilder GeneratePassword( ViewContext viewContext, ModelExplorer modelExplorer, string expression, object value, object htmlAttributes); /// <summary> /// Generate a &lt;input type="radio"&gt; element /// </summary> /// <param name="viewContext">A <see cref="ViewContext"/> instance for the current scope.</param> /// <param name="modelExplorer">The <see cref="ModelExplorer"/> for the <paramref name="expression"/>.</param> /// <param name="expression">Expression name, relative to the current model.</param> /// <param name="value">value of the given radio button</param> /// <param name="isChecked">Whether or not the radio button is checked</param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through /// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically /// created using <see cref="object"/> initializer syntax. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the route parameters. /// </param> /// <returns></returns> TagBuilder GenerateRadioButton( ViewContext viewContext, ModelExplorer modelExplorer, string expression, object value, bool? isChecked, object htmlAttributes); /// <summary> /// Generate a &lt;a&gt; element for a link to an action. /// </summary> /// <param name="viewContext">The <see cref="ViewContext"/> instance for the current scope.</param> /// <param name="linkText">The text to insert inside the element.</param> /// <param name="routeName">The name of the route to use for link generation.</param> /// <param name="protocol">The protocol (scheme) for the generated link.</param> /// <param name="hostName">The hostname for the generated link.</param> /// <param name="fragment">The fragment for the generated link.</param> /// <param name="routeValues"> /// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through /// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically /// created using <see cref="object"/> initializer syntax. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the route parameters. /// </param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes. /// </param> /// <returns> /// A <see cref="TagBuilder"/> instance for the &lt;a&gt; element. /// </returns> TagBuilder GenerateRouteLink( ViewContext viewContext, string linkText, string routeName, string protocol, string hostName, string fragment, object routeValues, object htmlAttributes); /// <summary> /// Generate a &lt;select&gt; element for the <paramref name="expression"/>. /// </summary> /// <param name="viewContext">A <see cref="ViewContext"/> instance for the current scope.</param> /// <param name="modelExplorer"> /// <see cref="ModelExplorer"/> for the <paramref name="expression"/>. If <c>null</c>, determines validation /// attributes using <paramref name="viewContext"/> and the <paramref name="expression"/>. /// </param> /// <param name="optionLabel">Optional text for a default empty &lt;option&gt; element.</param> /// <param name="expression">Expression name, relative to the current model.</param> /// <param name="selectList"> /// A collection of <see cref="SelectListItem"/> objects used to populate the &lt;select&gt; element with /// &lt;optgroup&gt; and &lt;option&gt; elements. If <c>null</c>, finds this collection at /// <c>ViewContext.ViewData[expression]</c>. /// </param> /// <param name="allowMultiple"> /// If <c>true</c>, includes a <c>multiple</c> attribute in the generated HTML. Otherwise generates a /// single-selection &lt;select&gt; element. /// </param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the HTML attributes for the &lt;select&gt; element. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes. /// </param> /// <returns>A new <see cref="TagBuilder"/> describing the &lt;select&gt; element.</returns> /// <remarks> /// <para> /// Combines <see cref="TemplateInfo.HtmlFieldPrefix"/> and <paramref name="expression"/> to set /// &lt;select&gt; element's "name" attribute. Sanitizes <paramref name="expression"/> to set element's "id" /// attribute. /// </para> /// <para> /// See <see cref="GetCurrentValues"/> for information about how current values are determined. /// </para> /// </remarks> TagBuilder GenerateSelect( ViewContext viewContext, ModelExplorer modelExplorer, string optionLabel, string expression, IEnumerable<SelectListItem> selectList, bool allowMultiple, object htmlAttributes); /// <summary> /// Generate a &lt;select&gt; element for the <paramref name="expression"/>. /// </summary> /// <param name="viewContext">A <see cref="ViewContext"/> instance for the current scope.</param> /// <param name="modelExplorer"> /// <see cref="ModelExplorer"/> for the <paramref name="expression"/>. If <c>null</c>, determines validation /// attributes using <paramref name="viewContext"/> and the <paramref name="expression"/>. /// </param> /// <param name="optionLabel">Optional text for a default empty &lt;option&gt; element.</param> /// <param name="expression">Expression name, relative to the current model.</param> /// <param name="selectList"> /// A collection of <see cref="SelectListItem"/> objects used to populate the &lt;select&gt; element with /// &lt;optgroup&gt; and &lt;option&gt; elements. If <c>null</c>, finds this collection at /// <c>ViewContext.ViewData[expression]</c>. /// </param> /// <param name="currentValues"> /// An <see cref="ICollection{String}"/> containing values for &lt;option&gt; elements to select. If /// <c>null</c>, selects &lt;option&gt; elements based on <see cref="SelectListItem.Selected"/> values in /// <paramref name="selectList"/>. /// </param> /// <param name="allowMultiple"> /// If <c>true</c>, includes a <c>multiple</c> attribute in the generated HTML. Otherwise generates a /// single-selection &lt;select&gt; element. /// </param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the HTML attributes for the &lt;select&gt; element. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes. /// </param> /// <returns>A new <see cref="TagBuilder"/> describing the &lt;select&gt; element.</returns> /// <remarks> /// <para> /// Combines <see cref="TemplateInfo.HtmlFieldPrefix"/> and <paramref name="expression"/> to set /// &lt;select&gt; element's "name" attribute. Sanitizes <paramref name="expression"/> to set element's "id" /// attribute. /// </para> /// <para> /// See <see cref="GetCurrentValues"/> for information about how the <paramref name="currentValues"/> /// collection may be created. /// </para> /// </remarks> TagBuilder GenerateSelect( ViewContext viewContext, ModelExplorer modelExplorer, string optionLabel, string expression, IEnumerable<SelectListItem> selectList, ICollection<string> currentValues, bool allowMultiple, object htmlAttributes); /// <summary> /// Generates &lt;optgroup&gt; and &lt;option&gt; elements. /// </summary> /// <param name="optionLabel">Optional text for a default empty &lt;option&gt; element.</param> /// <param name="selectList"> /// A collection of <see cref="SelectListItem"/> objects used to generate &lt;optgroup&gt; and &lt;option&gt; /// elements. /// </param> /// <returns> /// An <see cref="IHtmlContent"/> instance for &lt;optgroup&gt; and &lt;option&gt; elements. /// </returns> IHtmlContent GenerateGroupsAndOptions(string optionLabel, IEnumerable<SelectListItem> selectList); /// <summary> /// Generates a &lt;textarea&gt; element /// </summary> /// <param name="viewContext">A <see cref="ViewContext"/> instance for the current scope.</param> /// <param name="modelExplorer">The <see cref="ModelExplorer"/> for the <paramref name="expression"/>.</param> /// <param name="expression">Expression name, relative to the current model.</param> /// <param name="rows"></param> /// <param name="columns"></param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through /// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically /// created using <see cref="object"/> initializer syntax. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the route parameters. /// </param> /// <returns></returns> TagBuilder GenerateTextArea( ViewContext viewContext, ModelExplorer modelExplorer, string expression, int rows, int columns, object htmlAttributes); /// <summary> /// Generates a &lt;input type="text"&gt; element /// </summary> /// <param name="viewContext">A <see cref="ViewContext"/> instance for the current scope.</param> /// <param name="modelExplorer">The <see cref="ModelExplorer"/> for the <paramref name="expression"/>.</param> /// <param name="expression">Expression name, relative to the current model.</param> /// <param name="value"></param> /// <param name="format"></param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through /// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically /// created using <see cref="object"/> initializer syntax. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the route parameters. /// </param> /// <returns></returns> TagBuilder GenerateTextBox( ViewContext viewContext, ModelExplorer modelExplorer, string expression, object value, string format, object htmlAttributes); /// <summary> /// Generate a <paramref name="tag"/> element if the <paramref name="viewContext"/>'s /// <see cref="ActionContext.ModelState"/> contains an error for the <paramref name="expression"/>. /// </summary> /// <param name="viewContext">A <see cref="ViewContext"/> instance for the current scope.</param> /// <param name="modelExplorer">The <see cref="ModelExplorer"/> for the <paramref name="expression"/>.</param> /// <param name="expression">Expression name, relative to the current model.</param> /// <param name="message"> /// The message to be displayed. If <c>null</c> or empty, method extracts an error string from the /// <see cref="ModelBinding.ModelStateDictionary"/> object. Message will always be visible but client-side /// validation may update the associated CSS class. /// </param> /// <param name="tag"> /// The tag to wrap the <paramref name="message"/> in the generated HTML. Its default value is /// <see cref="ViewContext.ValidationMessageElement"/>. /// </param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes. /// </param> /// <returns></returns> /// <remarks><see cref="ViewContext.ValidationMessageElement"/> is <c>"span"</c> by default.</remarks> TagBuilder GenerateValidationMessage( ViewContext viewContext, ModelExplorer modelExplorer, string expression, string message, string tag, object htmlAttributes); /// <summary> /// Generates a &lt;div&gt; element which contains a list of validation errors. /// </summary> /// <param name="viewContext"></param> /// <param name="excludePropertyErrors"></param> /// <param name="message"></param> /// <param name="headerTag"></param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the parameters for a route. The parameters are retrieved through /// reflection by examining the properties of the <see cref="object"/>. This <see cref="object"/> is typically /// created using <see cref="object"/> initializer syntax. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the route parameters. /// </param> /// <returns></returns> TagBuilder GenerateValidationSummary( ViewContext viewContext, bool excludePropertyErrors, string message, string headerTag, object htmlAttributes); /// <summary> /// Gets the collection of current values for the given <paramref name="expression"/>. /// </summary> /// <param name="viewContext">A <see cref="ViewContext"/> instance for the current scope.</param> /// <param name="modelExplorer"> /// <see cref="ModelExplorer"/> for the <paramref name="expression"/>. If <c>null</c>, calculates the /// <paramref name="expression"/> result using <see cref="ViewDataDictionary.Eval(string)"/>. /// </param> /// <param name="expression">Expression name, relative to the current model.</param> /// <param name="allowMultiple"> /// If <c>true</c>, require a collection <paramref name="expression"/> result. Otherwise, treat result as a /// single value. /// </param> /// <returns> /// <para> /// <c>null</c> if no <paramref name="expression"/> result is found. Otherwise a /// <see cref="ICollection{String}"/> containing current values for the given /// <paramref name="expression"/>. /// </para> /// <para> /// Converts the <paramref name="expression"/> result to a <see cref="string"/>. If that result is an /// <see cref="System.Collections.IEnumerable"/> type, instead converts each item in the collection and returns /// them separately. /// </para> /// <para> /// If the <paramref name="expression"/> result or the element type is an <see cref="System.Enum"/>, returns a /// <see cref="string"/> containing the integer representation of the <see cref="System.Enum"/> value as well /// as all <see cref="System.Enum"/> names for that value. Otherwise returns the default <see cref="string"/> /// conversion of the value. /// </para> /// </returns> /// <remarks> /// See <see cref="M:GenerateSelect"/> for information about how the return value may be used. /// </remarks> ICollection<string> GetCurrentValues( ViewContext viewContext, ModelExplorer modelExplorer, string expression, bool allowMultiple); }
IHtmlGenerator
csharp
dotnet__aspnetcore
src/Http/Http/src/Internal/ItemsDictionary.cs
{ "start": 3963, "end": 4068 }
private sealed class ____ : IEnumerator<KeyValuePair<object, object?>> { // In own
EmptyEnumerator
csharp
unoplatform__uno
src/SourceGenerators/Uno.UI.SourceGenerators.Tests/XamlCodeGeneratorTests/Out/Given_MvvmGeneratedMembers/WBOP/ObservablePropertyGenerator_TestRepro.MyViewModel.g.cs
{ "start": 111, "end": 3352 }
partial class ____ { /// <inheritdoc cref="_isEnabled"/> [global::System.CodeDom.Compiler.GeneratedCode("CommunityToolkit.Mvvm.SourceGenerators.ObservablePropertyGenerator", "8.2.0.0")] [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public bool IsEnabled { get => _isEnabled; set { if (!global::System.Collections.Generic.EqualityComparer<bool>.Default.Equals(_isEnabled, value)) { OnIsEnabledChanging(value); OnIsEnabledChanging(default, value); OnPropertyChanging(global::CommunityToolkit.Mvvm.ComponentModel.__Internals.__KnownINotifyPropertyChangingArgs.IsEnabled); _isEnabled = value; OnIsEnabledChanged(value); OnIsEnabledChanged(default, value); OnPropertyChanged(global::CommunityToolkit.Mvvm.ComponentModel.__Internals.__KnownINotifyPropertyChangedArgs.IsEnabled); } } } /// <summary>Executes the logic for when <see cref="IsEnabled"/> is changing.</summary> /// <param name="value">The new property value being set.</param> /// <remarks>This method is invoked right before the value of <see cref="IsEnabled"/> is changed.</remarks> [global::System.CodeDom.Compiler.GeneratedCode("CommunityToolkit.Mvvm.SourceGenerators.ObservablePropertyGenerator", "8.2.0.0")] partial void OnIsEnabledChanging(bool value); /// <summary>Executes the logic for when <see cref="IsEnabled"/> is changing.</summary> /// <param name="oldValue">The previous property value that is being replaced.</param> /// <param name="newValue">The new property value being set.</param> /// <remarks>This method is invoked right before the value of <see cref="IsEnabled"/> is changed.</remarks> [global::System.CodeDom.Compiler.GeneratedCode("CommunityToolkit.Mvvm.SourceGenerators.ObservablePropertyGenerator", "8.2.0.0")] partial void OnIsEnabledChanging(bool oldValue, bool newValue); /// <summary>Executes the logic for when <see cref="IsEnabled"/> just changed.</summary> /// <param name="value">The new property value that was set.</param> /// <remarks>This method is invoked right after the value of <see cref="IsEnabled"/> is changed.</remarks> [global::System.CodeDom.Compiler.GeneratedCode("CommunityToolkit.Mvvm.SourceGenerators.ObservablePropertyGenerator", "8.2.0.0")] partial void OnIsEnabledChanged(bool value); /// <summary>Executes the logic for when <see cref="IsEnabled"/> just changed.</summary> /// <param name="oldValue">The previous property value that was replaced.</param> /// <param name="newValue">The new property value that was set.</param> /// <remarks>This method is invoked right after the value of <see cref="IsEnabled"/> is changed.</remarks> [global::System.CodeDom.Compiler.GeneratedCode("CommunityToolkit.Mvvm.SourceGenerators.ObservablePropertyGenerator", "8.2.0.0")] partial void OnIsEnabledChanged(bool oldValue, bool newValue); } }
MyViewModel
csharp
dotnet__aspnetcore
src/Mvc/test/Mvc.IntegrationTests/ServicesModelBinderIntegrationTest.cs
{ "start": 374, "end": 5818 }
public class ____ { [Fact] public async Task BindParameterFromService_WithData_GetsBound() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "Parameter1", BindingInfo = new BindingInfo() { BinderModelName = "CustomParameter", BindingSource = BindingSource.Services }, // Using a service type already in defaults. ParameterType = typeof(ITypeActivatorCache) }; var testContext = ModelBindingTestHelper.GetTestContext(); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var provider = Assert.IsAssignableFrom<ITypeActivatorCache>(modelBindingResult.Model); Assert.NotNull(provider); // ModelState Assert.True(modelState.IsValid); Assert.Empty(modelState.Keys); } [Fact] public async Task BindParameterFromService_NoPrefix_GetsBound() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor { Name = "ControllerProperty", BindingInfo = new BindingInfo { BindingSource = BindingSource.Services, }, // Use a service type already in defaults. ParameterType = typeof(ITypeActivatorCache), }; var testContext = ModelBindingTestHelper.GetTestContext(); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var provider = Assert.IsAssignableFrom<ITypeActivatorCache>(modelBindingResult.Model); Assert.NotNull(provider); // ModelState Assert.True(modelState.IsValid); Assert.Empty(modelState); } [Fact] public async Task BindEnumerableParameterFromService_NoPrefix_GetsBound() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor { Name = "ControllerProperty", BindingInfo = new BindingInfo { BindingSource = BindingSource.Services, }, // Use a service type already in defaults. ParameterType = typeof(IEnumerable<ITypeActivatorCache>), }; var testContext = ModelBindingTestHelper.GetTestContext(); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var formatterArray = Assert.IsType<ITypeActivatorCache[]>(modelBindingResult.Model); Assert.Single(formatterArray); // ModelState Assert.True(modelState.IsValid); Assert.Empty(modelState); } [Fact] public async Task BindEnumerableParameterFromService_NoService_GetsBound() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor { Name = "ControllerProperty", BindingInfo = new BindingInfo { BindingSource = BindingSource.Services, }, // Use a service type not available in DI. ParameterType = typeof(IEnumerable<IActionResult>), }; var testContext = ModelBindingTestHelper.GetTestContext(); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var actionResultArray = Assert.IsType<IActionResult[]>(modelBindingResult.Model); Assert.Empty(actionResultArray); // ModelState Assert.True(modelState.IsValid); Assert.Empty(modelState); } [Fact] public async Task BindParameterFromService_NoService_Throws() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor { Name = "ControllerProperty", BindingInfo = new BindingInfo { BindingSource = BindingSource.Services, }, // Use a service type not available in DI. ParameterType = typeof(IActionResult), }; var testContext = ModelBindingTestHelper.GetTestContext(); // Act & Assert var exception = await Assert.ThrowsAsync<InvalidOperationException>( () => parameterBinder.BindModelAsync(parameter, testContext)); Assert.Contains(typeof(IActionResult).FullName, exception.Message); }
ServicesModelBinderIntegrationTest
csharp
NLog__NLog
src/NLog/Internal/ExceptionHelper.cs
{ "start": 1830, "end": 7566 }
internal static class ____ { private const string LoggedKey = "NLog.ExceptionLoggedToInternalLogger"; /// <summary> /// Mark this exception as logged to the <see cref="InternalLogger"/>. /// </summary> /// <param name="exception"></param> /// <returns></returns> public static void MarkAsLoggedToInternalLogger(this Exception exception) { if (exception != null) { exception.Data[LoggedKey] = true; } } /// <summary> /// Is this exception logged to the <see cref="InternalLogger"/>? /// </summary> /// <param name="exception"></param> /// <returns><see langword="true"/> if the <paramref name="exception"/> has been logged to the <see cref="InternalLogger"/>.</returns> public static bool IsLoggedToInternalLogger(this Exception exception) { if (exception?.Data?.Count > 0) { return exception.Data[LoggedKey] as bool? ?? false; } return false; } /// <summary> /// Determines whether the exception must be rethrown and logs the error to the <see cref="InternalLogger"/> if <see cref="IsLoggedToInternalLogger"/> is <see langword="false"/>. /// /// Advised to log first the error to the <see cref="InternalLogger"/> before calling this method. /// </summary> /// <param name="exception">The exception to check.</param> /// <param name="loggerContext">Target Object context of the exception.</param> /// <param name="callerMemberName">Target Method context of the exception.</param> /// <returns><see langword="true"/> if the <paramref name="exception"/> must be rethrown, <see langword="false"/> otherwise.</returns> public static bool MustBeRethrown(this Exception exception, IInternalLoggerContext? loggerContext = null, string? callerMemberName = null) { if (exception.MustBeRethrownImmediately()) { //no further logging, because it can make severe exceptions only worse. return true; } var isConfigError = exception is NLogConfigurationException; var logFactory = loggerContext?.LogFactory; var throwExceptionsAll = logFactory?.ThrowExceptions == true || LogManager.ThrowExceptions; var shallRethrow = isConfigError ? (logFactory?.ThrowConfigExceptions ?? LogManager.ThrowConfigExceptions ?? throwExceptionsAll) : throwExceptionsAll; //we throw always configuration exceptions (historical) if (!exception.IsLoggedToInternalLogger()) { var level = shallRethrow ? LogLevel.Error : LogLevel.Warn; if (loggerContext != null) { if (string.IsNullOrEmpty(callerMemberName)) InternalLogger.Log(exception, level, "{0}: Error has been raised.", loggerContext); else InternalLogger.Log(exception, level, "{0}: Exception in {1}", loggerContext, callerMemberName); } else { InternalLogger.Log(exception, level, "Error has been raised."); } } return shallRethrow; } /// <summary> /// Determines whether the exception must be rethrown immediately, without logging the error to the <see cref="InternalLogger"/>. /// /// Only used this method in special cases. /// </summary> /// <param name="exception">The exception to check.</param> /// <returns><see langword="true"/> if the <paramref name="exception"/> must be rethrown, <see langword="false"/> otherwise.</returns> public static bool MustBeRethrownImmediately(this Exception exception) { if (exception is StackOverflowException) { return true; // StackOverflowException cannot be caught since .NetFramework 2.0 } if (exception is ThreadAbortException) { return true; // ThreadAbortException will automatically be rethrown at end of catch-block } if (exception is OutOfMemoryException) { return true; } #if DEBUG if (exception is InvalidCastException) { return true; } if (exception is NullReferenceException) { return true; } if (exception is ArgumentNullException) { return true; } if (exception is ArgumentOutOfRangeException) { return true; } if (exception is DivideByZeroException) { return true; } if (exception is OverflowException) { return true; } if (exception is System.Net.WebException) { return false; // Not a real InvalidOperationException } if (exception is InvalidOperationException) { return true; // Ex. Collection was modified } if (exception is IndexOutOfRangeException) { return true; } if (exception is System.Reflection.TargetInvocationException) { return true; // Compiler/reflection exception } #endif return false; } } }
ExceptionHelper
csharp
ServiceStack__ServiceStack
ServiceStack/tests/CheckMvc/CheckWebGlobalNamespace.dtos.cs
{ "start": 39494, "end": 39656 }
public partial class ____ : HelloBase<Poco> { public virtual string Result { get; set; } } [Serializable]
HelloWithGenericInheritance
csharp
SixLabors__ImageSharp
tests/ImageSharp.Tests/Memory/DiscontiguousBuffers/MemoryGroupIndex.cs
{ "start": 2460, "end": 3383 }
internal static class ____ { public static T GetElementAt<T>(this IMemoryGroup<T> group, MemoryGroupIndex idx) where T : struct { return group[idx.BufferIndex].Span[idx.ElementIndex]; } public static void SetElementAt<T>(this IMemoryGroup<T> group, MemoryGroupIndex idx, T value) where T : struct { group[idx.BufferIndex].Span[idx.ElementIndex] = value; } public static MemoryGroupIndex MinIndex<T>(this IMemoryGroup<T> group) where T : struct { return new MemoryGroupIndex(group.BufferLength, 0, 0); } public static MemoryGroupIndex MaxIndex<T>(this IMemoryGroup<T> group) where T : struct { return group.Count == 0 ? new MemoryGroupIndex(group.BufferLength, 0, 0) : new MemoryGroupIndex(group.BufferLength, group.Count - 1, group[group.Count - 1].Length); } }
MemoryGroupIndexExtensions
csharp
AvaloniaUI__Avalonia
src/Avalonia.Controls/RelativePanel.AttachedProperties.cs
{ "start": 85, "end": 25950 }
public partial class ____ { static RelativePanel() { ClipToBoundsProperty.OverrideDefaultValue<RelativePanel>(true); AffectsParentArrange<RelativePanel>( AlignLeftWithPanelProperty, AlignLeftWithProperty, LeftOfProperty, AlignRightWithPanelProperty, AlignRightWithProperty, RightOfProperty, AlignTopWithPanelProperty, AlignTopWithProperty, AboveProperty, AlignBottomWithPanelProperty, AlignBottomWithProperty, BelowProperty, AlignHorizontalCenterWithPanelProperty, AlignHorizontalCenterWithProperty, AlignVerticalCenterWithPanelProperty, AlignVerticalCenterWithProperty); AffectsParentMeasure<RelativePanel>( AlignLeftWithPanelProperty, AlignLeftWithProperty, LeftOfProperty, AlignRightWithPanelProperty, AlignRightWithProperty, RightOfProperty, AlignTopWithPanelProperty, AlignTopWithProperty, AboveProperty, AlignBottomWithPanelProperty, AlignBottomWithProperty, BelowProperty, AlignHorizontalCenterWithPanelProperty, AlignHorizontalCenterWithProperty, AlignVerticalCenterWithPanelProperty, AlignVerticalCenterWithProperty); } /// <summary> /// Gets the value of the RelativePanel.Above XAML attached property for the target element. /// </summary> /// <param name="obj">The object from which the property value is read.</param> /// <returns> /// The RelativePanel.Above XAML attached property value of the specified object. /// (The element to position this element above.) /// </returns> [ResolveByName] public static object GetAbove(AvaloniaObject obj) { return (object)obj.GetValue(AboveProperty); } /// <summary> /// Sets the value of the RelativePanel.Above XAML attached property for a target element. /// </summary> /// <param name="obj">The object to which the property value is written.</param> /// <param name="value">The value to set. (The element to position this element above.)</param> [ResolveByName] public static void SetAbove(AvaloniaObject obj, object value) { obj.SetValue(AboveProperty, value); } /// <summary> /// Identifies the <see cref="RelativePanel.AboveProperty"/> XAML attached property. /// </summary> public static readonly AttachedProperty<object> AboveProperty = AvaloniaProperty.RegisterAttached<Layoutable, object>("Above", typeof(RelativePanel)); /// <summary> /// Gets the value of the RelativePanel.AlignBottomWithPanel XAML attached property for the target element. /// </summary> /// <param name="obj">The object from which the property value is read.</param> /// <returns> /// The RelativePanel.AlignBottomWithPanel XAML attached property value of the specified /// object. (true to align this element's bottom edge with the panel's bottom edge; /// otherwise, false.) /// </returns> public static bool GetAlignBottomWithPanel(AvaloniaObject obj) { return (bool)obj.GetValue(AlignBottomWithPanelProperty); } /// <summary> /// Sets the value of the RelativePanel.Above XAML attached property for a target element. /// </summary> /// <param name="obj">The object to which the property value is written.</param> /// <param name="value"> /// The value to set. (true to align this element's bottom edge with the panel's /// bottom edge; otherwise, false.) /// </param> public static void SetAlignBottomWithPanel(AvaloniaObject obj, bool value) { obj.SetValue(AlignBottomWithPanelProperty, value); } /// <summary> /// Identifies the <see cref="RelativePanel.AlignBottomWithPanelProperty"/> XAML attached property. /// </summary> public static readonly AttachedProperty<bool> AlignBottomWithPanelProperty = AvaloniaProperty.RegisterAttached<Layoutable, bool>("AlignBottomWithPanel", typeof(RelativePanel)); /// <summary> /// Gets the value of the RelativePanel.AlignBottomWith XAML attached property for the target element. /// </summary> /// <param name="obj">The object from which the property value is read.</param> /// <returns> /// The RelativePanel.AlignBottomWith XAML attached property value of the specified object. /// (The element to align this element's bottom edge with.) /// </returns> [ResolveByName] public static object GetAlignBottomWith(AvaloniaObject obj) { return (object)obj.GetValue(AlignBottomWithProperty); } /// <summary> /// Sets the value of the RelativePanel.Above XAML attached property for a target element. /// </summary> /// <param name="obj">The object to which the property value is written.</param> /// <param name="value">The value to set. (The element to align this element's bottom edge with.)</param> [ResolveByName] public static void SetAlignBottomWith(AvaloniaObject obj, object value) { obj.SetValue(AlignBottomWithProperty, value); } /// <summary> /// Identifies the <see cref="RelativePanel.AlignBottomWithProperty"/> XAML attached property. /// </summary> public static readonly AttachedProperty<object> AlignBottomWithProperty = AvaloniaProperty.RegisterAttached<Layoutable, object>("AlignBottomWith", typeof(RelativePanel)); /// <summary> /// Gets the value of the RelativePanel.AlignHorizontalCenterWithPanel XAML attached property for the target element. /// </summary> /// <param name="obj">The object from which the property value is read.</param> /// <returns> /// The RelativePanel.AlignHorizontalCenterWithPanel XAML attached property value /// of the specified object. (true to horizontally center this element in the panel; /// otherwise, false.) /// </returns> public static bool GetAlignHorizontalCenterWithPanel(AvaloniaObject obj) { return (bool)obj.GetValue(AlignHorizontalCenterWithPanelProperty); } /// <summary> /// Sets the value of the RelativePanel.Above XAML attached property for a target element. /// </summary> /// <param name="obj">The object to which the property value is written.</param> /// <param name="value"> /// The value to set. (true to horizontally center this element in the panel; otherwise, /// false.) /// </param> public static void SetAlignHorizontalCenterWithPanel(AvaloniaObject obj, bool value) { obj.SetValue(AlignHorizontalCenterWithPanelProperty, value); } /// <summary> /// Identifies the <see cref="RelativePanel.AlignHorizontalCenterWithPanelProperty"/> XAML attached property. /// </summary> public static readonly AttachedProperty<bool> AlignHorizontalCenterWithPanelProperty = AvaloniaProperty.RegisterAttached<Layoutable, bool>("AlignHorizontalCenterWithPanel", typeof(RelativePanel), false); /// <summary> /// Gets the value of the RelativePanel.AlignHorizontalCenterWith XAML attached property for the target element. /// </summary> /// <param name="obj">The object from which the property value is read.</param> /// <returns> /// The RelativePanel.AlignHorizontalCenterWith XAML attached property value of the /// specified object. (The element to align this element's horizontal center with.) /// </returns> [ResolveByName] public static object GetAlignHorizontalCenterWith(AvaloniaObject obj) { return (object)obj.GetValue(AlignHorizontalCenterWithProperty); } /// <summary> /// Sets the value of the RelativePanel.Above XAML attached property for a target element. /// </summary> /// <param name="obj">The object to which the property value is written.</param> /// <param name="value">The value to set. (The element to align this element's horizontal center with.)</param> [ResolveByName] public static void SetAlignHorizontalCenterWith(AvaloniaObject obj, object value) { obj.SetValue(AlignHorizontalCenterWithProperty, value); } /// <summary> /// Identifies the <see cref="RelativePanel.AlignHorizontalCenterWithProperty"/> XAML attached property. /// </summary> public static readonly AttachedProperty<object> AlignHorizontalCenterWithProperty = AvaloniaProperty.RegisterAttached<Layoutable, object>("AlignHorizontalCenterWith", typeof(object), typeof(RelativePanel)); /// <summary> /// Gets the value of the RelativePanel.AlignLeftWithPanel XAML attached property for the target element. /// </summary> /// <param name="obj">The object from which the property value is read.</param> /// <returns> /// The RelativePanel.AlignLeftWithPanel XAML attached property value of the specified /// object. (true to align this element's left edge with the panel's left edge; otherwise, /// false.) /// </returns> public static bool GetAlignLeftWithPanel(AvaloniaObject obj) { return (bool)obj.GetValue(AlignLeftWithPanelProperty); } /// <summary> /// Sets the value of the RelativePanel.Above XAML attached property for a target element. /// </summary> /// <param name="obj">The object to which the property value is written.</param> /// <param name="value"> /// The value to set. (true to align this element's left edge with the panel's left /// edge; otherwise, false.) /// </param> public static void SetAlignLeftWithPanel(AvaloniaObject obj, bool value) { obj.SetValue(AlignLeftWithPanelProperty, value); } /// <summary> /// Identifies the <see cref="RelativePanel.AlignLeftWithPanelProperty"/> XAML attached property. /// </summary> public static readonly AttachedProperty<bool> AlignLeftWithPanelProperty = AvaloniaProperty.RegisterAttached<Layoutable, bool>("AlignLeftWithPanel", typeof(RelativePanel), false); /// <summary> /// Gets the value of the RelativePanel.AlignLeftWith XAML attached property for the target element. /// </summary> /// <param name="obj">The object from which the property value is read.</param> /// <returns> /// The RelativePanel.AlignLeftWith XAML attached property value of the specified /// object. (The element to align this element's left edge with.) /// </returns> [ResolveByName] public static object GetAlignLeftWith(AvaloniaObject obj) { return (object)obj.GetValue(AlignLeftWithProperty); } /// <summary> /// Sets the value of the RelativePanel.Above XAML attached property for a target element. /// </summary> /// <param name="obj">The object to which the property value is written.</param> /// <param name="value">The value to set. (The element to align this element's left edge with.)</param> [ResolveByName] public static void SetAlignLeftWith(AvaloniaObject obj, object value) { obj.SetValue(AlignLeftWithProperty, value); } /// <summary> /// Identifies the <see cref="RelativePanel.AlignLeftWithProperty"/> XAML attached property. /// </summary> public static readonly AttachedProperty<object> AlignLeftWithProperty = AvaloniaProperty.RegisterAttached<RelativePanel, Layoutable, object>("AlignLeftWith"); /// <summary> /// Gets the value of the RelativePanel.AlignRightWithPanel XAML attached property for the target element. /// </summary> /// <param name="obj">The object from which the property value is read.</param> /// <returns> /// The RelativePanel.AlignRightWithPanel XAML attached property value of the specified /// object. (true to align this element's right edge with the panel's right edge; /// otherwise, false.) /// </returns> public static bool GetAlignRightWithPanel(AvaloniaObject obj) { return (bool)obj.GetValue(AlignRightWithPanelProperty); } /// <summary> /// Sets the value of the RelativePanel.Above XAML attached property for a target element. /// </summary> /// <param name="obj">The object to which the property value is written.</param> /// <param name="value"> /// The value to set. (true to align this element's right edge with the panel's right /// edge; otherwise, false.) /// </param> public static void SetAlignRightWithPanel(AvaloniaObject obj, bool value) { obj.SetValue(AlignRightWithPanelProperty, value); } /// <summary> /// Identifies the <see cref="RelativePanel.AlignRightWithPanelProperty"/> XAML attached property. /// </summary> public static readonly AttachedProperty<bool> AlignRightWithPanelProperty = AvaloniaProperty.RegisterAttached<RelativePanel, Layoutable, bool>("AlignRightWithPanel", false); /// <summary> /// Gets the value of the RelativePanel.AlignRightWith XAML attached property for the target element. /// </summary> /// <param name="obj">The object from which the property value is read.</param> /// <returns> /// The RelativePanel.AlignRightWith XAML attached property value of the specified /// object. (The element to align this element's right edge with.) /// </returns> [ResolveByName] public static object GetAlignRightWith(AvaloniaObject obj) { return (object)obj.GetValue(AlignRightWithProperty); } /// <summary> /// Sets the value of the RelativePanel.AlignRightWith XAML attached property for a target element. /// </summary> /// <param name="obj">The object to which the property value is written.</param> /// <param name="value">The value to set. (The element to align this element's right edge with.)</param> [ResolveByName] public static void SetAlignRightWith(AvaloniaObject obj, object value) { obj.SetValue(AlignRightWithProperty, value); } /// <summary> /// Identifies the <see cref="RelativePanel.AlignRightWithProperty"/> XAML attached property. /// </summary> public static readonly AttachedProperty<object> AlignRightWithProperty = AvaloniaProperty.RegisterAttached<RelativePanel, Layoutable, object>("AlignRightWith"); /// <summary> /// Gets the value of the RelativePanel.AlignTopWithPanel XAML attached property for the target element. /// </summary> /// <param name="obj">The object from which the property value is read.</param> /// <returns> /// The RelativePanel.AlignTopWithPanel XAML attached property value of the specified /// object. (true to align this element's top edge with the panel's top edge; otherwise, /// false.) /// </returns> public static bool GetAlignTopWithPanel(AvaloniaObject obj) { return (bool)obj.GetValue(AlignTopWithPanelProperty); } /// <summary> /// Sets the value of the RelativePanel.AlignTopWithPanel XAML attached property for a target element. /// </summary> /// <param name="obj">The object to which the property value is written.</param> /// <param name="value"> /// The value to set. (true to align this element's top edge with the panel's top /// edge; otherwise, false.) /// </param> public static void SetAlignTopWithPanel(AvaloniaObject obj, bool value) { obj.SetValue(AlignTopWithPanelProperty, value); } /// <summary> /// Identifies the <see cref="RelativePanel.AlignTopWithPanelProperty"/> XAML attached property. /// </summary> public static readonly AttachedProperty<bool> AlignTopWithPanelProperty = AvaloniaProperty.RegisterAttached<RelativePanel, Layoutable, bool>("AlignTopWithPanel", false); /// <summary> /// Gets the value of the RelativePanel.AlignTopWith XAML attached property for the target element. /// </summary> /// <param name="obj">The object from which the property value is read.</param> /// <returns>The value to set. (The element to align this element's top edge with.)</returns> [ResolveByName] public static object GetAlignTopWith(AvaloniaObject obj) { return (object)obj.GetValue(AlignTopWithProperty); } /// <summary> /// Sets the value of the RelativePanel.AlignTopWith XAML attached property for a target element. /// </summary> /// <param name="obj">The object to which the property value is written.</param> /// <param name="value">The value to set. (The element to align this element's top edge with.)</param> [ResolveByName] public static void SetAlignTopWith(AvaloniaObject obj, object value) { obj.SetValue(AlignTopWithProperty, value); } /// <summary> /// Identifies the <see cref="RelativePanel.AlignTopWithProperty"/> XAML attached property. /// </summary> public static readonly AttachedProperty<object> AlignTopWithProperty = AvaloniaProperty.RegisterAttached<RelativePanel, Layoutable, object>("AlignTopWith"); /// <summary> /// Gets the value of the RelativePanel.AlignVerticalCenterWithPanel XAML attached property for the target element. /// </summary> /// <param name="obj">The object from which the property value is read.</param> /// <returns> /// The RelativePanel.AlignVerticalCenterWithPanel XAML attached property value of /// the specified object. (true to vertically center this element in the panel; otherwise, /// false.) /// </returns> public static bool GetAlignVerticalCenterWithPanel(AvaloniaObject obj) { return (bool)obj.GetValue(AlignVerticalCenterWithPanelProperty); } /// <summary> /// Sets the value of the RelativePanel.AlignVerticalCenterWithPanel XAML attached property for a target element. /// </summary> /// <param name="obj">The object to which the property value is written.</param> /// <param name="value"> /// The value to set. (true to vertically center this element in the panel; otherwise, /// false.) /// </param> public static void SetAlignVerticalCenterWithPanel(AvaloniaObject obj, bool value) { obj.SetValue(AlignVerticalCenterWithPanelProperty, value); } /// <summary> /// Identifies the <see cref="RelativePanel.AlignVerticalCenterWithPanelProperty"/> XAML attached property. /// </summary> public static readonly AttachedProperty<bool> AlignVerticalCenterWithPanelProperty = AvaloniaProperty.RegisterAttached<RelativePanel, Layoutable, bool>("AlignVerticalCenterWithPanel", false); /// <summary> /// Gets the value of the RelativePanel.AlignVerticalCenterWith XAML attached property for the target element. /// </summary> /// <param name="obj">The object from which the property value is read.</param> /// <returns>The value to set. (The element to align this element's vertical center with.)</returns> [ResolveByName] public static object GetAlignVerticalCenterWith(AvaloniaObject obj) { return (object)obj.GetValue(AlignVerticalCenterWithProperty); } /// <summary> /// Sets the value of the RelativePanel.AlignVerticalCenterWith XAML attached property for a target element. /// </summary> /// <param name="obj">The object to which the property value is written.</param> /// <param name="value">The value to set. (The element to align this element's horizontal center with.)</param> [ResolveByName] public static void SetAlignVerticalCenterWith(AvaloniaObject obj, object value) { obj.SetValue(AlignVerticalCenterWithProperty, value); } /// <summary> /// Identifies the <see cref="RelativePanel.AlignVerticalCenterWithProperty"/> XAML attached property. /// </summary> public static readonly AttachedProperty<object> AlignVerticalCenterWithProperty = AvaloniaProperty.RegisterAttached<RelativePanel, Layoutable, object>("AlignVerticalCenterWith"); /// <summary> /// Gets the value of the RelativePanel.Below XAML attached property for the target element. /// </summary> /// <param name="obj">The object from which the property value is read.</param> /// <returns> /// The RelativePanel.Below XAML attached property value of the specified object. /// (The element to position this element below.) /// </returns> [ResolveByName] public static object GetBelow(AvaloniaObject obj) { return (object)obj.GetValue(BelowProperty); } /// <summary> /// Sets the value of the RelativePanel.Above XAML attached property for a target element. /// </summary> /// <param name="obj">The object to which the property value is written.</param> /// <param name="value">The value to set. (The element to position this element below.)</param> [ResolveByName] public static void SetBelow(AvaloniaObject obj, object value) { obj.SetValue(BelowProperty, value); } /// <summary> /// Identifies the <see cref="RelativePanel.BelowProperty"/> XAML attached property. /// </summary> public static readonly AttachedProperty<object> BelowProperty = AvaloniaProperty.RegisterAttached<RelativePanel, Layoutable, object>("Below"); /// <summary> /// Gets the value of the RelativePanel.LeftOf XAML attached property for the target element. /// </summary> /// <param name="obj">The object from which the property value is read.</param> /// <returns> /// The RelativePanel.LeftOf XAML attached property value of the specified object. /// (The element to position this element to the left of.) /// </returns> [ResolveByName] public static object GetLeftOf(AvaloniaObject obj) { return (object)obj.GetValue(LeftOfProperty); } /// <summary> /// Sets the value of the RelativePanel.LeftOf XAML attached property for a target element. /// </summary> /// <param name="obj">The object to which the property value is written.</param> /// <param name="value">The value to set. (The element to position this element to the left of.)</param> [ResolveByName] public static void SetLeftOf(AvaloniaObject obj, object value) { obj.SetValue(LeftOfProperty, value); } /// <summary> /// Identifies the <see cref="RelativePanel.LeftOfProperty"/> XAML attached property. /// </summary> public static readonly AttachedProperty<object> LeftOfProperty = AvaloniaProperty.RegisterAttached<RelativePanel, Layoutable, object>("LeftOf"); /// <summary> /// Gets the value of the RelativePanel.RightOf XAML attached property for the target element. /// </summary> /// <param name="obj">The object from which the property value is read.</param> /// <returns> /// The RelativePanel.RightOf XAML attached property value of the specified object. /// (The element to position this element to the right of.) /// </returns> [ResolveByName] public static object GetRightOf(AvaloniaObject obj) { return (object)obj.GetValue(RightOfProperty); } /// <summary> /// Sets the value of the RelativePanel.RightOf XAML attached property for a target element. /// </summary> /// <param name="obj">The object to which the property value is written.</param> /// <param name="value">The value to set. (The element to position this element to the right of.)</param> [ResolveByName] public static void SetRightOf(AvaloniaObject obj, object value) { obj.SetValue(RightOfProperty, value); } /// <summary> /// Identifies the <see cref="RelativePanel.RightOfProperty"/> XAML attached property. /// </summary> public static readonly AttachedProperty<object> RightOfProperty = AvaloniaProperty.RegisterAttached<RelativePanel, Layoutable, object>("RightOf"); } }
RelativePanel
csharp
npgsql__npgsql
src/Npgsql/NpgsqlTypeLoadingOptions.cs
{ "start": 3066, "end": 3636 }
public enum ____ { /// <summary> /// No special server compatibility mode is active /// </summary> None, /// <summary> /// The server is an Amazon Redshift instance. /// </summary> [Obsolete("ServerCompatibilityMode.Redshift no longer does anything and can be safely removed.")] Redshift, /// <summary> /// The server is doesn't support full type loading from the PostgreSQL catalogs, support the basic set /// of types via information hardcoded inside Npgsql. /// </summary> NoTypeLoading, }
ServerCompatibilityMode
csharp
dotnet__maui
src/Controls/tests/DeviceTests/Elements/Shell/ShellTests.Android.cs
{ "start": 1040, "end": 24246 }
public partial class ____ { [Fact(DisplayName = "No crash going back using 'Shell.Current.GoToAsync(\"..\")'")] public async Task GoingBackUsingGoToAsyncMethod() { SetupBuilder(); var page1 = new ContentPage(); var page2Content = new Label { Text = "Test" }; var page2 = new ContentPage { Content = page2Content }; var pointerGestureRecognizer = new PointerGestureRecognizer(); pointerGestureRecognizer.PointerPressed += (sender, args) => { Console.WriteLine("Page Content pressed"); }; page2Content.GestureRecognizers.Add(pointerGestureRecognizer); var shell = await CreateShellAsync((shell) => { shell.Items.Add(new TabBar() { Items = { new ShellContent() { Route = "Item1", Content = page1 }, new ShellContent() { Route = "Item2", Content = page2 }, } }); }); await CreateHandlerAndAddToWindow<ShellHandler>(shell, async (handler) => { await OnLoadedAsync(page1); await shell.GoToAsync("//Item2"); await shell.GoToAsync(".."); await shell.GoToAsync("//Item1"); await shell.GoToAsync("//Item2"); await shell.Navigation.PopAsync(); await shell.GoToAsync("//Item1"); await shell.GoToAsync("//Item2"); await shell.GoToAsync(".."); }); } [Theory] [InlineData(true)] [InlineData(false)] public async Task CanHideNavBarShadow(bool navBarHasShadow) { SetupBuilder(); var contentPage = new ContentPage() { Title = "Flyout Item" }; var shell = await CreateShellAsync(shell => { shell.CurrentItem = new FlyoutItem() { Items = { contentPage } }; shell.FlyoutContent = new VerticalStackLayout() { new Label(){ Text = "Flyout Content"} }; Shell.SetNavBarHasShadow(contentPage, navBarHasShadow); }); await CreateHandlerAndAddToWindow<ShellRenderer>(shell, async (handler) => { await Task.Delay(100); var platformToolbar = GetPlatformToolbar(handler); var appBar = platformToolbar.Parent.GetParentOfType<AppBarLayout>(); if (navBarHasShadow) Assert.True(appBar.Elevation > 0); else Assert.True(appBar.Elevation == 0); }); } protected async Task CheckFlyoutState(ShellRenderer handler, bool desiredState) { var drawerLayout = GetDrawerLayout(handler); var flyout = drawerLayout.GetChildAt(1); if (drawerLayout.IsDrawerOpen(flyout) == desiredState) { Assert.Equal(desiredState, drawerLayout.IsDrawerOpen(flyout)); return; } var taskCompletionSource = new TaskCompletionSource<bool>(); flyout.LayoutChange += OnLayoutChanged; try { await taskCompletionSource.Task.WaitAsync(TimeSpan.FromSeconds(2)); } catch (TimeoutException) { } flyout.LayoutChange -= OnLayoutChanged; Assert.Equal(desiredState, drawerLayout.IsDrawerOpen(flyout)); return; void OnLayoutChanged(object sender, global::Android.Views.View.LayoutChangeEventArgs e) { if (drawerLayout.IsDrawerOpen(flyout) == desiredState) { taskCompletionSource.SetResult(true); flyout.LayoutChange -= OnLayoutChanged; } } } [Fact(DisplayName = "FlyoutItems Render When FlyoutBehavior Starts As Locked")] public async Task FlyoutItemsRendererWhenFlyoutBehaviorStartsAsLocked() { SetupBuilder(); var shell = await CreateShellAsync(shell => { shell.CurrentItem = new FlyoutItem() { Items = { new ContentPage() }, Title = "Flyout Item" }; shell.FlyoutBehavior = FlyoutBehavior.Locked; }); await CreateHandlerAndAddToWindow<ShellRenderer>(shell, async (handler) => { await Task.Delay(100); var dl = GetDrawerLayout(handler); var flyoutContainer = GetFlyoutMenuReyclerView(handler); Assert.True(flyoutContainer.MeasuredWidth > 0); Assert.True(flyoutContainer.MeasuredHeight > 0); }); } [Fact(DisplayName = "Shell with Flyout Disabled Doesn't Render Flyout")] public async Task ShellWithFlyoutDisabledDoesntRenderFlyout() { SetupBuilder(); var shell = await CreateShellAsync((shell) => { shell.Items.Add(new ContentPage()); }); shell.FlyoutBehavior = FlyoutBehavior.Disabled; await CreateHandlerAndAddToWindow<ShellRenderer>(shell, (handler) => { var dl = GetDrawerLayout(handler); Assert.Equal(1, dl.ChildCount); shell.FlyoutBehavior = FlyoutBehavior.Flyout; Assert.Equal(2, dl.ChildCount); return Task.CompletedTask; }); } [Fact(DisplayName = "FooterTemplate Measures to Set Flyout Width When Flyout Locked")] public async Task FooterTemplateMeasuresToSetFlyoutWidth() { SetupBuilder(); VerticalStackLayout footer = new VerticalStackLayout() { new Label(){ Text = "Hello there"} }; var shell = await CreateShellAsync(shell => { shell.CurrentItem = new FlyoutItem() { Items = { new ContentPage() }, Title = "Flyout Item" }; shell.FlyoutBehavior = FlyoutBehavior.Locked; shell.FlyoutWidth = 20; shell.FlyoutFooter = footer; }); await CreateHandlerAndAddToWindow<ShellRenderer>(shell, async (handler) => { await OnFrameSetToNotEmpty(footer); Assert.True(Math.Abs(20 - footer.Frame.Width) < 1); Assert.True(footer.Frame.Height > 0); }); } [Fact(DisplayName = "Flyout Footer and Default Flyout Items Render")] public async Task FlyoutFooterRenderersWithDefaultFlyoutItems() { SetupBuilder(); VerticalStackLayout footer = new VerticalStackLayout() { new Label() { Text = "Hello there"} }; var shell = await CreateShellAsync(shell => { shell.CurrentItem = new FlyoutItem() { Items = { new ContentPage() }, Title = "Flyout Item" }; shell.FlyoutFooter = footer; }); await CreateHandlerAndAddToWindow<ShellRenderer>(shell, async (handler) => { await Task.Delay(100); var dl = GetDrawerLayout(handler); await OpenFlyout(handler); var flyoutContainer = GetFlyoutMenuReyclerView(handler); Assert.True(flyoutContainer.MeasuredWidth > 0); Assert.True(flyoutContainer.MeasuredHeight > 0); }); } [Fact] public async Task FlyoutItemsRenderWhenFlyoutHeaderIsSet() { SetupBuilder(); VerticalStackLayout header = new VerticalStackLayout() { new Label() { Text = "Hello there"} }; var shell = await CreateShellAsync(shell => { shell.CurrentItem = new FlyoutItem() { Items = { new ContentPage() }, Title = "Flyout Item" }; shell.FlyoutHeader = header; }); await CreateHandlerAndAddToWindow<ShellRenderer>(shell, async (handler) => { await Task.Delay(100); var dl = GetDrawerLayout(handler); await OpenFlyout(handler); var flyoutContainer = GetFlyoutMenuReyclerView(handler); Assert.True(flyoutContainer.MeasuredWidth > 0); Assert.True(flyoutContainer.MeasuredHeight > 0); }); } [Fact] public async Task FlyoutHeaderRendersCorrectSizeWithFlyoutContentSet() { SetupBuilder(); VerticalStackLayout header = new VerticalStackLayout() { new Label() { Text = "Flyout Header"} }; var shell = await CreateShellAsync(shell => { shell.CurrentItem = new FlyoutItem() { Items = { new ContentPage() }, Title = "Flyout Item" }; shell.FlyoutHeader = header; shell.FlyoutContent = new VerticalStackLayout() { new Label(){ Text = "Flyout Content"} }; shell.FlyoutFooter = new VerticalStackLayout() { new Label(){ Text = "Flyout Footer"} }; }); await CreateHandlerAndAddToWindow<ShellRenderer>(shell, async (handler) => { await Task.Delay(100); var headerPlatformView = header.ToPlatform(); var appBar = headerPlatformView.GetParentOfType<AppBarLayout>(); Assert.Equal(appBar.MeasuredHeight - appBar.PaddingTop, headerPlatformView.MeasuredHeight); }); } [Fact] public async Task SwappingOutAndroidContextDoesntCrash() { SetupBuilder(); var shell = await CreateShellAsync(shell => { shell.Items.Add(new FlyoutItem() { Route = "FlyoutItem1", Items = { new ContentPage() }, Title = "Flyout Item" }); shell.Items.Add(new FlyoutItem() { Route = "FlyoutItem2", Items = { new ContentPage() }, Title = "Flyout Item" }); }); var window = new Controls.Window(shell); var mauiContextStub1 = ContextStub.CreateNew(MauiContext); await CreateHandlerAndAddToWindow<IWindowHandler>(window, async (handler) => { await OnLoadedAsync(shell.CurrentPage); await OnNavigatedToAsync(shell.CurrentPage); await Task.Delay(100); await shell.GoToAsync("//FlyoutItem2"); }, mauiContextStub1); var mauiContextStub2 = ContextStub.CreateNew(MauiContext); await CreateHandlerAndAddToWindow<IWindowHandler>(window, async (handler) => { await OnLoadedAsync(shell.CurrentPage); await OnNavigatedToAsync(shell.CurrentPage); await Task.Delay(100); await shell.GoToAsync("//FlyoutItem1"); await shell.GoToAsync("//FlyoutItem2"); }, mauiContextStub2); } [Fact] public async Task ChangingBottomTabAttributesDoesntRecreateBottomTabs() { SetupBuilder(); var shell = await CreateShellAsync(shell => { shell.Items.Add(new Tab() { Items = { new ContentPage() }, Title = "Tab 1", Icon = "red.png" }); shell.Items.Add(new Tab() { Items = { new ContentPage() }, Title = "Tab 2", Icon = "red.png" }); }); await CreateHandlerAndAddToWindow<ShellRenderer>(shell, async (handler) => { var menu = GetDrawerLayout(handler).GetFirstChildOfType<BottomNavigationView>().Menu; var menuItem1 = menu.GetItem(0); var menuItem2 = menu.GetItem(1); var icon1 = menuItem1.Icon; var icon2 = menuItem2.Icon; var title1 = menuItem1.TitleFormatted; var title2 = menuItem2.TitleFormatted; shell.CurrentItem.Items[0].Title = "new Title 1"; shell.CurrentItem.Items[0].Icon = "blue.png"; shell.CurrentItem.Items[1].Title = "new Title 2"; shell.CurrentItem.Items[1].Icon = "blue.png"; // let the icon and title propagate await AssertEventually(() => menuItem1.Icon != icon1); menu = GetDrawerLayout(handler).GetFirstChildOfType<BottomNavigationView>().Menu; Assert.Equal(menuItem1, menu.GetItem(0)); Assert.Equal(menuItem2, menu.GetItem(1)); menuItem1.Icon.AssertColorAtCenter(global::Android.Graphics.Color.Blue); menuItem2.Icon.AssertColorAtCenter(global::Android.Graphics.Color.Blue); Assert.NotEqual(icon1, menuItem1.Icon); Assert.NotEqual(icon2, menuItem2.Icon); Assert.NotEqual(title1, menuItem1.TitleFormatted); Assert.NotEqual(title2, menuItem2.TitleFormatted); }); } [Fact] public async Task RemovingBottomTabDoesntRecreateMenu() { SetupBuilder(); var shell = await CreateShellAsync(shell => { shell.Items.Add(new Tab() { Items = { new ContentPage() }, Title = "Tab 1", Icon = "red.png" }); shell.Items.Add(new Tab() { Items = { new ContentPage() }, Title = "Tab 2", Icon = "red.png" }); shell.Items.Add(new Tab() { Items = { new ContentPage() }, Title = "Tab 3", Icon = "red.png" }); }); await CreateHandlerAndAddToWindow<ShellRenderer>(shell, async (handler) => { var bottomView = GetDrawerLayout(handler).GetFirstChildOfType<BottomNavigationView>(); var menu = bottomView.Menu; var menuItem1 = menu.GetItem(0); var menuItem2 = menu.GetItem(1); shell.CurrentItem.Items.RemoveAt(2); // let the change propagate await AssertEventually(() => bottomView.Menu.Size() == 2); menu = bottomView.Menu; Assert.Equal(menuItem1, menu.GetItem(0)); Assert.Equal(menuItem2, menu.GetItem(1)); }); } [Fact] public async Task AddingBottomTabDoesntRecreateMenu() { SetupBuilder(); var shell = await CreateShellAsync(shell => { shell.Items.Add(new Tab() { Items = { new ContentPage() }, Title = "Tab 1", Icon = "red.png" }); shell.Items.Add(new Tab() { Items = { new ContentPage() }, Title = "Tab 3", Icon = "red.png" }); }); await CreateHandlerAndAddToWindow<ShellRenderer>(shell, async (handler) => { var bottomView = GetDrawerLayout(handler).GetFirstChildOfType<BottomNavigationView>(); var menu = bottomView.Menu; var menuItem1 = menu.GetItem(0); var menuItem2 = menu.GetItem(1); var menuItem2Icon = menuItem2.Icon; shell.CurrentItem.Items.Insert(1, new Tab() { Items = { new ContentPage() }, Title = "Tab 2", Icon = "green.png" }); // let the change propagate await AssertEventually(() => bottomView.Menu.GetItem(1).Icon != menuItem2Icon); menu = bottomView.Menu; Assert.Equal(menuItem1, menu.GetItem(0)); Assert.Equal(menuItem2, menu.GetItem(1)); menu.GetItem(1).Icon.AssertColorAtCenter(global::Android.Graphics.Color.Green); menu.GetItem(2).Icon.AssertColorAtCenter(global::Android.Graphics.Color.Red); }); } //src/Compatibility/Core/tests/Android/ShellTests.cs [Fact(DisplayName = "Flyout Header Changes When Updated")] public async Task FlyoutHeaderReactsToChanges() { SetupBuilder(); var initialHeader = new Label() { Text = "Hello" }; var newHeader = new Label() { Text = "Hello Part 2" }; var shell = await CreateShellAsync(shell => { shell.CurrentItem = new FlyoutItem() { Items = { new ContentPage() }, Title = "Flyout Item" }; shell.FlyoutHeader = initialHeader; }); await CreateHandlerAndAddToWindow<ShellRenderer>(shell, async (handler) => { var initialHeaderPlatformView = initialHeader.ToPlatform(); Assert.NotNull(initialHeaderPlatformView); Assert.NotNull(initialHeader.Handler); shell.FlyoutHeader = newHeader; var newHeaderPlatformView = newHeader.ToPlatform(); Assert.NotNull(newHeaderPlatformView); Assert.NotNull(newHeader.Handler); Assert.Null(initialHeader.Handler); await OpenFlyout(handler); var appBar = newHeaderPlatformView.GetParentOfType<AppBarLayout>(); Assert.NotNull(appBar); }); } //src/Compatibility/Core/tests/Android/ShellTests.cs [Fact(DisplayName = "Ensure Default Colors are White for BottomNavigationView")] public async Task ShellTabColorsDefaultToWhite() { SetupBuilder(); var shell = await CreateShellAsync(shell => { shell.Items.Add(new Tab() { Items = { new ContentPage() }, Title = "Tab 1" }); }); await CreateHandlerAndAddToWindow<ShellRenderer>(shell, (handler) => { var bottomNavigationView = GetDrawerLayout(handler).GetFirstChildOfType<BottomNavigationView>(); Assert.NotNull(bottomNavigationView); var background = bottomNavigationView.Background; Assert.NotNull(background); if (background is ColorChangeRevealDrawable changeRevealDrawable) { Assert.Equal(global::Android.Graphics.Color.White, changeRevealDrawable.EndColor); } }); } [Fact(DisplayName = "ShellContentFragment.Destroy handles null _shellContext gracefully")] public async Task ShellContentFragmentDestroyHandlesNullShellContext() { SetupBuilder(); var shell = await CreateShellAsync(shell => { shell.Items.Add(new TabBar() { Items = { new ShellContent() { Route = "Item1", Content = new ContentPage { Title = "Page 1" } }, new ShellContent() { Route = "Item2", Content = new ContentPage { Title = "Page 2" } }, } }); }); await CreateHandlerAndAddToWindow<ShellHandler>(shell, async (handler) => { await OnLoadedAsync(shell.CurrentPage); await OnNavigatedToAsync(shell.CurrentPage); // Navigate to trigger fragment creation await shell.GoToAsync("//Item2"); await OnNavigatedToAsync(shell.CurrentPage); // Test normal destruction - should work without issues await shell.GoToAsync("//Item1"); await OnNavigatedToAsync(shell.CurrentPage); // Test null context scenario var exception = Record.Exception(() => { // Create fragment with null context - this should not throw Page page = new ContentPage(); var fragment = new ShellContentFragment((IShellContext)null, page); // Dispose the fragment which calls Destroy internally // This validates the null-conditional operators in Destroy method fragment.Dispose(); }); // Verify no exception was thrown - validates (_shellContext?.Shell as IShellController)?.RemoveAppearanceObserver(this); Assert.Null(exception); }); } protected AView GetFlyoutPlatformView(ShellRenderer shellRenderer) { var drawerLayout = GetDrawerLayout(shellRenderer); return drawerLayout.GetChildrenOfType<ShellFlyoutLayout>().First(); } internal Graphics.Rect GetFlyoutFrame(ShellRenderer shellRenderer) { var platformView = GetFlyoutPlatformView(shellRenderer); var context = platformView.Context; return new Graphics.Rect(0, 0, context.FromPixels(platformView.MeasuredWidth- (platformView.PaddingLeft + platformView.PaddingRight)), context.FromPixels(platformView.MeasuredHeight - (platformView.PaddingTop + platformView.PaddingBottom))); } internal Graphics.Rect GetFrameRelativeToFlyout(ShellRenderer shellRenderer, IView view) { var platformView = (view.Handler as IPlatformViewHandler).PlatformView; return platformView.GetFrameRelativeTo(GetFlyoutPlatformView(shellRenderer)); } protected async Task OpenFlyout(ShellRenderer shellRenderer, TimeSpan? timeOut = null) { var flyoutView = GetFlyoutPlatformView(shellRenderer); var drawerLayout = GetDrawerLayout(shellRenderer); if (!drawerLayout.FlyoutFirstDrawPassFinished) await Task.Delay(10); var hamburger = GetPlatformToolbar((IPlatformViewHandler)shellRenderer).GetChildrenOfType<AppCompatImageButton>().FirstOrDefault() ?? throw new InvalidOperationException("Unable to find Drawer Button"); timeOut = timeOut ?? TimeSpan.FromSeconds(2); TaskCompletionSource<object> taskCompletionSource = new TaskCompletionSource<object>(); drawerLayout.DrawerOpened += OnDrawerOpened; hamburger.PerformClick(); await taskCompletionSource.Task.WaitAsync(timeOut.Value); void OnDrawerOpened(object sender, DrawerLayout.DrawerOpenedEventArgs e) { drawerLayout.DrawerOpened -= OnDrawerOpened; taskCompletionSource.SetResult(true); } } protected async Task<double> ScrollFlyoutToBottom(ShellRenderer shellRenderer) { IShellContext shellContext = shellRenderer; DrawerLayout dl = shellContext.CurrentDrawerLayout; var viewGroup = dl.GetChildAt(1) as ViewGroup; var scrollView = viewGroup?.GetChildAt(0); if (scrollView is RecyclerView rv) { return await ScrollRecyclerViewToBottom(rv); } else if (scrollView is MauiScrollView mauisv) { return await ScrollMauiScrollViewToBottom(mauisv); } else { throw new Exception("RecyclerView or MauiScrollView not found"); } } async Task<double> ScrollRecyclerViewToBottom(RecyclerView flyoutItems) { TaskCompletionSource<object> result = new TaskCompletionSource<object>(); flyoutItems.ScrollChange += OnFlyoutItemsScrollChange; flyoutItems.ScrollToPosition(flyoutItems.GetAdapter().ItemCount - 1); await result.Task.WaitAsync(TimeSpan.FromSeconds(2)); await Task.Delay(10); void OnFlyoutItemsScrollChange(object sender, AView.ScrollChangeEventArgs e) { flyoutItems.ScrollChange -= OnFlyoutItemsScrollChange; result.TrySetResult(true); } // The appbar layout won't offset if you programmatically scroll the RecyclerView // I haven't found a way to match the exact behavior when you touch and scroll // I think we'd have to actually send touch events through adb var coordinatorLayout = flyoutItems.Parent.GetParentOfType<CoordinatorLayout>(); var appbarLayout = coordinatorLayout.GetFirstChildOfType<AppBarLayout>(); var clLayoutParams = appbarLayout.LayoutParameters as CoordinatorLayout.LayoutParams; var behavior = clLayoutParams.Behavior as AppBarLayout.Behavior; var headerContainer = appbarLayout.GetFirstChildOfType<HeaderContainer>(); var verticalOffset = flyoutItems.ComputeVerticalScrollOffset(); behavior.OnNestedPreScroll(coordinatorLayout, appbarLayout, flyoutItems, 0, verticalOffset, new int[2], ViewCompat.TypeTouch); await Task.Delay(10); return verticalOffset; } async Task<double> ScrollMauiScrollViewToBottom(MauiScrollView flyoutItems) { TaskCompletionSource<object> result = new TaskCompletionSource<object>(); flyoutItems.ScrollChange += OnFlyoutItemsScrollChange; flyoutItems.ScrollTo(0, flyoutItems.Height); await result.Task.WaitAsync(TimeSpan.FromSeconds(2)); await Task.Delay(10); void OnFlyoutItemsScrollChange(object sender, NestedScrollView.ScrollChangeEventArgs e) { flyoutItems.ScrollChange -= OnFlyoutItemsScrollChange; result.TrySetResult(true); } // The appbar layout won't offset if you programmatically scroll the RecyclerView // I haven't found a way to match the exact behavior when you touch and scroll // I think we'd have to actually send touch events through adb var coordinatorLayout = flyoutItems.Parent.GetParentOfType<CoordinatorLayout>(); var appbarLayout = coordinatorLayout.GetFirstChildOfType<AppBarLayout>(); var clLayoutParams = appbarLayout.LayoutParameters as CoordinatorLayout.LayoutParams; var behavior = clLayoutParams.Behavior as AppBarLayout.Behavior; var headerContainer = appbarLayout.GetFirstChildOfType<HeaderContainer>(); #pragma warning disable XAOBS001 // Obsolete var verticalOffset = flyoutItems.ComputeVerticalScrollOffset(); #pragma warning restore XAOBS001 // Obsolete behavior.OnNestedPreScroll(coordinatorLayout, appbarLayout, flyoutItems, 0, verticalOffset, new int[2], ViewCompat.TypeTouch); await Task.Delay(10); return verticalOffset; } ShellFlyoutRenderer GetDrawerLayout(ShellRenderer shellRenderer) { IShellContext shellContext = shellRenderer; return (ShellFlyoutRenderer)shellContext.CurrentDrawerLayout; } RecyclerView GetFlyoutMenuReyclerView(ShellRenderer shellRenderer) { IShellContext shellContext = shellRenderer; DrawerLayout dl = shellContext.CurrentDrawerLayout; var flyout = dl.GetChildAt(0); RecyclerView flyoutContainer = null; var ViewGroup = dl.GetChildAt(1) as ViewGroup; var rc = ViewGroup.GetChildAt(0) as RecyclerView; if (dl.GetChildAt(1) is ViewGroup vg1 && vg1.GetChildAt(0) is RecyclerView rvc) { flyoutContainer = rvc; } return flyoutContainer ?? throw new Exception("RecyclerView not found"); } async Task TapToSelect(ContentPage page) { var shellContent = page.Parent as ShellContent; var shellSection = shellContent.Parent as ShellSection; var shellItem = shellSection.Parent as ShellItem; var shell = shellItem.Parent as Shell; await OnNavigatedToAsync(shell.CurrentPage); if (shellItem != shell.CurrentItem) throw new NotImplementedException(); if (shellSection != shell.CurrentItem.CurrentItem) throw new NotImplementedException(); var pagerParent = (shell.CurrentPage.Handler as IPlatformViewHandler) .PlatformView.GetParentOfType<ViewPager2>(); pagerParent.CurrentItem = shellSection.Items.IndexOf(shellContent); await OnNavigatedToAsync(page); } } }
ShellTests
csharp
dotnet__machinelearning
src/Microsoft.ML.Core/Data/ISchemaBindableMapper.cs
{ "start": 1877, "end": 2021 }
internal interface ____ { ISchemaBoundMapper Bind(IHostEnvironment env, RoleMappedSchema schema); } /// <summary> /// This
ISchemaBindableMapper
csharp
MassTransit__MassTransit
src/MassTransit/Audit/MetadataFactories/DefaultSendMetadataFactory.cs
{ "start": 78, "end": 1461 }
public class ____ : ISendMetadataFactory { MessageAuditMetadata ISendMetadataFactory.CreateAuditMetadata<T>(SendContext<T> context) { return CreateMetadata(context, "Send"); } MessageAuditMetadata ISendMetadataFactory.CreateAuditMetadata<T>(PublishContext<T> context) { return CreateMetadata(context, "Publish"); } static MessageAuditMetadata CreateMetadata(SendContext context, string contextType) { return new MessageAuditMetadata { ContextType = contextType, ConversationId = context.ConversationId, CorrelationId = context.CorrelationId, InitiatorId = context.InitiatorId, MessageId = context.MessageId, RequestId = context.RequestId, SentTime = context.SentTime, DestinationAddress = context.DestinationAddress?.AbsoluteUri, SourceAddress = context.SourceAddress?.AbsoluteUri, FaultAddress = context.FaultAddress?.AbsoluteUri, ResponseAddress = context.ResponseAddress?.AbsoluteUri, InputAddress = "", Headers = context.Headers?.GetAll()?.ToDictionary(k => k.Key, v => v.Value.ToString()) }; } } }
DefaultSendMetadataFactory
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/ContainerTests/Common_Tests/Common_Consumer.cs
{ "start": 4114, "end": 5631 }
public class ____ : InMemoryContainerTestFixture { [Test] public async Task Should_receive_using_the_first_consumer() { const string name = "Joe"; await InputQueueSendEndpoint.Send(new SimpleMessageClass(name)); var lastConsumer = await SimpleConsumer.LastConsumer; Assert.That(lastConsumer, Is.Not.Null); var last = await lastConsumer.Last; Assert.That(last.Name, Is.EqualTo(name)); var wasDisposed = await lastConsumer.Dependency.WasDisposed; Assert.Multiple(() => { Assert.That(wasDisposed, Is.True, "Dependency was not disposed"); Assert.That(lastConsumer.Dependency.SomethingDone, Is.True, "Dependency was disposed before consumer executed"); }); } protected override IServiceCollection ConfigureServices(IServiceCollection collection) { collection.RegisterConsumer<SimpleConsumer>(); collection.AddScoped<ISimpleConsumerDependency, SimpleConsumerDependency>(); collection.AddScoped<AnotherMessageConsumer, AnotherMessageConsumerImpl>(); return collection; } protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator) { configurator.ConfigureConsumer<SimpleConsumer>(BusRegistrationContext); } }
Registering_a_consumer_directly_in_the_container
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.System.Display/DisplayRequest.cs
{ "start": 336, "end": 1591 }
public partial class ____ { #if false || false || false || IS_UNIT_TESTS || false || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("IS_UNIT_TESTS", "__SKIA__", "__NETSTD_REFERENCE__")] public DisplayRequest() { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.System.Display.DisplayRequest", "DisplayRequest.DisplayRequest()"); } #endif // Forced skipping of method Windows.System.Display.DisplayRequest.DisplayRequest() #if false || false || false || IS_UNIT_TESTS || false || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("IS_UNIT_TESTS", "__SKIA__", "__NETSTD_REFERENCE__")] public void RequestActive() { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.System.Display.DisplayRequest", "void DisplayRequest.RequestActive()"); } #endif #if false || false || false || IS_UNIT_TESTS || false || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("IS_UNIT_TESTS", "__SKIA__", "__NETSTD_REFERENCE__")] public void RequestRelease() { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.System.Display.DisplayRequest", "void DisplayRequest.RequestRelease()"); } #endif } }
DisplayRequest
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack/Html/MarkdownDeep/Token.cs
{ "start": 1869, "end": 2564 }
internal class ____ { // Constructor public Token(TokenType type, int startOffset, int length) { this.type = type; this.startOffset = startOffset; this.length = length; } // Constructor public Token(TokenType type, object data) { this.type = type; this.data = data; } public override string ToString() { if (true || data == null) { return string.Format("{0} - {1} - {2}", type.ToString(), startOffset, length); } else { return string.Format("{0} - {1} - {2} -> {3}", type.ToString(), startOffset, length, data.ToString()); } } public TokenType type; public int startOffset; public int length; public object data; } }
Token
csharp
dotnet__orleans
src/Orleans.Serialization/Codecs/DateTimeCodec.cs
{ "start": 309, "end": 2088 }
public sealed class ____ : IFieldCodec<DateTime> { void IFieldCodec<DateTime>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, DateTime value) { ReferenceCodec.MarkValueField(writer.Session); writer.WriteFieldHeader(fieldIdDelta, expectedType, typeof(DateTime), WireType.Fixed64); writer.WriteInt64(value.ToBinary()); } /// <summary> /// Writes a field without type info (expected type is statically known). /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, DateTime value) where TBufferWriter : IBufferWriter<byte> { ReferenceCodec.MarkValueField(writer.Session); writer.WriteFieldHeaderExpected(fieldIdDelta, WireType.Fixed64); writer.WriteInt64(value.ToBinary()); } /// <inheritdoc/> DateTime IFieldCodec<DateTime>.ReadValue<TInput>(ref Reader<TInput> reader, Field field) => ReadValue(ref reader, field); /// <summary> /// Reads a <see cref="DateTime"/> value. /// </summary> /// <typeparam name="TInput">The reader input type.</typeparam> /// <param name="reader">The reader.</param> /// <param name="field">The field.</param> /// <returns>The <see cref="DateTime"/> value.</returns> public static DateTime ReadValue<TInput>(ref Reader<TInput> reader, Field field) { ReferenceCodec.MarkValueField(reader.Session); field.EnsureWireType(WireType.Fixed64); return DateTime.FromBinary(reader.ReadInt64()); } } }
DateTimeCodec
csharp
JamesNK__Newtonsoft.Json
Src/Newtonsoft.Json/Utilities/ConvertUtils.cs
{ "start": 30818, "end": 55927 }
private static class ____ { /// <summary> /// Exponents for both powers of 10 and 0.1 /// </summary> private static readonly int[] MultExp64Power10 = new int[] { 4, 7, 10, 14, 17, 20, 24, 27, 30, 34, 37, 40, 44, 47, 50 }; /// <summary> /// Normalized powers of 10 /// </summary> private static readonly ulong[] MultVal64Power10 = new ulong[] { 0xa000000000000000, 0xc800000000000000, 0xfa00000000000000, 0x9c40000000000000, 0xc350000000000000, 0xf424000000000000, 0x9896800000000000, 0xbebc200000000000, 0xee6b280000000000, 0x9502f90000000000, 0xba43b74000000000, 0xe8d4a51000000000, 0x9184e72a00000000, 0xb5e620f480000000, 0xe35fa931a0000000, }; /// <summary> /// Normalized powers of 0.1 /// </summary> private static readonly ulong[] MultVal64Power10Inv = new ulong[] { 0xcccccccccccccccd, 0xa3d70a3d70a3d70b, 0x83126e978d4fdf3c, 0xd1b71758e219652e, 0xa7c5ac471b478425, 0x8637bd05af6c69b7, 0xd6bf94d5e57a42be, 0xabcc77118461ceff, 0x89705f4136b4a599, 0xdbe6fecebdedd5c2, 0xafebff0bcb24ab02, 0x8cbccc096f5088cf, 0xe12e13424bb40e18, 0xb424dc35095cd813, 0x901d7cf73ab0acdc, }; /// <summary> /// Exponents for both powers of 10^16 and 0.1^16 /// </summary> private static readonly int[] MultExp64Power10By16 = new int[] { 54, 107, 160, 213, 266, 319, 373, 426, 479, 532, 585, 638, 691, 745, 798, 851, 904, 957, 1010, 1064, 1117, }; /// <summary> /// Normalized powers of 10^16 /// </summary> private static readonly ulong[] MultVal64Power10By16 = new ulong[] { 0x8e1bc9bf04000000, 0x9dc5ada82b70b59e, 0xaf298d050e4395d6, 0xc2781f49ffcfa6d4, 0xd7e77a8f87daf7fa, 0xefb3ab16c59b14a0, 0x850fadc09923329c, 0x93ba47c980e98cde, 0xa402b9c5a8d3a6e6, 0xb616a12b7fe617a8, 0xca28a291859bbf90, 0xe070f78d39275566, 0xf92e0c3537826140, 0x8a5296ffe33cc92c, 0x9991a6f3d6bf1762, 0xaa7eebfb9df9de8a, 0xbd49d14aa79dbc7e, 0xd226fc195c6a2f88, 0xe950df20247c83f8, 0x81842f29f2cce373, 0x8fcac257558ee4e2, }; /// <summary> /// Normalized powers of 0.1^16 /// </summary> private static readonly ulong[] MultVal64Power10By16Inv = new ulong[] { 0xe69594bec44de160, 0xcfb11ead453994c3, 0xbb127c53b17ec165, 0xa87fea27a539e9b3, 0x97c560ba6b0919b5, 0x88b402f7fd7553ab, 0xf64335bcf065d3a0, 0xddd0467c64bce4c4, 0xc7caba6e7c5382ed, 0xb3f4e093db73a0b7, 0xa21727db38cb0053, 0x91ff83775423cc29, 0x8380dea93da4bc82, 0xece53cec4a314f00, 0xd5605fcdcf32e217, 0xc0314325637a1978, 0xad1c8eab5ee43ba2, 0x9becce62836ac5b0, 0x8c71dcd9ba0b495c, 0xfd00b89747823938, 0xe3e27a444d8d991a, }; /// <summary> /// Packs <paramref name="val"/>*10^<paramref name="scale"/> as 64-bit floating point value according to IEEE 754 standard /// </summary> /// <param name="negative">Sign</param> /// <param name="val">Mantissa</param> /// <param name="scale">Exponent</param> /// <remarks> /// Adoption of native function NumberToDouble() from coreclr sources, /// see https://github.com/dotnet/coreclr/blob/master/src/classlibnative/bcltype/number.cpp#L451 /// </remarks> public static double PackDouble(bool negative, ulong val, int scale) { // handle zero value if (val == 0) { return negative ? -0.0 : 0.0; } // normalize the mantissa int exp = 64; if ((val & 0xFFFFFFFF00000000) == 0) { val <<= 32; exp -= 32; } if ((val & 0xFFFF000000000000) == 0) { val <<= 16; exp -= 16; } if ((val & 0xFF00000000000000) == 0) { val <<= 8; exp -= 8; } if ((val & 0xF000000000000000) == 0) { val <<= 4; exp -= 4; } if ((val & 0xC000000000000000) == 0) { val <<= 2; exp -= 2; } if ((val & 0x8000000000000000) == 0) { val <<= 1; exp -= 1; } if (scale < 0) { scale = -scale; // check scale bounds if (scale >= 22 * 16) { // underflow return negative ? -0.0 : 0.0; } // perform scaling int index = scale & 15; if (index != 0) { exp -= MultExp64Power10[index - 1] - 1; val = Mul64Lossy(val, MultVal64Power10Inv[index - 1], ref exp); } index = scale >> 4; if (index != 0) { exp -= MultExp64Power10By16[index - 1] - 1; val = Mul64Lossy(val, MultVal64Power10By16Inv[index - 1], ref exp); } } else { // check scale bounds if (scale >= 22 * 16) { // overflow return negative ? double.NegativeInfinity : double.PositiveInfinity; } // perform scaling int index = scale & 15; if (index != 0) { exp += MultExp64Power10[index - 1]; val = Mul64Lossy(val, MultVal64Power10[index - 1], ref exp); } index = scale >> 4; if (index != 0) { exp += MultExp64Power10By16[index - 1]; val = Mul64Lossy(val, MultVal64Power10By16[index - 1], ref exp); } } // round & scale down if ((val & (1 << 10)) != 0) { // IEEE round to even ulong tmp = val + ((1UL << 10) - 1 + ((val >> 11) & 1)); if (tmp < val) { // overflow tmp = (tmp >> 1) | 0x8000000000000000; exp++; } val = tmp; } // return the exponent to a biased state exp += 0x3FE; // handle overflow, underflow, "Epsilon - 1/2 Epsilon", denormalized, and the normal case if (exp <= 0) { if (exp == -52 && (val >= 0x8000000000000058)) { // round X where {Epsilon > X >= 2.470328229206232730000000E-324} up to Epsilon (instead of down to zero) val = 0x0000000000000001; } else if (exp <= -52) { // underflow val = 0; } else { // denormalized value val >>= (-exp + 12); } } else if (exp >= 0x7FF) { // overflow val = 0x7FF0000000000000; } else { // normal positive exponent case val = ((ulong)exp << 52) | ((val >> 11) & 0x000FFFFFFFFFFFFF); } // apply sign if (negative) { val |= 0x8000000000000000; } return BitConverter.Int64BitsToDouble((long)val); } private static ulong Mul64Lossy(ulong a, ulong b, ref int exp) { ulong a_hi = (a >> 32); uint a_lo = (uint)a; ulong b_hi = (b >> 32); uint b_lo = (uint)b; ulong result = a_hi * b_hi; // save some multiplications if lo-parts aren't big enough to produce carry // (hi-parts will be always big enough, since a and b are normalized) if ((b_lo & 0xFFFF0000) != 0) { result += (a_hi * b_lo) >> 32; } if ((a_lo & 0xFFFF0000) != 0) { result += (a_lo * b_hi) >> 32; } // normalize if ((result & 0x8000000000000000) == 0) { result <<= 1; exp--; } return result; } } public static ParseResult DoubleTryParse(char[] chars, int start, int length, out double value) { value = 0; if (length == 0) { return ParseResult.Invalid; } bool isNegative = (chars[start] == '-'); if (isNegative) { // text just a negative sign if (length == 1) { return ParseResult.Invalid; } start++; length--; } int i = start; int end = start + length; int numDecimalStart = end; int numDecimalEnd = end; int exponent = 0; ulong mantissa = 0UL; int mantissaDigits = 0; int exponentFromMantissa = 0; for (; i < end; i++) { char c = chars[i]; switch (c) { case '.': if (i == start) { return ParseResult.Invalid; } if (i + 1 == end) { return ParseResult.Invalid; } if (numDecimalStart != end) { // multiple decimal points return ParseResult.Invalid; } numDecimalStart = i + 1; break; case 'e': case 'E': if (i == start) { return ParseResult.Invalid; } if (i == numDecimalStart) { // E follows decimal point return ParseResult.Invalid; } i++; if (i == end) { return ParseResult.Invalid; } if (numDecimalStart < end) { numDecimalEnd = i - 1; } c = chars[i]; bool exponentNegative = false; switch (c) { case '-': exponentNegative = true; i++; break; case '+': i++; break; } // parse 3 digit for (; i < end; i++) { c = chars[i]; if (c < '0' || c > '9') { return ParseResult.Invalid; } int newExponent = (10 * exponent) + (c - '0'); // stops updating exponent when overflowing if (exponent < newExponent) { exponent = newExponent; } } if (exponentNegative) { exponent = -exponent; } break; default: if (c < '0' || c > '9') { return ParseResult.Invalid; } if (i == start && c == '0') { i++; if (i != end) { c = chars[i]; if (c == '.') { goto case '.'; } if (c == 'e' || c == 'E') { goto case 'E'; } return ParseResult.Invalid; } } if (mantissaDigits < 19) { mantissa = (10 * mantissa) + (ulong)(c - '0'); if (mantissa > 0) { ++mantissaDigits; } } else { ++exponentFromMantissa; } break; } } exponent += exponentFromMantissa; // correct the decimal point exponent -= (numDecimalEnd - numDecimalStart); value = IEEE754.PackDouble(isNegative, mantissa, exponent); return double.IsInfinity(value) ? ParseResult.Overflow : ParseResult.Success; } #endif public static ParseResult DecimalTryParse(char[] chars, int start, int length, out decimal value) { value = 0M; const decimal decimalMaxValueHi28 = 7922816251426433759354395033M; const ulong decimalMaxValueHi19 = 7922816251426433759UL; const ulong decimalMaxValueLo9 = 354395033UL; const char decimalMaxValueLo1 = '5'; if (length == 0) { return ParseResult.Invalid; } bool isNegative = (chars[start] == '-'); if (isNegative) { // text just a negative sign if (length == 1) { return ParseResult.Invalid; } start++; length--; } int i = start; int end = start + length; int numDecimalStart = end; int numDecimalEnd = end; int exponent = 0; ulong hi19 = 0UL; ulong lo10 = 0UL; int mantissaDigits = 0; int exponentFromMantissa = 0; char? digit29 = null; bool? storeOnly28Digits = null; for (; i < end; i++) { char c = chars[i]; switch (c) { case '.': if (i == start) { return ParseResult.Invalid; } if (i + 1 == end) { return ParseResult.Invalid; } if (numDecimalStart != end) { // multiple decimal points return ParseResult.Invalid; } numDecimalStart = i + 1; break; case 'e': case 'E': if (i == start) { return ParseResult.Invalid; } if (i == numDecimalStart) { // E follows decimal point return ParseResult.Invalid; } i++; if (i == end) { return ParseResult.Invalid; } if (numDecimalStart < end) { numDecimalEnd = i - 1; } c = chars[i]; bool exponentNegative = false; switch (c) { case '-': exponentNegative = true; i++; break; case '+': i++; break; } // parse 3 digit for (; i < end; i++) { c = chars[i]; if (c < '0' || c > '9') { return ParseResult.Invalid; } int newExponent = (10 * exponent) + (c - '0'); // stops updating exponent when overflowing if (exponent < newExponent) { exponent = newExponent; } } if (exponentNegative) { exponent = -exponent; } break; default: if (c < '0' || c > '9') { return ParseResult.Invalid; } if (i == start && c == '0') { i++; if (i != end) { c = chars[i]; if (c == '.') { goto case '.'; } if (c == 'e' || c == 'E') { goto case 'E'; } return ParseResult.Invalid; } } if (mantissaDigits < 29 && (mantissaDigits != 28 || !(storeOnly28Digits ?? (storeOnly28Digits = (hi19 > decimalMaxValueHi19 || (hi19 == decimalMaxValueHi19 && (lo10 > decimalMaxValueLo9 || (lo10 == decimalMaxValueLo9 && c > decimalMaxValueLo1))))).GetValueOrDefault()))) { if (mantissaDigits < 19) { hi19 = (hi19 * 10UL) + (ulong)(c - '0'); } else { lo10 = (lo10 * 10UL) + (ulong)(c - '0'); } ++mantissaDigits; } else { if (!digit29.HasValue) { digit29 = c; } ++exponentFromMantissa; } break; } } exponent += exponentFromMantissa; // correct the decimal point exponent -= (numDecimalEnd - numDecimalStart); if (mantissaDigits <= 19) { value = hi19; } else { value = (hi19 / new decimal(1, 0, 0, false, (byte)(mantissaDigits - 19))) + lo10; } if (exponent > 0) { mantissaDigits += exponent; if (mantissaDigits > 29) { return ParseResult.Overflow; } if (mantissaDigits == 29) { if (exponent > 1) { value /= new decimal(1, 0, 0, false, (byte)(exponent - 1)); if (value > decimalMaxValueHi28) { return ParseResult.Overflow; } } else if (value == decimalMaxValueHi28 && digit29 > decimalMaxValueLo1) { return ParseResult.Overflow; } value *= 10M; } else { value /= new decimal(1, 0, 0, false, (byte)exponent); } } else { if (digit29 >= '5' && exponent >= -28) { ++value; } if (exponent < 0) { if (mantissaDigits + exponent + 28 <= 0) { value = isNegative ? -0M : 0M; return ParseResult.Success; } if (exponent >= -28) { value *= new decimal(1, 0, 0, false, (byte)(-exponent)); } else { value /= 1e28M; value *= new decimal(1, 0, 0, false, (byte)(-exponent - 28)); } } } if (isNegative) { value = -value; } return ParseResult.Success; } public static bool TryConvertGuid(string s, out Guid g) { // GUID has to have format 00000000-0000-0000-0000-000000000000 #if !HAVE_GUID_TRY_PARSE if (s == null) { throw new ArgumentNullException("s"); } Regex format = new Regex("^[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}$"); Match match = format.Match(s); if (match.Success) { g = new Guid(s); return true; } g = Guid.Empty; return false; #else return Guid.TryParseExact(s, "D", out g); #endif } public static bool TryHexTextToInt(char[] text, int start, int end, out int value) { value = 0; for (int i = start; i < end; i++) { char ch = text[i]; int chValue; if (ch <= 57 && ch >= 48) { chValue = ch - 48; } else if (ch <= 70 && ch >= 65) { chValue = ch - 55; } else if (ch <= 102 && ch >= 97) { chValue = ch - 87; } else { value = 0; return false; } value += chValue << ((end - 1 - i) * 4); } return true; } } }
IEEE754
csharp
unoplatform__uno
src/Uno.UI.Runtime.Skia.Win32/Graphics/Win32NativeOpenGLWrapper.cs
{ "start": 417, "end": 4658 }
internal class ____ : INativeOpenGLWrapper { private static readonly Type _type = typeof(Win32NativeOpenGLWrapper); private static readonly Lazy<IntPtr> _opengl32 = new Lazy<IntPtr>(() => { if (!NativeLibrary.TryLoad("opengl32.dll", _type.Assembly, DllImportSearchPath.UserDirectories, out var _handle)) { if (_type.Log().IsEnabled(LogLevel.Error)) { _type.Log().Error("opengl32.dll was not loaded successfully."); } } return _handle; }); private readonly HDC _hdc; private readonly HGLRC _glContext; private readonly HWND _hwnd; public Win32NativeOpenGLWrapper(XamlRoot xamlRoot) { if (XamlRootMap.GetHostForRoot(xamlRoot) is not Win32WindowWrapper wrapper) { throw new InvalidOperationException($"The XamlRoot and the XamlRootMap must be initialized before constructing a {_type.Name}."); } _hwnd = (HWND)(wrapper.NativeWindow as Win32NativeWindow)!.Hwnd; _hdc = PInvoke.GetDC(_hwnd); if (_hdc == IntPtr.Zero) { throw new InvalidOperationException($"{nameof(PInvoke.GetDC)} failed: {Win32Helper.GetErrorMessage()}"); } PIXELFORMATDESCRIPTOR pfd = new(); pfd.nSize = (ushort)Marshal.SizeOf(pfd); pfd.nVersion = 1; pfd.dwFlags = PFD_FLAGS.PFD_DRAW_TO_WINDOW | PFD_FLAGS.PFD_SUPPORT_OPENGL | PFD_FLAGS.PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_PIXEL_TYPE.PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cRedBits = 8; pfd.cGreenBits = 8; pfd.cBlueBits = 8; pfd.cAlphaBits = 8; pfd.cDepthBits = 16; pfd.cStencilBits = 1; // anything > 0 is fine, we will most likely get 8 pfd.iLayerType = PFD_LAYER_TYPE.PFD_MAIN_PLANE; var pixelFormat = PInvoke.ChoosePixelFormat(_hdc, in pfd); if (pixelFormat == 0) { var choosePixelFormatError = Win32Helper.GetErrorMessage(); var success = PInvoke.ReleaseDC(_hwnd, _hdc) == 0; if (!success) { this.LogError()?.Error($"{nameof(PInvoke.ReleaseDC)} failed: {Win32Helper.GetErrorMessage()}"); } throw new InvalidOperationException($"{nameof(PInvoke.ChoosePixelFormat)} failed: {choosePixelFormatError}. Falling back to software rendering."); } // To inspect the chosen pixel format: // PIXELFORMATDESCRIPTOR temp_pfd = default; // unsafe // { // PInvoke.DescribePixelFormat(_hdc, pixelFormat, (uint)Marshal.SizeOf<PIXELFORMATDESCRIPTOR>(), &temp_pfd); // } if (PInvoke.SetPixelFormat(_hdc, pixelFormat, in pfd) == 0) { var setPixelFormatError = Win32Helper.GetErrorMessage(); var success = PInvoke.ReleaseDC(_hwnd, _hdc) == 0; if (!success) { this.LogError()?.Error($"{nameof(PInvoke.ReleaseDC)} failed: {Win32Helper.GetErrorMessage()}"); } throw new InvalidOperationException($"{nameof(PInvoke.SetPixelFormat)} failed: {setPixelFormatError}. Falling back to software rendering."); } _glContext = PInvoke.wglCreateContext(_hdc); if (_glContext == IntPtr.Zero) { var createContextError = Win32Helper.GetErrorMessage(); var success = PInvoke.ReleaseDC(_hwnd, _hdc) == 0; if (!success) { this.LogError()?.Error($"{nameof(PInvoke.ReleaseDC)} failed: {Win32Helper.GetErrorMessage()}"); } throw new InvalidOperationException($"{nameof(PInvoke.wglCreateContext)} failed: {createContextError}. Falling back to software rendering."); } } // https://sharovarskyi.com/blog/posts/csharp-win32-opengl-silknet/ public bool TryGetProcAddress(string proc, out nint addr) { if (_opengl32.Value != IntPtr.Zero && NativeLibrary.TryGetExport(_opengl32.Value, proc, out addr)) { return true; } addr = PInvoke.wglGetProcAddress(proc); return addr != IntPtr.Zero; } public nint GetProcAddress(string proc) { if (TryGetProcAddress(proc, out var address)) { return address; } throw new InvalidOperationException("No function was found with the name " + proc + "."); } public void Dispose() { var success = PInvoke.wglDeleteContext(_glContext) == 0; if (!success) { this.LogError()?.Error($"{nameof(PInvoke.wglDeleteContext)} failed."); } var success2 = PInvoke.ReleaseDC(_hwnd, _hdc) == 0; if (!success2) { this.LogError()?.Error($"{nameof(PInvoke.ReleaseDC)} failed: {Win32Helper.GetErrorMessage()}"); } } public IDisposable MakeCurrent() { return new Win32Helper.WglCurrentContextDisposable(_hdc, _glContext); } }
Win32NativeOpenGLWrapper
csharp
pythonnet__pythonnet
src/runtime/Native/StolenReference.cs
{ "start": 1939, "end": 2645 }
static class ____ { [Pure] [DebuggerHidden] public static IntPtr DangerousGetAddressOrNull(this in StolenReference reference) => reference.Pointer; [Pure] [DebuggerHidden] public static IntPtr DangerousGetAddress(this in StolenReference reference) => reference.Pointer == IntPtr.Zero ? throw new NullReferenceException() : reference.Pointer; [DebuggerHidden] public static StolenReference AnalyzerWorkaround(this in StolenReference reference) { IntPtr ptr = reference.DangerousGetAddressOrNull(); return StolenReference.TakeNullable(ref ptr); } } }
StolenReferenceExtensions
csharp
dotnet__reactive
Rx.NET/Source/src/System.Reactive/Linq/Observable/TakeLastBuffer.cs
{ "start": 2671, "end": 4412 }
internal sealed class ____ : Sink<TSource, IList<TSource>> { private readonly TimeSpan _duration; private readonly Queue<Reactive.TimeInterval<TSource>> _queue; public _(TimeSpan duration, IObserver<IList<TSource>> observer) : base(observer) { _duration = duration; _queue = new Queue<Reactive.TimeInterval<TSource>>(); } private IStopwatch? _watch; public void Run(IObservable<TSource> source, IScheduler scheduler) { _watch = scheduler.StartStopwatch(); Run(source); } public override void OnNext(TSource value) { var now = _watch!.Elapsed; _queue.Enqueue(new Reactive.TimeInterval<TSource>(value, now)); Trim(now); } public override void OnCompleted() { var now = _watch!.Elapsed; Trim(now); var res = new List<TSource>(_queue.Count); while (_queue.Count > 0) { res.Add(_queue.Dequeue().Value); } ForwardOnNext(res); ForwardOnCompleted(); } private void Trim(TimeSpan now) { while (_queue.Count > 0 && now - _queue.Peek().Interval >= _duration) { _queue.Dequeue(); } } } } } }
_
csharp
SixLabors__ImageSharp
tests/ImageSharp.Tests/Processing/Processors/Convolution/ConvolutionProcessorHelpersTest.cs
{ "start": 243, "end": 2006 }
public class ____ { [Theory] [InlineData(3)] [InlineData(5)] [InlineData(9)] [InlineData(22)] [InlineData(33)] [InlineData(80)] public void VerifyGaussianKernelDecomposition(int radius) { int kernelSize = (radius * 2) + 1; float sigma = radius / 3F; float[] kernel = ConvolutionProcessorHelpers.CreateGaussianBlurKernel(kernelSize, sigma); DenseMatrix<float> matrix = DotProduct(kernel, kernel); bool result = matrix.TryGetLinearlySeparableComponents(out float[] row, out float[] column); Assert.True(result); Assert.NotNull(row); Assert.NotNull(column); Assert.Equal(row.Length, matrix.Rows); Assert.Equal(column.Length, matrix.Columns); float[,] dotProduct = DotProduct(row, column); for (int y = 0; y < column.Length; y++) { for (int x = 0; x < row.Length; x++) { Assert.True(Math.Abs(matrix[y, x] - dotProduct[y, x]) < 0.0001F); } } } [Fact] public void VerifyNonSeparableMatrix() { bool result = LaplacianKernels.LaplacianOfGaussianXY.TryGetLinearlySeparableComponents( out float[] row, out float[] column); Assert.False(result); Assert.Null(row); Assert.Null(column); } private static DenseMatrix<float> DotProduct(float[] row, float[] column) { float[,] matrix = new float[column.Length, row.Length]; for (int x = 0; x < row.Length; x++) { for (int y = 0; y < column.Length; y++) { matrix[y, x] = row[x] * column[y]; } } return matrix; } }
ConvolutionProcessorHelpersTest
csharp
xunit__xunit
src/xunit.v3.core/CollectionBehaviorAttribute.cs
{ "start": 236, "end": 2130 }
public sealed class ____ : Attribute, ICollectionBehaviorAttribute { /// <summary> /// Initializes a new instance of the <see cref="CollectionBehaviorAttribute" /> class. /// Uses the default collection behavior (<see cref="CollectionBehavior.CollectionPerClass"/>). /// </summary> public CollectionBehaviorAttribute() { } #pragma warning disable CA1019 // We don't want a property accessor for CollectionBehavior because it's just a type selector /// <summary> /// Initializes a new instance of the <see cref="CollectionBehaviorAttribute" /> class /// with the given built-in collection behavior. /// </summary> /// <param name="collectionBehavior">The collection behavior for the assembly.</param> public CollectionBehaviorAttribute(CollectionBehavior collectionBehavior) => // This is an attribute constructor; throwing here would be wrong, so we just always fall back to the default CollectionFactoryType = collectionBehavior switch { CollectionBehavior.CollectionPerClass => typeof(CollectionPerClassTestCollectionFactory), CollectionBehavior.CollectionPerAssembly => typeof(CollectionPerAssemblyTestCollectionFactory), _ => null, }; #pragma warning restore CA1019 /// <summary> /// Initializes a new instance of the <see cref="CollectionBehaviorAttribute" /> class /// with the given custom collection behavior. /// </summary> /// <param name="collectionFactoryType">The factory type</param> public CollectionBehaviorAttribute(Type collectionFactoryType) => CollectionFactoryType = collectionFactoryType; /// <inheritdoc/> public Type? CollectionFactoryType { get; } /// <inheritdoc/> public bool DisableTestParallelization { get; set; } /// <inheritdoc/> public int MaxParallelThreads { get; set; } /// <inheritdoc/> public ParallelAlgorithm ParallelAlgorithm { get; set; } = ParallelAlgorithm.Conservative; }
CollectionBehaviorAttribute
csharp
unoplatform__uno
src/Uno.UI/Controls/NativeFramePresente.Properties.UIKit.cs
{ "start": 278, "end": 1182 }
public partial class ____ : FrameworkElement { #region IsNavigationBarHidden DependencyProperty /// <summary> /// Provides a Xaml access to the <see cref="UINavigationController.NavigationBarHidden"/> property. /// </summary> public int IsNavigationBarHidden { get => (int)GetValue(IsNavigationBarHiddenProperty); set => SetValue(IsNavigationBarHiddenProperty, value); } public static DependencyProperty IsNavigationBarHiddenProperty { get; } = DependencyProperty.Register( "IsNavigationBarHidden", typeof(int), typeof(NativeFramePresenter), new FrameworkPropertyMetadata( false, (s, e) => ((NativeFramePresenter)s)?.OnIsNavigationBarHiddenChanged(e) ) ); private void OnIsNavigationBarHiddenChanged(DependencyPropertyChangedEventArgs e) => NavigationController.NavigationBarHidden = (bool)e.NewValue; #endregion } }
NativeFramePresenter
csharp
simplcommerce__SimplCommerce
src/Modules/SimplCommerce.Module.PaymentMomo/Areas/PaymentMomo/Components/MomoLandingViewComponent.cs
{ "start": 439, "end": 1378 }
public class ____ : ViewComponent { private readonly IRepositoryWithTypedId<PaymentProvider, string> _paymentProviderRepository; public MomoLandingViewComponent(IRepositoryWithTypedId<PaymentProvider, string> paymentProviderRepository) { _paymentProviderRepository = paymentProviderRepository; } public async Task<IViewComponentResult> InvokeAsync(Guid checkoutId) { var momoProvider = await _paymentProviderRepository.Query().FirstOrDefaultAsync(x => x.Id == PaymentProviderHelper.MomoPaymentProviderId); var momoSetting = JsonConvert.DeserializeObject<MomoPaymentConfigForm>(momoProvider.AdditionalSettings); var model = new MomoCheckoutForm(); model.PaymentFee = momoSetting.PaymentFee; model.CheckoutId = checkoutId; return View(this.GetViewPath(), model); } } }
MomoLandingViewComponent
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.ContentManagement.Display/ContentDisplay/IContentPartDisplayDriverResolver.cs
{ "start": 65, "end": 304 }
public interface ____ { IList<IContentPartDisplayDriver> GetDisplayModeDrivers(string partName, string displayMode); IList<IContentPartDisplayDriver> GetEditorDrivers(string partName, string editor); }
IContentPartDisplayDriverResolver
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Media.Streaming.Adaptive/AdaptiveMediaSourceDiagnosticType.cs
{ "start": 270, "end": 1602 }
public enum ____ { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ ManifestUnchangedUponReload = 0, #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ ManifestMismatchUponReload = 1, #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ ManifestSignaledEndOfLiveEventUponReload = 2, #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ MediaSegmentSkipped = 3, #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ ResourceNotFound = 4, #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ ResourceTimedOut = 5, #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ ResourceParsingError = 6, #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ BitrateDisabled = 7, #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ FatalMediaSourceError = 8, #endif } #endif }
AdaptiveMediaSourceDiagnosticType
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/test/Types.Analyzers.Integration.Tests/Product.cs
{ "start": 140, "end": 248 }
public class ____ { public required string Id { get; set; } } [InterfaceType<Product>] public static
Product
csharp
ChilliCream__graphql-platform
src/StrawberryShake/CodeGeneration/test/CodeGeneration.CSharp.Tests/SchemaGeneratorTests.cs
{ "start": 3411, "end": 10185 }
interface ____ { id: ID! } type NewsItem implements Node { id: ID! feedId: UUID! feedUrl: String! html: String! image: String! keywords: [String!]! language: String! summary: String! text: String! title: String! updated: DateTime url: String! } type NewsItemCollectionSegment { items: [NewsItem] "Information to aid in pagination." pageInfo: CollectionSegmentInfo! } "Information about the offset pagination." type CollectionSegmentInfo { "Indicates whether more items exist following the set defined by the clients arguments." hasNextPage: Boolean! "Indicates whether more items exist prior the set defined by the clients arguments." hasPreviousPage: Boolean! } """, "extend schema @key(fields: \"id\")"); } [Fact] public void Create_PeopleSearch_From_ActiveDirectory_Schema() { AssertResult( @"query PeopleSearch($term:String! $skip:Int $take:Int $inactive:Boolean) { people: peopleSearch( term: $term includeInactive: $inactive skip: $skip take: $take ) { totalCount pageInfo { hasNextPage hasPreviousPage } items { ...PeopleSearchResult } } } fragment PeopleSearchResult on Person { id key displayName isActive department { id name } image title manager { id key displayName } }", "extend schema @key(fields: \"id\")", FileResource.Open("ActiveDirectory.Schema.graphql")); } [Fact] public void Create_GetFeatsPage() { AssertResult( @"query GetFeatsPage($skip: Int, $take: Int) { feats(skip: $skip, take: $take) { items { name, level, canBeLearnedMoreThanOnce, actionType { name } } } }", "extend schema @key(fields: \"id\")", FileResource.Open("Schema_Bug_1.graphql")); } [Fact] public void Create_GetFeatById() { AssertResult( @"query GetFeatById($id: UUID!) { feats(where: {id: {eq: $id}}) { items { id, name, level, details { text } } } }", "extend schema @key(fields: \"id\")", FileResource.Open("Schema_Bug_1.graphql")); } [Fact] public void Create_DataType_Query() { AssertResult( @"query GetAllFoos { test { profile { name } } }", "extend schema @key(fields: \"id\")", @"schema { query: Query } type Query { test: [Foo!]! } type Foo { profile: Profile! } type Profile { # id: ID! # Can no longer generate if no id is present name: String }"); } [Fact] public void Create_UpdateMembers_Mutation() { AssertResult( @"mutation UpdateMembers($input: UpdateProjectMembersInput!) { project { updateMembers(input: $input) { correlationId } } }", "extend schema @key(fields: \"id\")", FileResource.Open("Schema_Bug_2.graphql")); } [Fact] public void QueryInterference() { AssertResult( """ query GetFeatsPage( $skip: Int! $take: Int! $searchTerm: String! = "" $order: [FeatSortInput!] = [{ name: ASC }] ) { feats( skip: $skip take: $take order: $order where: { or: [ { name: { contains: $searchTerm } } { traits: { some: { name: { contains: $searchTerm } } } } ] } ) { totalCount items { ...FeatsPage } } } fragment FeatsPage on Feat { id name level canBeLearnedMoreThanOnce details { text } } """, @"query GetFeatById($id: UUID!) { feats(where: { id: { eq: $id } }) { items { ...FeatById } } } fragment FeatById on Feat { id name level special trigger details { text } actionType { name } }", "extend schema @key(fields: \"id\")", FileResource.Open("Schema_Bug_1.graphql")); } [Fact] public void NodeTypenameCollision() { AssertResult( @" type Query { node(id: ID!): Node workspaces: [Workspace!]! }
Node
csharp
ChilliCream__graphql-platform
src/StrawberryShake/CodeGeneration/test/CodeGeneration.CSharp.Tests/Integration/EntityIdOrDataTest.Client.cs
{ "start": 17680, "end": 18578 }
private sealed class ____ : System.IServiceProvider, System.IDisposable { private readonly System.IServiceProvider _provider; public ClientServiceProvider(System.IServiceProvider provider) { _provider = provider; } public object? GetService(System.Type serviceType) { return _provider.GetService(serviceType); } public void Dispose() { if (_provider is System.IDisposable d) { d.Dispose(); } } } } } namespace StrawberryShake.CodeGeneration.CSharp.Integration.EntityIdOrData { // StrawberryShake.CodeGeneration.CSharp.Generators.ResultTypeGenerator [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")]
ClientServiceProvider
csharp
dotnet__aspire
tests/Aspire.Hosting.RabbitMQ.Tests/RabbitMQPublicApiTests.cs
{ "start": 248, "end": 4671 }
public class ____(ITestOutputHelper testOutputHelper) { [Fact] public void AddRabbitMQShouldThrowWhenBuilderIsNull() { IDistributedApplicationBuilder builder = null!; const string name = "rabbitMQ"; var action = () => builder.AddRabbitMQ(name); var exception = Assert.Throws<ArgumentNullException>(action); Assert.Equal(nameof(builder), exception.ParamName); } [Theory] [InlineData(true)] [InlineData(false)] public void AddRabbitMQShouldThrowWhenNameIsNullOrEmpty(bool isNull) { var builder = TestDistributedApplicationBuilder.CreateWithTestContainerRegistry(testOutputHelper); var name = isNull ? null! : string.Empty; var action = () => builder.AddRabbitMQ(name); var exception = isNull ? Assert.Throws<ArgumentNullException>(action) : Assert.Throws<ArgumentException>(action); Assert.Equal(nameof(name), exception.ParamName); } [Fact] public void WithDataVolumeShouldThrowWhenBuilderIsNull() { IResourceBuilder<RabbitMQServerResource> builder = null!; var action = () => builder.WithDataVolume(); var exception = Assert.Throws<ArgumentNullException>(action); Assert.Equal(nameof(builder), exception.ParamName); } [Fact] public void WithDataBindMountShouldThrowWhenBuilderIsNull() { IResourceBuilder<RabbitMQServerResource> builder = null!; const string source = "/var/lib/rabbitmq"; var action = () => builder.WithDataBindMount(source); var exception = Assert.Throws<ArgumentNullException>(action); Assert.Equal(nameof(builder), exception.ParamName); } [Theory] [InlineData(true)] [InlineData(false)] public void WithDataBindMountShouldThrowWhenSourceIsNullOrEmpty(bool isNull) { var builder = TestDistributedApplicationBuilder.CreateWithTestContainerRegistry(testOutputHelper); var rabbitMQ = builder.AddRabbitMQ("rabbitMQ"); var source = isNull ? null! : string.Empty; var action = () => rabbitMQ.WithDataBindMount(source); var exception = isNull ? Assert.Throws<ArgumentNullException>(action) : Assert.Throws<ArgumentException>(action); Assert.Equal(nameof(source), exception.ParamName); } [Fact] public void WithManagementPluginShouldThrowWhenBuilderIsNull() { IResourceBuilder<RabbitMQServerResource> builder = null!; var action = () => builder.WithManagementPlugin(); var exception = Assert.Throws<ArgumentNullException>(action); Assert.Equal(nameof(builder), exception.ParamName); } [Fact] public void WithManagementPluginWithPortShouldThrowWhenBuilderIsNull() { IResourceBuilder<RabbitMQServerResource> builder = null!; const int port = 15672; var action = () => builder.WithManagementPlugin(port); var exception = Assert.Throws<ArgumentNullException>(action); Assert.Equal(nameof(builder), exception.ParamName); } [Theory] [InlineData(true)] [InlineData(false)] public void CtorRabbitMQServerResourceShouldThrowWhenNameIsNullOrEmpty(bool isNull) { var builder = TestDistributedApplicationBuilder.CreateWithTestContainerRegistry(testOutputHelper); var name = isNull ? null! : string.Empty; const string passwordValue = nameof(passwordValue); ParameterResource? userName = null; var password = ParameterResourceBuilderExtensions.CreateDefaultPasswordParameter(builder, passwordValue); var action = () => new RabbitMQServerResource(name: name, userName: userName, password: password); var exception = isNull ? Assert.Throws<ArgumentNullException>(action) : Assert.Throws<ArgumentException>(action); Assert.Equal(nameof(name), exception.ParamName); } [Fact] public void CtorRabbitMQServerResourceShouldThrowWhenPasswordIsNull() { string name = "rabbitMQ"; ParameterResource? userName = null; ParameterResource password = null!; var action = () => new RabbitMQServerResource(name: name, userName: userName, password: password); var exception = Assert.Throws<ArgumentNullException>(action); Assert.Equal(nameof(password), exception.ParamName); } }
RabbitMQPublicApiTests
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/ITestBusConfiguration.cs
{ "start": 279, "end": 560 }
public class ____ : ITestBusConfiguration { public void ConfigureBus<T>(IBusRegistrationContext context, IBusFactoryConfigurator<T> configurator) where T : IReceiveEndpointConfigurator { } }
Json
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.Seo/Startup.cs
{ "start": 697, "end": 1919 }
public sealed class ____ : StartupBase { public override void ConfigureServices(IServiceCollection services) { services.AddDataMigration<Migrations>(); services.AddContentPart<SeoMetaPart>() .UseDisplayDriver<SeoMetaPartDisplayDriver>() .AddHandler<SeoMetaPartHandler>(); services.AddScoped<IContentDisplayDriver, SeoContentDriver>(); services.AddScoped<IContentTypePartDefinitionDisplayDriver, SeoMetaPartSettingsDisplayDriver>(); // This must be last, and the module dependent on Contents so this runs after the part handlers. services.AddScoped<IContentHandler, SeoMetaSettingsHandler>(); services.AddScoped<IDocumentIndexHandler, SeoMetaPartContentIndexHandler>(); services.AddPermissionProvider<SeoPermissionProvider>(); services.AddSiteDisplayDriver<RobotsSettingsDisplayDriver>(); services.AddNavigationProvider<AdminMenu>(); services.AddTransient<IRobotsProvider, SiteSettingsRobotsProvider>(); } public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { app.UseMiddleware<RobotsMiddleware>(); } }
Startup
csharp
jellyfin__jellyfin
MediaBrowser.XbmcMetadata/Parsers/SeriesNfoSeasonParser.cs
{ "start": 386, "end": 2485 }
public class ____ : BaseNfoParser<Season> { /// <summary> /// Initializes a new instance of the <see cref="SeriesNfoSeasonParser"/> class. /// </summary> /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param> /// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param> /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param> /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param> /// <param name="userDataManager">Instance of the <see cref="IUserDataManager"/> interface.</param> /// <param name="directoryService">Instance of the <see cref="IDirectoryService"/> interface.</param> public SeriesNfoSeasonParser( ILogger logger, IConfigurationManager config, IProviderManager providerManager, IUserManager userManager, IUserDataManager userDataManager, IDirectoryService directoryService) : base(logger, config, providerManager, userManager, userDataManager, directoryService) { } /// <inheritdoc /> protected override bool SupportsUrlAfterClosingXmlTag => true; /// <inheritdoc /> protected override void FetchDataFromXmlNode(XmlReader reader, MetadataResult<Season> itemResult) { var item = itemResult.Item; if (reader.Name == "namedseason") { var parsed = int.TryParse(reader.GetAttribute("number"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var seasonNumber); var name = reader.ReadElementContentAsString(); if (parsed && !string.IsNullOrWhiteSpace(name) && item.IndexNumber.HasValue && seasonNumber == item.IndexNumber.Value) { item.Name = name; } } else { reader.Skip(); } } } }
SeriesNfoSeasonParser
csharp
dotnet__extensions
test/Libraries/Microsoft.Extensions.Diagnostics.Probes.Tests/MockHealthCheckService.cs
{ "start": 352, "end": 1261 }
internal class ____ : HealthCheckService { private readonly Task<HealthReport> _healthyReport = CreateHealthReport(HealthStatus.Healthy); private readonly Task<HealthReport> _unhealthyReport = CreateHealthReport(HealthStatus.Unhealthy); public bool IsHealthy = true; public override Task<HealthReport> CheckHealthAsync(Func<HealthCheckRegistration, bool>? predicate, CancellationToken cancellationToken = default) { return IsHealthy ? _healthyReport : _unhealthyReport; } private static Task<HealthReport> CreateHealthReport(HealthStatus healthStatus) { HealthReportEntry entry = new HealthReportEntry(healthStatus, null, TimeSpan.Zero, null, null); var healthStatusRecords = new Dictionary<string, HealthReportEntry> { { "id", entry } }; return Task.FromResult(new HealthReport(healthStatusRecords, TimeSpan.Zero)); } }
MockHealthCheckService
csharp
GtkSharp__GtkSharp
Source/Libs/GLibSharp/MainLoop.cs
{ "start": 33, "end": 905 }
class ____ // // Author: Jeroen Zwartepoorte <jeroen@xs4all.nl> // // Copyright (c) 2004 Jeroen Zwartepoorte // // This program is free software; you can redistribute it and/or // modify it under the terms of version 2 of the Lesser GNU General // Public License as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. using System; using System.Runtime.InteropServices; namespace GLib {
implementation
csharp
bitwarden__server
src/Core/Settings/GlobalSettings.cs
{ "start": 27753, "end": 27941 }
public class ____ { public string AccessKeyId { get; set; } public string AccessKeySecret { get; set; } public string Region { get; set; } }
AmazonSettings
csharp
AutoMapper__AutoMapper
src/UnitTests/CustomMapping.cs
{ "start": 30565, "end": 30689 }
public class ____ { public int Id { get; set; } public string NumberValue { get; set; } }
SourceDto
csharp
dotnet__efcore
benchmark/EFCore.SqlServer.Benchmarks/Support/SqlServerBenchmarkEnvironment.cs
{ "start": 439, "end": 1404 }
public static class ____ { public static IConfiguration Config { get; } static SqlServerBenchmarkEnvironment() { var configBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config.json", optional: true) .AddEnvironmentVariables(); Config = configBuilder.Build() .GetSection("Test:SqlServer"); } private const string DefaultConnectionString = "Data Source=(localdb)\\MSSQLLocalDB;Database=master;Integrated Security=True;Connect Timeout=30;ConnectRetryCount=0"; public static string DefaultConnection => Config["DefaultConnection"] ?? DefaultConnectionString; public static string CreateConnectionString(string name, string fileName = null, bool? multipleActiveResultSets = null) => new SqlConnectionStringBuilder(DefaultConnection) { InitialCatalog = name }.ToString(); }
SqlServerBenchmarkEnvironment
csharp
louthy__language-ext
LanguageExt.Tests/Transformer/Traverse/Arr/Sync/Either.cs
{ "start": 161, "end": 1448 }
public class ____ { [Fact] public void LeftIsSingletonLeft() { var ma = Left<Error, Arr<int>>(Error.New("alt")); var mb = ma.KindT<Either<Error>, Arr, Arr<int>, int>() .SequenceM() .AsT<Arr, Either<Error>, Either<Error, int>, int>() .As(); var mc = Array(Left<Error, int>(Error.New("alt"))); Assert.True(mb == mc); } [Fact] public void RightEmptyIsEmpty() { var ma = Right<Error, Arr<int>>(Empty); var mb = ma.KindT<Either<Error>, Arr, Arr<int>, int>() .SequenceM() .AsT<Arr, Either<Error>, Either<Error, int>, int>() .As(); var mc = Array<Either<Error, int>>(); Assert.True(mb == mc); } [Fact] public void RightNonEmptyArrIsArrRight() { var ma = Right<Error, Arr<int>>(Array(1, 2, 3, 4)); var mb = ma.KindT<Either<Error>, Arr, Arr<int>, int>() .SequenceM() .AsT<Arr, Either<Error>, Either<Error, int>, int>() .As(); var mc = Array(Right<Error, int>(1), Right<Error, int>(2), Right<Error, int>(3), Right<Error, int>(4)); Assert.True(mb == mc); } }
EitherArr
csharp
abpframework__abp
framework/src/Volo.Abp.AspNetCore.Components.Web.Theming/Toolbars/StandardToolbars.cs
{ "start": 65, "end": 145 }
public static class ____ { public const string Main = "Main"; }
StandardToolbars
csharp
dotnet__machinelearning
src/Microsoft.ML.Data/DataLoadSave/Binary/Codecs.cs
{ "start": 12799, "end": 15080 }
private sealed class ____ : ValueReaderBase<ReadOnlyMemory<char>> { private readonly int _entries; private readonly int[] _boundaries; private int _index; private readonly string _text; public Reader(TextCodec codec, Stream stream, int items) : base(codec.Factory, stream) { _entries = Reader.ReadInt32(); Contracts.CheckDecode(_entries == items); _index = -1; _boundaries = new int[_entries + 1]; int bPrev = 0; for (int i = 1; i < _boundaries.Length; ++i) { int b = _boundaries[i] = Reader.ReadInt32(); Contracts.CheckDecode(b >= (bPrev & LengthMask) || (b & LengthMask) == (bPrev & LengthMask)); bPrev = b; } _text = Reader.ReadString(); Contracts.CheckDecode(_text.Length == (_boundaries[_entries] & LengthMask)); } public override void MoveNext() { Contracts.Check(++_index < _entries, "reader already read all values"); } public override void Get(ref ReadOnlyMemory<char> value) { Contracts.Assert(_index < _entries); int b = _boundaries[_index + 1]; int start = _boundaries[_index] & LengthMask; if (b >= 0) value = _text.AsMemory().Slice(start, (b & LengthMask) - start); else { //For backward compatibility when NA values existed, treat them //as empty string. value = ReadOnlyMemory<char>.Empty; } } } } /// <summary> /// This is a boolean code that reads from a form that serialized /// 1 bit per value. The old encoding (implemented by a different codec) /// uses 2 bits per value so NA values can be supported. /// </summary>
Reader
csharp
EventStore__EventStore
src/KurrentDB.Core/LogAbstraction/IRecordFactory.cs
{ "start": 287, "end": 374 }
public interface ____ { ISystemLogRecord CreateEpoch(EpochRecord epoch); }
IRecordFactory
csharp
icsharpcode__ILSpy
ICSharpCode.BamlDecompiler/Handlers/Blocks/PropertyArrayHandler.cs
{ "start": 1182, "end": 1906 }
internal class ____ : IHandler { public BamlRecordType Type => BamlRecordType.PropertyArrayStart; public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) { var record = (PropertyArrayStartRecord)((BamlBlockNode)node).Header; var doc = new BamlElement(node); var elemAttr = ctx.ResolveProperty(record.AttributeId); doc.Xaml = new XElement(elemAttr.ToXName(ctx, null)); doc.Xaml.Element.AddAnnotation(elemAttr); parent.Xaml.Element.Add(doc.Xaml.Element); HandlerMap.ProcessChildren(ctx, (BamlBlockNode)node, doc); elemAttr.DeclaringType.ResolveNamespace(doc.Xaml, ctx); doc.Xaml.Element.Name = elemAttr.ToXName(ctx, null); return doc; } } }
PropertyArrayHandler
csharp
protobuf-net__protobuf-net
src/protobuf-net.Test/Nullables/CollectionsWithNullsTests_DuplicateMessageNames.cs
{ "start": 4940, "end": 5442 }
class ____ { [ProtoMember(1), NullWrappedValue] public List<Bar> Items1 { get; set; } = new(); [ProtoMember(2), NullWrappedValue(AsGroup = true)] public List<Bar> Items2 { get; set; } = new(); [ProtoMember(3)] // [SupportNull] defined in test public List<Bar> Items3 { get; set; } = new(); } } } namespace ProtoBuf.Test.Nullables.Test1 { [ProtoContract]
DuplicateFieldTypesWithDifferentNullWrappingModel
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.Demo/Models/CustomViewModel.cs
{ "start": 80, "end": 168 }
public class ____ : ShapeViewModel { public string Value { get; set; } }
CustomViewModel
csharp
FoundatioFx__Foundatio
src/Foundatio/Messaging/MessageBusBase.cs
{ "start": 15349, "end": 16304 }
protected class ____ { private readonly ConcurrentDictionary<Type, bool> _assignableTypesCache = new(); public string Id { get; private set; } = Guid.NewGuid().ToString("N"); public CancellationToken CancellationToken { get; set; } public Type Type { get; set; } public Type GenericType { get; set; } public Func<object, CancellationToken, Task> Action { get; set; } public bool IsAssignableFrom(Type type) { if (type is null) return false; return _assignableTypesCache.GetOrAdd(type, t => { if (t.IsClass) { var typedMessageType = typeof(IMessage<>).MakeGenericType(t); if (Type == typedMessageType) return true; } return Type.GetTypeInfo().IsAssignableFrom(t); }); } } }
Subscriber
csharp
EventStore__EventStore
src/KurrentDB.Core.Tests/Services/ElectionsService/ElectionsServiceTests.cs
{ "start": 39381, "end": 40528 }
public class ____ : ElectionsFixture { public when_receiving_accept_for_not_the_current_installed_view() : base(NodeFactory(3), NodeFactory(2), NodeFactory(1)) { _sut.Handle(new GossipMessage.GossipUpdated(new ClusterInfo( MemberInfoFromVNode(_node, _timeProvider.UtcNow, VNodeState.Unknown, true, 0, _epochId, 0), MemberInfoFromVNode(_nodeTwo, _timeProvider.UtcNow, VNodeState.Unknown, true, 0, _epochId, 0), MemberInfoFromVNode(_nodeThree, _timeProvider.UtcNow, VNodeState.Unknown, true, 0, _epochId, 0)))); } [Test] public void should_ignore_accept() { _sut.Handle(new ElectionMessage.StartElections()); _sut.Handle(new ElectionMessage.ViewChange(_nodeTwo.InstanceId, _nodeTwo.HttpEndPoint, 0)); _sut.Handle(new ElectionMessage.PrepareOk(0, _nodeTwo.InstanceId, _nodeTwo.HttpEndPoint, 0, 0, _epochId, Guid.Empty, 0, 0, 0, 0, new ClusterInfo())); _publisher.Messages.Clear(); _sut.Handle(new ElectionMessage.Accept(_nodeTwo.InstanceId, _nodeTwo.HttpEndPoint, _nodeThree.InstanceId, _nodeThree.HttpEndPoint, 1)); Assert.IsEmpty(_publisher.Messages); } }
when_receiving_accept_for_not_the_current_installed_view
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/DeclarativeValidationTests.cs
{ "start": 481, "end": 861 }
public class ____ : IReturn<EmptyResponse> { [ValidateNotEmpty] [ValidateMaximumLength(20)] public string Site { get; set; } public List<DeclarativeChildValidation> DeclarativeValidations { get; set; } public List<FluentChildValidation> FluentValidations { get; set; } public List<NoValidators> NoValidators { get; set; } }
DeclarativeCollectiveValidationTest
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/test/Types.Tests/Types/Relay/NodeResolverTests.cs
{ "start": 11662, "end": 11800 }
public class ____ { public EntityNoId GetEntity(int id) => new EntityNoId { Data = id }; }
QueryEntityRenamed
csharp
grpc__grpc-dotnet
src/Grpc.AspNetCore.Server/Model/ServiceMethodProviderContext.cs
{ "start": 7138, "end": 7303 }
class ____ TResponse : class { var methodModel = new MethodModel(method, pattern, metadata, invoker); Methods.Add(methodModel); } }
where
csharp
microsoft__FASTER
cs/samples/FasterLogSample/Program.cs
{ "start": 8787, "end": 9117 }
private struct ____ : IReadOnlySpanBatch { private readonly int batchSize; public ReadOnlySpanBatch(int batchSize) => this.batchSize = batchSize; public ReadOnlySpan<byte> Get(int index) => staticEntry; public int TotalEntries() => batchSize; } } }
ReadOnlySpanBatch
csharp
unoplatform__uno
src/Uno.UI.RuntimeTests/MUX/Microsoft_UI_Xaml_Controls/ScrollPresenter/ScrollPresenterLayoutTests.cs
{ "start": 743, "end": 798 }
partial class ____ : MUXApiTestBase {
ScrollPresenterTests
csharp
atata-framework__atata
test/Atata.IntegrationTests/Sessions/AtataSessionCollectionTests.cs
{ "start": 15215, "end": 18842 }
public sealed class ____ { [Test] public async Task WhenNoBuilder() { // Arrange await using AtataContext context = await AtataContext.CreateDefaultNonScopedBuilder().BuildAsync(); // Act var call = context.Sessions.Invoking(x => x.BuildAsync<FakeSession>()); // Assert await call.Should().ThrowExactlyAsync<AtataSessionBuilderNotFoundException>() .WithMessage("Failed to find session builder for FakeSession in AtataContext { * }."); } [Test] public async Task WhenThereIsBuilderWithAnotherName() { // Arrange await using AtataContext context = await AtataContext.CreateDefaultNonScopedBuilder() .Sessions.Add<FakeSessionBuilder>(x => x .UseStartScopes(AtataContextScopes.None) .UseName("some1")) .BuildAsync(); // Act var call = context.Sessions.Invoking(x => x.BuildAsync<FakeSession>("some2")); // Assert await call.Should().ThrowExactlyAsync<AtataSessionBuilderNotFoundException>() .WithMessage("Failed to find session builder for FakeSession { * } in AtataContext { * }."); } [Test] public async Task WithoutName_WhenThereIsBuilder() { // Arrange await using AtataContext context = await AtataContext.CreateDefaultNonScopedBuilder() .Sessions.Add<FakeSessionBuilder>(x => x.UseStartScopes(AtataContextScopes.None)) .BuildAsync(); // Act var session = await context.Sessions.BuildAsync<FakeSession>(); // Assert session.IsBorrowed.Should().BeFalse(); session.IsTakenFromPool.Should().BeFalse(); session.Context.Should().Be(context); session.OwnerContext.Should().Be(context); context.Sessions.Should().BeEquivalentTo([session]); } [Test] public async Task WithName_WhenThereIsBuilder() { // Arrange await using AtataContext context = await AtataContext.CreateDefaultNonScopedBuilder() .Sessions.Add<FakeSessionBuilder>(x => x .UseStartScopes(AtataContextScopes.None) .UseName("some")) .BuildAsync(); // Act var session = await context.Sessions.BuildAsync<FakeSession>("some"); // Assert session.IsBorrowed.Should().BeFalse(); session.IsTakenFromPool.Should().BeFalse(); session.Context.Should().Be(context); session.OwnerContext.Should().Be(context); context.Sessions.Should().BeEquivalentTo([session]); } [Test] public async Task WithoutName_WhenThereIsBuilderWithBuiltSession() { // Arrange await using AtataContext context = await AtataContext.CreateDefaultNonScopedBuilder() .Sessions.Add<FakeSessionBuilder>() .BuildAsync(); // Act var session = await context.Sessions.BuildAsync<FakeSession>(); // Assert session.IsBorrowed.Should().BeFalse(); session.IsTakenFromPool.Should().BeFalse(); session.Context.Should().Be(context); session.OwnerContext.Should().Be(context); context.Sessions.Should().HaveCount(2); context.Sessions[1].Should().BeEquivalentTo(session); } }
BuildAsync
csharp
dotnet__aspnetcore
src/Http/Routing/test/UnitTests/Builder/FallbackEndpointRouteBuilderExtensionsTest.cs
{ "start": 267, "end": 1695 }
public class ____ { private EndpointDataSource GetBuilderEndpointDataSource(IEndpointRouteBuilder endpointRouteBuilder) => Assert.Single(endpointRouteBuilder.DataSources); [Fact] public void MapFallback_AddFallbackMetadata() { var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(EmptyServiceProvider.Instance)); RequestDelegate initialRequestDelegate = static (context) => Task.CompletedTask; builder.MapFallback(initialRequestDelegate); var dataSource = GetBuilderEndpointDataSource(builder); var endpoint = Assert.Single(dataSource.Endpoints); Assert.Contains(FallbackMetadata.Instance, endpoint.Metadata); Assert.Equal(int.MaxValue, ((RouteEndpoint)endpoint).Order); } [Fact] public void MapFallback_Pattern_AddFallbackMetadata() { var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(EmptyServiceProvider.Instance)); RequestDelegate initialRequestDelegate = static (context) => Task.CompletedTask; builder.MapFallback("/", initialRequestDelegate); var dataSource = GetBuilderEndpointDataSource(builder); var endpoint = Assert.Single(dataSource.Endpoints); Assert.Contains(FallbackMetadata.Instance, endpoint.Metadata); Assert.Equal(int.MaxValue, ((RouteEndpoint)endpoint).Order); }
FallbackEndpointRouteBuilderExtensionsTest
csharp
ServiceStack__ServiceStack
ServiceStack.Redis/tests/ServiceStack.Redis.Tests/RedisStatsTests.cs
{ "start": 118, "end": 1216 }
public class ____ : RedisClientTestsBase { [OneTimeSetUp] public void OneTimeSetUp() { RedisConfig.AssumeServerVersion = 2821; } [Test] [Ignore("too long")] public void Batch_and_Pipeline_requests_only_counts_as_1_request() { var reqCount = RedisNativeClient.RequestsPerHour; var map = new Dictionary<string, string>(); 10.Times(i => map["key" + i] = "value" + i); Redis.SetValues(map); Assert.That(RedisNativeClient.RequestsPerHour, Is.EqualTo(reqCount + 1)); var keyTypes = new Dictionary<string, string>(); using (var pipeline = Redis.CreatePipeline()) { map.Keys.Each(key => pipeline.QueueCommand(r => r.Type(key), x => keyTypes[key] = x)); pipeline.Flush(); } Assert.That(RedisNativeClient.RequestsPerHour, Is.EqualTo(reqCount + 2)); Assert.That(keyTypes.Count, Is.EqualTo(map.Count)); } } }
RedisStatsTests
csharp
CommunityToolkit__WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.UI.Controls.DataGrid.Design/Controls/DataGrid.Metadata.cs
{ "start": 830, "end": 9458 }
internal class ____ : AttributeTableBuilder { public DataGridMetadata() : base() { AddCallback(ControlTypes.DataGrid, b => { b.AddCustomAttributes(new FeatureAttribute(typeof(DataGridDefaults))); b.AddCustomAttributes(nameof(DataGrid.AlternatingRowBackground), new CategoryAttribute(Resources.CategoryRows)); b.AddCustomAttributes(nameof(DataGrid.AreRowDetailsFrozen), new CategoryAttribute(Resources.CategoryRows)); b.AddCustomAttributes(nameof(DataGrid.AreRowGroupHeadersFrozen), new CategoryAttribute(Resources.CategoryHeaders)); b.AddCustomAttributes(nameof(DataGrid.AutoGenerateColumns), new CategoryAttribute(Resources.CategoryColumns)); b.AddCustomAttributes(nameof(DataGrid.CanUserReorderColumns), new CategoryAttribute(Resources.CategoryColumns)); b.AddCustomAttributes(nameof(DataGrid.CanUserResizeColumns), new CategoryAttribute(Resources.CategoryColumns)); b.AddCustomAttributes(nameof(DataGrid.CanUserSortColumns), new CategoryAttribute(Resources.CategoryColumns)); b.AddCustomAttributes(nameof(DataGrid.CellStyle), new CategoryAttribute(Resources.CategoryColumns)); b.AddCustomAttributes(nameof(DataGrid.ClipboardCopyMode), new CategoryAttribute(Resources.CategoryText)); b.AddCustomAttributes(nameof(DataGrid.ColumnHeaderHeight), new CategoryAttribute(Resources.CategoryHeaders)); b.AddCustomAttributes(nameof(DataGrid.ColumnHeaderStyle), new CategoryAttribute(Resources.CategoryHeaders)); b.AddCustomAttributes(nameof(DataGrid.Columns), new CategoryAttribute(Resources.CategoryColumns)); b.AddCustomAttributes(nameof(DataGrid.ColumnWidth), new CategoryAttribute(Resources.CategoryColumns)); b.AddCustomAttributes(nameof(DataGrid.CurrentColumn), new CategoryAttribute(Resources.CategoryText)); b.AddCustomAttributes(nameof(DataGrid.DragIndicatorStyle), new CategoryAttribute(Resources.CategoryText)); b.AddCustomAttributes(nameof(DataGrid.DropLocationIndicatorStyle), new CategoryAttribute(Resources.CategoryText)); b.AddCustomAttributes(nameof(DataGrid.FrozenColumnCount), new CategoryAttribute(Resources.CategoryColumns)); b.AddCustomAttributes(nameof(DataGrid.GridLinesVisibility), new CategoryAttribute(Resources.CategoryGridLines)); b.AddCustomAttributes(nameof(DataGrid.HeadersVisibility), new CategoryAttribute(Resources.CategoryHeaders)); b.AddCustomAttributes(nameof(DataGrid.HorizontalGridLinesBrush), new CategoryAttribute(Resources.CategoryGridLines)); b.AddCustomAttributes(nameof(DataGrid.HorizontalScrollBarVisibility), new CategoryAttribute(Resources.CategoryLayout)); b.AddCustomAttributes(nameof(DataGrid.IsReadOnly), new CategoryAttribute(Resources.CategoryText)); b.AddCustomAttributes(nameof(DataGrid.IsValid), new CategoryAttribute(Resources.CategoryText)); b.AddCustomAttributes(nameof(DataGrid.ItemsSource), new CategoryAttribute(Resources.CategoryColumns)); b.AddCustomAttributes(nameof(DataGrid.MaxColumnWidth), new CategoryAttribute(Resources.CategoryColumns)); b.AddCustomAttributes(nameof(DataGrid.MinColumnWidth), new CategoryAttribute(Resources.CategoryColumns)); b.AddCustomAttributes(nameof(DataGrid.RowBackground), new CategoryAttribute(Resources.CategoryRows)); b.AddCustomAttributes(nameof(DataGrid.RowDetailsTemplate), new CategoryAttribute(Resources.CategoryRows)); b.AddCustomAttributes(nameof(DataGrid.RowDetailsVisibilityMode), new CategoryAttribute(Resources.CategoryRows)); b.AddCustomAttributes(nameof(DataGrid.RowGroupHeaderPropertyNameAlternative), new CategoryAttribute(Resources.CategoryHeaders)); b.AddCustomAttributes(nameof(DataGrid.RowGroupHeaderStyles), new CategoryAttribute(Resources.CategoryHeaders)); b.AddCustomAttributes(nameof(DataGrid.RowHeaderStyle), new CategoryAttribute(Resources.CategoryHeaders)); b.AddCustomAttributes(nameof(DataGrid.RowHeaderWidth), new CategoryAttribute(Resources.CategoryHeaders)); b.AddCustomAttributes(nameof(DataGrid.RowHeight), new CategoryAttribute(Resources.CategoryRows)); b.AddCustomAttributes(nameof(DataGrid.RowStyle), new CategoryAttribute(Resources.CategoryRows)); b.AddCustomAttributes(nameof(DataGrid.SelectedIndex), new CategoryAttribute(Resources.CategoryCommon)); b.AddCustomAttributes(nameof(DataGrid.SelectedItem), new CategoryAttribute(Resources.CategoryCommon)); b.AddCustomAttributes(nameof(DataGrid.SelectedItems), new CategoryAttribute(Resources.CategoryAppearance)); b.AddCustomAttributes(nameof(DataGrid.SelectionMode), new CategoryAttribute(Resources.CategoryRows)); b.AddCustomAttributes(nameof(DataGrid.VerticalGridLinesBrush), new CategoryAttribute(Resources.CategoryGridLines)); b.AddCustomAttributes(nameof(DataGrid.VerticalScrollBarVisibility), new CategoryAttribute(Resources.CategoryLayout)); b.AddCustomAttributes(new ToolboxCategoryAttribute(ToolboxCategoryPaths.Toolkit, false)); }); AddCallback(ControlTypes.DataGridColumn, b => { b.AddCustomAttributes(nameof(DataGridColumn.CanUserResize), new CategoryAttribute(Resources.CategoryLayout)); b.AddCustomAttributes(nameof(DataGridColumn.CanUserSort), new CategoryAttribute(Resources.CategorySort)); b.AddCustomAttributes(nameof(DataGridColumn.Header), new CategoryAttribute(Resources.CategoryHeader)); b.AddCustomAttributes(nameof(DataGridColumn.HeaderStyle), new CategoryAttribute(Resources.CategoryHeader)); b.AddCustomAttributes(nameof(DataGridColumn.MaxWidth), new CategoryAttribute(Resources.CategoryLayout)); b.AddCustomAttributes(nameof(DataGridColumn.MinWidth), new CategoryAttribute(Resources.CategoryLayout)); b.AddCustomAttributes(nameof(DataGridColumn.SortDirection), new CategoryAttribute(Resources.CategorySort)); b.AddCustomAttributes(nameof(DataGridColumn.Visibility), new CategoryAttribute(Resources.CategoryAppearance)); b.AddCustomAttributes(nameof(DataGridColumn.Width), new CategoryAttribute(Resources.CategoryLayout)); }); AddCallback(ControlTypes.DataGridBoundColumn, b => { b.AddCustomAttributes(nameof(DataGridBoundColumn.Binding), new CategoryAttribute(Resources.CategoryCellBinding)); }); AddCallback(ControlTypes.DataGridTextColumn, b => { b.AddCustomAttributes(nameof(DataGridTextColumn.FontFamily), new CategoryAttribute(Resources.CategoryText)); b.AddCustomAttributes(nameof(DataGridTextColumn.FontSize), new CategoryAttribute(Resources.CategoryText)); b.AddCustomAttributes(nameof(DataGridTextColumn.FontStyle), new CategoryAttribute(Resources.CategoryText)); b.AddCustomAttributes(nameof(DataGridTextColumn.FontWeight), new CategoryAttribute(Resources.CategoryText)); b.AddCustomAttributes(nameof(DataGridTextColumn.Foreground), new CategoryAttribute(Resources.CategoryText)); }); AddCallback(ControlTypes.DataGridCheckBoxColumn, b => { b.AddCustomAttributes(nameof(DataGridCheckBoxColumn.IsThreeState), new CategoryAttribute(Resources.CategoryCommon)); }); AddCallback(ControlTypes.DataGridTemplateColumn, b => { b.AddCustomAttributes(nameof(DataGridTemplateColumn.CellEditingTemplate), new CategoryAttribute(Resources.CategoryCellTemplate)); b.AddCustomAttributes(nameof(DataGridTemplateColumn.CellTemplate), new CategoryAttribute(Resources.CategoryCellTemplate)); }); } } }
DataGridMetadata
csharp
MassTransit__MassTransit
src/MassTransit/Consumers/Configuration/InstanceMessageConnector.cs
{ "start": 506, "end": 638 }
public class ____<TConsumer, TMessage> : IInstanceMessageConnector<TConsumer> where TConsumer :
InstanceMessageConnector
csharp
dotnet__machinelearning
src/Microsoft.ML.Data/DataView/ArrayDataViewBuilder.cs
{ "start": 18848, "end": 19253 }
private sealed class ____ : Column<string, ReadOnlyMemory<char>> { public StringToTextColumn(string[] values) : base(TextDataViewType.Instance, values) { } protected override void CopyOut(in string src, ref ReadOnlyMemory<char> dst) { dst = src.AsMemory(); } }
StringToTextColumn
csharp
abpframework__abp
framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ApiExploring/AbpApiDefinitionController.cs
{ "start": 191, "end": 649 }
public class ____ : AbpController, IRemoteService { protected readonly IApiDescriptionModelProvider ModelProvider; public AbpApiDefinitionController(IApiDescriptionModelProvider modelProvider) { ModelProvider = modelProvider; } [HttpGet] public virtual ApplicationApiDescriptionModel Get(ApplicationApiDescriptionModelRequestDto model) { return ModelProvider.CreateApiModel(model); } }
AbpApiDefinitionController
csharp
dotnet__aspnetcore
src/Security/Authentication/test/WsFederation/WsFederationTest_Handler.cs
{ "start": 728, "end": 10803 }
public class ____ { [Fact] public async Task VerifySchemeDefaults() { var services = new ServiceCollection(); services.AddSingleton<IConfiguration>(new ConfigurationManager()); services.AddAuthentication().AddWsFederation(); var sp = services.BuildServiceProvider(); var schemeProvider = sp.GetRequiredService<IAuthenticationSchemeProvider>(); var scheme = await schemeProvider.GetSchemeAsync(WsFederationDefaults.AuthenticationScheme); Assert.NotNull(scheme); Assert.Equal("WsFederationHandler", scheme.HandlerType.Name); Assert.Equal(WsFederationDefaults.AuthenticationScheme, scheme.DisplayName); } [Fact] public async Task MissingConfigurationThrows() { using var host = new HostBuilder() .ConfigureWebHost(builder => builder.UseTestServer() .Configure(ConfigureApp) .ConfigureServices(services => { services.AddAuthentication(sharedOptions => { sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; sharedOptions.DefaultChallengeScheme = WsFederationDefaults.AuthenticationScheme; }) .AddCookie() .AddWsFederation(); })) .Build(); await host.StartAsync(); using var server = host.GetTestServer(); var httpClient = server.CreateClient(); // Verify if the request is redirected to STS with right parameters var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => httpClient.GetAsync("/")); Assert.Equal("Provide MetadataAddress, Configuration, or ConfigurationManager to WsFederationOptions", exception.Message); } [Fact] public async Task ChallengeRedirects() { var httpClient = await CreateClient(); // Verify if the request is redirected to STS with right parameters var response = await httpClient.GetAsync("/"); Assert.Equal("https://login.windows.net/4afbc689-805b-48cf-a24c-d4aa3248a248/wsfed", response.Headers.Location.GetLeftPart(System.UriPartial.Path)); var queryItems = QueryHelpers.ParseQuery(response.Headers.Location.Query); Assert.Equal("http://Automation1", queryItems["wtrealm"]); Assert.True(queryItems["wctx"].ToString().Equals(CustomStateDataFormat.ValidStateData), "wctx does not equal ValidStateData"); Assert.Equal(httpClient.BaseAddress + "signin-wsfed", queryItems["wreply"]); Assert.Equal("wsignin1.0", queryItems["wa"]); } [Fact] public async Task MapWillNotAffectRedirect() { var httpClient = await CreateClient(); // Verify if the request is redirected to STS with right parameters var response = await httpClient.GetAsync("/mapped-challenge"); Assert.Equal("https://login.windows.net/4afbc689-805b-48cf-a24c-d4aa3248a248/wsfed", response.Headers.Location.GetLeftPart(System.UriPartial.Path)); var queryItems = QueryHelpers.ParseQuery(response.Headers.Location.Query); Assert.Equal("http://Automation1", queryItems["wtrealm"]); Assert.True(queryItems["wctx"].ToString().Equals(CustomStateDataFormat.ValidStateData), "wctx does not equal ValidStateData"); Assert.Equal(httpClient.BaseAddress + "signin-wsfed", queryItems["wreply"]); Assert.Equal("wsignin1.0", queryItems["wa"]); } [Fact] public async Task PreMappedWillAffectRedirect() { var httpClient = await CreateClient(); // Verify if the request is redirected to STS with right parameters var response = await httpClient.GetAsync("/premapped-challenge"); Assert.Equal("https://login.windows.net/4afbc689-805b-48cf-a24c-d4aa3248a248/wsfed", response.Headers.Location.GetLeftPart(System.UriPartial.Path)); var queryItems = QueryHelpers.ParseQuery(response.Headers.Location.Query); Assert.Equal("http://Automation1", queryItems["wtrealm"]); Assert.True(queryItems["wctx"].ToString().Equals(CustomStateDataFormat.ValidStateData), "wctx does not equal ValidStateData"); Assert.Equal(httpClient.BaseAddress + "premapped-challenge/signin-wsfed", queryItems["wreply"]); Assert.Equal("wsignin1.0", queryItems["wa"]); } [Fact] public async Task ValidTokenIsAccepted() { var httpClient = await CreateClient(); // Verify if the request is redirected to STS with right parameters var response = await httpClient.GetAsync("/"); var queryItems = QueryHelpers.ParseQuery(response.Headers.Location.Query); var request = new HttpRequestMessage(HttpMethod.Post, queryItems["wreply"]); CopyCookies(response, request); request.Content = CreateSignInContent("WsFederation/ValidToken.xml", queryItems["wctx"]); response = await httpClient.SendAsync(request); Assert.Equal(HttpStatusCode.Found, response.StatusCode); request = new HttpRequestMessage(HttpMethod.Get, response.Headers.Location); CopyCookies(response, request); response = await httpClient.SendAsync(request); // Did the request end in the actual resource requested for Assert.Equal(WsFederationDefaults.AuthenticationScheme, await response.Content.ReadAsStringAsync()); } [Fact] public async Task ValidUnsolicitedTokenIsRefused() { var httpClient = await CreateClient(); var form = CreateSignInContent("WsFederation/ValidToken.xml", suppressWctx: true); var exception = await Assert.ThrowsAsync<AuthenticationFailureException>(() => httpClient.PostAsync(httpClient.BaseAddress + "signin-wsfed", form)); Assert.Contains("Unsolicited logins are not allowed.", exception.InnerException.Message); } [Fact] public async Task ValidUnsolicitedTokenIsAcceptedWhenAllowed() { var httpClient = await CreateClient(allowUnsolicited: true); var form = CreateSignInContent("WsFederation/ValidToken.xml", suppressWctx: true); var response = await httpClient.PostAsync(httpClient.BaseAddress + "signin-wsfed", form); Assert.Equal(HttpStatusCode.Found, response.StatusCode); var request = new HttpRequestMessage(HttpMethod.Get, response.Headers.Location); CopyCookies(response, request); response = await httpClient.SendAsync(request); // Did the request end in the actual resource requested for Assert.Equal(WsFederationDefaults.AuthenticationScheme, await response.Content.ReadAsStringAsync()); } [Fact] public async Task InvalidTokenIsRejected() { var httpClient = await CreateClient(); // Verify if the request is redirected to STS with right parameters var response = await httpClient.GetAsync("/"); var queryItems = QueryHelpers.ParseQuery(response.Headers.Location.Query); var request = new HttpRequestMessage(HttpMethod.Post, queryItems["wreply"]); CopyCookies(response, request); request.Content = CreateSignInContent("WsFederation/InvalidToken.xml", queryItems["wctx"]); response = await httpClient.SendAsync(request); // Did the request end in the actual resource requested for Assert.Equal("AuthenticationFailed", await response.Content.ReadAsStringAsync()); } [Fact] public async Task RemoteSignoutRequestTriggersSignout() { var httpClient = await CreateClient(); var response = await httpClient.GetAsync("/signin-wsfed?wa=wsignoutcleanup1.0"); response.EnsureSuccessStatusCode(); var cookie = response.Headers.GetValues(HeaderNames.SetCookie).Single(); Assert.Equal(".AspNetCore.Cookies=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; samesite=lax; httponly", cookie); Assert.Equal("OnRemoteSignOut", response.Headers.GetValues("EventHeader").Single()); Assert.Equal("", await response.Content.ReadAsStringAsync()); } [Fact] public async Task EventsResolvedFromDI() { using var host = new HostBuilder() .ConfigureWebHost(builder => builder.UseTestServer() .ConfigureServices(services => { services.AddSingleton<MyWsFedEvents>(); services.AddAuthentication(sharedOptions => { sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; sharedOptions.DefaultChallengeScheme = WsFederationDefaults.AuthenticationScheme; }) .AddCookie() .AddWsFederation(options => { options.Wtrealm = "http://Automation1"; options.MetadataAddress = "https://login.windows.net/4afbc689-805b-48cf-a24c-d4aa3248a248/federationmetadata/2007-06/federationmetadata.xml"; options.BackchannelHttpHandler = new WaadMetadataDocumentHandler(); options.EventsType = typeof(MyWsFedEvents); }); }) .Configure(app => { app.Run(context => context.ChallengeAsync()); })) .Build(); await host.StartAsync(); using var server = host.GetTestServer(); var result = await server.CreateClient().GetAsync(""); Assert.Contains("CustomKey=CustomValue", result.Headers.Location.Query); }
WsFederationTestHandlers
csharp
CommunityToolkit__Maui
samples/CommunityToolkit.Maui.Sample/Views/Popups/ExplicitStylePopup.xaml.cs
{ "start": 222, "end": 325 }
public partial class ____ { public ExplicitStylePopup() { InitializeComponent(); } }
ExplicitStylePopup
csharp
aspnetboilerplate__aspnetboilerplate
test/aspnet-core-demo/AbpAspNetCoreDemo/Controllers/ModelValidationController.cs
{ "start": 120, "end": 384 }
public class ____ : DemoControllerBase { public IActionResult Index() { return View(); } [HttpPost] public IActionResult CreateUser(UserModel model, string test) { return View("Index", model); } }
ModelValidationController
csharp
ChilliCream__graphql-platform
src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs
{ "start": 6365974, "end": 6366841 }
public partial record ____ { public ValidateFusionConfigurationCompositionPayloadData(global::System.String __typename, global::System.Collections.Generic.IReadOnlyList<global::ChilliCream.Nitro.CommandLine.Cloud.Client.State.IValidateFusionConfigurationCompositionErrorData>? errors = default !) { this.__typename = __typename ?? throw new global::System.ArgumentNullException(nameof(__typename)); Errors = errors; } public global::System.String __typename { get; init; } public global::System.Collections.Generic.IReadOnlyList<global::ChilliCream.Nitro.CommandLine.Cloud.Client.State.IValidateFusionConfigurationCompositionErrorData>? Errors { get; init; } } [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
ValidateFusionConfigurationCompositionPayloadData
csharp
ServiceStack__ServiceStack
ServiceStack.Text/src/ServiceStack.Text/PclExport.NetFx.cs
{ "start": 636, "end": 12885 }
public class ____ : PclExport { public static NetFxPclExport Provider = new(); public NetFxPclExport() { this.DirSep = Path.DirectorySeparatorChar; this.AltDirSep = Path.DirectorySeparatorChar == '/' ? '\\' : '/'; this.RegexOptions = RegexOptions.Compiled; this.InvariantComparison = StringComparison.InvariantCulture; this.InvariantComparisonIgnoreCase = StringComparison.InvariantCultureIgnoreCase; this.InvariantComparer = StringComparer.InvariantCulture; this.InvariantComparerIgnoreCase = StringComparer.InvariantCultureIgnoreCase; this.PlatformName = Platforms.NetFX; ReflectionOptimizer.Instance = EmitReflectionOptimizer.Provider; } public static PclExport Configure() { Configure(Provider); return Provider; } public override string ToInvariantUpper(char value) { return value.ToString(CultureInfo.InvariantCulture).ToUpper(); } public override bool IsAnonymousType(Type type) { return type.HasAttribute<CompilerGeneratedAttribute>() && type.IsGenericType && type.Name.Contains("AnonymousType") && (type.Name.StartsWith("<>", StringComparison.Ordinal) || type.Name.StartsWith("VB$", StringComparison.Ordinal)) && (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic; } public const string AppSettingsKey = "servicestack:license"; public const string EnvironmentKey = "SERVICESTACK_LICENSE"; public override void RegisterLicenseFromConfig() { string licenceKeyText; try { //Automatically register license key stored in <appSettings/> licenceKeyText = System.Configuration.ConfigurationManager.AppSettings[AppSettingsKey]; if (!string.IsNullOrEmpty(licenceKeyText)) { LicenseUtils.RegisterLicense(licenceKeyText); return; } } catch (NotSupportedException) { return; } // Ignore Unity/IL2CPP Exception catch (Exception ex) { licenceKeyText = Environment.GetEnvironmentVariable(EnvironmentKey)?.Trim(); if (string.IsNullOrEmpty(licenceKeyText)) throw; try { LicenseUtils.RegisterLicense(licenceKeyText); } catch { throw ex; } } //or SERVICESTACK_LICENSE Environment variable licenceKeyText = Environment.GetEnvironmentVariable(EnvironmentKey)?.Trim(); if (!string.IsNullOrEmpty(licenceKeyText)) { LicenseUtils.RegisterLicense(licenceKeyText); } } public override async Task WriteAndFlushAsync(Stream stream, byte[] bytes) { await stream.WriteAsync(bytes, 0, bytes.Length).ConfigAwait(); await stream.FlushAsync().ConfigAwait(); } public override void AddCompression(WebRequest webReq) { var httpReq = (HttpWebRequest)webReq; httpReq.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); httpReq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } public override Stream GetRequestStream(WebRequest webRequest) { return webRequest.GetRequestStream(); } public override WebResponse GetResponse(WebRequest webRequest) { return webRequest.GetResponse(); } #if !LITE public override bool IsDebugBuild(Assembly assembly) { return assembly.AllAttributes() .OfType<System.Diagnostics.DebuggableAttribute>() .Select(attr => attr.IsJITTrackingEnabled) .FirstOrDefault(); } #endif public override string MapAbsolutePath(string relativePath, string appendPartialPathModifier) { if (relativePath.StartsWith("~")) { var assemblyDirectoryPath = Path.GetDirectoryName(new Uri(typeof(PathUtils).Assembly.EscapedCodeBase).LocalPath); // Escape the assembly bin directory to the hostname directory var hostDirectoryPath = appendPartialPathModifier != null ? assemblyDirectoryPath + appendPartialPathModifier : assemblyDirectoryPath; return Path.GetFullPath(relativePath.Replace("~", hostDirectoryPath)); } return relativePath; } public override Assembly LoadAssembly(string assemblyPath) { return Assembly.LoadFrom(assemblyPath); } public override void AddHeader(WebRequest webReq, string name, string value) { webReq.Headers.Add(name, value); } public override Type FindType(string typeName, string assemblyName) { var binPath = AssemblyUtils.GetAssemblyBinPath(Assembly.GetExecutingAssembly()); Assembly assembly = null; var assemblyDllPath = binPath + $"{assemblyName}.dll"; if (File.Exists(assemblyDllPath)) { assembly = AssemblyUtils.LoadAssembly(assemblyDllPath); } var assemblyExePath = binPath + $"{assemblyName}.exe"; if (File.Exists(assemblyExePath)) { assembly = AssemblyUtils.LoadAssembly(assemblyExePath); } return assembly != null ? assembly.GetType(typeName) : null; } public override string GetAssemblyCodeBase(Assembly assembly) { return assembly.CodeBase; } public override string GetAssemblyPath(Type source) { var assemblyUri = new Uri(source.Assembly.EscapedCodeBase); return assemblyUri.LocalPath; } public override bool InSameAssembly(Type t1, Type t2) { return t1.Assembly == t2.Assembly; } public override Type GetGenericCollectionType(Type type) { return type.FindInterfaces((t, critera) => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(ICollection<>), null).FirstOrDefault(); } public override string ToXsdDateTimeString(DateTime dateTime) { #if !LITE return System.Xml.XmlConvert.ToString(dateTime.ToStableUniversalTime(), System.Xml.XmlDateTimeSerializationMode.Utc); #else return dateTime.ToStableUniversalTime().ToString(DateTimeSerializer.XsdDateTimeFormat); #endif } public override string ToLocalXsdDateTimeString(DateTime dateTime) { #if !LITE return System.Xml.XmlConvert.ToString(dateTime, System.Xml.XmlDateTimeSerializationMode.Local); #else return dateTime.ToString(DateTimeSerializer.XsdDateTimeFormat); #endif } public override DateTime ParseXsdDateTime(string dateTimeStr) { #if !LITE return System.Xml.XmlConvert.ToDateTime(dateTimeStr, System.Xml.XmlDateTimeSerializationMode.Utc); #else return DateTime.ParseExact(dateTimeStr, DateTimeSerializer.XsdDateTimeFormat, CultureInfo.InvariantCulture); #endif } #if !LITE public override DateTime ParseXsdDateTimeAsUtc(string dateTimeStr) { return System.Xml.XmlConvert.ToDateTime(dateTimeStr, System.Xml.XmlDateTimeSerializationMode.Utc).Prepare(parsedAsUtc: true); } #endif public override DateTime ToStableUniversalTime(DateTime dateTime) { // .Net 2.0 - 3.5 has an issue with DateTime.ToUniversalTime, but works ok with TimeZoneInfo.ConvertTimeToUtc. // .Net 4.0+ does this under the hood anyway. return TimeZoneInfo.ConvertTimeToUtc(dateTime); } public override ParseStringDelegate GetDictionaryParseMethod<TSerializer>(Type type) { if (type == typeof(Hashtable)) { return SerializerUtils<TSerializer>.ParseHashtable; } return null; } public override ParseStringSpanDelegate GetDictionaryParseStringSpanMethod<TSerializer>(Type type) { if (type == typeof(Hashtable)) { return SerializerUtils<TSerializer>.ParseHashtable; } return null; } public override ParseStringDelegate GetSpecializedCollectionParseMethod<TSerializer>(Type type) { if (type == typeof(StringCollection)) { return SerializerUtils<TSerializer>.ParseStringCollection<TSerializer>; } return null; } public override ParseStringSpanDelegate GetSpecializedCollectionParseStringSpanMethod<TSerializer>(Type type) { if (type == typeof(StringCollection)) { return SerializerUtils<TSerializer>.ParseStringCollection<TSerializer>; } return null; } public override ParseStringDelegate GetJsReaderParseMethod<TSerializer>(Type type) { #if !LITE if (type.IsAssignableFrom(typeof(System.Dynamic.IDynamicMetaObjectProvider)) || type.HasInterface(typeof(System.Dynamic.IDynamicMetaObjectProvider))) { return DeserializeDynamic<TSerializer>.Parse; } #endif return null; } public override ParseStringSpanDelegate GetJsReaderParseStringSpanMethod<TSerializer>(Type type) { #if !LITE if (type.IsAssignableFrom(typeof(System.Dynamic.IDynamicMetaObjectProvider)) || type.HasInterface(typeof(System.Dynamic.IDynamicMetaObjectProvider))) { return DeserializeDynamic<TSerializer>.ParseStringSpan; } #endif return null; } public override void CloseStream(Stream stream) { stream.Close(); } public override LicenseKey VerifyLicenseKeyText(string licenseKeyText) { if (!licenseKeyText.VerifyLicenseKeyText(out LicenseKey key)) throw new ArgumentException("licenseKeyText"); return key; } public override void BeginThreadAffinity() { Thread.BeginThreadAffinity(); } public override void EndThreadAffinity() { Thread.EndThreadAffinity(); } public override void Config(HttpWebRequest req, bool? allowAutoRedirect = null, TimeSpan? timeout = null, TimeSpan? readWriteTimeout = null, string userAgent = null, bool? preAuthenticate = null) { req.MaximumResponseHeadersLength = int.MaxValue; //throws "The message length limit was exceeded" exception if (allowAutoRedirect.HasValue) req.AllowAutoRedirect = allowAutoRedirect.Value; if (readWriteTimeout.HasValue) req.ReadWriteTimeout = (int)readWriteTimeout.Value.TotalMilliseconds; if (timeout.HasValue) req.Timeout = (int)timeout.Value.TotalMilliseconds; if (userAgent != null) req.UserAgent = userAgent; if (preAuthenticate.HasValue) req.PreAuthenticate = preAuthenticate.Value; } public override DataContractAttribute GetWeakDataContract(Type type) { return type.GetWeakDataContract(); } public override DataMemberAttribute GetWeakDataMember(PropertyInfo pi) { return pi.GetWeakDataMember(); } public override DataMemberAttribute GetWeakDataMember(FieldInfo pi) { return pi.GetWeakDataMember(); } }
NetFxPclExport
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/src/Types.Analyzers/Models/DataLoaderParameterKind.cs
{ "start": 48, "end": 287 }
public enum ____ { Key = 0, Service = 1, ContextData = 2, CancellationToken = 3, SelectorBuilder = 4, PagingArguments = 5, PredicateBuilder = 6, SortDefinition = 7, QueryContext = 8 }
DataLoaderParameterKind
csharp
PrismLibrary__Prism
src/Maui/Prism.Maui/Navigation/IWindowManager.cs
{ "start": 144, "end": 995 }
public interface ____ { /// <summary> /// Gets a read-only collection of all currently open windows. /// </summary> IReadOnlyList<Window> Windows { get; } /// <summary> /// Gets the currently active window, if any. /// </summary> Window? Current { get; } /// <summary> /// Opens a new window. /// </summary> /// <param name="window">The Window object to be opened.</param> /// <exception cref="ArgumentNullException">Thrown if the window parameter is null.</exception> void OpenWindow(Window window); /// <summary> /// Closes a specified window. /// </summary> /// <param name="window">The Window object to be closed.</param> /// <exception cref="ArgumentNullException">Thrown if the window parameter is null.</exception> void CloseWindow(Window window); }
IWindowManager
csharp
dotnet__aspnetcore
src/Components/Endpoints/test/FormMapping/BrowserFileFromFormFileTests.cs
{ "start": 428, "end": 4074 }
public class ____ { [Fact] public void Name_ReturnsFormFileFileName_NotFormFileName() { // Arrange const string expectedFileName = "document.pdf"; const string formFieldName = "fileInput"; var mockFormFile = new Mock<IFormFile>(); mockFormFile.Setup(x => x.FileName).Returns(expectedFileName); mockFormFile.Setup(x => x.Name).Returns(formFieldName); var browserFile = new BrowserFileFromFormFile(mockFormFile.Object); // Act var actualName = browserFile.Name; // Assert Assert.Equal(expectedFileName, actualName); Assert.NotEqual(formFieldName, actualName); } [Fact] public void TryRead_IBrowserFile_ReturnsCorrectFileName() { // Arrange const string prefixName = "fileInput"; const string expectedFileName = "upload.txt"; var culture = CultureInfo.GetCultureInfo("en-US"); var mockFormFile = new Mock<IFormFile>(); mockFormFile.Setup(x => x.FileName).Returns(expectedFileName); mockFormFile.Setup(x => x.Name).Returns(prefixName); var formFileCollection = new Mock<IFormFileCollection>(); formFileCollection.Setup(x => x.GetFile(prefixName)).Returns(mockFormFile.Object); var buffer = prefixName.ToCharArray().AsMemory(); var reader = new FormDataReader(new Dictionary<FormKey, StringValues>(), culture, buffer, formFileCollection.Object); reader.PushPrefix(prefixName); var converter = new FileConverter<IBrowserFile>(); // Act var result = converter.TryRead(ref reader, typeof(IBrowserFile), default!, out var browserFile, out var found); // Assert Assert.True(result); Assert.True(found); Assert.NotNull(browserFile); Assert.Equal(expectedFileName, browserFile.Name); } [Fact] public void TryRead_IBrowserFileList_ReturnsCorrectFileNames() { // Arrange const string prefixName = "fileInputs"; const string expectedFileName1 = "file1.txt"; const string expectedFileName2 = "file2.jpg"; var culture = CultureInfo.GetCultureInfo("en-US"); var mockFormFile1 = new Mock<IFormFile>(); mockFormFile1.Setup(x => x.FileName).Returns(expectedFileName1); mockFormFile1.Setup(x => x.Name).Returns(prefixName); var mockFormFile2 = new Mock<IFormFile>(); mockFormFile2.Setup(x => x.FileName).Returns(expectedFileName2); mockFormFile2.Setup(x => x.Name).Returns(prefixName); var formFiles = new List<IFormFile> { mockFormFile1.Object, mockFormFile2.Object }; var formFileCollection = new Mock<IFormFileCollection>(); formFileCollection.Setup(x => x.GetFiles(prefixName)).Returns(formFiles); var buffer = prefixName.ToCharArray().AsMemory(); var reader = new FormDataReader(new Dictionary<FormKey, StringValues>(), culture, buffer, formFileCollection.Object); reader.PushPrefix(prefixName); var converter = new FileConverter<IReadOnlyList<IBrowserFile>>(); // Act var result = converter.TryRead(ref reader, typeof(IReadOnlyList<IBrowserFile>), default!, out var browserFiles, out var found); // Assert Assert.True(result); Assert.True(found); Assert.NotNull(browserFiles); Assert.Equal(2, browserFiles.Count); Assert.Equal(expectedFileName1, browserFiles[0].Name); Assert.Equal(expectedFileName2, browserFiles[1].Name); } }
BrowserFileFromFormFileTests
csharp
CommunityToolkit__Maui
samples/CommunityToolkit.Maui.Sample/Pages/Behaviors/UserStoppedTypingBehaviorPage.xaml.cs
{ "start": 116, "end": 402 }
public partial class ____ : BasePage<UserStoppedTypingBehaviorViewModel> { public UserStoppedTypingBehaviorPage(UserStoppedTypingBehaviorViewModel userStoppedTypingBehaviorViewModel) : base(userStoppedTypingBehaviorViewModel) { InitializeComponent(); } }
UserStoppedTypingBehaviorPage
csharp
CommunityToolkit__WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.UI.Controls.Primitives/WrapPanel/WrapPanel.Data.cs
{ "start": 2478, "end": 3361 }
private struct ____ { public Row(List<UvRect> childrenRects, UvMeasure size) { ChildrenRects = childrenRects; Size = size; } public List<UvRect> ChildrenRects { get; } public UvMeasure Size { get; set; } public UvRect Rect => ChildrenRects.Count > 0 ? new UvRect { Position = ChildrenRects[0].Position, Size = Size } : new UvRect { Position = UvMeasure.Zero, Size = Size }; public void Add(UvMeasure position, UvMeasure size) { ChildrenRects.Add(new UvRect { Position = position, Size = size }); Size = new UvMeasure { U = position.U + size.U, V = Math.Max(Size.V, size.V), }; } } } }
Row
csharp
icsharpcode__ILSpy
ICSharpCode.Decompiler/Metadata/LightJson/JsonObject.cs
{ "start": 491, "end": 5357 }
internal sealed class ____ : IEnumerable<KeyValuePair<string, JsonValue>>, IEnumerable<JsonValue> { private IDictionary<string, JsonValue> properties; /// <summary> /// Initializes a new instance of the <see cref="JsonObject"/> class. /// </summary> public JsonObject() { this.properties = new Dictionary<string, JsonValue>(); } /// <summary> /// Gets the number of properties in this JsonObject. /// </summary> /// <value>The number of properties in this JsonObject.</value> public int Count { get { return this.properties.Count; } } /// <summary> /// Gets or sets the property with the given key. /// </summary> /// <param name="key">The key of the property to get or set.</param> /// <remarks> /// The getter will return JsonValue.Null if the given key is not associated with any value. /// </remarks> public JsonValue this[string key] { get { JsonValue value; if (this.properties.TryGetValue(key, out value)) { return value; } else { return JsonValue.Null; } } set { this.properties[key] = value; } } /// <summary> /// Adds a key with a null value to this collection. /// </summary> /// <param name="key">The key of the property to be added.</param> /// <remarks>Returns this JsonObject.</remarks> /// <returns>The <see cref="JsonObject"/> that was added.</returns> public JsonObject Add(string key) { return this.Add(key, JsonValue.Null); } /// <summary> /// Adds a value associated with a key to this collection. /// </summary> /// <param name="key">The key of the property to be added.</param> /// <param name="value">The value of the property to be added.</param> /// <returns>Returns this JsonObject.</returns> public JsonObject Add(string key, JsonValue value) { this.properties.Add(key, value); return this; } /// <summary> /// Removes a property with the given key. /// </summary> /// <param name="key">The key of the property to be removed.</param> /// <returns> /// Returns true if the given key is found and removed; otherwise, false. /// </returns> public bool Remove(string key) { return this.properties.Remove(key); } /// <summary> /// Clears the contents of this collection. /// </summary> /// <returns>Returns this JsonObject.</returns> public JsonObject Clear() { this.properties.Clear(); return this; } /// <summary> /// Changes the key of one of the items in the collection. /// </summary> /// <remarks> /// This method has no effects if the <i>oldKey</i> does not exists. /// If the <i>newKey</i> already exists, the value will be overwritten. /// </remarks> /// <param name="oldKey">The name of the key to be changed.</param> /// <param name="newKey">The new name of the key.</param> /// <returns>Returns this JsonObject.</returns> public JsonObject Rename(string oldKey, string newKey) { if (oldKey == newKey) { // Renaming to the same name just does nothing return this; } JsonValue value; if (this.properties.TryGetValue(oldKey, out value)) { this[newKey] = value; this.Remove(oldKey); } return this; } /// <summary> /// Determines whether this collection contains an item assosiated with the given key. /// </summary> /// <param name="key">The key to locate in this collection.</param> /// <returns>Returns true if the key is found; otherwise, false.</returns> public bool ContainsKey(string key) { return this.properties.ContainsKey(key); } /// <summary> /// Determines whether this collection contains the given JsonValue. /// </summary> /// <param name="value">The value to locate in this collection.</param> /// <returns>Returns true if the value is found; otherwise, false.</returns> public bool Contains(JsonValue value) { return this.properties.Values.Contains(value); } /// <summary> /// Returns an enumerator that iterates through this collection. /// </summary> /// <returns>The enumerator that iterates through this collection.</returns> public IEnumerator<KeyValuePair<string, JsonValue>> GetEnumerator() { return this.properties.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through this collection. /// </summary> /// <returns>The enumerator that iterates through this collection.</returns> IEnumerator<JsonValue> IEnumerable<JsonValue>.GetEnumerator() { return this.properties.Values.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through this collection. /// </summary> /// <returns>The enumerator that iterates through this collection.</returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } [ExcludeFromCodeCoverage]
JsonObject
csharp
dotnetcore__FreeSql
Providers/FreeSql.Provider.MsAccess/Curd/MsAccessSelect.cs
{ "start": 16492, "end": 17062 }
class ____ T4 : class { public MsAccessSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } public override string ToSql(string field = null) => MsAccessSelect<T1>.ToSqlStatic(_commonUtils, _commonExpression, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, this.GetTableRuleUnions(), _aliasRule, _tosqlAppendContent, _whereGlobalFilter, _orm); }
where
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.Email.DataProvider/EmailDataProviderTriggerDetails.cs
{ "start": 318, "end": 1337 }
public partial class ____ { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ internal EmailDataProviderTriggerDetails() { } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::Windows.ApplicationModel.Email.DataProvider.EmailDataProviderConnection Connection { get { throw new global::System.NotImplementedException("The member EmailDataProviderConnection EmailDataProviderTriggerDetails.Connection is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=EmailDataProviderConnection%20EmailDataProviderTriggerDetails.Connection"); } } #endif // Forced skipping of method Windows.ApplicationModel.Email.DataProvider.EmailDataProviderTriggerDetails.Connection.get } }
EmailDataProviderTriggerDetails
csharp
ChilliCream__graphql-platform
src/HotChocolate/Data/src/Data/QueryContextParameterExpressionBuilder.cs
{ "start": 313, "end": 3359 }
internal sealed class ____() : IParameterExpressionBuilder , IParameterBindingFactory , IParameterBinding { private static readonly MethodInfo s_createQueryContext = typeof(QueryContextParameterExpressionBuilder) .GetMethod(nameof(CreateQueryContext), BindingFlags.Static | BindingFlags.NonPublic)!; private static readonly ConcurrentDictionary<Type, FactoryCacheEntry> s_expressionCache = new(); public ArgumentKind Kind => ArgumentKind.Custom; public bool IsPure => false; public bool IsDefaultHandler => false; public bool CanHandle(ParameterInfo parameter) => parameter.ParameterType.IsGenericType && parameter.ParameterType.GetGenericTypeDefinition() == typeof(QueryContext<>); public bool CanHandle(ParameterDescriptor parameter) => parameter.Type.IsGenericType && parameter.Type.GetGenericTypeDefinition() == typeof(QueryContext<>); public Expression Build(ParameterExpressionBuilderContext context) { var resolverContext = context.ResolverContext; var parameterType = context.Parameter.ParameterType; var factoryCacheEntry = s_expressionCache.GetOrAdd( parameterType, type => { var entityType = type.GetGenericArguments()[0]; var factoryMethod = s_createQueryContext.MakeGenericMethod(entityType); var factory = Expression.Call(factoryMethod, resolverContext); return new FactoryCacheEntry(factoryMethod, factory); }); if (factoryCacheEntry.Factory is not null) { return factoryCacheEntry.Factory; } var factory = Expression.Call(factoryCacheEntry.FactoryMethod, resolverContext); s_expressionCache.TryUpdate(parameterType, factoryCacheEntry with { Factory = factory }, factoryCacheEntry); return factory; } public IParameterBinding Create(ParameterDescriptor parameter) => this; public T Execute<T>(IResolverContext context) { var factoryCacheEntry = s_expressionCache.GetOrAdd( typeof(T), type => { var entityType = type.GetGenericArguments()[0]; var factoryMethod = s_createQueryContext.MakeGenericMethod(entityType); return new FactoryCacheEntry(factoryMethod); }); return (T)factoryCacheEntry.FactoryMethod.Invoke(null, [context])!; } private static QueryContext<T> CreateQueryContext<T>(IResolverContext context) { var selection = context.Selection; var filterContext = context.GetFilterContext(); var sortContext = context.GetSortingContext(); return new QueryContext<T>( selection.AsSelector<T>(), filterContext?.AsPredicate<T>(), sortContext?.AsSortDefinition<T>()); }
QueryContextParameterExpressionBuilder
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Platform/AlphaFormat.cs
{ "start": 139, "end": 633 }
public enum ____ { /// <summary> /// All pixels have their alpha premultiplied in their color components. /// </summary> Premul, /// <summary> /// All pixels have their color components stored without any regard to the alpha. e.g. this is the default configuration for PNG images. /// </summary> Unpremul, /// <summary> /// All pixels are stored as opaque. /// </summary> Opaque } }
AlphaFormat
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/NotExpression.cs
{ "start": 179, "end": 354 }
public class ____ : IPredicate { private readonly IPredicate _predicate; /// <summary> /// Initialize a new instance of the <see cref="NotExpression" />
NotExpression
csharp
unoplatform__uno
src/Uno.UI/UI/Xaml/Controls/ScrollPresenter/ScrollPresenterTestHooks.cs
{ "start": 440, "end": 12194 }
internal partial class ____ { private static ScrollPresenterTestHooks s_testHooks; public ScrollPresenterTestHooks() { } private static ScrollPresenterTestHooks EnsureGlobalTestHooks() { return s_testHooks ??= new ScrollPresenterTestHooks(); } internal static bool AreAnchorNotificationsRaised { get { var hooks = EnsureGlobalTestHooks(); return hooks.m_areAnchorNotificationsRaised; } set { var hooks = EnsureGlobalTestHooks(); hooks.m_areAnchorNotificationsRaised = value; } } internal static bool AreInteractionSourcesNotificationsRaised { get { var hooks = EnsureGlobalTestHooks(); return hooks.m_areInteractionSourcesNotificationsRaised; } set { var hooks = EnsureGlobalTestHooks(); hooks.m_areInteractionSourcesNotificationsRaised = value; } } internal static bool AreExpressionAnimationStatusNotificationsRaised { get { var hooks = EnsureGlobalTestHooks(); return hooks.m_areExpressionAnimationStatusNotificationsRaised; } set { var hooks = EnsureGlobalTestHooks(); hooks.m_areExpressionAnimationStatusNotificationsRaised = value; } } internal static bool? IsAnimationsEnabledOverride { get { var hooks = EnsureGlobalTestHooks(); return hooks.m_isAnimationsEnabledOverride; } set { var hooks = EnsureGlobalTestHooks(); hooks.m_isAnimationsEnabledOverride = value; } } internal static void GetOffsetsChangeVelocityParameters(out int millisecondsPerUnit, out int minMilliseconds, out int maxMilliseconds) { var hooks = EnsureGlobalTestHooks(); millisecondsPerUnit = hooks.m_offsetsChangeMsPerUnit; minMilliseconds = hooks.m_offsetsChangeMinMs; maxMilliseconds = hooks.m_offsetsChangeMaxMs; } internal static void SetOffsetsChangeVelocityParameters(int millisecondsPerUnit, int minMilliseconds, int maxMilliseconds) { var hooks = EnsureGlobalTestHooks(); hooks.m_offsetsChangeMsPerUnit = millisecondsPerUnit; hooks.m_offsetsChangeMinMs = minMilliseconds; hooks.m_offsetsChangeMaxMs = maxMilliseconds; } internal static void GetZoomFactorChangeVelocityParameters(out int millisecondsPerUnit, out int minMilliseconds, out int maxMilliseconds) { var hooks = EnsureGlobalTestHooks(); millisecondsPerUnit = hooks.m_zoomFactorChangeMsPerUnit; minMilliseconds = hooks.m_zoomFactorChangeMinMs; maxMilliseconds = hooks.m_zoomFactorChangeMaxMs; } internal static void SetZoomFactorChangeVelocityParameters(int millisecondsPerUnit, int minMilliseconds, int maxMilliseconds) { var hooks = EnsureGlobalTestHooks(); hooks.m_zoomFactorChangeMsPerUnit = millisecondsPerUnit; hooks.m_zoomFactorChangeMinMs = minMilliseconds; hooks.m_zoomFactorChangeMaxMs = maxMilliseconds; } internal static void GetContentLayoutOffsetX(ScrollPresenter scrollPresenter, out float contentLayoutOffsetX) { if (scrollPresenter is not null) { contentLayoutOffsetX = scrollPresenter.GetContentLayoutOffsetX(); } else { contentLayoutOffsetX = 0.0f; } } internal static void SetContentLayoutOffsetX(ScrollPresenter scrollPresenter, float contentLayoutOffsetX) { if (scrollPresenter is not null) { scrollPresenter.SetContentLayoutOffsetX(contentLayoutOffsetX); } } internal static void GetContentLayoutOffsetY(ScrollPresenter scrollPresenter, out float contentLayoutOffsetY) { if (scrollPresenter is not null) { contentLayoutOffsetY = scrollPresenter.GetContentLayoutOffsetY(); } else { contentLayoutOffsetY = 0.0f; } } internal static void SetContentLayoutOffsetY(ScrollPresenter scrollPresenter, float contentLayoutOffsetY) { if (scrollPresenter is not null) { scrollPresenter.SetContentLayoutOffsetY(contentLayoutOffsetY); } } internal static Vector2 GetArrangeRenderSizesDelta(ScrollPresenter scrollPresenter) { if (scrollPresenter is not null) { return scrollPresenter.GetArrangeRenderSizesDelta(); } return new Vector2(0.0f, 0.0f); } internal static Vector2 GetMinPosition(ScrollPresenter scrollPresenter) { if (scrollPresenter is not null) { return scrollPresenter.GetMinPosition(); } return new Vector2(0.0f, 0.0f); } internal static Vector2 GetMaxPosition(ScrollPresenter scrollPresenter) { if (scrollPresenter is not null) { return scrollPresenter.GetMaxPosition(); } return new Vector2(0.0f, 0.0f); } internal static ScrollPresenterViewChangeResult GetScrollCompletedResult(ScrollingScrollCompletedEventArgs scrollCompletedEventArgs) { if (scrollCompletedEventArgs is not null) { ScrollPresenterViewChangeResult result = scrollCompletedEventArgs.Result; return TestHooksViewChangeResult(result); } return ScrollPresenterViewChangeResult.Completed; } internal static ScrollPresenterViewChangeResult GetZoomCompletedResult(ScrollingZoomCompletedEventArgs zoomCompletedEventArgs) { if (zoomCompletedEventArgs is not null) { ScrollPresenterViewChangeResult result = zoomCompletedEventArgs.Result; return TestHooksViewChangeResult(result); } return ScrollPresenterViewChangeResult.Completed; } internal void NotifyAnchorEvaluated( ScrollPresenter sender, UIElement anchorElement, double viewportAnchorPointHorizontalOffset, double viewportAnchorPointVerticalOffset) { var hooks = EnsureGlobalTestHooks(); if (AnchorEvaluated is not null) { var anchorEvaluatedEventArgs = new ScrollPresenterTestHooksAnchorEvaluatedEventArgs( anchorElement, viewportAnchorPointHorizontalOffset, viewportAnchorPointVerticalOffset); AnchorEvaluated.Invoke(sender, anchorEvaluatedEventArgs); } } public static event TypedEventHandler<ScrollPresenter, ScrollPresenterTestHooksAnchorEvaluatedEventArgs> AnchorEvaluated; internal void NotifyInteractionSourcesChanged( ScrollPresenter sender, Microsoft.UI.Composition.Interactions.CompositionInteractionSourceCollection interactionSources) { var hooks = EnsureGlobalTestHooks(); if (InteractionSourcesChanged is not null) { var interactionSourcesChangedEventArgs = new ScrollPresenterTestHooksInteractionSourcesChangedEventArgs( interactionSources); InteractionSourcesChanged.Invoke(sender, interactionSourcesChangedEventArgs); } } public static event TypedEventHandler<ScrollPresenter, ScrollPresenterTestHooksInteractionSourcesChangedEventArgs> InteractionSourcesChanged; internal void NotifyExpressionAnimationStatusChanged( ScrollPresenter sender, bool isExpressionAnimationStarted, string propertyName) { var hooks = EnsureGlobalTestHooks(); if (ExpressionAnimationStatusChanged is not null) { var expressionAnimationStatusChangedEventArgs = new ScrollPresenterTestHooksExpressionAnimationStatusChangedEventArgs( isExpressionAnimationStarted, propertyName); ExpressionAnimationStatusChanged.Invoke(sender, expressionAnimationStatusChangedEventArgs); } } public static event TypedEventHandler<ScrollPresenter, ScrollPresenterTestHooksExpressionAnimationStatusChangedEventArgs> ExpressionAnimationStatusChanged; internal void NotifyContentLayoutOffsetXChanged(ScrollPresenter sender) { var hooks = EnsureGlobalTestHooks(); if (hooks.ContentLayoutOffsetXChanged is not null) { hooks.ContentLayoutOffsetXChanged.Invoke(sender, null); } } public event TypedEventHandler<ScrollPresenter, object> ContentLayoutOffsetXChanged; internal void NotifyContentLayoutOffsetYChanged(ScrollPresenter sender) { var hooks = EnsureGlobalTestHooks(); if (hooks.ContentLayoutOffsetYChanged is not null) { hooks.ContentLayoutOffsetYChanged.Invoke(sender, null); } } public event TypedEventHandler<ScrollPresenter, object> ContentLayoutOffsetYChanged; internal static IList<ScrollSnapPointBase> GetConsolidatedHorizontalScrollSnapPoints(ScrollPresenter scrollPresenter) { if (scrollPresenter is not null) { return scrollPresenter.GetConsolidatedHorizontalScrollSnapPoints(); } else { return new List<ScrollSnapPointBase>(); } } internal static IList<ScrollSnapPointBase> GetConsolidatedVerticalScrollSnapPoints(ScrollPresenter scrollPresenter) { if (scrollPresenter is not null) { return scrollPresenter.GetConsolidatedVerticalScrollSnapPoints(); } else { return new List<ScrollSnapPointBase>(); } } internal static IList<ZoomSnapPointBase> GetConsolidatedZoomSnapPoints(ScrollPresenter scrollPresenter) { if (scrollPresenter is not null) { return scrollPresenter.GetConsolidatedZoomSnapPoints(); } else { return new List<ZoomSnapPointBase>(); } } internal static Vector2 GetHorizontalSnapPointActualApplicableZone( ScrollPresenter scrollPresenter, ScrollSnapPointBase scrollSnapPoint) { if (scrollSnapPoint is not null) { var snapPointWrapper = scrollPresenter.GetHorizontalSnapPointWrapper(scrollSnapPoint); var zone = snapPointWrapper.ActualApplicableZone(); return new Vector2((float)zone.Item1, (float)zone.Item2); } else { return new Vector2(0.0f, 0.0f); } } internal static Vector2 GetVerticalSnapPointActualApplicableZone( ScrollPresenter scrollPresenter, ScrollSnapPointBase scrollSnapPoint) { if (scrollSnapPoint is not null) { var snapPointWrapper = scrollPresenter.GetVerticalSnapPointWrapper(scrollSnapPoint); var zone = snapPointWrapper.ActualApplicableZone(); return new Vector2((float)zone.Item1, (float)zone.Item2); } else { return new Vector2(0.0f, 0.0f); } } internal static Vector2 GetZoomSnapPointActualApplicableZone( ScrollPresenter scrollPresenter, ZoomSnapPointBase zoomSnapPoint) { if (zoomSnapPoint is not null) { var snapPointWrapper = scrollPresenter.GetZoomSnapPointWrapper(zoomSnapPoint); var zone = snapPointWrapper.ActualApplicableZone(); return new Vector2((float)zone.Item1, (float)zone.Item2); } else { return new Vector2(0.0f, 0.0f); } } internal static int GetHorizontalSnapPointCombinationCount( ScrollPresenter scrollPresenter, ScrollSnapPointBase scrollSnapPoint) { if (scrollSnapPoint is not null) { var snapPointWrapper = scrollPresenter.GetHorizontalSnapPointWrapper(scrollSnapPoint); return snapPointWrapper.CombinationCount(); } else { return 0; } } internal static int GetVerticalSnapPointCombinationCount( ScrollPresenter scrollPresenter, ScrollSnapPointBase scrollSnapPoint) { if (scrollSnapPoint is not null) { var snapPointWrapper = scrollPresenter.GetVerticalSnapPointWrapper(scrollSnapPoint); return snapPointWrapper.CombinationCount(); } else { return 0; } } internal static int GetZoomSnapPointCombinationCount( ScrollPresenter scrollPresenter, ZoomSnapPointBase zoomSnapPoint) { if (zoomSnapPoint is not null) { var snapPointWrapper = scrollPresenter.GetZoomSnapPointWrapper(zoomSnapPoint); return snapPointWrapper.CombinationCount(); } else { return 0; } } internal static Color GetSnapPointVisualizationColor(SnapPointBase snapPoint) { #if DEBUG if (snapPoint is not null) { return snapPoint.VisualizationColor; } #endif // DBG return Colors.Black; } internal static void SetSnapPointVisualizationColor(SnapPointBase snapPoint, Color color) { #if DEBUG if (snapPoint is not null) { snapPoint.VisualizationColor = color; } #endif // DBG } private static ScrollPresenterViewChangeResult TestHooksViewChangeResult(ScrollPresenterViewChangeResult result) { switch (result) { case ScrollPresenterViewChangeResult.Ignored: return ScrollPresenterViewChangeResult.Ignored; case ScrollPresenterViewChangeResult.Interrupted: return ScrollPresenterViewChangeResult.Interrupted; default: return ScrollPresenterViewChangeResult.Completed; } } }
ScrollPresenterTestHooks
csharp
dotnet__orleans
test/Grains/TestGrainInterfaces/ISampleStreamingGrain.cs
{ "start": 397, "end": 643 }
public interface ____ : IGrainWithGuidKey { Task BecomeConsumer(Guid streamId, string streamNamespace, string providerToUse); Task StopConsuming(); Task<int> GetNumberConsumed(); }
ISampleStreaming_ConsumerGrain
csharp
MonoGame__MonoGame
MonoGame.Framework/Platform/Native/Graphics.Interop.cs
{ "start": 1058, "end": 1129 }
struct ____ { } [StructLayout(LayoutKind.Sequential)]
MGG_OcclusionQuery
csharp
EventStore__EventStore
src/KurrentDB.TestClient/Program.cs
{ "start": 609, "end": 651 }
internal enum ____ { Csv, Json }
StatsFormat
csharp
SixLabors__ImageSharp
src/ImageSharp/Processing/Processors/Transforms/Linear/AutoOrientProcessor{TPixel}.cs
{ "start": 457, "end": 4462 }
internal class ____<TPixel> : ImageProcessor<TPixel> where TPixel : unmanaged, IPixel<TPixel> { /// <summary> /// Initializes a new instance of the <see cref="AutoOrientProcessor{TPixel}"/> class. /// </summary> /// <param name="configuration">The configuration which allows altering default behaviour or extending the library.</param> /// <param name="source">The source <see cref="Image{TPixel}"/> for the current processor instance.</param> /// <param name="sourceRectangle">The source area to process for the current processor instance.</param> public AutoOrientProcessor(Configuration configuration, Image<TPixel> source, Rectangle sourceRectangle) : base(configuration, source, sourceRectangle) { } /// <inheritdoc/> protected override void BeforeImageApply() { ushort orientation = GetExifOrientation(this.Source); Size size = this.SourceRectangle.Size; switch (orientation) { case ExifOrientationMode.TopRight: new FlipProcessor(FlipMode.Horizontal).Execute(this.Configuration, this.Source, this.SourceRectangle); break; case ExifOrientationMode.BottomRight: new RotateProcessor((int)RotateMode.Rotate180, size).Execute(this.Configuration, this.Source, this.SourceRectangle); break; case ExifOrientationMode.BottomLeft: new FlipProcessor(FlipMode.Vertical).Execute(this.Configuration, this.Source, this.SourceRectangle); break; case ExifOrientationMode.LeftTop: new RotateProcessor((int)RotateMode.Rotate90, size).Execute(this.Configuration, this.Source, this.SourceRectangle); new FlipProcessor(FlipMode.Horizontal).Execute(this.Configuration, this.Source, this.SourceRectangle); break; case ExifOrientationMode.RightTop: new RotateProcessor((int)RotateMode.Rotate90, size).Execute(this.Configuration, this.Source, this.SourceRectangle); break; case ExifOrientationMode.RightBottom: new FlipProcessor(FlipMode.Vertical).Execute(this.Configuration, this.Source, this.SourceRectangle); new RotateProcessor((int)RotateMode.Rotate270, size).Execute(this.Configuration, this.Source, this.SourceRectangle); break; case ExifOrientationMode.LeftBottom: new RotateProcessor((int)RotateMode.Rotate270, size).Execute(this.Configuration, this.Source, this.SourceRectangle); break; case ExifOrientationMode.Unknown: case ExifOrientationMode.TopLeft: default: break; } base.BeforeImageApply(); } /// <inheritdoc/> protected override void OnFrameApply(ImageFrame<TPixel> sourceBase) { // All processing happens at the image level within BeforeImageApply(); } /// <summary> /// Returns the current EXIF orientation /// </summary> /// <param name="source">The image to auto rotate.</param> /// <returns>The <see cref="ushort"/></returns> private static ushort GetExifOrientation(Image<TPixel> source) { if (source.Metadata.ExifProfile is null) { return ExifOrientationMode.Unknown; } if (!source.Metadata.ExifProfile.TryGetValue(ExifTag.Orientation, out IExifValue<ushort>? value)) { return ExifOrientationMode.Unknown; } ushort orientation; if (value.DataType == ExifDataType.Short) { orientation = value.Value; } else { orientation = Convert.ToUInt16(value.Value); source.Metadata.ExifProfile.RemoveValue(ExifTag.Orientation); } source.Metadata.ExifProfile.SetValue(ExifTag.Orientation, ExifOrientationMode.TopLeft); return orientation; } }
AutoOrientProcessor
csharp
cake-build__cake
src/Cake.Common/Tools/OctopusDeploy/OctopusDeployPacker.cs
{ "start": 409, "end": 3795 }
public sealed class ____ : OctopusDeployTool<OctopusPackSettings> { /// <summary> /// Initializes a new instance of the <see cref="OctopusDeployPacker"/> class. /// </summary> /// <param name="fileSystem">The file system.</param> /// <param name="environment">The environment.</param> /// <param name="processRunner">The process runner.</param> /// <param name="tools">The tool locator.</param> public OctopusDeployPacker(IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator tools) : base(fileSystem, environment, processRunner, tools) { } /// <summary> /// Creates an Octopus deploy package with the specified ID. /// </summary> /// <param name="id">The package ID.</param> /// <param name="settings">The settings.</param> public void Pack(string id, OctopusPackSettings settings) { ArgumentNullException.ThrowIfNull(id); var arguments = GetArguments(id, settings); Run(settings, arguments); } private ProcessArgumentBuilder GetArguments(string id, OctopusPackSettings settings) { var builder = new ProcessArgumentBuilder(); builder.Append("pack"); builder.Append($"--id {id}"); if (!string.IsNullOrWhiteSpace(settings.Version)) { builder.AppendSwitch("--version", settings.Version); } if (settings.OutFolder != null) { builder.AppendSwitchQuoted("--outFolder", settings.OutFolder.MakeAbsolute(Environment).FullPath); } if (settings.BasePath != null) { builder.AppendSwitchQuoted("--basePath", settings.BasePath.MakeAbsolute(Environment).FullPath); } if (!string.IsNullOrWhiteSpace(settings.Author)) { builder.AppendSwitchQuoted("--author", settings.Author); } if (!string.IsNullOrWhiteSpace(settings.Title)) { builder.AppendSwitchQuoted("--title", settings.Title); } if (!string.IsNullOrWhiteSpace(settings.Description)) { builder.AppendSwitchQuoted("--description", settings.Description); } if (!string.IsNullOrWhiteSpace(settings.ReleaseNotes)) { builder.AppendSwitchQuoted("--releaseNotes", settings.ReleaseNotes); } if (settings.ReleaseNotesFile != null) { builder.AppendSwitchQuoted("--releaseNotesFile", settings.ReleaseNotesFile.MakeAbsolute(Environment).FullPath); } if (settings.Include != null) { foreach (var include in settings.Include) { builder.AppendSwitchQuoted("--include", include); } } if (settings.Overwrite) { builder.Append("--overwrite"); } if (settings.Format == OctopusPackFormat.Zip) { builder.AppendSwitch("--format", "Zip"); } return builder; } } }
OctopusDeployPacker
csharp
EventStore__EventStore
src/KurrentDB.Core.Tests/Services/ElectionsService/Randomized/elections_service_4_nodes_full_gossip_some_http_loss_some_dup.cs
{ "start": 323, "end": 1136 }
public class ____ { private RandomizedElectionsTestCase _randomCase; [SetUp] public void SetUp() { _randomCase = new RandomizedElectionsTestCase(ElectionParams.MaxIterationCount, instancesCnt: 4, httpLossProbability: 0.3, httpDupProbability: 0.3, httpMaxDelay: 20, timerMinDelay: 100, timerMaxDelay: 200); _randomCase.Init(); } [Test, Category("LongRunning"), Category("Network")] public void should_always_arrive_at_coherent_results([Range(0, ElectionParams.TestRunCount - 1)] int run) { var success = _randomCase.Run(); if (!success) _randomCase.Logger.LogMessages(); Console.WriteLine("There were a total of {0} messages in this run.", _randomCase.Logger.ProcessedItems.Count()); Assert.True(success); } }
elections_service_4_nodes_full_gossip_some_http_loss_some_dup
csharp
ChilliCream__graphql-platform
src/HotChocolate/AspNetCore/src/Transport.Abstractions/OperationResult.cs
{ "start": 324, "end": 515 }
public sealed class ____ : IDisposable { private readonly IDisposable? _memoryOwner; /// <summary> /// Initializes a new instance of the <see cref="OperationResult"/>
OperationResult
csharp
dotnet__efcore
src/ef/Commands/DatabaseDropCommand.Configure.cs
{ "start": 290, "end": 784 }
internal partial class ____ : ContextCommandBase { private CommandOption? _force; private CommandOption? _dryRun; public override void Configure(CommandLineApplication command) { command.Description = Resources.DatabaseDropDescription; _force = command.Option("-f|--force", Resources.DatabaseDropForceDescription); _dryRun = command.Option("--dry-run", Resources.DatabaseDropDryRunDescription); base.Configure(command); } }
DatabaseDropCommand
csharp
FluentValidation__FluentValidation
src/FluentValidation/TestHelper/ITestValidationContinuation.cs
{ "start": 221, "end": 420 }
public interface ____ : IEnumerable<ValidationFailure> { IEnumerable<ValidationFailure> UnmatchedFailures { get; } IEnumerable<ValidationFailure> MatchedFailures { get; } }
ITestValidationContinuation
csharp
icsharpcode__ILSpy
ICSharpCode.Decompiler.Tests/TestCases/Ugly/AggressiveScalarReplacementOfAggregates.Expected.cs
{ "start": 72, "end": 179 }
public class ____ { public Program thisField; public int field1; public string field2; }
DisplayClass
csharp
dotnet__machinelearning
src/Microsoft.ML.FastTree/Training/ScoreTracker.cs
{ "start": 359, "end": 4323 }
internal class ____ { public string DatasetName; public Dataset Dataset; public double[] Scores; protected double[] InitScores; public delegate void ScoresUpdatedDelegate(); public ScoresUpdatedDelegate ScoresUpdated; public ScoreTracker(ScoreTracker s) { DatasetName = s.DatasetName; Dataset = s.Dataset; InitScores = s.InitScores; Scores = (double[])s.Scores.Clone(); } public ScoreTracker(string datasetName, Dataset set, double[] initScores) { Initialize(datasetName, set, initScores); } public void Initialize(string datasetName, Dataset set, double[] initScores) { DatasetName = datasetName; Dataset = set; InitScores = initScores; InitializeScores(initScores); } //Creates linear combination of scores1 + tree * multiplier internal void Initialize(ScoreTracker scores1, InternalRegressionTree tree, DocumentPartitioning partitioning, double multiplier) { InitScores = null; if (Scores == null || Scores.Length != scores1.Scores.Length) { Scores = (double[])scores1.Scores.Clone(); } else { Array.Copy(scores1.Scores, Scores, Scores.Length); } AddScores(tree, partitioning, multiplier); SendScoresUpdatedMessage(); } //InitScores -initScores can be null in such case the scores are reinitialized to Zero private void InitializeScores(double[] initScores) { if (initScores == null) { if (Scores == null) Scores = new double[Dataset.NumDocs]; else Array.Clear(Scores, 0, Scores.Length); } else { if (initScores.Length != Dataset.NumDocs) throw Contracts.Except("The length of initScores do not match the length of training set"); Scores = (double[])initScores.Clone(); } SendScoresUpdatedMessage(); } public virtual void SetScores(double[] scores) { Scores = scores; SendScoresUpdatedMessage(); } public void SendScoresUpdatedMessage() { if (ScoresUpdated != null) ScoresUpdated(); } public void RandomizeScores(int rngSeed, bool reverseRandomization) { Random rndStart = new Random(rngSeed); for (int i = 0; i < Scores.Length; ++i) Scores[i] += 10.0 * rndStart.NextDouble() * (reverseRandomization ? -1.0 : 1.0); SendScoresUpdatedMessage(); } internal virtual void AddScores(InternalRegressionTree tree, double multiplier) { tree.AddOutputsToScores(Dataset, Scores, multiplier); SendScoresUpdatedMessage(); } //Use faster method for score update with Partitioning // suitable for TrainSet internal virtual void AddScores(InternalRegressionTree tree, DocumentPartitioning partitioning, double multiplier) { Parallel.For(0, tree.NumLeaves, new ParallelOptions { MaxDegreeOfParallelism = BlockingThreadPool.NumThreads }, (leaf) => { int[] documents; int begin; int count; partitioning.ReferenceLeafDocuments(leaf, out documents, out begin, out count); double output = tree.LeafValue(leaf) * multiplier; for (int i = begin; i < begin + count; ++i) Scores[documents[i]] += output; }); SendScoresUpdatedMessage(); } } //Accelerated gradient descent score tracker
ScoreTracker
csharp
AutoMapper__AutoMapper
src/UnitTests/Bug/BaseMapWithIncludesAndUnincludedMappings.cs
{ "start": 252, "end": 296 }
public class ____ : ADTO { }
BDTO2
csharp
abpframework__abp
framework/test/Volo.Abp.Json.Tests/Volo/Abp/Json/InputAndOutputDateTimeFormat_Tests.cs
{ "start": 1883, "end": 2062 }
public class ____ { public DateTime DateTime1 { get; set; } public DateTime? DateTime2 { get; set; } } } [Collection("AbpJsonNewtonsoftJsonTest")]
DateTimeDto
csharp
dotnet__machinelearning
src/Microsoft.Data.Analysis/DataFrameColumns/StringDataFrameColumn.cs
{ "start": 561, "end": 22095 }
public partial class ____ : DataFrameColumn, IEnumerable<string> { public static int MaxCapacity = ArrayUtility.ArrayMaxSize / Unsafe.SizeOf<IntPtr>(); // Max Size in bytes / size of pointer (8 bytes on x64) private readonly List<List<string>> _stringBuffers = new List<List<string>>(); // To store more than intMax number of strings public StringDataFrameColumn(string name, long length = 0) : base(name, length, typeof(string)) { int numberOfBuffersRequired = (int)(length / MaxCapacity + 1); for (int i = 0; i < numberOfBuffersRequired; i++) { long bufferLen = length - _stringBuffers.Count * MaxCapacity; List<string> buffer = new List<string>((int)Math.Min(MaxCapacity, bufferLen)); _stringBuffers.Add(buffer); for (int j = 0; j < bufferLen; j++) { buffer.Add(default); } } _nullCount = length; } public StringDataFrameColumn(string name, IEnumerable<string> values) : base(name, 0, typeof(string)) { values = values ?? throw new ArgumentNullException(nameof(values)); if (_stringBuffers.Count == 0) { _stringBuffers.Add(new List<string>()); } foreach (var value in values) { Append(value); } } private long _nullCount; public override long NullCount => _nullCount; protected internal override void Resize(long length) { if (length < Length) throw new ArgumentException(Strings.CannotResizeDown, nameof(length)); for (long i = Length; i < length; i++) { Append(null); } } public void Append(string value) { List<string> lastBuffer = _stringBuffers[_stringBuffers.Count - 1]; if (lastBuffer.Count == MaxCapacity) { lastBuffer = new List<string>(); _stringBuffers.Add(lastBuffer); } lastBuffer.Add(value); if (value == null) _nullCount++; Length++; } /// <summary> /// Applies a function to all values in the column, that are not null. /// </summary> /// <param name="func">The function to apply.</param> /// /// <param name="inPlace">A boolean flag to indicate if the operation should be in place.</param> /// <returns>A new <see cref="PrimitiveDataFrameColumn{T}"/> if <paramref name="inPlace"/> is not set. Returns this column otherwise.</returns> public StringDataFrameColumn Apply(Func<string, string> func, bool inPlace = false) { var column = inPlace ? this : Clone(); for (long i = 0; i < column.Length; i++) { var value = column[i]; if (value != null) column[i] = func(value); } return column; } private int GetBufferIndexContainingRowIndex(long rowIndex) { if (rowIndex >= Length) { throw new ArgumentOutOfRangeException(Strings.IndexIsGreaterThanColumnLength, nameof(rowIndex)); } return (int)(rowIndex / MaxCapacity); } protected override object GetValue(long rowIndex) { int bufferIndex = GetBufferIndexContainingRowIndex(rowIndex); return _stringBuffers[bufferIndex][(int)(rowIndex % MaxCapacity)]; } protected override IReadOnlyList<object> GetValues(long startIndex, int length) { var ret = new List<object>(); int bufferIndex = GetBufferIndexContainingRowIndex(startIndex); int bufferOffset = (int)(startIndex % MaxCapacity); while (ret.Count < length && bufferIndex < _stringBuffers.Count) { for (int i = bufferOffset; ret.Count < length && i < _stringBuffers[bufferIndex].Count; i++) { ret.Add(_stringBuffers[bufferIndex][i]); } bufferIndex++; bufferOffset = 0; } return ret; } protected override void SetValue(long rowIndex, object value) { if (value == null || value is string) { int bufferIndex = GetBufferIndexContainingRowIndex(rowIndex); int bufferOffset = (int)(rowIndex % MaxCapacity); var oldValue = this[rowIndex]; _stringBuffers[bufferIndex][bufferOffset] = (string)value; if (oldValue != (string)value) { if (value == null) _nullCount++; if (oldValue == null && _nullCount > 0) _nullCount--; } } else { throw new ArgumentException(string.Format(Strings.MismatchedValueType, typeof(string)), nameof(value)); } } public new string this[long rowIndex] { get => (string)GetValue(rowIndex); set => SetValue(rowIndex, value); } public new List<string> this[long startIndex, int length] { get { var ret = new List<string>(); int bufferIndex = GetBufferIndexContainingRowIndex(startIndex); int bufferOffset = (int)(startIndex % MaxCapacity); while (ret.Count < length && bufferIndex < _stringBuffers.Count) { for (int i = bufferOffset; ret.Count < length && i < _stringBuffers[bufferIndex].Count; i++) { ret.Add(_stringBuffers[bufferIndex][i]); } bufferIndex++; bufferOffset = 0; } return ret; } } public IEnumerator<string> GetEnumerator() { foreach (List<string> buffer in _stringBuffers) { foreach (string value in buffer) { yield return value; } } } protected override IEnumerator GetEnumeratorCore() => GetEnumerator(); public override DataFrameColumn Clamp<U>(U min, U max, bool inPlace = false) => throw new NotSupportedException(); public override DataFrameColumn Filter<U>(U min, U max) => throw new NotSupportedException(); public new StringDataFrameColumn Sort(bool ascending = true, bool putNullValuesLast = true) { return (StringDataFrameColumn)base.Sort(ascending, putNullValuesLast); } protected internal override PrimitiveDataFrameColumn<long> GetSortIndices(bool ascending, bool putNullValuesLast) { var comparer = Comparer<string>.Default; List<int[]> bufferSortIndices = new List<int[]>(_stringBuffers.Count); var columnNullIndices = new Int64DataFrameColumn("NullIndices", NullCount); long nullIndicesSlot = 0; foreach (List<string> buffer in _stringBuffers) { var sortIndices = new int[buffer.Count]; for (int i = 0; i < buffer.Count; i++) { sortIndices[i] = i; if (buffer[i] == null) { columnNullIndices[nullIndicesSlot] = i + bufferSortIndices.Count * MaxCapacity; nullIndicesSlot++; } } // TODO: Refactor the sort routine to also work with IList? string[] array = buffer.ToArray(); IntrospectiveSort(array, array.Length, sortIndices, comparer); bufferSortIndices.Add(sortIndices); } // Simple merge sort to build the full column's sort indices ValueTuple<string, int> GetFirstNonNullValueStartingAtIndex(int stringBufferIndex, int startIndex) { string value = _stringBuffers[stringBufferIndex][bufferSortIndices[stringBufferIndex][startIndex]]; while (value == null && ++startIndex < bufferSortIndices[stringBufferIndex].Length) { value = _stringBuffers[stringBufferIndex][bufferSortIndices[stringBufferIndex][startIndex]]; } return (value, startIndex); } SortedDictionary<string, List<ValueTuple<int, int>>> heapOfValueAndListOfTupleOfSortAndBufferIndex = new SortedDictionary<string, List<ValueTuple<int, int>>>(comparer); List<List<string>> buffers = _stringBuffers; for (int i = 0; i < buffers.Count; i++) { List<string> buffer = buffers[i]; ValueTuple<string, int> valueAndBufferSortIndex = GetFirstNonNullValueStartingAtIndex(i, 0); if (valueAndBufferSortIndex.Item1 == null) { // All nulls continue; } if (heapOfValueAndListOfTupleOfSortAndBufferIndex.ContainsKey(valueAndBufferSortIndex.Item1)) { heapOfValueAndListOfTupleOfSortAndBufferIndex[valueAndBufferSortIndex.Item1].Add((valueAndBufferSortIndex.Item2, i)); } else { heapOfValueAndListOfTupleOfSortAndBufferIndex.Add(valueAndBufferSortIndex.Item1, new List<ValueTuple<int, int>>() { (valueAndBufferSortIndex.Item2, i) }); } } var columnSortIndices = new Int64DataFrameColumn("SortIndices", Length); GetBufferSortIndex getBufferSortIndex = new GetBufferSortIndex((int bufferIndex, int sortIndex) => (bufferSortIndices[bufferIndex][sortIndex]) + bufferIndex * bufferSortIndices[0].Length); GetValueAndBufferSortIndexAtBuffer<string> getValueAtBuffer = new GetValueAndBufferSortIndexAtBuffer<string>((int bufferIndex, int sortIndex) => GetFirstNonNullValueStartingAtIndex(bufferIndex, sortIndex)); GetBufferLengthAtIndex getBufferLengthAtIndex = new GetBufferLengthAtIndex((int bufferIndex) => bufferSortIndices[bufferIndex].Length); PopulateColumnSortIndicesWithHeap(heapOfValueAndListOfTupleOfSortAndBufferIndex, columnSortIndices, columnNullIndices, ascending, putNullValuesLast, getBufferSortIndex, getValueAtBuffer, getBufferLengthAtIndex); return columnSortIndices; } public new StringDataFrameColumn Clone(DataFrameColumn mapIndices, bool invertMapIndices, long numberOfNullsToAppend) { return (StringDataFrameColumn)CloneImplementation(mapIndices, invertMapIndices, numberOfNullsToAppend); } public new StringDataFrameColumn Clone(long numberOfNullsToAppend = 0) { return (StringDataFrameColumn)CloneImplementation(numberOfNullsToAppend); } protected override DataFrameColumn CloneImplementation(long numberOfNullsToAppend) { StringDataFrameColumn ret = new StringDataFrameColumn(Name, Length); for (long i = 0; i < Length; i++) ret[i] = this[i]; for (long i = 0; i < numberOfNullsToAppend; i++) ret.Append(null); return ret; } protected override DataFrameColumn CloneImplementation(DataFrameColumn mapIndices, bool invertMapIndices = false, long numberOfNullsToAppend = 0) { StringDataFrameColumn clone; if (!(mapIndices is null)) { Type dataType = mapIndices.DataType; if (dataType != typeof(long) && dataType != typeof(int) && dataType != typeof(bool)) throw new ArgumentException(String.Format(Strings.MultipleMismatchedValueType, typeof(long), typeof(int), typeof(bool)), nameof(mapIndices)); if (mapIndices.DataType == typeof(long)) clone = CloneImplementation(mapIndices as PrimitiveDataFrameColumn<long>, invertMapIndices); else if (dataType == typeof(int)) clone = CloneImplementation(mapIndices as PrimitiveDataFrameColumn<int>, invertMapIndices); else clone = CloneImplementation(mapIndices as PrimitiveDataFrameColumn<bool>); for (long i = 0; i < numberOfNullsToAppend; i++) clone.Append(null); } else { clone = Clone(numberOfNullsToAppend); } return clone; } private StringDataFrameColumn CloneImplementation(PrimitiveDataFrameColumn<bool> boolColumn) { if (boolColumn.Length > Length) throw new ArgumentException(Strings.MapIndicesExceedsColumnLength, nameof(boolColumn)); StringDataFrameColumn ret = new StringDataFrameColumn(Name, 0); for (long i = 0; i < boolColumn.Length; i++) { bool? value = boolColumn[i]; if (value.HasValue && value.Value) ret.Append(this[i]); } return ret; } private StringDataFrameColumn CloneImplementation(PrimitiveDataFrameColumn<int> mapIndices, bool invertMapIndices = false) { mapIndices = mapIndices ?? throw new ArgumentNullException(nameof(mapIndices)); var ret = new StringDataFrameColumn(Name, mapIndices.Length); long rowIndex = 0; for (int b = 0; b < mapIndices.ColumnContainer.Buffers.Count; b++) { var span = mapIndices.ColumnContainer.Buffers[b].ReadOnlySpan; var validitySpan = mapIndices.ColumnContainer.NullBitMapBuffers[b].ReadOnlySpan; for (int i = 0; i < span.Length; i++) { long index = invertMapIndices ? mapIndices.Length - 1 - rowIndex : rowIndex; ret[index] = BitUtility.IsValid(validitySpan, i) ? this[span[i]] : null; rowIndex++; } } return ret; } private StringDataFrameColumn CloneImplementation(PrimitiveDataFrameColumn<long> mapIndices, bool invertMapIndices = false) { mapIndices = mapIndices ?? throw new ArgumentNullException(nameof(mapIndices)); var ret = new StringDataFrameColumn(Name, mapIndices.Length); long rowIndex = 0; for (int b = 0; b < mapIndices.ColumnContainer.Buffers.Count; b++) { var span = mapIndices.ColumnContainer.Buffers[b].ReadOnlySpan; var validitySpan = mapIndices.ColumnContainer.NullBitMapBuffers[b].ReadOnlySpan; for (int i = 0; i < span.Length; i++) { long index = invertMapIndices ? mapIndices.Length - 1 - rowIndex : rowIndex; ret[index] = BitUtility.IsValid(validitySpan, i) ? this[span[i]] : null; rowIndex++; } } return ret; } internal static DataFrame ValueCountsImplementation(Dictionary<string, ICollection<long>> groupedValues) { StringDataFrameColumn keys = new StringDataFrameColumn("Values", 0); PrimitiveDataFrameColumn<long> counts = new PrimitiveDataFrameColumn<long>("Counts"); foreach (KeyValuePair<string, ICollection<long>> keyValuePair in groupedValues) { keys.Append(keyValuePair.Key); counts.Append(keyValuePair.Value.Count); } return new DataFrame(new List<DataFrameColumn> { keys, counts }); } public override DataFrame ValueCounts() { Dictionary<string, ICollection<long>> groupedValues = GroupColumnValues<string>(out HashSet<long> _); return ValueCountsImplementation(groupedValues); } public override GroupBy GroupBy(int columnIndex, DataFrame parent) { Dictionary<string, ICollection<long>> dictionary = GroupColumnValues<string>(out HashSet<long> _); return new GroupBy<string>(parent, columnIndex, dictionary); } public override Dictionary<TKey, ICollection<long>> GroupColumnValues<TKey>(out HashSet<long> nullIndices) { if (typeof(TKey) == typeof(string)) { Dictionary<string, ICollection<long>> multimap = new Dictionary<string, ICollection<long>>(EqualityComparer<string>.Default); nullIndices = new HashSet<long>(); for (long i = 0; i < Length; i++) { string str = this[i]; if (str != null) { bool containsKey = multimap.TryGetValue(str, out ICollection<long> values); if (containsKey) { values.Add(i); } else { multimap.Add(str, new List<long>() { i }); } } else { nullIndices.Add(i); } } return multimap as Dictionary<TKey, ICollection<long>>; } else { throw new NotImplementedException(nameof(TKey)); } } /// <summary> /// Returns a new column with <see langword="null" /> elements replaced by <paramref name="value"/>. /// </summary> /// <remarks>Tries to convert value to the column's DataType</remarks> /// <param name="value"></param> /// <param name="inPlace">Indicates if the operation should be performed in place</param> public StringDataFrameColumn FillNulls(string value, bool inPlace = false) { if (value == null) throw new ArgumentNullException(nameof(value)); StringDataFrameColumn column = inPlace ? this : Clone(); for (long i = 0; i < column.Length; i++) { if (column[i] == null) column[i] = value; } return column; } protected override DataFrameColumn FillNullsImplementation(object value, bool inPlace) { if (value is string valueString) return FillNulls(valueString, inPlace); else throw new ArgumentException(String.Format(Strings.MismatchedValueType, typeof(string)), nameof(value)); } /// <inheritdoc/> public new StringDataFrameColumn DropNulls() { return (StringDataFrameColumn)DropNullsImplementation(); } protected override DataFrameColumn DropNullsImplementation() { var ret = new StringDataFrameColumn(Name, Length - NullCount); long j = 0; for (long i = 0; i < Length; i++) { var value = this[i]; if (value != null) { ret[j++] = value; } } return ret; } protected internal override void AddDataViewColumn(DataViewSchema.Builder builder) { builder.AddColumn(Name, TextDataViewType.Instance); } protected internal override Delegate GetDataViewGetter(DataViewRowCursor cursor) { return CreateValueGetterDelegate(cursor); } private ValueGetter<ReadOnlyMemory<char>> CreateValueGetterDelegate(DataViewRowCursor cursor) => (ref ReadOnlyMemory<char> value) => value = this[cursor.Position].AsMemory(); protected internal override void AddValueUsingCursor(DataViewRowCursor cursor, Delegate getter) { long row = cursor.Position; ReadOnlyMemory<char> value = default; Debug.Assert(getter != null, "Excepted getter to be valid"); (getter as ValueGetter<ReadOnlyMemory<char>>)(ref value); if (Length > row) { this[row] = value.ToString(); } else if (Length == row) { Append(value.ToString()); } else { throw new IndexOutOfRangeException(nameof(row)); } } protected internal override Delegate GetValueGetterUsingCursor(DataViewRowCursor cursor, DataViewSchema.Column schemaColumn) { return cursor.GetGetter<ReadOnlyMemory<char>>(schemaColumn); } public override Dictionary<long, ICollection<long>> GetGroupedOccurrences(DataFrameColumn other, out HashSet<long> otherColumnNullIndices) { return GetGroupedOccurrences<string>(other, out otherColumnNullIndices); } } }
StringDataFrameColumn
csharp
dotnet__reactive
Rx.NET/Source/tests/Tests.System.Reactive/Tests/Linq/Observable/UsingTest.cs
{ "start": 504, "end": 10201 }
public class ____ : ReactiveTest { [TestMethod] public void Using_ArgumentChecking() { ReactiveAssert.Throws<ArgumentNullException>(() => Observable.Using(null, DummyFunc<IDisposable, IObservable<int>>.Instance)); ReactiveAssert.Throws<ArgumentNullException>(() => Observable.Using(DummyFunc<IDisposable>.Instance, (Func<IDisposable, IObservable<int>>)null)); ReactiveAssert.Throws</*some*/Exception>(() => Observable.Using(() => DummyDisposable.Instance, d => default(IObservable<int>)).Subscribe()); ReactiveAssert.Throws<ArgumentNullException>(() => Observable.Using(() => DummyDisposable.Instance, d => DummyObservable<int>.Instance).Subscribe(null)); } [TestMethod] public void Using_Null() { var scheduler = new TestScheduler(); var disposeInvoked = 0L; var createInvoked = 0L; var xs = default(ITestableObservable<long>); var disposable = default(MockDisposable); var _d = default(MockDisposable); var res = scheduler.Start(() => Observable.Using( () => { disposeInvoked++; disposable = default; return disposable; }, d => { _d = d; createInvoked++; xs = scheduler.CreateColdObservable( OnNext(100, scheduler.Clock), OnCompleted<long>(200)); return xs; } ) ); Assert.Same(disposable, _d); res.Messages.AssertEqual( OnNext(300, 200L), OnCompleted<long>(400) ); Assert.Equal(1, createInvoked); Assert.Equal(1, disposeInvoked); xs.Subscriptions.AssertEqual( Subscribe(200, 400) ); Assert.Null(disposable); } [TestMethod] public void Using_Complete() { var scheduler = new TestScheduler(); var disposeInvoked = 0; var createInvoked = 0; var xs = default(ITestableObservable<long>); var disposable = default(MockDisposable); var _d = default(MockDisposable); var res = scheduler.Start(() => Observable.Using( () => { disposeInvoked++; disposable = new MockDisposable(scheduler); return disposable; }, d => { _d = d; createInvoked++; xs = scheduler.CreateColdObservable( OnNext(100, scheduler.Clock), OnCompleted<long>(200)); return xs; } ) ); Assert.Same(disposable, _d); res.Messages.AssertEqual( OnNext(300, 200L), OnCompleted<long>(400) ); Assert.Equal(1, createInvoked); Assert.Equal(1, disposeInvoked); xs.Subscriptions.AssertEqual( Subscribe(200, 400) ); disposable.AssertEqual( 200, 400 ); } [TestMethod] public void Using_Error() { var scheduler = new TestScheduler(); var disposeInvoked = 0; var createInvoked = 0; var xs = default(ITestableObservable<long>); var disposable = default(MockDisposable); var _d = default(MockDisposable); var ex = new Exception(); var res = scheduler.Start(() => Observable.Using( () => { disposeInvoked++; disposable = new MockDisposable(scheduler); return disposable; }, d => { _d = d; createInvoked++; xs = scheduler.CreateColdObservable( OnNext(100, scheduler.Clock), OnError<long>(200, ex)); return xs; } ) ); Assert.Same(disposable, _d); res.Messages.AssertEqual( OnNext(300, 200L), OnError<long>(400, ex) ); Assert.Equal(1, createInvoked); Assert.Equal(1, disposeInvoked); xs.Subscriptions.AssertEqual( Subscribe(200, 400) ); disposable.AssertEqual( 200, 400 ); } [TestMethod] public void Using_Dispose() { var scheduler = new TestScheduler(); var disposeInvoked = 0; var createInvoked = 0; var xs = default(ITestableObservable<long>); var disposable = default(MockDisposable); var _d = default(MockDisposable); var res = scheduler.Start(() => Observable.Using( () => { disposeInvoked++; disposable = new MockDisposable(scheduler); return disposable; }, d => { _d = d; createInvoked++; xs = scheduler.CreateColdObservable( OnNext(100, scheduler.Clock), OnNext(1000, scheduler.Clock + 1)); return xs; } ) ); Assert.Same(disposable, _d); res.Messages.AssertEqual( OnNext(300, 200L) ); Assert.Equal(1, createInvoked); Assert.Equal(1, disposeInvoked); xs.Subscriptions.AssertEqual( Subscribe(200, 1000) ); disposable.AssertEqual( 200, 1000 ); } [TestMethod] public void Using_ThrowResourceSelector() { var scheduler = new TestScheduler(); var disposeInvoked = 0; var createInvoked = 0; var ex = new Exception(); var res = scheduler.Start(() => Observable.Using<int, IDisposable>( () => { disposeInvoked++; throw ex; }, d => { createInvoked++; return Observable.Never<int>(); } ) ); res.Messages.AssertEqual( OnError<int>(200, ex) ); Assert.Equal(0, createInvoked); Assert.Equal(1, disposeInvoked); } [TestMethod] public void Using_ThrowResourceUsage() { var scheduler = new TestScheduler(); var ex = new Exception(); var disposeInvoked = 0; var createInvoked = 0; var disposable = default(MockDisposable); var res = scheduler.Start(() => Observable.Using<int, IDisposable>( () => { disposeInvoked++; disposable = new MockDisposable(scheduler); return disposable; }, d => { createInvoked++; throw ex; } ) ); res.Messages.AssertEqual( OnError<int>(200, ex) ); Assert.Equal(1, createInvoked); Assert.Equal(1, disposeInvoked); disposable.AssertEqual( 200, 200 ); } [TestMethod] public void Using_NestedCompleted() { var order = ""; Observable.Using(() => Disposable.Create(() => order += "3"), _ => Observable.Using(() => Disposable.Create(() => order += "2"), __ => Observable.Using(() => Disposable.Create(() => order += "1"), ___ => Observable.Return(Unit.Default)))) .Finally(() => order += "4") .Subscribe(); Assert.Equal("1234", order); } [TestMethod] public void Using_NestedDisposed() { var order = ""; Observable.Using(() => Disposable.Create(() => order += "3"), _ => Observable.Using(() => Disposable.Create(() => order += "2"), __ => Observable.Using(() => Disposable.Create(() => order += "1"), ___ => Observable.Never<Unit>()))) .Finally(() => order += "4") .Subscribe() .Dispose(); Assert.Equal("1234", order); } } }
UsingTest
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.UI.Input/SystemButtonEventController.cs
{ "start": 291, "end": 7478 }
public partial class ____ : global::Windows.UI.Input.AttachableInputObject { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ internal SystemButtonEventController() { } #endif // Forced skipping of method Windows.UI.Input.SystemButtonEventController.SystemFunctionButtonPressed.add // Forced skipping of method Windows.UI.Input.SystemButtonEventController.SystemFunctionButtonPressed.remove // Forced skipping of method Windows.UI.Input.SystemButtonEventController.SystemFunctionButtonReleased.add // Forced skipping of method Windows.UI.Input.SystemButtonEventController.SystemFunctionButtonReleased.remove // Forced skipping of method Windows.UI.Input.SystemButtonEventController.SystemFunctionLockChanged.add // Forced skipping of method Windows.UI.Input.SystemButtonEventController.SystemFunctionLockChanged.remove // Forced skipping of method Windows.UI.Input.SystemButtonEventController.SystemFunctionLockIndicatorChanged.add // Forced skipping of method Windows.UI.Input.SystemButtonEventController.SystemFunctionLockIndicatorChanged.remove #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static global::Windows.UI.Input.SystemButtonEventController CreateForDispatcherQueue(global::Windows.System.DispatcherQueue queue) { throw new global::System.NotImplementedException("The member SystemButtonEventController SystemButtonEventController.CreateForDispatcherQueue(DispatcherQueue queue) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=SystemButtonEventController%20SystemButtonEventController.CreateForDispatcherQueue%28DispatcherQueue%20queue%29"); } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public event global::Windows.Foundation.TypedEventHandler<global::Windows.UI.Input.SystemButtonEventController, global::Windows.UI.Input.SystemFunctionButtonEventArgs> SystemFunctionButtonPressed { [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] add { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Input.SystemButtonEventController", "event TypedEventHandler<SystemButtonEventController, SystemFunctionButtonEventArgs> SystemButtonEventController.SystemFunctionButtonPressed"); } [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] remove { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Input.SystemButtonEventController", "event TypedEventHandler<SystemButtonEventController, SystemFunctionButtonEventArgs> SystemButtonEventController.SystemFunctionButtonPressed"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public event global::Windows.Foundation.TypedEventHandler<global::Windows.UI.Input.SystemButtonEventController, global::Windows.UI.Input.SystemFunctionButtonEventArgs> SystemFunctionButtonReleased { [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] add { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Input.SystemButtonEventController", "event TypedEventHandler<SystemButtonEventController, SystemFunctionButtonEventArgs> SystemButtonEventController.SystemFunctionButtonReleased"); } [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] remove { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Input.SystemButtonEventController", "event TypedEventHandler<SystemButtonEventController, SystemFunctionButtonEventArgs> SystemButtonEventController.SystemFunctionButtonReleased"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public event global::Windows.Foundation.TypedEventHandler<global::Windows.UI.Input.SystemButtonEventController, global::Windows.UI.Input.SystemFunctionLockChangedEventArgs> SystemFunctionLockChanged { [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] add { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Input.SystemButtonEventController", "event TypedEventHandler<SystemButtonEventController, SystemFunctionLockChangedEventArgs> SystemButtonEventController.SystemFunctionLockChanged"); } [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] remove { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Input.SystemButtonEventController", "event TypedEventHandler<SystemButtonEventController, SystemFunctionLockChangedEventArgs> SystemButtonEventController.SystemFunctionLockChanged"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public event global::Windows.Foundation.TypedEventHandler<global::Windows.UI.Input.SystemButtonEventController, global::Windows.UI.Input.SystemFunctionLockIndicatorChangedEventArgs> SystemFunctionLockIndicatorChanged { [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] add { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Input.SystemButtonEventController", "event TypedEventHandler<SystemButtonEventController, SystemFunctionLockIndicatorChangedEventArgs> SystemButtonEventController.SystemFunctionLockIndicatorChanged"); } [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] remove { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Input.SystemButtonEventController", "event TypedEventHandler<SystemButtonEventController, SystemFunctionLockIndicatorChangedEventArgs> SystemButtonEventController.SystemFunctionLockIndicatorChanged"); } } #endif } }
SystemButtonEventController
csharp
dotnet__maui
src/Essentials/samples/Samples/ViewModel/LauncherViewModel.cs
{ "start": 214, "end": 2484 }
public class ____ : BaseViewModel { string fileAttachmentName; string fileAttachmentContents; public string LaunchUri { get; set; } public ICommand LaunchCommand { get; } public ICommand CanLaunchCommand { get; } public ICommand LaunchMailCommand { get; } public ICommand LaunchBrowserCommand { get; } public ICommand LaunchFileCommand { get; } public LauncherViewModel() { LaunchCommand = new Command(OnLaunch); LaunchMailCommand = new Command(OnLaunchMail); LaunchBrowserCommand = new Command(OnLaunchBrowser); CanLaunchCommand = new Command(CanLaunch); LaunchFileCommand = new Command<Microsoft.Maui.Controls.View>(OnFileRequest); } public string FileAttachmentContents { get => fileAttachmentContents; set => SetProperty(ref fileAttachmentContents, value); } public string FileAttachmentName { get => fileAttachmentName; set => SetProperty(ref fileAttachmentName, value); } async void OnLaunchBrowser() { await Launcher.OpenAsync("https://github.com/xamarin/Essentials"); } async void OnLaunch() { try { await Launcher.OpenAsync(LaunchUri); } catch (Exception ex) { await DisplayAlertAsync($"Uri {LaunchUri} could not be launched: {ex}"); } } async void OnLaunchMail() { await Launcher.OpenAsync("mailto:"); } async void CanLaunch() { try { var canBeLaunched = await Launcher.CanOpenAsync(LaunchUri); await DisplayAlertAsync($"Uri {LaunchUri} can be launched: {canBeLaunched}"); } catch (Exception ex) { await DisplayAlertAsync($"Uri {LaunchUri} could not be verified as launchable: {ex}"); } } async void OnFileRequest(Microsoft.Maui.Controls.View element) { if (!string.IsNullOrWhiteSpace(FileAttachmentContents)) { // create a temprary file var fn = string.IsNullOrWhiteSpace(FileAttachmentName) ? "Attachment.txt" : FileAttachmentName.Trim(); var file = Path.Combine(FileSystem.CacheDirectory, fn); File.WriteAllText(file, FileAttachmentContents); var rect = element.GetAbsoluteBounds(); rect.Y += 40; await Launcher.OpenAsync(new OpenFileRequest { File = new ReadOnlyFile(file), PresentationSourceBounds = rect }); } } } }
LauncherViewModel
csharp
microsoft__semantic-kernel
dotnet/test/VectorData/VectorData.ConformanceTests/TypeTests/DataTypeTests.cs
{ "start": 23260, "end": 24061 }
public class ____ : RecordBase { public byte Byte { get; set; } public short Short { get; set; } public int Int { get; set; } public long Long { get; set; } public float Float { get; set; } public double Double { get; set; } public decimal Decimal { get; set; } public string? String { get; set; } public bool Bool { get; set; } public Guid Guid { get; set; } public DateTime DateTime { get; set; } public DateTimeOffset DateTimeOffset { get; set; } #if NET8_0_OR_GREATER public DateOnly DateOnly { get; set; } public TimeOnly TimeOnly { get; set; } #endif public string[] StringArray { get; set; } = null!; public int? NullableInt { get; set; } } }
DefaultRecord
csharp
dotnet__reactive
Rx.NET/Source/src/System.Reactive/TaskObservable.cs
{ "start": 971, "end": 1051 }
public interface ____<out T> : IObservable<T> { // NB: An
ITaskObservable