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
abpframework__abp
framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Entities/Caching/EntityCacheWithoutCacheItem.cs
{ "start": 127, "end": 706 }
public class ____<TEntity, TKey> : EntityCacheBase<TEntity, TEntity, TKey> where TEntity : Entity<TKey> { public EntityCacheWithoutCacheItem( IReadOnlyRepository<TEntity, TKey> repository, IDistributedCache<EntityCacheItemWrapper<TEntity>, TKey> cache, IUnitOfWorkManager unitOfWorkManager) : base(repository, cache, unitOfWorkManager) { } protected override EntityCacheItemWrapper<TEntity>? MapToCacheItem(TEntity? entity) { return new EntityCacheItemWrapper<TEntity>(entity); } }
EntityCacheWithoutCacheItem
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Rendering/Composition/Drawing/ServerResourceHelperExtensions.cs
{ "start": 198, "end": 1847 }
static class ____ { public static IBrush? GetServer(this IBrush? brush, Compositor? compositor) { if (compositor == null) return brush; if (brush == null) return null; if (brush is IImmutableBrush immutable) return immutable; if (brush is ICompositionRenderResource<IBrush> resource) return resource.GetForCompositor(compositor); ThrowNotCompatible(brush); return null; } public static IPen? GetServer(this IPen? pen, Compositor? compositor) { if (compositor == null) return pen; if (pen == null) return null; if (pen is ImmutablePen immutable) return immutable; if (pen is ICompositionRenderResource<IPen> resource) return resource.GetForCompositor(compositor); ThrowNotCompatible(pen); return null; } [MethodImpl(MethodImplOptions.NoInlining), DoesNotReturn] static void ThrowNotCompatible(object o) => throw new InvalidOperationException(o.GetType() + " is not compatible with composition"); public static ITransform? GetServer(this ITransform? transform, Compositor? compositor) { if (compositor == null) return transform; if (transform == null) return null; if (transform is ImmutableTransform immutable) return immutable; if (transform is ICompositionRenderResource<ITransform> resource) resource.GetForCompositor(compositor); return new ImmutableTransform(transform.Value); } }
ServerResourceHelperExtensions
csharp
dotnet__tye
src/Microsoft.Tye.Core/LaunchedServiceBuilder.cs
{ "start": 270, "end": 641 }
public abstract class ____ : ServiceBuilder { public LaunchedServiceBuilder(string name, ServiceSource source) : base(name, source) { } public List<EnvironmentVariableBuilder> EnvironmentVariables { get; } = new List<EnvironmentVariableBuilder>(); public int Replicas { get; set; } = 1; } }
LaunchedServiceBuilder
csharp
abpframework__abp
framework/test/Volo.Abp.Features.Tests/Volo/Abp/Features/FeatureValueProviderManager_Tests.cs
{ "start": 1315, "end": 1731 }
public class ____ : FeatureValueProvider { public const string ProviderName = "D"; public override string Name => ProviderName; public TestDuplicateFeatureValueProvider(IFeatureStore settingStore) : base(settingStore) { } public override Task<string> GetOrNullAsync(FeatureDefinition setting) { throw new NotImplementedException(); } }
TestDuplicateFeatureValueProvider
csharp
AutoMapper__AutoMapper
src/UnitTests/CustomMapping.cs
{ "start": 26063, "end": 26205 }
public class ____ : AutoMapperSpecBase { private Destination _result;
When_specifying_a_custom_constructor_function_for_custom_converters
csharp
MassTransit__MassTransit
src/MassTransit.Abstractions/Contexts/JobContext.cs
{ "start": 1924, "end": 2120 }
public interface ____<out TMessage> : JobContext where TMessage : class { /// <summary> /// The message that initiated the job /// </summary> TMessage Job { get; } }
JobContext
csharp
abpframework__abp
modules/docs/src/Volo.Docs.Application.Contracts/Volo/Docs/DocsRemoteServiceConsts.cs
{ "start": 27, "end": 194 }
public static class ____ { public const string RemoteServiceName = "AbpDocs"; public const string ModuleName = "docs"; } }
DocsRemoteServiceConsts
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/test/Validation.Tests/Types/FurColor.cs
{ "start": 69, "end": 290 }
public class ____ : EnumType { protected override void Configure(IEnumTypeDescriptor descriptor) { descriptor.Value("RED"); descriptor.Value("BLUE"); descriptor.Value("GREEN"); } }
FurColor
csharp
rabbitmq__rabbitmq-dotnet-client
projects/RabbitMQ.Client/IChannelExtensions.cs
{ "start": 1651, "end": 2188 }
class ____.</summary> public static Task<string> BasicConsumeAsync(this IChannel channel, string queue, bool autoAck, IAsyncBasicConsumer consumer, CancellationToken cancellationToken = default) => channel.BasicConsumeAsync(queue: queue, autoAck: autoAck, consumerTag: string.Empty, noLocal: false, exclusive: false, arguments: null, consumer: consumer, cancellationToken); /// <summary>Asynchronously start a Basic content-
consumer
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp/UI/Inputs/IInputType.cs
{ "start": 95, "end": 318 }
public interface ____ { string Name { get; } object this[string key] { get; set; } IDictionary<string, object> Attributes { get; } IValueValidator Validator { get; set; } } }
IInputType
csharp
scriban__scriban
src/Scriban.Tests/ScriptRewriterTests.cs
{ "start": 344, "end": 3166 }
public class ____ { [TestCaseSource(typeof(TestFilesHelper), nameof(TestFilesHelper.ListAllTestFiles))] public void ScriptRewriter_Returns_Original_Script(string inputFileName) { var template = LoadTemplate(inputFileName); var rewriter = new TestCloneScriptRewriter(); var result = rewriter.Visit(template.Page); // The base ScriptRewriter never changes any node, so we should end up with the same instance Assert.AreNotSame(template.Page, result); } [TestCaseSource(typeof(TestFilesHelper), nameof(TestFilesHelper.ListAllTestFiles))] public void LeafCopyScriptRewriter_Returns_Identical_Script(string inputFileName) { var template = LoadTemplate(inputFileName); var rewriter = new TestCloneScriptRewriter(); var result = rewriter.Visit(template.Page); // This rewriter makes copies of leaf nodes instead of returning the original nodes, // so we should end up with another instance identical to the original. Assert.AreNotSame(template.Page, result); Assert.AreEqual(ToText(template.Page), ToText(result)); } private string ToText(ScriptNode node) { var output = new StringBuilder(); var context = new ScriptPrinter(new StringBuilderOutput(output)); context.Write(node); return output.ToString(); } private Template LoadTemplate(string inputName) { var templateSource = TestFilesHelper.LoadTestFile(inputName); var parser = inputName.Contains("500-liquid") ? (Func<string, string, ParserOptions?, LexerOptions?, Template>) Template.ParseLiquid : Template.Parse; var options = new LexerOptions(); if (inputName.Contains("liquid")) { options.Lang = ScriptLang.Liquid; } else if (inputName.Contains("scientific")) { options.Lang = ScriptLang.Scientific; } var template = parser(templateSource, inputName, default, options); if (template.HasErrors || template.Page == null) { if (inputName.Contains("error")) { Assert.Ignore("Template has errors and didn't parse correctly. This is expected for an `error` test."); } else { Console.WriteLine(template.Messages); Assert.Fail("Template has errors and didn't parse correctly. This is not expected."); } } return template; }
ScriptRewriterTests
csharp
dotnet__aspire
src/Aspire.Dashboard/Model/ResourceViewModel.cs
{ "start": 724, "end": 8058 }
public sealed class ____ { private readonly ImmutableArray<HealthReportViewModel> _healthReports = []; private readonly KnownResourceState? _knownState; private Lazy<ImmutableArray<string>>? _cachedAddresses; public required string Name { get; init; } public required string ResourceType { get; init; } public required string DisplayName { get; init; } public required string Uid { get; init; } public required string? State { get; init; } public required string? StateStyle { get; init; } public required DateTime? CreationTimeStamp { get; init; } public required DateTime? StartTimeStamp { get; init; } public required DateTime? StopTimeStamp { get; init; } public required ImmutableArray<EnvironmentVariableViewModel> Environment { get; init; } public required ImmutableArray<UrlViewModel> Urls { get; init; } public required ImmutableArray<VolumeViewModel> Volumes { get; init; } public required ImmutableArray<RelationshipViewModel> Relationships { get; init; } public required ImmutableDictionary<string, ResourcePropertyViewModel> Properties { get; init; } public required ImmutableArray<CommandViewModel> Commands { get; init; } /// <summary>The health status of the resource. <see langword="null"/> indicates that health status is expected but not yet available.</summary> public HealthStatus? HealthStatus { get; private set; } public bool IsHidden { private get; init; } public bool SupportsDetailedTelemetry { get; init; } public string? IconName { get; init; } public IconVariant? IconVariant { get; init; } /// <summary> /// Gets the cached addresses for this resource that can be used for peer matching. /// This includes addresses extracted from URLs, connection strings, and parameter values. /// </summary> public ImmutableArray<string> CachedAddresses => (_cachedAddresses ??= new Lazy<ImmutableArray<string>>(ExtractResourceAddresses)).Value; private ImmutableArray<string> ExtractResourceAddresses() { var addresses = new List<string>(); // Extract addresses from URL endpoints foreach (var service in Urls) { var hostAndPort = service.Url.GetComponents(UriComponents.HostAndPort, UriFormat.UriEscaped); addresses.Add(hostAndPort); } // Extract addresses from connection strings using comprehensive parsing if (Properties.TryGetValue(KnownProperties.Resource.ConnectionString, out var connectionStringProperty) && connectionStringProperty.Value.TryConvertToString(out var connectionString) && ConnectionStringParser.TryDetectHostAndPort(connectionString, out var host, out var port)) { var endpoint = port.HasValue ? $"{host}:{port.Value}" : host; addresses.Add(endpoint); } // Extract addresses from parameter values (for Parameter resources that contain URLs or host:port values) if (Properties.TryGetValue(KnownProperties.Parameter.Value, out var parameterValueProperty) && parameterValueProperty.Value.TryConvertToString(out var parameterValue) && ConnectionStringParser.TryDetectHostAndPort(parameterValue, out var parameterHost, out var parameterPort)) { var parameterEndpoint = parameterPort.HasValue ? $"{parameterHost}:{parameterPort.Value}" : parameterHost; addresses.Add(parameterEndpoint); } return addresses.ToImmutableArray(); } public required ImmutableArray<HealthReportViewModel> HealthReports { get => _healthReports; init { _healthReports = value; HealthStatus = ComputeHealthStatus(value, KnownState); } } public KnownResourceState? KnownState { get => _knownState; init { _knownState = value; HealthStatus = ComputeHealthStatus(_healthReports, value); } } internal bool MatchesFilter(string filter) { // TODO let ResourceType define the additional data values we include in searches return Name.Contains(filter, StringComparisons.UserTextSearch); } public string? GetResourcePropertyValue(string propertyName) { if (Properties.TryGetValue(propertyName, out var value)) { if (value.Value.TryConvertToString(out var s)) { return s; } } return null; } public bool IsResourceHidden(bool showHiddenResources) { if (showHiddenResources) { return false; } return IsHidden || KnownState is KnownResourceState.Hidden; } internal static HealthStatus? ComputeHealthStatus(ImmutableArray<HealthReportViewModel> healthReports, KnownResourceState? state) { if (state != KnownResourceState.Running) { return null; } return healthReports.Length == 0 // If there are no health reports and the resource is running, assume it's healthy. ? Microsoft.Extensions.Diagnostics.HealthChecks.HealthStatus.Healthy // If there are health reports, the health status is the minimum of the health status of the reports. // If any of the reports is null (first health check has not returned), the health status is unhealthy. : healthReports.MinBy(r => r.HealthStatus)?.HealthStatus ?? Microsoft.Extensions.Diagnostics.HealthChecks.HealthStatus.Unhealthy; } public static string GetResourceName(ResourceViewModel resource, IDictionary<string, ResourceViewModel> allResources, bool showHiddenResources = false) { return GetResourceName(resource, allResources.Values); } public static string GetResourceName(ResourceViewModel resource, IEnumerable<ResourceViewModel> allResources, bool showHiddenResources = false) { var count = 0; foreach (var item in allResources) { if (item.IsResourceHidden(showHiddenResources)) { continue; } if (string.Equals(item.DisplayName, resource.DisplayName, StringComparisons.ResourceName)) { count++; if (count >= 2) { // There are multiple resources with the same display name so they're part of a replica set. // Need to use the name which has a unique ID to tell them apart. return resource.Name; } } } return resource.DisplayName; } public static bool TryGetResourceByName(string resourceName, IDictionary<string, ResourceViewModel> resourceByName, [NotNullWhen(true)] out ResourceViewModel? resource) { if (resourceByName.TryGetValue(resourceName, out resource)) { return true; } var resourcesWithDisplayName = resourceByName.Values.Where(r => string.Equals(resourceName, r.DisplayName, StringComparisons.ResourceName)).ToList(); if (resourcesWithDisplayName.Count == 1) { resource = resourcesWithDisplayName.Single(); return true; } return false; } }
ResourceViewModel
csharp
MassTransit__MassTransit
src/MassTransit/Serialization/EnvelopeMessageContext.cs
{ "start": 99, "end": 2582 }
public class ____ : MessageContext { readonly MessageEnvelope _envelope; readonly IObjectDeserializer _objectDeserializer; Guid? _conversationId; Guid? _correlationId; Uri? _destinationAddress; Uri? _faultAddress; Headers? _headers; Guid? _initiatorId; Guid? _messageId; Guid? _requestId; Uri? _responseAddress; Uri? _sourceAddress; public EnvelopeMessageContext(MessageEnvelope envelope, IObjectDeserializer objectDeserializer) { _envelope = envelope; _objectDeserializer = objectDeserializer; } public Guid? MessageId => _messageId ??= ConvertIdToGuid(_envelope.MessageId); public Guid? RequestId => _requestId ??= ConvertIdToGuid(_envelope.RequestId); public Guid? CorrelationId => _correlationId ??= ConvertIdToGuid(_envelope.CorrelationId); public Guid? ConversationId => _conversationId ??= ConvertIdToGuid(_envelope.ConversationId); public Guid? InitiatorId => _initiatorId ??= ConvertIdToGuid(_envelope.InitiatorId); public DateTime? ExpirationTime => _envelope.ExpirationTime; public Uri? SourceAddress => _sourceAddress ??= ConvertToUri(_envelope.SourceAddress); public Uri? DestinationAddress => _destinationAddress ??= ConvertToUri(_envelope.DestinationAddress); public Uri? ResponseAddress => _responseAddress ??= ConvertToUri(_envelope.ResponseAddress); public Uri? FaultAddress => _faultAddress ??= ConvertToUri(_envelope.FaultAddress); public DateTime? SentTime => _envelope.SentTime; public Headers Headers => _headers ??= GetHeaders(); public HostInfo Host => _envelope.Host ?? HostMetadataCache.Empty; Headers GetHeaders() { return _envelope.Headers != null ? new ReadOnlyDictionaryHeaders(_objectDeserializer, _envelope.Headers) : EmptyHeaders.Instance; } static Guid? ConvertIdToGuid(string? id) { if (string.IsNullOrWhiteSpace(id)) return default; if (Guid.TryParse(id, out var messageId)) return messageId; throw new FormatException("The Id was not a Guid: " + id); } static Uri? ConvertToUri(string? uri) { return string.IsNullOrWhiteSpace(uri) ? null : new Uri(uri); } } }
EnvelopeMessageContext
csharp
dotnet__aspnetcore
src/Http/Http.Abstractions/src/Extensions/MapWhenExtensions.cs
{ "start": 396, "end": 1513 }
public static class ____ { /// <summary> /// Branches the request pipeline based on the result of the given predicate. /// </summary> /// <param name="app"></param> /// <param name="predicate">Invoked with the request environment to determine if the branch should be taken</param> /// <param name="configuration">Configures a branch to take</param> /// <returns></returns> public static IApplicationBuilder MapWhen(this IApplicationBuilder app, Predicate predicate, Action<IApplicationBuilder> configuration) { ArgumentNullException.ThrowIfNull(app); ArgumentNullException.ThrowIfNull(predicate); ArgumentNullException.ThrowIfNull(configuration); // create branch var branchBuilder = app.New(); configuration(branchBuilder); var branch = branchBuilder.Build(); // put middleware in pipeline var options = new MapWhenOptions { Predicate = predicate, Branch = branch, }; return app.Use(next => new MapWhenMiddleware(next, options).Invoke); } }
MapWhenExtensions
csharp
dotnet__maui
src/Graphics/src/Graphics/ITextAttributes.cs
{ "start": 148, "end": 928 }
public interface ____ { /// <summary> /// Gets or sets the font used for rendering text. /// </summary> IFont Font { get; set; } /// <summary> /// Gets or sets the size of the font in points. /// </summary> float FontSize { get; set; } /// <summary> /// Gets or sets the margin around the text. /// </summary> float Margin { get; set; } /// <summary> /// Gets or sets the color of the text. /// </summary> Color TextFontColor { get; set; } /// <summary> /// Gets or sets the horizontal alignment of the text. /// </summary> HorizontalAlignment HorizontalAlignment { get; set; } /// <summary> /// Gets or sets the vertical alignment of the text. /// </summary> VerticalAlignment VerticalAlignment { get; set; } } }
ITextAttributes
csharp
dotnet__BenchmarkDotNet
tests/BenchmarkDotNet.Tests/Attributes/ParamsAllValuesVerifyTests.cs
{ "start": 3864, "end": 4177 }
public class ____ { [ParamsAllValues] public int? ParamProperty { get; set; } [Benchmark] public void Benchmark() { } } #pragma warning restore BDN1304 #pragma warning disable BDN1303
WithNotAllowedNullableTypeError
csharp
microsoft__PowerToys
src/modules/cmdpal/ext/Microsoft.CmdPal.Ext.Shell/Icons.cs
{ "start": 276, "end": 654 }
internal sealed class ____ { internal static IconInfo RunV2Icon { get; } = IconHelpers.FromRelativePath("Assets\\Run.svg"); internal static IconInfo FolderIcon { get; } = new IconInfo("📁"); internal static IconInfo AdminIcon { get; } = new IconInfo("\xE7EF"); // Admin Icon internal static IconInfo UserIcon { get; } = new IconInfo("\xE7EE"); // User Icon }
Icons
csharp
dotnet__maui
src/Core/src/Dispatching/Dispatcher.iOS.cs
{ "start": 2149, "end": 2605 }
public partial class ____ { static Dispatcher? GetForCurrentThreadImplementation() { #pragma warning disable BI1234, CA1416, CA1422 // Type or member is obsolete, has [UnsupportedOSPlatform("ios6.0")], deprecated but still works var q = DispatchQueue.CurrentQueue; #pragma warning restore BI1234, CA1416, CA1422 // Type or member is obsolete if (q != DispatchQueue.MainQueue) return null; return new Dispatcher(q); } } }
DispatcherProvider
csharp
microsoft__garnet
libs/common/RespStrings.cs
{ "start": 122, "end": 1170 }
public class ____ { public static ReadOnlySpan<byte> EMPTYARRAY => "*0\r\n"u8; public static ReadOnlySpan<byte> EMPTYSET => "~0\r\n"u8; public static ReadOnlySpan<byte> EMPTYMAP => "%0\r\n"u8; public static ReadOnlySpan<byte> INFINITY => "INF"u8; public static ReadOnlySpan<byte> POS_INFINITY => "+INF"u8; public static ReadOnlySpan<byte> NEG_INFINITY => "-INF"u8; public static ReadOnlySpan<byte> INTEGERZERO => ":0\r\n"u8; public static ReadOnlySpan<byte> INTEGERONE => ":1\r\n"u8; public static ReadOnlySpan<byte> RESP2_NULLARRAY => "*-1\r\n"u8; public static ReadOnlySpan<byte> RESP2_NULLBULK => "$-1\r\n"u8; public static ReadOnlySpan<byte> RESP3_NULL => "_\r\n"u8; public static ReadOnlySpan<byte> RESP3_FALSE => "#f\r\n"u8; public static ReadOnlySpan<byte> RESP3_TRUE => "#t\r\n"u8; public static ReadOnlySpan<byte> VerbatimMarkdown => "mkd"u8; public static ReadOnlySpan<byte> VerbatimTxt => "txt"u8; } }
RespStrings
csharp
dotnet__efcore
test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs
{ "start": 160080, "end": 160297 }
public class ____ { public int Id { get; set; } public RelatedEntity738 ParentEntity { get; set; } public IEnumerable<RelatedEntity740> ChildEntities { get; set; } }
RelatedEntity739
csharp
FastEndpoints__FastEndpoints
Src/Security/JwtCreationOptions.cs
{ "start": 347, "end": 3604 }
class ____ JwtCreationOptions(JwtCreationOptions? globalInstance) { if (globalInstance is null) return; SigningKey = globalInstance.SigningKey; SigningStyle = globalInstance.SigningStyle; SigningAlgorithm = globalInstance.SigningAlgorithm; KeyIsPemEncoded = globalInstance.KeyIsPemEncoded; AsymmetricKidGenerator = globalInstance.AsymmetricKidGenerator; Audience = globalInstance.Audience; Issuer = globalInstance.Issuer; CompressionAlgorithm = globalInstance.CompressionAlgorithm; //NOTE: // we're skipping ExpireAt and User properties because they need to set by the user everytime a token is created. // without this kind of cloning, the global instance would be used everywhere causing issues. } /// <summary> /// the key used to sign jwts symmetrically or the base64 encoded private-key when jwts are signed asymmetrically. /// </summary> /// <remarks>the key can be in PEM format. make sure to set <see cref="KeyIsPemEncoded" /> to <c>true</c> if the key is PEM encoded.</remarks> public string SigningKey { get; set; } = default!; /// <summary> /// specifies how tokens are to be signed. symmetrically or asymmetrically. /// </summary> /// <remarks>don't forget to set an appropriate <see cref="SigningAlgorithm" /> if changing to <see cref="TokenSigningStyle.Symmetric" /></remarks> public TokenSigningStyle SigningStyle { get; set; } = TokenSigningStyle.Symmetric; /// <summary> /// security algorithm used to sign keys. /// </summary> /// <remarks> /// defaults to HmacSha256 for symmetric keys. don't forget to set an appropriate algorithm when changing <see cref="SigningStyle" /> to /// <see cref="TokenSigningStyle.Asymmetric" /> /// </remarks> public string SigningAlgorithm { get; set; } = SecurityAlgorithms.HmacSha256; /// <summary> /// specifies whether the key is pem encoded. /// </summary> public bool KeyIsPemEncoded { get; set; } #pragma warning disable CS1574 /// <summary> /// if specified, this function will be used to generate a <c>kid</c> for asymmetric key generation. /// the <c>string</c> value returned from this function will be set on the <see cref="RsaSecurityKey" />.<see cref="RsaSecurityKey.KeyId" /> property. /// </summary> public Func<RSA, string>? AsymmetricKidGenerator { get; set; } /// <summary> /// specify the privileges of the user /// NOTE: this should be specified at the time of jwt creation. /// </summary> public UserPrivileges User { get; } = new(); /// <summary> /// the value for the 'audience' claim. /// </summary> public string? Audience { get; set; } /// <summary> /// the issuer /// </summary> public string? Issuer { get; set; } /// <summary> /// the value of the 'expiration' claim. should be in utc. /// NOTE: this should be set at the time of token creation. /// </summary> public DateTime? ExpireAt { get; set; } /// <summary> /// the compression algorithm compressing the token payload. /// </summary> public string? CompressionAlgorithm { get; set; } }
internal
csharp
dotnet__aspnetcore
src/Mvc/Mvc.Core/src/RequestSizeLimitAttribute.cs
{ "start": 503, "end": 2150 }
public class ____ : Attribute, IFilterFactory, IOrderedFilter, IRequestSizeLimitMetadata { private readonly long _bytes; /// <summary> /// Creates a new instance of <see cref="RequestSizeLimitAttribute"/>. /// </summary> /// <param name="bytes">The request body size limit.</param> public RequestSizeLimitAttribute(long bytes) { _bytes = bytes; } /// <summary> /// Gets the order value for determining the order of execution of filters. Filters execute in /// ascending numeric value of the <see cref="Order"/> property. /// </summary> /// <remarks> /// <para> /// Filters are executed in an ordering determined by an ascending sort of the <see cref="Order"/> property. /// </para> /// <para> /// The default Order for this attribute is 900 because it must run before ValidateAntiForgeryTokenAttribute and /// after any filter which does authentication or login in order to allow them to behave as expected (ie Unauthenticated or Redirect instead of 400). /// </para> /// <para> /// Look at <see cref="IOrderedFilter.Order"/> for more detailed info. /// </para> /// </remarks> public int Order { get; set; } = 900; /// <inheritdoc /> public bool IsReusable => true; /// <inheritdoc /> public IFilterMetadata CreateInstance(IServiceProvider serviceProvider) { var filter = serviceProvider.GetRequiredService<RequestSizeLimitFilter>(); filter.Bytes = _bytes; return filter; } /// <inheritdoc /> long? IRequestSizeLimitMetadata.MaxRequestBodySize => _bytes; }
RequestSizeLimitAttribute
csharp
dotnet__orleans
test/Orleans.CodeGenerator.Tests/snapshots/OrleansSourceGeneratorTests.TestBasicClassWithInitOnlyProperty.verified.cs
{ "start": 8232, "end": 8843 }
internal sealed class ____ : global::Orleans.Serialization.Configuration.TypeManifestProviderBase { protected override void ConfigureInner(global::Orleans.Serialization.Configuration.TypeManifestOptions config) { config.Serializers.Add(typeof(OrleansCodeGen.TestProject.Codec_DemoDataWithInitOnly)); config.Copiers.Add(typeof(OrleansCodeGen.TestProject.Copier_DemoDataWithInitOnly)); config.Activators.Add(typeof(OrleansCodeGen.TestProject.Activator_DemoDataWithInitOnly)); } } } #pragma warning restore CS1591, RS0016, RS0041
Metadata_TestProject
csharp
MassTransit__MassTransit
tests/MassTransit.RabbitMqTransport.Tests/OutboxFault_Specs.cs
{ "start": 2613, "end": 3114 }
class ____<T> : IFilter<SendContext<T>> where T : class { public Task Send(SendContext<T> context, IPipe<SendContext<T>> next) { // if (context.Message is SomeInstanceEvent { Count: 2 }) // context.Serializer = new DeathComesMeSerializer(); return next.Send(context); } public void Probe(ProbeContext context) { } }
SomeSendFilter
csharp
protobuf-net__protobuf-net
src/Examples/Remoting/RemotingDemo.cs
{ "start": 3790, "end": 9793 }
public class ____ { [Fact] [Ignore("small messages known to be slower")] public void SmallPayload() { AppDomain app = AppDomain.CreateDomain("Isolated", null, AppDomain.CurrentDomain.BaseDirectory, AppDomain.CurrentDomain.RelativeSearchPath, false); try { // create a server and two identical messages Server local = new Server(), remote = (Server)app.CreateInstanceAndUnwrap(typeof(Server).Assembly.FullName, typeof(Server).FullName); RegularFragment frag1 = new RegularFragment { Foo = 27, Bar = 123.45F }; Serializer.PrepareSerializer<ProtoFragment>(); ProtoFragment frag2 = new ProtoFragment { Foo = frag1.Foo, Bar = frag1.Bar }; // verify basic transport RegularFragment localFrag1 = local.SomeMethod1(frag1), remoteFrag1 = remote.SomeMethod1(frag1); ProtoFragment localFrag2 = local.SomeMethod2(frag2), remoteFrag2 = remote.SomeMethod2(frag2); Assert.NotSame(localFrag1, remoteFrag1); Assert.NotSame(localFrag2, remoteFrag2); Assert.Equal(localFrag1.Foo, remoteFrag1.Foo); Assert.Equal(localFrag1.Bar, remoteFrag1.Bar); Assert.Equal(localFrag2.Foo, remoteFrag2.Foo); Assert.Equal(localFrag2.Bar, remoteFrag2.Bar); Assert.Equal(localFrag1.Foo, localFrag2.Foo); Assert.Equal(localFrag1.Bar, localFrag2.Bar); const int LOOP = 5000; Stopwatch regWatch = Stopwatch.StartNew(); for (int i = 0; i < LOOP; i++) { remoteFrag1 = remote.SomeMethod1(remoteFrag1); } regWatch.Stop(); Stopwatch protoWatch = Stopwatch.StartNew(); for (int i = 0; i < LOOP; i++) { remoteFrag2 = remote.SomeMethod2(remoteFrag2); } protoWatch.Stop(); Assert.True(3 <= 5); //, "just checking..."); Assert.True(protoWatch.ElapsedMilliseconds <= regWatch.ElapsedMilliseconds); } finally { AppDomain.Unload(app); } } [Fact] public void TestRawSerializerPerformance() { RegularFragment frag1 = new RegularFragment { Foo = 27, Bar = 123.45F }; ProtoFragment frag2 = new ProtoFragment { Foo = frag1.Foo, Bar = frag1.Bar }; Type regular = typeof(RegularFragment), proto = typeof(ProtoFragment); var model = RuntimeTypeModel.Create(); model.AutoAddMissingTypes = false; model.Add(typeof(ProtoFragment), true); const int LOOP = 10000; Roundtrip(() => new BinaryFormatter(), LOOP, (ser, dest) => ser.Serialize(dest, frag1), (ser, src) => ser.Deserialize(src)); Roundtrip("BinaryFormatter via pb-net", () => new BinaryFormatter(), LOOP, (ser, dest) => ser.Serialize(dest, frag2), (ser, src) => ser.Deserialize(src)); Roundtrip(() => model, LOOP, (ser, dest) => ser.Serialize(dest, frag2), (ser, src) => ser.Deserialize(src, null, proto)); Roundtrip(() => new XmlSerializer(proto), LOOP, (ser, dest) => ser.Serialize(dest, frag2), (ser, src) => ser.Deserialize(src)); Roundtrip(() => new DataContractSerializer(regular), LOOP, (ser, dest) => ser.WriteObject(dest, frag1), (ser, src) => ser.ReadObject(src)); Roundtrip(() => new NetDataContractSerializer(), LOOP, (ser, dest) => ser.Serialize(dest, frag1), (ser, src) => ser.Deserialize(src)); model.CompileInPlace(); Roundtrip("CompileInPlace", () => model, LOOP * 50, (ser, dest) => ser.Serialize(dest, frag2), (ser, src) => ser.Deserialize(src, null, proto)); Roundtrip("Compile", () => model.Compile(), LOOP * 50, (ser, dest) => ser.Serialize(dest, frag2), (ser, src) => ser.Deserialize(src, null, proto)); } static void Roundtrip<T>(Func<T> ctor, int loop, Action<T, Stream> write, Func<T, Stream, object> read) where T : class { Roundtrip(typeof(T).Name, ctor, loop, write, read); } static void Roundtrip<T>(string caption, Func<T> ctor, int loop, Action<T, Stream> write, Func<T, Stream, object> read) where T : class { T ser = ctor(); using (MemoryStream ms = new MemoryStream()) { write(ser, ms); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); Stopwatch writeWatch = Stopwatch.StartNew(); for (int i = 0; i < loop; i++) { ms.SetLength(0); write(ser, ms); } writeWatch.Stop(); ms.Position = 0; read(ser, ms); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); Stopwatch readWatch = Stopwatch.StartNew(); for (int i = 0; i < loop; i++) { ms.Position = 0; read(ser, ms); } readWatch.Stop(); Console.WriteLine("{0}:\tread: {1}μs/item; write: {2}μs/item; bytes: {3})", caption, (readWatch.ElapsedMilliseconds * 1000.0) / loop, (writeWatch.ElapsedMilliseconds * 1000.0) / loop, ms.Length); } } } } #endif
RemotingDemo
csharp
abpframework__abp
modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/Claims/AbpDefaultOpenIddictClaimsPrincipalHandler.cs
{ "start": 329, "end": 3561 }
public class ____ : IAbpOpenIddictClaimsPrincipalHandler, ITransientDependency { public virtual Task HandleAsync(AbpOpenIddictClaimsPrincipalHandlerContext context) { var securityStampClaimType = context .ScopeServiceProvider .GetRequiredService<IOptions<IdentityOptions>>().Value .ClaimsIdentity.SecurityStampClaimType; foreach (var claim in context.Principal.Claims) { if (claim.Type == AbpClaimTypes.TenantId) { claim.SetDestinations(OpenIddictConstants.Destinations.AccessToken, OpenIddictConstants.Destinations.IdentityToken); continue; } if (claim.Type == AbpClaimTypes.SessionId) { claim.SetDestinations(OpenIddictConstants.Destinations.AccessToken, OpenIddictConstants.Destinations.IdentityToken); continue; } switch (claim.Type) { case OpenIddictConstants.Claims.PreferredUsername: claim.SetDestinations(OpenIddictConstants.Destinations.AccessToken); if (context.Principal.HasScope(OpenIddictConstants.Scopes.Profile)) { claim.SetDestinations(OpenIddictConstants.Destinations.AccessToken, OpenIddictConstants.Destinations.IdentityToken); } break; case JwtRegisteredClaimNames.UniqueName: claim.SetDestinations(OpenIddictConstants.Destinations.AccessToken); if (context.Principal.HasScope(OpenIddictConstants.Scopes.Profile)) { claim.SetDestinations(OpenIddictConstants.Destinations.AccessToken, OpenIddictConstants.Destinations.IdentityToken); } break; case OpenIddictConstants.Claims.Email: claim.SetDestinations(OpenIddictConstants.Destinations.AccessToken); if (context.Principal.HasScope(OpenIddictConstants.Scopes.Email)) { claim.SetDestinations(OpenIddictConstants.Destinations.AccessToken, OpenIddictConstants.Destinations.IdentityToken); } break; case OpenIddictConstants.Claims.Role: claim.SetDestinations(OpenIddictConstants.Destinations.AccessToken); if (context.Principal.HasScope(OpenIddictConstants.Scopes.Roles)) { claim.SetDestinations(OpenIddictConstants.Destinations.AccessToken, OpenIddictConstants.Destinations.IdentityToken); } break; default: // Never include the security stamp in the access and identity tokens, as it's a secret value. if (claim.Type != securityStampClaimType) { claim.SetDestinations(OpenIddictConstants.Destinations.AccessToken); } break; } } return Task.CompletedTask; } }
AbpDefaultOpenIddictClaimsPrincipalHandler
csharp
smartstore__Smartstore
src/Smartstore/Engine/Modularity/IProvider.cs
{ "start": 98, "end": 147 }
interface ____ a provider /// </summary>
for
csharp
dotnet__aspnetcore
src/Components/Endpoints/src/FormMapping/Converters/DictionaryAdapters/ImmutableSortedDictionaryBufferAdapter.cs
{ "start": 241, "end": 1000 }
internal sealed class ____<TKey, TValue> : IDictionaryBufferAdapter<ImmutableSortedDictionary<TKey, TValue>, ImmutableSortedDictionary<TKey, TValue>.Builder, TKey, TValue> where TKey : IParsable<TKey> { public static ImmutableSortedDictionary<TKey, TValue>.Builder Add(ref ImmutableSortedDictionary<TKey, TValue>.Builder buffer, TKey key, TValue value) { buffer.Add(key, value); return buffer; } public static ImmutableSortedDictionary<TKey, TValue>.Builder CreateBuffer() => ImmutableSortedDictionary.CreateBuilder<TKey, TValue>(); public static ImmutableSortedDictionary<TKey, TValue> ToResult(ImmutableSortedDictionary<TKey, TValue>.Builder buffer) => buffer.ToImmutable(); }
ImmutableSortedDictionaryBufferAdapter
csharp
xunit__xunit
src/xunit.v3.runner.utility.tests/Frameworks/v2/Xunit2AcceptanceTests.cs
{ "start": 9030, "end": 9830 }
public class ____ { [Fact] public async ValueTask NoTestMethods() { using var assembly = await CSharpAcceptanceTestV2Assembly.Create(code: ""); var controller = TestableXunit2.Create(assembly.FileName, null, true); var settings = new FrontControllerFindAndRunSettings(TestData.TestFrameworkDiscoveryOptions(), TestData.TestFrameworkExecutionOptions()); using var sink = SpyMessageSink<ITestAssemblyFinished>.Create(); controller.FindAndRun(sink, settings); sink.Finished.WaitOne(); Assert.Empty(sink.Messages.OfType<ITestPassed>()); Assert.Empty(sink.Messages.OfType<ITestFailed>()); Assert.Empty(sink.Messages.OfType<ITestSkipped>()); } [Fact] public async ValueTask DoesNotRunTestsWhenExplicitOnly() { var code = @" using System; using Xunit;
FindAndRun
csharp
microsoft__PowerToys
src/modules/PowerOCR/PowerOCR/Models/ResultTable.cs
{ "start": 487, "end": 21799 }
public class ____ { public List<ResultColumn> Columns { get; set; } = new(); public List<ResultRow> Rows { get; set; } = new(); public Rect BoundingRect { get; set; } public List<int> ColumnLines { get; set; } = new(); public List<int> RowLines { get; set; } = new(); public Canvas? TableLines { get; set; } public ResultTable(ref List<WordBorder> wordBorders, DpiScale dpiScale) { int borderBuffer = 3; var leftsMin = wordBorders.Select(x => x.Left).Min(); var topsMin = wordBorders.Select(x => x.Top).Min(); var rightsMax = wordBorders.Select(x => x.Right).Max(); var bottomsMax = wordBorders.Select(x => x.Bottom).Max(); Rectangle bordersBorder = new() { X = (int)leftsMin - borderBuffer, Y = (int)topsMin - borderBuffer, Width = (int)(rightsMax + borderBuffer), Height = (int)(bottomsMax + borderBuffer), }; bordersBorder.Width = (int)(bordersBorder.Width * dpiScale.DpiScaleX); bordersBorder.Height = (int)(bordersBorder.Height * dpiScale.DpiScaleY); AnalyzeAsTable(wordBorders, bordersBorder); } private void ParseRowAndColumnLines() { // Draw Bounding Rect int topBound = 0; int bottomBound = topBound; int leftBound = 0; int rightBound = leftBound; if (Rows.Count >= 1) { topBound = (int)Rows[0].Top; bottomBound = (int)Rows[Rows.Count - 1].Bottom; } if (Columns.Count >= 1) { leftBound = (int)Columns[0].Left; rightBound = (int)Columns[Columns.Count - 1].Right; } BoundingRect = new() { Width = (rightBound - leftBound) + 10, Height = (bottomBound - topBound) + 10, X = leftBound - 5, Y = topBound - 5, }; // parse columns ColumnLines = new(); for (int i = 0; i < Columns.Count - 1; i++) { int columnMid = (int)(Columns[i].Right + Columns[i + 1].Left) / 2; ColumnLines.Add(columnMid); } // parse rows RowLines = new(); for (int i = 0; i < Rows.Count - 1; i++) { int rowMid = (int)(Rows[i].Bottom + Rows[i + 1].Top) / 2; RowLines.Add(rowMid); } } public static List<WordBorder> ParseOcrResultIntoWordBorders(OcrResult ocrResult, DpiScale dpi) { List<WordBorder> wordBorders = new(); int lineNumber = 0; foreach (OcrLine ocrLine in ocrResult.Lines) { double top = ocrLine.Words.Select(x => x.BoundingRect.Top).Min(); double bottom = ocrLine.Words.Select(x => x.BoundingRect.Bottom).Max(); double left = ocrLine.Words.Select(x => x.BoundingRect.Left).Min(); double right = ocrLine.Words.Select(x => x.BoundingRect.Right).Max(); Rect lineRect = new() { X = left, Y = top, Width = Math.Abs(right - left), Height = Math.Abs(bottom - top), }; StringBuilder lineText = new(); ocrLine.GetTextFromOcrLine(true, lineText); WordBorder wordBorderBox = new() { Width = lineRect.Width / dpi.DpiScaleX, Height = lineRect.Height / dpi.DpiScaleY, Top = lineRect.Y, Left = lineRect.X, Word = lineText.ToString().Trim(), LineNumber = lineNumber, }; wordBorders.Add(wordBorderBox); lineNumber++; } return wordBorders; } public void AnalyzeAsTable(ICollection<WordBorder> wordBorders, Rectangle rectCanvasSize) { int hitGridSpacing = 3; int numberOfVerticalLines = rectCanvasSize.Width / hitGridSpacing; int numberOfHorizontalLines = rectCanvasSize.Height / hitGridSpacing; Canvas tableIntersectionCanvas = new(); List<int> rowAreas = CalculateRowAreas(rectCanvasSize, hitGridSpacing, numberOfHorizontalLines, tableIntersectionCanvas, wordBorders); List<ResultRow> resultRows = CalculateResultRows(hitGridSpacing, rowAreas); List<int> columnAreas = CalculateColumnAreas(rectCanvasSize, hitGridSpacing, numberOfVerticalLines, tableIntersectionCanvas, wordBorders); List<ResultColumn> resultColumns = CalculateResultColumns(hitGridSpacing, columnAreas); Rect tableBoundingRect = new() { X = columnAreas.FirstOrDefault(), Y = rowAreas.FirstOrDefault(), Width = columnAreas.LastOrDefault() - columnAreas.FirstOrDefault(), Height = rowAreas.LastOrDefault() - rowAreas.FirstOrDefault(), }; CombineOutliers(wordBorders, resultRows, tableIntersectionCanvas, resultColumns, tableBoundingRect); Rows.Clear(); Rows.AddRange(resultRows); Columns.Clear(); Columns.AddRange(resultColumns); ParseRowAndColumnLines(); DrawTable(); } private static List<ResultRow> CalculateResultRows(int hitGridSpacing, List<int> rowAreas) { List<ResultRow> resultRows = new(); int rowTop = 0; int rowCount = 0; for (int i = 0; i < rowAreas.Count; i++) { int thisLine = rowAreas[i]; // check if should set this as top if (i == 0) { rowTop = thisLine; } else if (i - 1 > 0) { int prevRow = rowAreas[i - 1]; if (thisLine - prevRow != hitGridSpacing) { rowTop = thisLine; } } // check to see if at bottom of row if (i == rowAreas.Count - 1) { resultRows.Add(new ResultRow { Top = rowTop, Bottom = thisLine, ID = rowCount }); rowCount++; } else if (i + 1 < rowAreas.Count) { int nextRow = rowAreas[i + 1]; if (nextRow - thisLine != hitGridSpacing) { resultRows.Add(new ResultRow { Top = rowTop, Bottom = thisLine, ID = rowCount }); rowCount++; } } } return resultRows; } private static List<int> CalculateRowAreas(Rectangle rectCanvasSize, int hitGridSpacing, int numberOfHorizontalLines, Canvas tableIntersectionCanvas, ICollection<WordBorder> wordBorders) { List<int> rowAreas = new(); for (int i = 0; i < numberOfHorizontalLines; i++) { Border horizontalLine = new() { Height = 1, Width = rectCanvasSize.Width, Opacity = 0, Background = new SolidColorBrush(Colors.Gray), }; Rect horizontalLineRect = new(0, i * hitGridSpacing, horizontalLine.Width, horizontalLine.Height); _ = tableIntersectionCanvas.Children.Add(horizontalLine); Canvas.SetTop(horizontalLine, i * 3); CheckIntersectionsWithWordBorders(hitGridSpacing, wordBorders, rowAreas, i, horizontalLineRect); } return rowAreas; } private static void CheckIntersectionsWithWordBorders(int hitGridSpacing, ICollection<WordBorder> wordBorders, List<int> rowAreas, int i, Rect horizontalLineRect) { foreach (WordBorder wb in wordBorders) { if (wb.IntersectsWith(horizontalLineRect)) { rowAreas.Add(i * hitGridSpacing); break; } } } private static void CombineOutliers(ICollection<WordBorder> wordBorders, List<ResultRow> resultRows, Canvas tableIntersectionCanvas, List<ResultColumn> resultColumns, Rect tableBoundingRect) { // try 4 times to refine the rows and columns for outliers // on the fifth time set the word boundary properties for (int r = 0; r < 5; r++) { int outlierThreshold = 2; List<int> outlierRowIDs = FindOutlierRowIds(wordBorders, resultRows, tableIntersectionCanvas, tableBoundingRect, r, outlierThreshold); if (outlierRowIDs.Count > 0) { MergeTheseRowIDs(resultRows, outlierRowIDs); } List<int> outlierColumnIDs = FindOutlierColumnIds(wordBorders, tableIntersectionCanvas, resultColumns, tableBoundingRect, outlierThreshold); if (outlierColumnIDs.Count > 0 && r != 4) { MergeTheseColumnIDs(resultColumns, outlierColumnIDs); } } } private static List<int> FindOutlierRowIds( ICollection<WordBorder> wordBorders, ICollection<ResultRow> resultRows, Canvas tableIntersectionCanvas, Rect tableBoundingRect, int r, int outlierThreshold) { List<int> outlierRowIDs = new(); foreach (ResultRow row in resultRows) { int numberOfIntersectingWords = 0; Border rowBorder = new() { Height = row.Bottom - row.Top, Width = tableBoundingRect.Width, Background = new SolidColorBrush(Colors.Red), Tag = row.ID, }; tableIntersectionCanvas.Children.Add(rowBorder); Canvas.SetLeft(rowBorder, tableBoundingRect.X); Canvas.SetTop(rowBorder, row.Top); Rect rowRect = new(tableBoundingRect.X, row.Top, rowBorder.Width, rowBorder.Height); foreach (WordBorder wb in wordBorders) { if (wb.IntersectsWith(rowRect)) { numberOfIntersectingWords++; wb.ResultRowID = row.ID; } } if (numberOfIntersectingWords <= outlierThreshold && r != 4) { outlierRowIDs.Add(row.ID); } } return outlierRowIDs; } private static List<int> FindOutlierColumnIds( ICollection<WordBorder> wordBorders, Canvas tableIntersectionCanvas, List<ResultColumn> resultColumns, Rect tableBoundingRect, int outlierThreshold) { List<int> outlierColumnIDs = new(); foreach (ResultColumn column in resultColumns) { int numberOfIntersectingWords = 0; Border columnBorder = new() { Height = tableBoundingRect.Height, Width = column.Right - column.Left, Background = new SolidColorBrush(Colors.Blue), Opacity = 0.2, Tag = column.ID, }; tableIntersectionCanvas.Children.Add(columnBorder); Canvas.SetLeft(columnBorder, column.Left); Canvas.SetTop(columnBorder, tableBoundingRect.Y); Rect columnRect = new(column.Left, tableBoundingRect.Y, columnBorder.Width, columnBorder.Height); foreach (WordBorder wb in wordBorders) { if (wb.IntersectsWith(columnRect)) { numberOfIntersectingWords++; wb.ResultColumnID = column.ID; } } if (numberOfIntersectingWords <= outlierThreshold) { outlierColumnIDs.Add(column.ID); } } return outlierColumnIDs; } private static List<ResultColumn> CalculateResultColumns(int hitGridSpacing, List<int> columnAreas) { List<ResultColumn> resultColumns = new(); int columnLeft = 0; int columnCount = 0; for (int i = 0; i < columnAreas.Count; i++) { int thisLine = columnAreas[i]; // check if should set this as top if (i == 0) { columnLeft = thisLine; } else if (i - 1 > 0) { int prevColumn = columnAreas[i - 1]; if (thisLine - prevColumn != hitGridSpacing) { columnLeft = thisLine; } } // check to see if at last Column if (i == columnAreas.Count - 1) { resultColumns.Add(new ResultColumn { Left = columnLeft, Right = thisLine, ID = columnCount }); columnCount++; } else if (i + 1 < columnAreas.Count) { int nextColumn = columnAreas[i + 1]; if (nextColumn - thisLine != hitGridSpacing) { resultColumns.Add(new ResultColumn { Left = columnLeft, Right = thisLine, ID = columnCount }); columnCount++; } } } return resultColumns; } private static List<int> CalculateColumnAreas(Rectangle rectCanvasSize, int hitGridSpacing, int numberOfVerticalLines, Canvas tableIntersectionCanvas, ICollection<WordBorder> wordBorders) { List<int> columnAreas = new(); for (int i = 0; i < numberOfVerticalLines; i++) { Border vertLine = new() { Height = rectCanvasSize.Height, Width = 1, Opacity = 0, Background = new SolidColorBrush(Colors.Gray), }; _ = tableIntersectionCanvas.Children.Add(vertLine); Canvas.SetLeft(vertLine, i * hitGridSpacing); Rect vertLineRect = new(i * hitGridSpacing, 0, vertLine.Width, vertLine.Height); foreach (WordBorder wb in wordBorders) { if (wb.IntersectsWith(vertLineRect)) { columnAreas.Add(i * hitGridSpacing); break; } } } return columnAreas; } private static void MergeTheseColumnIDs(List<ResultColumn> resultColumns, List<int> outlierColumnIDs) { for (int i = 0; i < outlierColumnIDs.Count; i++) { for (int j = 0; j < resultColumns.Count; j++) { ResultColumn column = resultColumns[j]; if (column.ID == outlierColumnIDs[i]) { if (j == 0) { // merge with next column if possible if (j + 1 < resultColumns.Count) { ResultColumn nextColumn = resultColumns[j + 1]; nextColumn.Left = column.Left; } } else if (j == resultColumns.Count - 1) { // merge with previous column if (j - 1 >= 0) { ResultColumn prevColumn = resultColumns[j - 1]; prevColumn.Right = column.Right; } } else { // merge with closet column ResultColumn prevColumn = resultColumns[j - 1]; ResultColumn nextColumn = resultColumns[j + 1]; int distanceToPrev = (int)(column.Left - prevColumn.Right); int distanceToNext = (int)(nextColumn.Left - column.Right); if (distanceToNext < distanceToPrev) { // merge with next column nextColumn.Left = column.Left; } else { // merge with prev column prevColumn.Right = column.Right; } } resultColumns.RemoveAt(j); } } } } public static void GetTextFromTabledWordBorders(StringBuilder stringBuilder, List<WordBorder> wordBorders, bool isSpaceJoining) { List<WordBorder>? selectedBorders = wordBorders.Where(w => w.IsSelected).ToList(); if (selectedBorders.Count == 0) { selectedBorders.AddRange(wordBorders); } List<string> lineList = new(); int? lastLineNum = 0; int lastColumnNum = 0; if (selectedBorders.FirstOrDefault() != null) { lastLineNum = selectedBorders.FirstOrDefault()!.LineNumber; } selectedBorders = selectedBorders.OrderBy(x => x.ResultColumnID).ToList(); selectedBorders = selectedBorders.OrderBy(x => x.ResultRowID).ToList(); int numberOfDistinctRows = selectedBorders.Select(x => x.ResultRowID).Distinct().Count(); foreach (WordBorder border in selectedBorders) { if (lineList.Count == 0) { lastLineNum = border.ResultRowID; } if (border.ResultRowID != lastLineNum) { if (isSpaceJoining) { stringBuilder.Append(string.Join(' ', lineList)); } else { stringBuilder.Append(string.Join(string.Empty, lineList)); } stringBuilder.Replace(" \t ", "\t"); stringBuilder.Replace("\t ", "\t"); stringBuilder.Replace(" \t", "\t"); stringBuilder.Append(Environment.NewLine); lineList.Clear(); lastLineNum = border.ResultRowID; } if (border.ResultColumnID != lastColumnNum && numberOfDistinctRows > 1) { string borderWord = border.Word; int numberOfOffColumns = border.ResultColumnID - lastColumnNum; if (numberOfOffColumns < 0) { lastColumnNum = 0; } numberOfOffColumns = border.ResultColumnID - lastColumnNum; if (numberOfOffColumns > 0) { lineList.Add(new string('\t', numberOfOffColumns)); } } lastColumnNum = border.ResultColumnID; lineList.Add(border.Word); } stringBuilder.Append(string.Join(string.Empty, lineList)); } private static void MergeTheseRowIDs(List<ResultRow> resultRows, List<int> outlierRowIDs) { } private void DrawTable() { // Draw the lines and bounds of the table SolidColorBrush tableColor = new(System.Windows.Media.Color.FromArgb(255, 40, 118, 126)); TableLines = new Canvas() { Tag = "TableLines", }; Border tableOutline = new() { Width = this.BoundingRect.Width, Height = this.BoundingRect.Height, BorderThickness = new Thickness(3), BorderBrush = tableColor, }; TableLines.Children.Add(tableOutline); Canvas.SetTop(tableOutline, this.BoundingRect.Y); Canvas.SetLeft(tableOutline, this.BoundingRect.X); foreach (int columnLine in this.ColumnLines) { Border vertLine = new() { Width = 2, Height = this.BoundingRect.Height, Background = tableColor, }; TableLines.Children.Add(vertLine); Canvas.SetTop(vertLine, this.BoundingRect.Y); Canvas.SetLeft(vertLine, columnLine); } foreach (int rowLine in this.RowLines) { Border horizontalLine = new() { Height = 2, Width = this.BoundingRect.Width, Background = tableColor, }; TableLines.Children.Add(horizontalLine); Canvas.SetTop(horizontalLine, rowLine); Canvas.SetLeft(horizontalLine, this.BoundingRect.X); } } public static string GetWordsAsTable(List<WordBorder> wordBorders, DpiScale dpiScale, bool isSpaceJoining) { List<WordBorder> smallerBorders = new(); foreach (WordBorder originalWB in wordBorders) { WordBorder newWB = new() { Word = originalWB.Word, Left = originalWB.Left, Top = originalWB.Top, Width = originalWB.Width > 10 ? originalWB.Width - 6 : originalWB.Width, Height = originalWB.Height > 10 ? originalWB.Height - 6 : originalWB.Height, ResultRowID = originalWB.ResultRowID, ResultColumnID = originalWB.ResultColumnID, }; smallerBorders.Add(newWB); } ResultTable resultTable = new(ref smallerBorders, dpiScale); StringBuilder stringBuilder = new(); GetTextFromTabledWordBorders( stringBuilder, smallerBorders, isSpaceJoining); return stringBuilder.ToString(); } }
ResultTable
csharp
dotnet__maui
src/Compatibility/Core/src/WPF/Microsoft.Windows.Shell/Standard/ShellProvider.cs
{ "start": 42634, "end": 43674 }
internal static class ____ { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static string GetPathFromShellItem(IShellItem item) { return item.GetDisplayName(SIGDN.DESKTOPABSOLUTEPARSING); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static IShellItem2 GetShellItemForPath(string path) { if (string.IsNullOrEmpty(path)) { // Internal function. Should have verified this before calling if we cared. return null; } Guid iidShellItem2 = new Guid(IID.ShellItem2); object unk; HRESULT hr = NativeMethods.SHCreateItemFromParsingName(path, null, ref iidShellItem2, out unk); // Silently absorb errors such as ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND. // Let others pass through if (hr == (HRESULT)Win32Error.ERROR_FILE_NOT_FOUND || hr == (HRESULT)Win32Error.ERROR_PATH_NOT_FOUND) { hr = HRESULT.S_OK; unk = null; } hr.ThrowIfFailed(); return (IShellItem2)unk; } } #endregion }
ShellUtil
csharp
EventStore__EventStore
src/KurrentDB.Plugins/MD5/IMD5ProviderFactory.cs
{ "start": 217, "end": 363 }
public interface ____ { /// <summary> /// Builds an MD5 provider for the MD5 plugin /// </summary> IMD5Provider Build(); }
IMD5ProviderFactory
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.Indexing.Core/Deployments/IndexProfileDeploymentStep.cs
{ "start": 122, "end": 385 }
public sealed class ____ : DeploymentStep { public IndexProfileDeploymentStep() { Name = CreateOrUpdateIndexProfileStep.StepKey; } public bool IncludeAll { get; set; } public string[] IndexNames { get; set; } }
IndexProfileDeploymentStep
csharp
louthy__language-ext
LanguageExt.Core/Immutable Collections/Seq/SeqEmptyInternal.cs
{ "start": 126, "end": 1716 }
internal class ____<A> : ISeqInternal<A> { public static ISeqInternal<A> Default = new SeqEmptyInternal<A>(); public A this[int index] => throw new IndexOutOfRangeException(); public Option<A> At(int index) => default; public A Head => throw Exceptions.SequenceEmpty; public ISeqInternal<A> Tail => this; public bool IsEmpty => true; public ISeqInternal<A> Init => this; public A Last => throw Exceptions.SequenceEmpty; public int Count => 0; public ISeqInternal<A> Add(A value) => SeqStrict<A>.FromSingleValue(value); public ISeqInternal<A> Cons(A value) => SeqStrict<A>.FromSingleValue(value); public S Fold<S>(S state, Func<S, A, S> f) => state; public S FoldBack<S>(S state, Func<S, A, S> f) => state; public ISeqInternal<A> Skip(int amount) => this; public ISeqInternal<A> Strict() => this; public ISeqInternal<A> Take(int amount) => this; public IEnumerator<A> GetEnumerator() { yield break; } IEnumerator IEnumerable.GetEnumerator() { yield break; } public Unit Iter(Action<A> f) => default; public bool Exists(Func<A, bool> f) => false; public bool ForAll(Func<A, bool> f) => true; public SeqType Type => SeqType.Empty; public override int GetHashCode() => FNV32.OffsetBasis; public int GetHashCode(int offsetBasis) => offsetBasis; }
SeqEmptyInternal
csharp
xunit__xunit
src/xunit.v3.runner.utility/Frameworks/XunitFrontController.cs
{ "start": 589, "end": 4085 }
public class ____ : IFrontController { bool disposed; readonly IFrontController innerController; XunitFrontController(IFrontController innerController) => this.innerController = Guard.ArgumentNotNull(innerController); /// <inheritdoc/> public bool CanUseAppDomains => innerController.CanUseAppDomains; /// <inheritdoc/> public string TargetFramework => innerController.TargetFramework; /// <inheritdoc/> public string TestAssemblyUniqueID => innerController.TestAssemblyUniqueID; /// <inheritdoc/> public string TestFrameworkDisplayName => innerController.TestFrameworkDisplayName; /// <summary> /// Returns an implementation of <see cref="IFrontController"/> which can be used for both discovery and execution. /// If the assembly does not appear to be a test assembly, returns <c>null</c>. /// </summary> /// <param name="projectAssembly">The test project assembly.</param> /// <param name="sourceInformationProvider">The optional source information provider.</param> /// <param name="diagnosticMessageSink">The optional message sink which receives <see cref="IDiagnosticMessage"/> /// and <see cref="IInternalDiagnosticMessage"/> messages.</param> /// <param name="testProcessLauncher">The test process launcher, used to launch v3 test processes. /// If not provided, <see cref="LocalOutOfProcessTestProcessLauncher"/> will be used. (This value is /// not used when running v1 or v2 test proceses.)</param> public static IFrontController? Create( XunitProjectAssembly projectAssembly, ISourceInformationProvider? sourceInformationProvider = null, IMessageSink? diagnosticMessageSink = null, ITestProcessLauncher? testProcessLauncher = null) { Guard.ArgumentNotNull(projectAssembly); Guard.ArgumentNotNull(projectAssembly.AssemblyMetadata); var assemblyFileName = projectAssembly.AssemblyFileName; var assemblyFolder = Path.GetDirectoryName(assemblyFileName); return projectAssembly.AssemblyMetadata.XunitVersion switch { // We don't use GetSourceInformationProvider for v3, because we rely on FactAttribute decorations rather than Cecil 3 => new XunitFrontController(Xunit3.ForDiscoveryAndExecution(projectAssembly, sourceInformationProvider, diagnosticMessageSink, testProcessLauncher)), 2 => new XunitFrontController(Xunit2.ForDiscoveryAndExecution(projectAssembly, sourceInformationProvider, diagnosticMessageSink)), #if NETFRAMEWORK 1 => new XunitFrontController(Xunit1.ForDiscoveryAndExecution(projectAssembly, sourceInformationProvider, diagnosticMessageSink)), #endif _ => null, }; } /// <inheritdoc/> public async ValueTask DisposeAsync() { if (disposed) return; disposed = true; GC.SuppressFinalize(this); await innerController.SafeDisposeAsync(); } /// <inheritdoc/> public virtual void Find( IMessageSink messageSink, FrontControllerFindSettings settings) { Guard.ArgumentNotNull(messageSink); Guard.ArgumentNotNull(settings); innerController.Find(messageSink, settings); } /// <inheritdoc/> public void FindAndRun( IMessageSink messageSink, FrontControllerFindAndRunSettings settings) { Guard.ArgumentNotNull(messageSink); Guard.ArgumentNotNull(settings); innerController.FindAndRun(messageSink, settings); } /// <inheritdoc/> public void Run( IMessageSink messageSink, FrontControllerRunSettings settings) { Guard.ArgumentNotNull(messageSink); Guard.ArgumentNotNull(settings); innerController.Run(messageSink, settings); } }
XunitFrontController
csharp
icsharpcode__ILSpy
ICSharpCode.ILSpyX/MermaidDiagrammer/ClassDiagrammer.cs
{ "start": 1303, "end": 1455 }
class ____ from a source assembly. /// Serialized into JSON by <see cref="GenerateHtmlDiagrammer.SerializeModel(ClassDiagrammer)"/>.</summary>
diagrammer
csharp
dotnet__aspire
src/Aspire.Hosting/ApplicationModel/AfterEndpointsAllocatedEvent.cs
{ "start": 787, "end": 1896 }
interface ____ resolve dependencies including /// <see cref="DistributedApplicationModel"/> service which is passed in as an argument /// in <see cref="Aspire.Hosting.Lifecycle.IDistributedApplicationLifecycleHook.AfterEndpointsAllocatedAsync(Aspire.Hosting.ApplicationModel.DistributedApplicationModel, CancellationToken)"/>. /// <example> /// Subscribe to the <see cref="AfterEndpointsAllocatedEvent"/> event and resolve the distributed application model. /// <code lang="C#"> /// var builder = DistributedApplication.CreateBuilder(args); /// builder.Eventing.Subscribe&lt;AfterEndpointsAllocatedEvent&gt;(async (@event, cancellationToken) =&gt; { /// var appModel = @event.ServiceProvider.GetRequiredService&lt;DistributedApplicationModel&gt;(); /// // Update configuration of resource based on final endpoint configuration /// }); /// </code> /// </example> /// </remarks> [Obsolete("The AfterEndpointsAllocatedEvent is deprecated and will be removed in a future version. Use the resource specific events BeforeResourceStartedEvent or ResourceEndpointsAllocatedEvent instead depending on your needs.")]
to
csharp
dotnet__aspnetcore
src/Mvc/Mvc.DataAnnotations/src/RequiredAttributeAdapter.cs
{ "start": 451, "end": 1595 }
public sealed class ____ : AttributeAdapterBase<RequiredAttribute> { /// <summary> /// Initializes a new instance of <see cref="RequiredAttributeAdapter"/>. /// </summary> /// <param name="attribute">The <see cref="RequiredAttribute"/>.</param> /// <param name="stringLocalizer">The <see cref="IStringLocalizer"/>.</param> public RequiredAttributeAdapter(RequiredAttribute attribute, IStringLocalizer? stringLocalizer) : base(attribute, stringLocalizer) { } /// <inheritdoc /> public override void AddValidation(ClientModelValidationContext context) { ArgumentNullException.ThrowIfNull(context); MergeAttribute(context.Attributes, "data-val", "true"); MergeAttribute(context.Attributes, "data-val-required", GetErrorMessage(context)); } /// <inheritdoc /> public override string GetErrorMessage(ModelValidationContextBase validationContext) { ArgumentNullException.ThrowIfNull(validationContext); return GetErrorMessage(validationContext.ModelMetadata, validationContext.ModelMetadata.GetDisplayName()); } }
RequiredAttributeAdapter
csharp
dotnet__orleans
src/Orleans.Streaming/Generator/GeneratorPooledCache.cs
{ "start": 4936, "end": 7120 }
private class ____ : IQueueCacheCursor { private readonly PooledQueueCache cache; private readonly object cursor; private IBatchContainer current; public Cursor(PooledQueueCache cache, StreamId streamId, StreamSequenceToken token) { this.cache = cache; cursor = cache.GetCursor(streamId, token); } public void Dispose() { } public IBatchContainer GetCurrent(out Exception exception) { exception = null; return current; } public bool MoveNext() { IBatchContainer next; if (!cache.TryGetNextMessage(cursor, out next)) { return false; } current = next; return true; } public void Refresh(StreamSequenceToken token) { } public void RecordDeliveryFailure() { } } /// <inheritdoc /> public int GetMaxAddCount() { return 100; } /// <inheritdoc /> public void AddToCache(IList<IBatchContainer> messages) { DateTime utcNow = DateTime.UtcNow; List<CachedMessage> generatedMessages = messages .Cast<GeneratedBatchContainer>() .Select(batch => QueueMessageToCachedMessage(batch, utcNow)) .ToList(); cache.Add(generatedMessages, utcNow); } /// <inheritdoc /> public bool TryPurgeFromCache(out IList<IBatchContainer> purgedItems) { purgedItems = null; this.evictionStrategy.PerformPurge(DateTime.UtcNow); return false; } /// <inheritdoc /> public IQueueCacheCursor GetCacheCursor(StreamId streamId, StreamSequenceToken token) { return new Cursor(cache, streamId, token); } /// <inheritdoc /> public bool IsUnderPressure() { return false; } } }
Cursor
csharp
dotnet__orleans
src/Orleans.Transactions.TestKit.Base/FaultInjection/ControlledInjection/FaultInjectionTransactionState.cs
{ "start": 249, "end": 723 }
public class ____ { [Id(0)] public TransactionFaultInjectPhase FaultInjectionPhase = TransactionFaultInjectPhase.None; [Id(1)] public FaultInjectionType FaultInjectionType = FaultInjectionType.None; public void Reset() { this.FaultInjectionType = FaultInjectionType.None; this.FaultInjectionPhase = TransactionFaultInjectPhase.None; } } [GenerateSerializer]
FaultInjectionControl
csharp
Cysharp__MemoryPack
sandbox/NativeAot/Program.cs
{ "start": 591, "end": 791 }
public abstract class ____<T> : IMemoryPackFormatter2<T> { public abstract void Serialize<TBufferWriter>(scoped ref T? value) where TBufferWriter : IBufferWriter<byte>; }
MemoryPackFormatter2
csharp
AvaloniaUI__Avalonia
src/Windows/Avalonia.Win32/Win32Platform.cs
{ "start": 652, "end": 1145 }
public static class ____ { public static AppBuilder UseWin32(this AppBuilder builder) { return builder .UseStandardRuntimePlatformSubsystem() .UseWindowingSubsystem( () => Win32.Win32Platform.Initialize( AvaloniaLocator.Current.GetService<Win32PlatformOptions>() ?? new Win32PlatformOptions()), "Win32"); } } } namespace Avalonia.Win32 {
Win32ApplicationExtensions
csharp
icsharpcode__ILSpy
ILSpy/Analyzers/TreeNodes/AnalyzedEventTreeNode.cs
{ "start": 1363, "end": 3380 }
internal sealed class ____ : AnalyzerEntityTreeNode { readonly IEvent analyzedEvent; readonly string prefix; public AnalyzedEventTreeNode(IEvent analyzedEvent, IEntity? source, string prefix = "") { this.analyzedEvent = analyzedEvent ?? throw new ArgumentNullException(nameof(analyzedEvent)); this.prefix = prefix; this.LazyLoading = true; this.SourceMember = source; } public override IEntity Member => analyzedEvent; public override object Icon => EventTreeNode.GetIcon(analyzedEvent); // TODO: This way of formatting is not suitable for events which explicitly implement interfaces. public override object Text => prefix + Language.EventToString(analyzedEvent, includeDeclaringTypeName: true, includeNamespace: false, includeNamespaceOfDeclaringTypeName: true); protected override void LoadChildren() { if (analyzedEvent.CanAdd) this.Children.Add(new AnalyzedAccessorTreeNode(analyzedEvent.AddAccessor, this.SourceMember, "add")); if (analyzedEvent.CanRemove) this.Children.Add(new AnalyzedAccessorTreeNode(analyzedEvent.RemoveAccessor, this.SourceMember, "remove")); if (TryFindBackingField(analyzedEvent, out var backingField)) this.Children.Add(new AnalyzedFieldTreeNode(backingField, this.SourceMember)); foreach (var lazy in Analyzers) { var analyzer = lazy.Value; Debug.Assert(analyzer != null); if (analyzer.Show(analyzedEvent)) { this.Children.Add(new AnalyzerSearchTreeNode(analyzedEvent, analyzer, lazy.Metadata?.Header)); } } } bool TryFindBackingField(IEvent analyzedEvent, [NotNullWhen(true)] out IField? backingField) { backingField = null; foreach (var field in analyzedEvent.DeclaringTypeDefinition?.GetFields(options: GetMemberOptions.IgnoreInheritedMembers) ?? []) { if (field.Name == analyzedEvent.Name && field.Accessibility == Decompiler.TypeSystem.Accessibility.Private) { backingField = field; return true; } } return false; } } }
AnalyzedEventTreeNode
csharp
dotnet__aspnetcore
src/Mvc/Mvc.ViewFeatures/test/Filters/LifecyclePropertyTest.cs
{ "start": 2634, "end": 2826 }
public class ____ { public string TestProperty { get; set; } public int ValueTypeProperty { get; set; } public int? NullableProperty { get; set; } } }
TestSubject
csharp
unoplatform__uno
src/Uno.UI/UI/Xaml/Controls/ScrollPresenter/ScrollPresenter.idl.cs
{ "start": 872, "end": 958 }
public enum ____ { Disabled = 0, Enabled = 1, Auto = 2, }
ScrollingAnimationMode
csharp
microsoft__PowerToys
src/settings-ui/Settings.UI/SettingsXAML/Controls/TitleBar/TitleBar.Properties.cs
{ "start": 9283, "end": 9335 }
public enum ____ { Standard, Tall, }
DisplayMode
csharp
CommunityToolkit__WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.UI.Animations/Builders/NormalizedKeyFrameAnimationBuilder{T}.Xaml.cs
{ "start": 662, "end": 2305 }
public sealed class ____ : NormalizedKeyFrameAnimationBuilder<T>, AnimationBuilder.IXamlAnimationFactory { /// <summary> /// Initializes a new instance of the <see cref="NormalizedKeyFrameAnimationBuilder{T}.Xaml"/> class. /// </summary> /// <param name="property">The target property to animate.</param> /// <param name="delay">The target delay for the animation.</param> /// <param name="duration">The target duration for the animation.</param> /// <param name="repeat">The repeat options for the animation.</param> public Xaml(string property, TimeSpan? delay, TimeSpan duration, RepeatOption repeat) : base(property, delay, duration, repeat) { } /// <inheritdoc/> public override INormalizedKeyFrameAnimationBuilder<T> ExpressionKeyFrame( double progress, string expression, EasingType easingType, EasingMode easingMode) { throw new InvalidOperationException("Expression keyframes can only be used on the composition layer"); } /// <inheritdoc/> public Timeline GetAnimation(DependencyObject targetHint) { return TimedKeyFrameAnimationBuilder<T>.GetAnimation( targetHint, this.property, this.delay, this.duration, this.repeat, this.keyFrames.GetArraySegment()); } } } }
Xaml
csharp
duplicati__duplicati
Duplicati/Library/Backend/OneDrive/MicrosoftGraphTypes.cs
{ "start": 4436, "end": 5301 }
public enum ____ { /// <summary> /// The drive has plenty of remaining quota /// </summary> Normal, /// <summary> /// Remaining quota is under 10% /// </summary> Nearing, /// <summary> /// Remaining quota is under 1% /// </summary> Critical, /// <summary> /// No remaining quota - files can only be deleted and no new files can be added /// </summary> Exceeded, // Newer versions of JSON.NET add StringEnumCaseInsensitiveConverter, which can be used to serialize/deserialize enums // without respecting cases. Once we can use that, we can remove these copies of the nicely named enums. normal = Normal, nearing = Nearing, critical = Critical, exceeded = Exceeded, }
QuotaState
csharp
PrismLibrary__Prism
e2e/Maui/MauiRegionsModule/ViewModels/RegionViewCViewModel.cs
{ "start": 63, "end": 282 }
public class ____ : RegionViewModelBase { public RegionViewCViewModel(INavigationService navigationService, IPageAccessor pageAccessor) : base(navigationService, pageAccessor) { } }
RegionViewCViewModel
csharp
unoplatform__uno
src/Uno.Foundation/Metadata/ActivatableAttribute.cs
{ "start": 296, "end": 536 }
class ____ be activated with no parameters, /// starting in a particular version. /// </summary> /// <param name="version"></param> public ActivatableAttribute(uint version) : base() { } /// <summary> /// Indicates that the runtime
can
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.ContentFields/Settings/HtmlFieldSettingsDriver.cs
{ "start": 314, "end": 1362 }
public sealed class ____ : ContentPartFieldDefinitionDisplayDriver<HtmlField> { public override IDisplayResult Edit(ContentPartFieldDefinition partFieldDefinition, BuildEditorContext context) { return Initialize<HtmlSettingsViewModel>("HtmlFieldSettings_Edit", model => { var settings = partFieldDefinition.GetSettings<HtmlFieldSettings>(); model.SanitizeHtml = settings.SanitizeHtml; model.Hint = settings.Hint; }).Location("Content:20"); } public override async Task<IDisplayResult> UpdateAsync(ContentPartFieldDefinition partFieldDefinition, UpdatePartFieldEditorContext context) { var model = new HtmlSettingsViewModel(); var settings = new HtmlFieldSettings(); await context.Updater.TryUpdateModelAsync(model, Prefix); settings.SanitizeHtml = model.SanitizeHtml; settings.Hint = model.Hint; context.Builder.WithSettings(settings); return Edit(partFieldDefinition, context); } }
HtmlFieldSettingsDriver
csharp
kgrzybek__modular-monolith-with-ddd
src/Modules/Meetings/Application/Meetings/ChangeMeetingMainAttributes/ChangeMeetingMainAttributesCommandHandler.cs
{ "start": 314, "end": 1773 }
internal class ____ : ICommandHandler<ChangeMeetingMainAttributesCommand> { private readonly IMemberContext _memberContext; private readonly IMeetingRepository _meetingRepository; public ChangeMeetingMainAttributesCommandHandler(IMemberContext memberContext, IMeetingRepository meetingRepository) { _memberContext = memberContext; _meetingRepository = meetingRepository; } public async Task Handle(ChangeMeetingMainAttributesCommand request, CancellationToken cancellationToken) { var meeting = await _meetingRepository.GetByIdAsync(new MeetingId(request.MeetingId)); meeting.ChangeMainAttributes( request.Title, MeetingTerm.CreateNewBetweenDates(request.TermStartDate, request.TermStartDate), request.Description, MeetingLocation.CreateNew(request.MeetingLocationName, request.MeetingLocationAddress, request.MeetingLocationPostalCode, request.MeetingLocationCity), MeetingLimits.Create(request.AttendeesLimit, request.GuestsLimit), Term.CreateNewBetweenDates(request.RSVPTermStartDate, request.RSVPTermEndDate), request.EventFeeValue.HasValue ? MoneyValue.Of(request.EventFeeValue.Value, request.EventFeeCurrency) : MoneyValue.Undefined, _memberContext.MemberId); } } }
ChangeMeetingMainAttributesCommandHandler
csharp
AutoFixture__AutoFixture
Src/AutoFixture.NUnit3.UnitTest/VolatileNameTestMethodBuilderTest.cs
{ "start": 134, "end": 899 }
public class ____ { [Test] public void VolatileNameTestMethodBuilderIsResilientToParameterEnumerationException() { // Arrange var anyMethod = new MethodWrapper(typeof(TestNameStrategiesFixture), nameof(TestNameStrategiesFixture.VolatileNameDecoratedMethod)); var sut = new VolatileNameTestMethodBuilder(); var throwingParameters = Enumerable.Range(0, 1).Select<int, object>(_ => throw new Exception()); // Act var testMethod = sut.Build(anyMethod, null, throwingParameters, 0); // Assert Assert.That(testMethod.Name, Is.EqualTo(nameof(TestNameStrategiesFixture.VolatileNameDecoratedMethod))); } } }
VolatileNameTestMethodBuilderTest
csharp
unoplatform__uno
src/Uno.UI.Tests/Windows_UI_XAML_Controls/Frame/Given_Frame.cs
{ "start": 9241, "end": 9286 }
class ____ : SourceTypePage { }
SourceTypePage1
csharp
LibreHardwareMonitor__LibreHardwareMonitor
LibreHardwareMonitorLib/Interop/IntelGcl.cs
{ "start": 11460, "end": 11580 }
public struct ____ { private IntPtr pNext; } [StructLayout(LayoutKind.Sequential)]
ctl_api_handle_t
csharp
reactiveui__ReactiveUI
src/ReactiveUI.Tests/Locator/DefaultViewLocatorTests.cs
{ "start": 3580, "end": 4291 }
interface ____]. /// </summary> [Test] public void CanResolveViewFromViewModelClassUsingInterfaceRegistration() { var resolver = new ModernDependencyResolver(); resolver.InitializeSplat(); resolver.InitializeReactiveUI(); resolver.Register(static () => new FooView(), typeof(IFooView)); using (resolver.WithResolver()) { var fixture = new DefaultViewLocator(); var vm = new FooViewModel(); var result = fixture.ResolveView(vm); Assert.That(result, Is.TypeOf<FooView>()); } } /// <summary> /// Test that makes sure that this instance [can resolve view from view model
registration
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.Contents/Deployment/ExportContentToDeploymentTarget/ExportContentToDeploymentTargetDeploymentStepDriver.cs
{ "start": 196, "end": 1075 }
public sealed class ____ : DisplayDriver<DeploymentStep, ExportContentToDeploymentTargetDeploymentStep> { public override Task<IDisplayResult> DisplayAsync(ExportContentToDeploymentTargetDeploymentStep step, BuildDisplayContext context) { return CombineAsync( View("ExportContentToDeploymentTargetDeploymentStep_Fields_Summary", step).Location(OrchardCoreConstants.DisplayType.Summary, "Content"), View("ExportContentToDeploymentTargetDeploymentStep_Fields_Thumbnail", step).Location("Thumbnail", "Content") ); } public override IDisplayResult Edit(ExportContentToDeploymentTargetDeploymentStep step, BuildEditorContext context) { return View("ExportContentToDeploymentTargetDeploymentStep_Fields_Edit", step).Location("Content"); } }
ExportContentToDeploymentTargetDeploymentStepDriver
csharp
nuke-build__nuke
source/Nuke.Common/Tools/Docker/Docker.Generated.cs
{ "start": 454454, "end": 454840 }
public partial class ____ : DockerOptionsBase { } #endregion #region DockerConfigInspectSettings /// <inheritdoc cref="DockerTasks.DockerConfigInspect(Nuke.Common.Tools.Docker.DockerConfigInspectSettings)"/> [PublicAPI] [ExcludeFromCodeCoverage] [Command(Type = typeof(DockerTasks), Command = nameof(DockerTasks.DockerConfigInspect), Arguments = "config inspect")]
DockerTrustSignerSettings
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Interfaces/Jetbrains.Annotations.cs
{ "start": 33504, "end": 33864 }
internal sealed class ____ : Attribute { } /// <summary> /// Indicates the condition parameter of the assertion method. The method itself should be /// marked by <see cref="AssertionMethodAttribute"/> attribute. The mandatory argument of /// the attribute is the assertion type. /// </summary> [AttributeUsage(AttributeTargets.Parameter)]
AssertionMethodAttribute
csharp
abpframework__abp
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/Services/SourceCodeDownloadService.cs
{ "start": 390, "end": 7983 }
public class ____ : ITransientDependency { public ModuleProjectBuilder ModuleProjectBuilder { get; } public NugetPackageProjectBuilder NugetPackageProjectBuilder { get; } public NpmPackageProjectBuilder NpmPackageProjectBuilder { get; } public ILogger<SourceCodeDownloadService> Logger { get; set; } public SourceCodeDownloadService(ModuleProjectBuilder moduleProjectBuilder, NugetPackageProjectBuilder nugetPackageProjectBuilder, NpmPackageProjectBuilder npmPackageProjectBuilder) { ModuleProjectBuilder = moduleProjectBuilder; NugetPackageProjectBuilder = nugetPackageProjectBuilder; NpmPackageProjectBuilder = npmPackageProjectBuilder; Logger = NullLogger<SourceCodeDownloadService>.Instance; } public async Task DownloadModuleAsync(string moduleName, string outputFolder, string version, string gitHubAbpLocalRepositoryPath, string gitHubVoloLocalRepositoryPath, AbpCommandLineOptions options) { Logger.LogInformation($"Downloading source code of {moduleName} ({(version != null ? "v" + version : "Latest")})"); Logger.LogInformation("Output folder: " + outputFolder); var result = await ModuleProjectBuilder.BuildAsync( new ProjectBuildArgs( SolutionName.Parse(moduleName), moduleName, version, outputFolder, DatabaseProvider.NotSpecified, DatabaseManagementSystem.NotSpecified, UiFramework.NotSpecified, null, false, gitHubAbpLocalRepositoryPath, gitHubVoloLocalRepositoryPath, null, options ) ); using (var templateFileStream = new MemoryStream(result.ZipContent)) { using (var zipInputStream = new ZipInputStream(templateFileStream)) { var zipEntry = zipInputStream.GetNextEntry(); while (zipEntry != null) { if (IsAngularTestFile(zipEntry.Name)) { zipEntry = zipInputStream.GetNextEntry(); continue; } var fullZipToPath = Path.Combine(outputFolder, zipEntry.Name); var directoryName = Path.GetDirectoryName(fullZipToPath); if (!string.IsNullOrEmpty(directoryName)) { Directory.CreateDirectory(directoryName); } var fileName = Path.GetFileName(fullZipToPath); if (fileName.Length == 0) { zipEntry = zipInputStream.GetNextEntry(); continue; } var buffer = new byte[4096]; // 4K is optimum using (var streamWriter = File.Create(fullZipToPath)) { StreamUtils.Copy(zipInputStream, streamWriter, buffer); } zipEntry = zipInputStream.GetNextEntry(); } } } Logger.LogInformation($"'{moduleName}' has been successfully downloaded to '{outputFolder}'"); } public async Task DownloadNugetPackageAsync(string packageName, string outputFolder, string version) { Logger.LogInformation("Downloading source code of " + packageName); Logger.LogInformation("Version: " + (version ?? "Latest")); Logger.LogInformation("Output folder: " + outputFolder); var result = await NugetPackageProjectBuilder.BuildAsync( new ProjectBuildArgs( SolutionName.Parse(packageName), packageName, version, outputFolder ) ); using (var templateFileStream = new MemoryStream(result.ZipContent)) { using (var zipInputStream = new ZipInputStream(templateFileStream)) { var zipEntry = zipInputStream.GetNextEntry(); while (zipEntry != null) { var fullZipToPath = Path.Combine(outputFolder, zipEntry.Name); var directoryName = Path.GetDirectoryName(fullZipToPath); if (!string.IsNullOrEmpty(directoryName)) { Directory.CreateDirectory(directoryName); } var fileName = Path.GetFileName(fullZipToPath); if (fileName.Length == 0) { zipEntry = zipInputStream.GetNextEntry(); continue; } var buffer = new byte[4096]; // 4K is optimum using (var streamWriter = File.Create(fullZipToPath)) { StreamUtils.Copy(zipInputStream, streamWriter, buffer); } zipEntry = zipInputStream.GetNextEntry(); } } } Logger.LogInformation($"'{packageName}' has been successfully downloaded to '{outputFolder}'"); } public async Task DownloadNpmPackageAsync(string packageName, string outputFolder, string version) { Logger.LogInformation("Downloading source code of " + packageName); Logger.LogInformation("Version: " + (version ?? "Latest")); Logger.LogInformation("Output folder: " + outputFolder); var result = await NpmPackageProjectBuilder.BuildAsync( new ProjectBuildArgs( SolutionName.Parse(packageName), packageName, version, outputFolder ) ); using (var templateFileStream = new MemoryStream(result.ZipContent)) { using (var zipInputStream = new ZipInputStream(templateFileStream)) { var zipEntry = zipInputStream.GetNextEntry(); while (zipEntry != null) { var fullZipToPath = Path.Combine(outputFolder, zipEntry.Name); var directoryName = Path.GetDirectoryName(fullZipToPath); if (!string.IsNullOrEmpty(directoryName)) { Directory.CreateDirectory(directoryName); } var fileName = Path.GetFileName(fullZipToPath); if (fileName.Length == 0) { zipEntry = zipInputStream.GetNextEntry(); continue; } var buffer = new byte[4096]; // 4K is optimum using (var streamWriter = File.Create(fullZipToPath)) { StreamUtils.Copy(zipInputStream, streamWriter, buffer); } zipEntry = zipInputStream.GetNextEntry(); } } } Logger.LogInformation($"'{packageName}' has been successfully downloaded to '{outputFolder}'"); } private bool IsAngularTestFile(string zipEntryName) { if (string.IsNullOrEmpty(zipEntryName)) { return false; } if (zipEntryName.StartsWith("angular/") && !zipEntryName.StartsWith("angular/projects")) { return true; } return false; } }
SourceCodeDownloadService
csharp
MapsterMapper__Mapster
src/Mapster.Tests/WhenMappingWithIReadOnlyDictionary.cs
{ "start": 10375, "end": 10523 }
public class ____ { public IReadOnlyDictionary<SimplePoco, int> Dict { get; set; } } } }
OtherClassWithPocoKeyDictionary
csharp
louthy__language-ext
LanguageExt.Tests/CollectionOrderingTests.cs
{ "start": 79, "end": 6047 }
public class ____ { [Fact] public void TestSetOrdering1() { var x = Set(1, 2, 3, 4, 5); var y = Set(1, 2, 3, 4, 5); Assert.True(x.CompareTo(y) == 0); Assert.False(x < y); Assert.True(x <= y); Assert.False(x > y); Assert.True(x >= y); } [Fact] public void TestSetOrdering2() { var x = Set(1, 2, 3, 4, 5); var y = Set(1, 2, 3, 4, 6); Assert.True(x.CompareTo(y) < 0); Assert.True(x.CompareTo(y) <= 0); Assert.True(x < y); Assert.True(x <= y); Assert.False(x > y); Assert.False(x >= y); } [Fact] public void TestSetOrdering3() { var x = Set(1, 2, 3, 4, 6); var y = Set(1, 2, 3, 4, 5); Assert.True(x.CompareTo(y) > 0); Assert.True(x.CompareTo(y) >= 0); Assert.False(x < y); Assert.False(x <= y); Assert.True(x > y); Assert.True(x >= y); } [Fact] public void TestSetOrdering4() { var x = Set(1, 2, 3, 4, 5); var y = Set(1, 2, 3, 4); Assert.True(x.CompareTo(y) > 0); Assert.True(x.CompareTo(y) >= 0); Assert.False(x < y); Assert.False(x <= y); Assert.True(x > y); Assert.True(x >= y); } [Fact] public void TestSetOrdering5() { var x = Set(1, 2, 3, 4); var y = Set(1, 2, 3, 4, 5); Assert.True(x.CompareTo(y) < 0); Assert.True(x.CompareTo(y) <= 0); Assert.True(x < y); Assert.True(x <= y); Assert.False(x > y); Assert.False(x >= y); } [Fact] public void TestListOrdering1() { var x = List(1, 2, 3, 4, 5); var y = List(1, 2, 3, 4, 5); Assert.True(x.CompareTo(y) == 0); Assert.False(x < y); Assert.True(x <= y); Assert.False(x > y); Assert.True(x >= y); } [Fact] public void TestListOrdering2() { var x = List(1, 2, 3, 4, 5); var y = List(1, 2, 3, 4, 6); Assert.True(x.CompareTo(y) < 0); Assert.True(x.CompareTo(y) <= 0); Assert.True(x < y); Assert.True(x <= y); Assert.False(x > y); Assert.False(x >= y); } [Fact] public void TestListOrdering3() { var x = List(1, 2, 3, 4, 6); var y = List(1, 2, 3, 4, 5); Assert.True(x.CompareTo(y) > 0); Assert.True(x.CompareTo(y) >= 0); Assert.False(x < y); Assert.False(x <= y); Assert.True(x > y); Assert.True(x >= y); } [Fact] public void TestListOrdering4() { var x = List(1, 2, 3, 4, 5); var y = List(1, 2, 3, 4); Assert.True(x.CompareTo(y) > 0); Assert.True(x.CompareTo(y) >= 0); Assert.False(x < y); Assert.False(x <= y); Assert.True(x > y); Assert.True(x >= y); } [Fact] public void TestListOrdering5() { var x = List(1, 2, 3, 4); var y = List(1, 2, 3, 4, 5); Assert.True(x.CompareTo(y) < 0); Assert.True(x.CompareTo(y) <= 0); Assert.True(x < y); Assert.True(x <= y); Assert.False(x > y); Assert.False(x >= y); } [Fact] public void TestMapOrdering1() { var x = Map((1, 'a'), (2, 'a'), (3, 'a'), (4, 'a'), (5, 'a')); var y = Map((1, 'a'), (2, 'a'), (3, 'a'), (4, 'a'), (5, 'a')); Assert.True(x.CompareTo(y) == 0); Assert.False(x < y); Assert.True(x <= y); Assert.False(x > y); Assert.True(x >= y); } [Fact] public void TestMapOrdering2() { var x = Map((1, 'a'), (2, 'a'), (3, 'a'), (4, 'a'), (5, 'a')); var y = Map((1, 'a'), (2, 'a'), (3, 'a'), (4, 'a'), (6, 'a')); Assert.True(x.CompareTo(y) < 0); Assert.True(x.CompareTo(y) <= 0); Assert.True(x < y); Assert.True(x <= y); Assert.False(x > y); Assert.False(x >= y); } [Fact] public void TestMapOrdering3() { var x = Map((1, 'a'), (2, 'a'), (3, 'a'), (4, 'a'), (6, 'a')); var y = Map((1, 'a'), (2, 'a'), (3, 'a'), (4, 'a'), (5, 'a')); Assert.True(x.CompareTo(y) > 0); Assert.True(x.CompareTo(y) >= 0); Assert.False(x < y); Assert.False(x <= y); Assert.True(x > y); Assert.True(x >= y); } [Fact] public void TestMapOrdering4() { var x = Map((1, 'a'), (2, 'a'), (3, 'a'), (4, 'a'), (5, 'a')); var y = Map((1, 'a'), (2, 'a'), (3, 'a'), (4, 'a')); Assert.True(x.CompareTo(y) > 0); Assert.True(x.CompareTo(y) >= 0); Assert.False(x < y); Assert.False(x <= y); Assert.True(x > y); Assert.True(x >= y); } [Fact] public void TestMapOrdering5() { var x = Map((1, 'a'), (2, 'a'), (3, 'a'), (4, 'a')); var y = Map((1, 'a'), (2, 'a'), (3, 'a'), (4, 'a'), (5, 'a')); Assert.True(x.CompareTo(y) < 0); Assert.True(x.CompareTo(y) <= 0); Assert.True(x < y); Assert.True(x <= y); Assert.False(x > y); Assert.False(x >= y); } }
CollectionOrderingTests
csharp
dotnet__efcore
test/EFCore.SqlServer.FunctionalTests/Query/PrecompiledQuerySqlServerTest.cs
{ "start": 39630, "end": 39793 }
public class ____ // { // public int Id { get; set; } // public string StringProperty { get; set; } // public List<Post> Post { get; set; } // } // //
Blog
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/SagaStateMachineTests/Dynamic Modify/Transition_Specs.cs
{ "start": 2332, "end": 2619 }
class ____ : SagaStateMachineInstance { public State CurrentState { get; set; } public bool EnterCalled { get; set; } public Guid CorrelationId { get; set; } } } [TestFixture(Category = "Dynamic Modify")]
Instance
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.ServiceHost.Tests/Examples/funq_easy_registration.cs
{ "start": 744, "end": 1880 }
public class ____ : IBaz { public IBar Bar { get; set; } public Baz(IBar bar) { Bar = bar; } } [Test] public void should_be_able_to_get_service_impl() { var c = new Container(); c.EasyRegister<IFoo, Foo>(); Assert.IsInstanceOf<Foo>(c.Resolve<IFoo>()); } [Test] public void should_be_able_to_inject_dependency() { var c = new Container(); c.EasyRegister<IFoo, Foo>(); c.EasyRegister<IBar, Bar>(); var bar = c.Resolve<IBar>() as Bar; Assert.IsNotNull(bar.Foo); } [Test] public void should_be_able_to_chain_dependencies() { var c = new Container(); var testFoo = new Foo(); c.Register<IFoo>(testFoo); c.EasyRegister<IBar, Bar>(); c.EasyRegister<IBaz, Baz>(); var baz = c.Resolve<IBaz>() as Baz; var bar = baz.Bar as Bar; Assert.AreSame(bar.Foo, testFoo); } } }
Baz
csharp
dotnet__efcore
test/EFCore.Relational.Tests/TestUtilities/TestRelationalConventionSetBuilder.cs
{ "start": 194, "end": 590 }
public class ____( ProviderConventionSetBuilderDependencies dependencies, RelationalConventionSetBuilderDependencies relationalDependencies) : RelationalConventionSetBuilder(dependencies, relationalDependencies) { public static ConventionSet Build() => ConventionSet.CreateConventionSet(FakeRelationalTestHelpers.Instance.CreateContext()); }
TestRelationalConventionSetBuilder
csharp
nuke-build__nuke
source/Nuke.Common/Attributes/FileSystemGlobbingAttributeBase.cs
{ "start": 455, "end": 744 }
public class ____ : FileSystemGlobbingAttributeBase { public FileGlobbingAttribute(params string[] patterns) : base(patterns, Globbing.GlobFiles) { } } // TODO: document [PublicAPI] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
FileGlobbingAttribute
csharp
protobuf-net__protobuf-net
src/protobuf-net/Meta/MetaType.cs
{ "start": 113077, "end": 114480 }
enum ____ '{@enum.Name}'{CommentSuffix(reservation)}."); } } } if (_subTypes is not null) { foreach (var subType in _subTypes) { if (subType.FieldNumber >= reservation.From && subType.FieldNumber <= reservation.To) { throw new InvalidOperationException($"Field {subType.FieldNumber} is reserved and cannot be used for sub-type '{subType.DerivedType.Type.NormalizeName()}'{CommentSuffix(reservation)}."); } } } } else { if (_fields is not null) { foreach (var field in _fields) { if (field.Name == reservation.Name) { throw new InvalidOperationException($"Field '{field.Name}' is reserved and cannot be used for data member {field.FieldNumber}{CommentSuffix(reservation)}."); } } } if (_enums is not null) { foreach (var @
value
csharp
unoplatform__uno
src/Uno.UI/UI/Xaml/Data/BindingOperations.cs
{ "start": 280, "end": 1330 }
partial class ____ { /// <summary> /// Associates a <see cref="Binding"/> with a target property on a target object. /// This method is the code equivalent to using a {Binding} markup extension in XAML markup. /// </summary> /// <param name="target">The object that should be the target of the evaluated binding.</param> /// <param name="dp">The property on the target to bind, specified by its identifier. These identifiers are usually available as static read-only properties on the type that defines the target object, or one of its base types.</param> /// <param name="binding">The binding to assign to the target property. This <see cref="Binding"/> should be initialized: important <see cref="Binding"/> properties such as <see cref="PropertyPath"/> Path should already be set before passing it as the parameter.</param> public static void SetBinding(DependencyObject target, DependencyProperty dp, BindingBase binding) { (target as IDependencyObjectStoreProvider)?.Store.SetBinding(dp, binding); } } }
BindingOperations
csharp
NLog__NLog
src/NLog/Config/XmlParserConfigurationElement.cs
{ "start": 1777, "end": 7609 }
internal sealed class ____ : ILoggingConfigurationElement { /// <summary> /// Gets the element name. /// </summary> public string Name { get; private set; } /// <summary> /// Gets the value of the element. /// </summary> public string? Value { get; private set; } /// <summary> /// Gets the dictionary of attribute values. /// </summary> public IList<KeyValuePair<string, string?>> AttributeValues { get; } /// <summary> /// Gets the collection of child elements. /// </summary> public IList<XmlParserConfigurationElement> Children { get; } public IEnumerable<KeyValuePair<string, string?>> Values { get { for (int i = 0; i < Children.Count; ++i) { var child = Children[i]; if (SingleValueElement(child)) { // Values assigned using nested node-elements. Maybe in combination with attributes return AttributeValues.Concat(Children.Where(item => SingleValueElement(item)).Select(item => new KeyValuePair<string, string?>(item.Name, item.Value ?? string.Empty))); } } return AttributeValues; } } IEnumerable<ILoggingConfigurationElement> ILoggingConfigurationElement.Children { get { for (int i = 0; i < Children.Count; ++i) { var child = Children[i]; if (!SingleValueElement(child)) return Children.Where(item => !SingleValueElement(item)).Cast<ILoggingConfigurationElement>(); } return ArrayHelper.Empty<ILoggingConfigurationElement>(); } } public XmlParserConfigurationElement(XmlParser.XmlParserElement xmlElement) : this(xmlElement, false) { } public XmlParserConfigurationElement(XmlParser.XmlParserElement xmlElement, bool nestedElement) { var namePrefixIndex = xmlElement.Name.IndexOf(':'); Name = namePrefixIndex >= 0 ? xmlElement.Name.Substring(namePrefixIndex + 1) : xmlElement.Name; Value = xmlElement.InnerText; #pragma warning disable CS8619 // Nullability of reference types in value doesn't match target type. AttributeValues = ParseAttributes(xmlElement, nestedElement); #pragma warning restore CS8619 // Nullability of reference types in value doesn't match target type. Children = ParseChildren(xmlElement, nestedElement); } private static bool SingleValueElement(XmlParserConfigurationElement child) { // Node-element that works like an attribute return child.Children.Count == 0 && child.AttributeValues.Count == 0 && child.Value != null; } private static IList<KeyValuePair<string, string>> ParseAttributes(XmlParser.XmlParserElement xmlElement, bool nestedElement) { var attributes = xmlElement.Attributes; if (attributes?.Count > 0) { if (!nestedElement) { for (int i = attributes.Count - 1; i >= 0; --i) { var attributeName = attributes[i].Key; if (IsSpecialXmlRootAttribute(attributeName)) { attributes.RemoveAt(i); } } } for (int j = 0; j < attributes.Count; ++j) { var attributePrefixIndex = attributes[j].Key.IndexOf(':'); if (attributePrefixIndex >= 0) attributes[j] = new KeyValuePair<string, string>(attributes[j].Key.Substring(attributePrefixIndex + 1), attributes[j].Value); } } return attributes ?? ArrayHelper.Empty<KeyValuePair<string, string>>(); } private static IList<XmlParserConfigurationElement> ParseChildren(XmlParser.XmlParserElement xmlElement, bool nestedElement) { var childElements = xmlElement.Children; if (childElements is null || childElements.Count == 0) return ArrayHelper.Empty<XmlParserConfigurationElement>(); var children = new List<XmlParserConfigurationElement>(); for (int i = 0; i < childElements.Count; ++i) { var child = childElements[i]; var nestedChild = nestedElement || !string.Equals(child.Name, "nlog", StringComparison.OrdinalIgnoreCase); children.Add(new XmlParserConfigurationElement(child, nestedChild)); } return children; } /// <summary> /// Special attribute we could ignore /// </summary> private static bool IsSpecialXmlRootAttribute(string attributeName) { if (attributeName?.StartsWith("xmlns", StringComparison.OrdinalIgnoreCase) == true) return true; if (attributeName?.IndexOf(":xmlns", StringComparison.OrdinalIgnoreCase) >= 0) return true; if (attributeName?.StartsWith("schemaLocation", StringComparison.OrdinalIgnoreCase) == true) return true; if (attributeName?.IndexOf(":schemaLocation", StringComparison.OrdinalIgnoreCase) >= 0) return true; if (attributeName?.StartsWith("xsi:", StringComparison.OrdinalIgnoreCase) == true) return true; return false; } } }
XmlParserConfigurationElement
csharp
PrismLibrary__Prism
src/Maui/Prism.Maui/Behaviors/NavigationPageTabbedParentBehavior.cs
{ "start": 266, "end": 1990 }
public sealed class ____ : BehaviorBase<NavigationPage> { /// <inheritdoc /> protected override void OnAttachedTo(NavigationPage bindable) { base.OnAttachedTo(bindable); bindable.PropertyChanged += OnRootPageSet; } private void OnRootPagePropertyChanged(object sender, PropertyChangedEventArgs e) { if (sender is not Page page || page.Parent is not NavigationPage navigationPage) { return; } if (e.PropertyName == DynamicTab.TitleProperty.PropertyName) { navigationPage.Title = DynamicTab.GetTitle(page); } if (e.PropertyName == DynamicTab.IconImageSourceProperty.PropertyName) { navigationPage.IconImageSource = DynamicTab.GetIconImageSource(page); } } /// <inheritdoc /> protected override void OnDetachingFrom(NavigationPage bindable) { base.OnDetachingFrom(bindable); // Sanity Check bindable.PropertyChanged -= OnRootPageSet; if (bindable.RootPage is not null) { bindable.RootPage.PropertyChanged -= OnRootPagePropertyChanged; } } private void OnRootPageSet(object sender, PropertyChangedEventArgs e) { if (sender is NavigationPage navigationPage && navigationPage.RootPage is not null) { navigationPage.PropertyChanged -= OnRootPageSet; navigationPage.RootPage.PropertyChanged += OnRootPagePropertyChanged; navigationPage.Title = DynamicTab.GetTitle(navigationPage.RootPage); navigationPage.IconImageSource = DynamicTab.GetIconImageSource(navigationPage.RootPage); } } }
NavigationPageTabbedParentBehavior
csharp
microsoft__garnet
libs/storage/Tsavorite/cs/test/RecoveryTests.cs
{ "start": 8040, "end": 22240 }
public class ____ { const int StackAllocMax = 12; const int RandSeed = 101; const long ExpectedValueBase = DeviceTypeRecoveryTests.NumUniqueKeys * (DeviceTypeRecoveryTests.NumOps / DeviceTypeRecoveryTests.NumUniqueKeys - 1); private static long ExpectedValue(int key) => ExpectedValueBase + key; private IDisposable storeDisp; private Guid logToken; private Guid indexToken; private IDevice log; private IDevice objlog; private bool smallSector; [SetUp] public void Setup() { smallSector = false; // Only clean these in the initial Setup, as tests use the other Setup() overload to recover logToken = Guid.Empty; indexToken = Guid.Empty; DeleteDirectory(MethodTestDir, true); } private TsavoriteKV<TData, TData, TStoreFunctions, TAllocator> Setup<TData, TStoreFunctions, TAllocator>(AllocatorType allocatorType, Func<TStoreFunctions> storeFunctionsCreator, Func<AllocatorSettings, TStoreFunctions, TAllocator> allocatorCreator) where TStoreFunctions : IStoreFunctions<TData, TData> where TAllocator : IAllocator<TData, TData, TStoreFunctions> { log = new LocalMemoryDevice(1L << 26, 1L << 22, 2, sector_size: smallSector ? 64 : (uint)512, fileName: Path.Join(MethodTestDir, $"{typeof(TData).Name}.log")); objlog = allocatorType == AllocatorType.Generic ? new LocalMemoryDevice(1L << 26, 1L << 22, 2, fileName: Path.Join(MethodTestDir, $"{typeof(TData).Name}.obj.log")) : null; var result = new TsavoriteKV<TData, TData, TStoreFunctions, TAllocator>(new() { IndexSize = DeviceTypeRecoveryTests.KeySpace, LogDevice = log, ObjectLogDevice = objlog, SegmentSize = 1L << 25, CheckpointDir = MethodTestDir }, storeFunctionsCreator() , allocatorCreator ); storeDisp = result; return result; } [TearDown] public void TearDown() => TearDown(deleteDir: true); private void TearDown(bool deleteDir) { storeDisp?.Dispose(); storeDisp = null; log?.Dispose(); log = null; objlog?.Dispose(); objlog = null; // Do NOT clean up here unless specified, as tests use this TearDown() to prepare for recovery if (deleteDir) DeleteDirectory(MethodTestDir); } private TsavoriteKV<TData, TData, TStoreFunctions, TAllocator> PrepareToRecover<TData, TStoreFunctions, TAllocator>(AllocatorType allocatorType, Func<TStoreFunctions> storeFunctionsCreator, Func<AllocatorSettings, TStoreFunctions, TAllocator> allocatorCreator) where TStoreFunctions : IStoreFunctions<TData, TData> where TAllocator : IAllocator<TData, TData, TStoreFunctions> { TearDown(deleteDir: false); return Setup<TData, TStoreFunctions, TAllocator>(allocatorType, storeFunctionsCreator, allocatorCreator); } [Test] [Category("TsavoriteKV")] [Category("CheckpointRestore")] public async ValueTask RecoveryTestByAllocatorType([Values] AllocatorType allocatorType, [Values] bool isAsync) { await TestDriver(allocatorType, isAsync); } [Test] [Category("TsavoriteKV")] [Category("CheckpointRestore")] public async ValueTask RecoveryTestFailOnSectorSize([Values] AllocatorType allocatorType, [Values] bool isAsync) { smallSector = true; await TestDriver(allocatorType, isAsync); } private async ValueTask TestDriver(AllocatorType allocatorType, [Values] bool isAsync) { var task = allocatorType switch { AllocatorType.FixedBlittable => RunTest<long, LongStoreFunctions, LongAllocator>(allocatorType, () => StoreFunctions<long, long>.Create(LongKeyComparer.Instance), (allocatorSettings, storeFunctions) => new(allocatorSettings, storeFunctions), Populate, Read, Recover, isAsync), AllocatorType.SpanByte => RunTest<SpanByte, SpanByteStoreFunctions, SpanByteAllocator<SpanByteStoreFunctions>>(allocatorType, StoreFunctions<SpanByte, SpanByte>.Create, (allocatorSettings, storeFunctions) => new(allocatorSettings, storeFunctions), Populate, Read, Recover, isAsync), AllocatorType.Generic => RunTest<MyValue, MyValueStoreFunctions, MyValueAllocator>(allocatorType, () => StoreFunctions<MyValue, MyValue>.Create(new MyValue.Comparer(), () => new MyValueSerializer(), () => new MyValueSerializer(), DefaultRecordDisposer<MyValue, MyValue>.Instance), (allocatorSettings, storeFunctions) => new(allocatorSettings, storeFunctions), Populate, Read, Recover, isAsync), _ => throw new ApplicationException("Unknown allocator type"), }; ; await task; } private async ValueTask RunTest<TData, TStoreFunctions, TAllocator>(AllocatorType allocatorType, Func<TStoreFunctions> storeFunctionsCreator, Func<AllocatorSettings, TStoreFunctions, TAllocator> allocatorCreator, Action<TsavoriteKV<TData, TData, TStoreFunctions, TAllocator>> populateAction, Action<TsavoriteKV<TData, TData, TStoreFunctions, TAllocator>> readAction, Func<TsavoriteKV<TData, TData, TStoreFunctions, TAllocator>, bool, ValueTask> recoverFunc, bool isAsync) where TStoreFunctions : IStoreFunctions<TData, TData> where TAllocator : IAllocator<TData, TData, TStoreFunctions> { var store = Setup<TData, TStoreFunctions, TAllocator>(allocatorType, storeFunctionsCreator, allocatorCreator); populateAction(store); readAction(store); if (smallSector) { Assert.ThrowsAsync<TsavoriteException>(async () => await Checkpoint(store, isAsync)); Assert.Pass("Verified expected exception; the test cannot continue, so exiting early with success"); } else await Checkpoint(store, isAsync); ClassicAssert.AreNotEqual(Guid.Empty, logToken); ClassicAssert.AreNotEqual(Guid.Empty, indexToken); readAction(store); store = PrepareToRecover<TData, TStoreFunctions, TAllocator>(allocatorType, storeFunctionsCreator, allocatorCreator); await recoverFunc(store, isAsync); readAction(store); } private void Populate(TsavoriteKV<long, long, LongStoreFunctions, LongAllocator> store) { using var session = store.NewSession<long, long, Empty, SimpleSimpleFunctions<long, long>>(new SimpleSimpleFunctions<long, long>()); var bContext = session.BasicContext; for (int i = 0; i < DeviceTypeRecoveryTests.NumOps; i++) _ = bContext.Upsert(i % DeviceTypeRecoveryTests.NumUniqueKeys, i); _ = bContext.CompletePending(true); } static int GetRandomLength(Random r) => r.Next(StackAllocMax) + 1; // +1 to remain in range 1..StackAllocMax private unsafe void Populate(TsavoriteKV<SpanByte, SpanByte, SpanByteStoreFunctions, SpanByteAllocator<SpanByteStoreFunctions>> store) { using var session = store.NewSession<SpanByte, int[], Empty, VLVectorFunctions>(new VLVectorFunctions()); var bContext = session.BasicContext; Random rng = new(RandSeed); // Single alloc outside the loop, to the max length we'll need. Span<int> keySpan = stackalloc int[1]; Span<int> valueSpan = stackalloc int[StackAllocMax]; for (int i = 0; i < DeviceTypeRecoveryTests.NumOps; i++) { // We must be consistent on length across iterations of each key value var key0 = i % (int)DeviceTypeRecoveryTests.NumUniqueKeys; if (key0 == 0) rng = new(RandSeed); keySpan[0] = key0; var keySpanByte = keySpan.AsSpanByte(); var len = GetRandomLength(rng); for (int j = 0; j < len; j++) valueSpan[j] = i; var valueSpanByte = valueSpan.Slice(0, len).AsSpanByte(); _ = bContext.Upsert(ref keySpanByte, ref valueSpanByte, Empty.Default); } _ = bContext.CompletePending(true); } private unsafe void Populate(TsavoriteKV<MyValue, MyValue, MyValueStoreFunctions, MyValueAllocator> store) { using var session = store.NewSession<MyInput, MyOutput, Empty, MyFunctions2>(new MyFunctions2()); var bContext = session.BasicContext; for (int i = 0; i < DeviceTypeRecoveryTests.NumOps; i++) { var key = new MyValue { value = i % (int)DeviceTypeRecoveryTests.NumUniqueKeys }; var value = new MyValue { value = i }; _ = bContext.Upsert(key, value); } _ = bContext.CompletePending(true); } private async ValueTask Checkpoint<TData, TStoreFunctions, TAllocator>(TsavoriteKV<TData, TData, TStoreFunctions, TAllocator> store, bool isAsync) where TStoreFunctions : IStoreFunctions<TData, TData> where TAllocator : IAllocator<TData, TData, TStoreFunctions> { if (isAsync) { var (success, token) = await store.TakeFullCheckpointAsync(CheckpointType.Snapshot); ClassicAssert.IsTrue(success); logToken = token; } else { while (!store.TryInitiateFullCheckpoint(out logToken, CheckpointType.Snapshot)) { } store.CompleteCheckpointAsync().AsTask().GetAwaiter().GetResult(); } indexToken = logToken; } private async ValueTask RecoverAndReadTest(TsavoriteKV<long, long, LongStoreFunctions, LongAllocator> store, bool isAsync) { await Recover(store, isAsync); Read(store); } private static void Read(TsavoriteKV<long, long, LongStoreFunctions, LongAllocator> store) { using var session = store.NewSession<long, long, Empty, SimpleSimpleFunctions<long, long>>(new SimpleSimpleFunctions<long, long>()); var bContext = session.BasicContext; for (var i = 0; i < DeviceTypeRecoveryTests.NumUniqueKeys; i++) { var status = bContext.Read(i % DeviceTypeRecoveryTests.NumUniqueKeys, default, out long output); ClassicAssert.IsTrue(status.Found, $"keyIndex {i}"); ClassicAssert.AreEqual(ExpectedValue(i), output); } } private async ValueTask RecoverAndReadTest(TsavoriteKV<SpanByte, SpanByte, SpanByteStoreFunctions, SpanByteAllocator<SpanByteStoreFunctions>> store, bool isAsync) { await Recover(store, isAsync); Read(store); } private static void Read(TsavoriteKV<SpanByte, SpanByte, SpanByteStoreFunctions, SpanByteAllocator<SpanByteStoreFunctions>> store) { using var session = store.NewSession<SpanByte, int[], Empty, VLVectorFunctions>(new VLVectorFunctions()); var bContext = session.BasicContext; Random rng = new(RandSeed); Span<int> keySpan = stackalloc int[1]; var keySpanByte = keySpan.AsSpanByte(); for (var i = 0; i < DeviceTypeRecoveryTests.NumUniqueKeys; i++) { keySpan[0] = i; var len = GetRandomLength(rng); int[] output = null; var status = bContext.Read(ref keySpanByte, ref output, Empty.Default); ClassicAssert.IsTrue(status.Found); for (int j = 0; j < len; j++) ClassicAssert.AreEqual(ExpectedValue(i), output[j], $"mismatched data at position {j}, len {len}"); } } private async ValueTask RecoverAndReadTest(TsavoriteKV<MyValue, MyValue, MyValueStoreFunctions, MyValueAllocator> store, bool isAsync) { await Recover(store, isAsync); Read(store); } private static void Read(TsavoriteKV<MyValue, MyValue, MyValueStoreFunctions, MyValueAllocator> store) { using var session = store.NewSession<MyInput, MyOutput, Empty, MyFunctions2>(new MyFunctions2()); var bContext = session.BasicContext; for (var i = 0; i < DeviceTypeRecoveryTests.NumUniqueKeys; i++) { var key = new MyValue { value = i }; var status = bContext.Read(key, default, out MyOutput output); ClassicAssert.IsTrue(status.Found, $"keyIndex {i}"); ClassicAssert.AreEqual(ExpectedValue(i), output.value.value); } } private async ValueTask Recover<TData, TStoreFunctions, TAllocator>(TsavoriteKV<TData, TData, TStoreFunctions, TAllocator> store, bool isAsync = false) where TStoreFunctions : IStoreFunctions<TData, TData> where TAllocator : IAllocator<TData, TData, TStoreFunctions> { if (isAsync) _ = await store.RecoverAsync(indexToken, logToken); else _ = store.Recover(indexToken, logToken); } } }
AllocatorTypeRecoveryTests
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/AutoQueryDataServiceTests.cs
{ "start": 9906, "end": 10328 }
public class ____ : Service { public IAutoQueryData AutoQuery { get; set; } public object Any(GetAllRockstarGenresData requestDto) { var memorySource = new MemoryDataSource<RockstarGenre>(Db.Select<RockstarGenre>(), requestDto, Request); var q = AutoQuery.CreateQuery(requestDto, Request, memorySource); return AutoQuery.Execute(requestDto, q, memorySource); } }
CustomDataQueryServices
csharp
ServiceStack__ServiceStack
ServiceStack/tests/NorthwindBlazor/ServiceModel/Bookings.cs
{ "start": 354, "end": 1444 }
public class ____ : AuditBase { [AutoIncrement] public int Id { get; set; } public string Name { get; set; } = default!; public RoomType RoomType { get; set; } public int RoomNumber { get; set; } [IntlDateTime(DateStyle.Long)] public DateTime BookingStartDate { get; set; } [IntlRelativeTime] public DateTime? BookingEndDate { get; set; } [IntlNumber(Currency = NumberCurrency.USD)] public decimal Cost { get; set; } [References(typeof(Coupon))] [Ref(Model = nameof(Coupon), RefId = nameof(Coupon.Id), RefLabel = nameof(Coupon.Description))] public string? CouponId { get; set; } [Reference] public Coupon Discount { get; set; } public string? Notes { get; set; } public bool? Cancelled { get; set; } [References(typeof(Address))] public long? PermanentAddressId { get; set; } [Reference] public Address? PermanentAddress { get; set; } [References(typeof(Address))] public long? PostalAddressId { get; set; } [Reference] public Address? PostalAddress { get; set; } }
Booking
csharp
dotnet__extensions
src/Libraries/Microsoft.Extensions.Telemetry.Abstractions/Latency/NullLatencyContextServiceCollectionExtensions.cs
{ "start": 426, "end": 1221 }
public static class ____ { /// <summary> /// Adds a no-op latency context to a dependency injection container. /// </summary> /// <param name="services">The dependency injection container to add the context to.</param> /// <returns>The value of <paramref name="services"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="services"/> is <see langword="null"/>.</exception> public static IServiceCollection AddNullLatencyContext(this IServiceCollection services) { _ = Throw.IfNull(services); services.TryAddSingleton<ILatencyContextProvider, NullLatencyContext>(); services.TryAddSingleton<ILatencyContextTokenIssuer, NullLatencyContext>(); return services; } }
NullLatencyContextServiceCollectionExtensions
csharp
dotnet__machinelearning
docs/samples/Microsoft.ML.Samples/Dynamic/Trainers/Regression/OrdinaryLeastSquares.cs
{ "start": 166, "end": 3462 }
public static class ____ { public static void Example() { // Create a new context for ML.NET operations. It can be used for // exception tracking and logging, as a catalog of available operations // and as the source of randomness. Setting the seed to a fixed number // in this example to make outputs deterministic. var mlContext = new MLContext(seed: 0); // Create a list of training data points. var dataPoints = GenerateRandomDataPoints(1000); // Convert the list of data points to an IDataView object, which is // consumable by ML.NET API. var trainingData = mlContext.Data.LoadFromEnumerable(dataPoints); // Define the trainer. var pipeline = mlContext.Regression.Trainers.Ols( labelColumnName: nameof(DataPoint.Label), featureColumnName: nameof(DataPoint.Features)); // Train the model. var model = pipeline.Fit(trainingData); // Create testing data. Use different random seed to make it different // from training data. var testData = mlContext.Data.LoadFromEnumerable( GenerateRandomDataPoints(5, seed: 123)); // Run the model on test data set. var transformedTestData = model.Transform(testData); // Convert IDataView object to a list. var predictions = mlContext.Data.CreateEnumerable<Prediction>( transformedTestData, reuseRowObject: false).ToList(); // Look at 5 predictions for the Label, side by side with the actual // Label for comparison. foreach (var p in predictions) Console.WriteLine($"Label: {p.Label:F3}, Prediction: {p.Score:F3}"); // Expected output: // Label: 0.985, Prediction: 0.961 // Label: 0.155, Prediction: 0.072 // Label: 0.515, Prediction: 0.455 // Label: 0.566, Prediction: 0.499 // Label: 0.096, Prediction: 0.080 // Evaluate the overall metrics var metrics = mlContext.Regression.Evaluate(transformedTestData); PrintMetrics(metrics); // Expected output: // Mean Absolute Error: 0.05 // Mean Squared Error: 0.00 // Root Mean Squared Error: 0.06 // RSquared: 0.97 (closer to 1 is better. The worst case is 0) } private static IEnumerable<DataPoint> GenerateRandomDataPoints(int count, int seed = 0) { var random = new Random(seed); for (int i = 0; i < count; i++) { float label = (float)random.NextDouble(); yield return new DataPoint { Label = label, // Create random features that are correlated with the label. Features = Enumerable.Repeat(label, 50).Select( x => x + (float)random.NextDouble()).ToArray() }; } } // Example with label and 50 feature values. A data set is a collection of // such examples.
Ols
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.Sitemaps.Abstractions/Handlers/SitemapUpdateContext.cs
{ "start": 42, "end": 125 }
public class ____ { public object UpdateObject { get; set; } }
SitemapUpdateContext
csharp
abpframework__abp
framework/test/Volo.Abp.VirtualFileSystem.Tests/Volo/Abp/VirtualFileSystem/DynamicFileProvider_Tests.cs
{ "start": 216, "end": 2296 }
public class ____ : AbpIntegratedTest<DynamicFileProvider_Tests.TestModule> { private readonly IDynamicFileProvider _dynamicFileProvider; public DynamicFileProvider_Tests() { _dynamicFileProvider = GetRequiredService<IDynamicFileProvider>(); } [Fact] public void Should_Get_Created_Files() { const string fileContent = "Hello World"; _dynamicFileProvider.AddOrUpdate( new InMemoryFileInfo( "/my-files/test.txt", fileContent.GetBytes(), "test.txt" ) ); var fileInfo = _dynamicFileProvider.GetFileInfo("/my-files/test.txt"); fileInfo.ShouldNotBeNull(); fileInfo.ReadAsString().ShouldBe(fileContent); } [Fact] public void Should_Get_Notified_On_File_Change() { //Create a dynamic file _dynamicFileProvider.AddOrUpdate( new InMemoryFileInfo( "/my-files/test.txt", "Hello World".GetBytes(), "test.txt" ) ); //Register to change on that file var fileCallbackCalled = false; ChangeToken.OnChange( () => _dynamicFileProvider.Watch("/my-files/test.txt"), () => { fileCallbackCalled = true; }); //Updating the file should trigger the callback _dynamicFileProvider.AddOrUpdate( new InMemoryFileInfo( "/my-files/test.txt", "Hello World UPDATED".GetBytes(), "test.txt" ) ); fileCallbackCalled.ShouldBeTrue(); //Updating the file should trigger the callback (2nd test) fileCallbackCalled = false; _dynamicFileProvider.AddOrUpdate( new InMemoryFileInfo( "/my-files/test.txt", "Hello World UPDATED 2".GetBytes(), "test.txt" ) ); fileCallbackCalled.ShouldBeTrue(); } [DependsOn(typeof(AbpVirtualFileSystemModule))]
DynamicFileProvider_Tests
csharp
dotnet__efcore
test/EFCore.Tests/ChangeTracking/Internal/FixupCompositeTest.cs
{ "start": 129017, "end": 129219 }
private class ____ { public int Id1 { get; set; } public Guid Id2 { get; set; } public int ParentId1 { get; set; } public Guid ParentId2 { get; set; } }
ChildPN
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp.Dapper/Dapper/Filters/Action/IDapperActionFilter.cs
{ "start": 93, "end": 277 }
public interface ____ : ITransientDependency { void ExecuteFilter<TEntity, TPrimaryKey>(TEntity entity) where TEntity : class, IEntity<TPrimaryKey>; } }
IDapperActionFilter
csharp
ChilliCream__graphql-platform
src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp/Extensions/PropertyBuilderExtensions.cs
{ "start": 105, "end": 776 }
internal static class ____ { public static PropertyBuilder SetPublic(this PropertyBuilder builder) { return builder.SetAccessModifier(AccessModifier.Public); } public static PropertyBuilder SetPrivate(this PropertyBuilder builder) { return builder.SetAccessModifier(AccessModifier.Private); } public static PropertyBuilder SetInternal(this PropertyBuilder builder) { return builder.SetAccessModifier(AccessModifier.Internal); } public static PropertyBuilder SetProtected(this PropertyBuilder builder) { return builder.SetAccessModifier(AccessModifier.Protected); } }
PropertyBuilderExtensions
csharp
dotnet__efcore
test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs
{ "start": 15639, "end": 15853 }
public class ____ { public int Id { get; set; } public RelatedEntity72 ParentEntity { get; set; } public IEnumerable<RelatedEntity74> ChildEntities { get; set; } }
RelatedEntity73
csharp
graphql-dotnet__graphql-dotnet
src/GraphQL.Tests/Complexity/LegacyComplexityMetaDataTests.cs
{ "start": 2493, "end": 4293 }
public class ____ : ObjectGraphType<int> { public Hero() { Field<IntGraphType>("id").Resolve(context => context.Source) .ComplexityImpact(0); Field<StringGraphType>("name").Resolve(context => $"Tom_{context.Source}"); Field<ListGraphType<Hero>>("friends").Resolve(context => new List<int> { 0, 1, 2 }.Where(x => x != context.Source).ToList()) .ComplexityImpact(3); } } private readonly ServiceProvider _provider; private readonly IDocumentBuilder _documentBuilder; private readonly LegacyComplexityConfiguration _config; private readonly ISchema _schema; private readonly IDocumentExecuter _executer; public ComplexityMetaDataFixture() { _provider = new ServiceCollection() .AddGraphQL(builder => builder .AddSchema<ComplexitySchema>() .AddLegacyComplexityAnalyzer() ).BuildServiceProvider(); _documentBuilder = _provider.GetRequiredService<IDocumentBuilder>(); _config = _provider.GetRequiredService<LegacyComplexityConfiguration>(); _schema = _provider.GetRequiredService<ISchema>(); _executer = _provider.GetRequiredService<IDocumentExecuter<ComplexitySchema>>(); } public async Task<LegacyComplexityResult> AnalyzeAsync(string query) { var result = await _executer.ExecuteAsync(o => { o.Query = query; o.RequestServices = _provider; }).ConfigureAwait(false); result.Errors.ShouldBeNull(); return LegacyComplexityValidationRule.Analyze(_documentBuilder.Build(query), _config.FieldImpact ?? 2f, _config.MaxRecursionCount, _schema); } public void Dispose() => _provider.Dispose(); }
Hero
csharp
FastEndpoints__FastEndpoints
Src/Library/Messaging/Commands/CommandHandlerDefinition.cs
{ "start": 27, "end": 267 }
sealed class ____ { internal Type HandlerType { get; set; } internal object? HandlerExecutor { get; set; } internal CommandHandlerDefinition(Type handlerType) { HandlerType = handlerType; } }
CommandHandlerDefinition
csharp
StackExchange__StackExchange.Redis
src/StackExchange.Redis/ResultProcessor.cs
{ "start": 60713, "end": 61518 }
private sealed class ____ : ResultProcessor<long> { private readonly long _defaultValue; public Int64DefaultValueProcessor(long defaultValue) => _defaultValue = defaultValue; protected override bool SetResultCore(PhysicalConnection connection, Message message, in RawResult result) { if (result.IsNull) { SetResult(message, _defaultValue); return true; } if (result.Resp2TypeBulkString == ResultType.Integer && result.TryGetInt64(out var i64)) { SetResult(message, i64); return true; } return false; } }
Int64DefaultValueProcessor
csharp
FastEndpoints__FastEndpoints
Src/Messaging/Messaging.Core/Interfaces/ICommandHandler.cs
{ "start": 381, "end": 985 }
public interface ____<in TCommand> : ICommandHandler<TCommand, Void> where TCommand : ICommand { /// <summary> /// accepts a command and does not return a result. /// </summary> /// <param name="command">the input command object</param> /// <param name="ct">optional cancellation token</param> new Task ExecuteAsync(TCommand command, CancellationToken ct); async Task<Void> ICommandHandler<TCommand, Void>.ExecuteAsync(TCommand command, CancellationToken ct) { await ExecuteAsync(command, ct); return Void.Instance; } } /// <summary> ///
ICommandHandler
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/test/Types.Tests/Configuration/Validation/ObjectTypeValidation.cs
{ "start": 5998, "end": 6079 }
interface ____ { cde: String }
B
csharp
dotnet__aspire
src/Aspire.Dashboard/Model/ResourceViewModelExtensions.cs
{ "start": 279, "end": 5097 }
internal static class ____ { public static bool IsContainer(this ResourceViewModel resource) { return StringComparers.ResourceType.Equals(resource.ResourceType, KnownResourceTypes.Container); } public static bool IsProject(this ResourceViewModel resource) { return StringComparers.ResourceType.Equals(resource.ResourceType, KnownResourceTypes.Project); } public static bool IsExecutable(this ResourceViewModel resource, bool allowSubtypes) { if (StringComparers.ResourceType.Equals(resource.ResourceType, KnownResourceTypes.Executable)) { return true; } if (allowSubtypes) { return StringComparers.ResourceType.Equals(resource.ResourceType, KnownResourceTypes.Project); } return false; } public static bool TryGetExitCode(this ResourceViewModel resource, out int exitCode) { return resource.TryGetCustomDataInt(KnownProperties.Resource.ExitCode, out exitCode); } public static bool TryGetContainerImage(this ResourceViewModel resource, [NotNullWhen(returnValue: true)] out string? containerImage) { return resource.TryGetCustomDataString(KnownProperties.Container.Image, out containerImage); } public static bool TryGetProjectPath(this ResourceViewModel resource, [NotNullWhen(returnValue: true)] out string? projectPath) { return resource.TryGetCustomDataString(KnownProperties.Project.Path, out projectPath); } public static bool TryGetExecutablePath(this ResourceViewModel resource, [NotNullWhen(returnValue: true)] out string? executablePath) { return resource.TryGetCustomDataString(KnownProperties.Executable.Path, out executablePath); } public static bool TryGetExecutableArguments(this ResourceViewModel resource, out ImmutableArray<string> arguments) { return resource.TryGetCustomDataStringArray(KnownProperties.Executable.Args, out arguments); } public static bool TryGetAppArgs(this ResourceViewModel resource, out ImmutableArray<string> arguments) { return resource.TryGetCustomDataStringArray(KnownProperties.Resource.AppArgs, out arguments); } public static bool TryGetAppArgsSensitivity(this ResourceViewModel resource, out ImmutableArray<bool> argParams) { return resource.TryGetCustomDataBoolArray(KnownProperties.Resource.AppArgsSensitivity, out argParams); } private static bool TryGetCustomDataString(this ResourceViewModel resource, string key, [NotNullWhen(returnValue: true)] out string? s) { if (resource.Properties.TryGetValue(key, out var property) && property.Value.TryConvertToString(out var valueString)) { s = valueString; return true; } s = null; return false; } private static bool TryGetCustomDataStringArray(this ResourceViewModel resource, string key, out ImmutableArray<string> strings) { if (resource.Properties.TryGetValue(key, out var property) && property is { Value: { ListValue: not null } value }) { var builder = ImmutableArray.CreateBuilder<string>(value.ListValue.Values.Count); foreach (var element in value.ListValue.Values) { if (!element.TryConvertToString(out var elementString)) { strings = default; return false; } builder.Add(elementString); } strings = builder.MoveToImmutable(); return true; } strings = default; return false; } private static bool TryGetCustomDataBoolArray(this ResourceViewModel resource, string key, out ImmutableArray<bool> bools) { if (resource.Properties.TryGetValue(key, out var property) && property is { Value: { ListValue: not null } value }) { var builder = ImmutableArray.CreateBuilder<bool>(value.ListValue.Values.Count); foreach (var element in value.ListValue.Values) { if (!element.HasNumberValue) { bools = default; return false; } builder.Add(Convert.ToBoolean(element.NumberValue)); } bools = builder.MoveToImmutable(); return true; } bools = default; return false; } private static bool TryGetCustomDataInt(this ResourceViewModel resource, string key, out int i) { if (resource.Properties.TryGetValue(key, out var property) && property.Value.TryConvertToInt(out i)) { return true; } i = 0; return false; } }
ResourceViewModelExtensions
csharp
Testably__Testably.Abstractions
Tests/Testably.Abstractions.Testing.Tests/MockFileSystemExtensionsTests.cs
{ "start": 140, "end": 576 }
public class ____ { [Fact] public async Task GetDefaultDrive_WithoutDrives_ShouldThrowInvalidOperationException() { MockFileSystem fileSystem = new(); (fileSystem.Storage as InMemoryStorage)?.RemoveDrive(string.Empty.PrefixRoot(fileSystem)); Exception? exception = Record.Exception(() => { fileSystem.GetDefaultDrive(); }); await That(exception).IsExactly<InvalidOperationException>(); } }
MockFileSystemExtensionsTests
csharp
smartstore__Smartstore
src/Smartstore.Core/Common/Services/GenericAttributeService.cs
{ "start": 201, "end": 4331 }
public partial class ____ : AsyncDbSaveHook<GenericAttribute>, IGenericAttributeService { private readonly SmartDbContext _db; private readonly IStoreContext _storeContext; private readonly IEventPublisher _eventPublisher; // Key = (EntityName, EntityId) private readonly Dictionary<(string, int), GenericAttributeCollection> _collectionCache = []; public GenericAttributeService(SmartDbContext db, IStoreContext storeContext, IEventPublisher eventPublisher) { _db = db; _storeContext = storeContext; _eventPublisher = eventPublisher; } #region Hook public override Task<HookResult> OnAfterSaveAsync(IHookedEntity entry, CancellationToken cancelToken) => Task.FromResult(HookResult.Ok); public override async Task OnAfterSaveCompletedAsync(IEnumerable<IHookedEntity> entries, CancellationToken cancelToken) { // Publish OrderUpdated event for attributes referring to order entities. var orderIds = entries .Select(x => x.Entity) .OfType<GenericAttribute>() .Where(x => x.KeyGroup.EqualsNoCase(nameof(Order)) && x.EntityId > 0) .Select(x => x.EntityId) .Distinct() .ToArray(); if (orderIds.Any()) { var orders = await _db.Orders.GetManyAsync(orderIds, true); foreach (var order in orders) { await _eventPublisher.PublishOrderUpdatedAsync(order); } } } #endregion public virtual GenericAttributeCollection GetAttributesForEntity(string entityName, int entityId) { Guard.NotEmpty(entityName); if (entityId <= 0) { // Return a read-only collection return new GenericAttributeCollection(entityName); } var key = (entityName.ToLowerInvariant(), entityId); if (!_collectionCache.TryGetValue(key, out var collection)) { var query = from attr in _db.GenericAttributes where attr.EntityId == entityId && attr.KeyGroup == entityName select attr; collection = new GenericAttributeCollection(query, entityName, entityId, _storeContext.CurrentStore.Id); _collectionCache[key] = collection; } return collection; } public virtual async Task PrefetchAttributesAsync(string entityName, int[] entityIds) { Guard.NotEmpty(entityName); Guard.NotNull(entityIds); if (entityIds.Length == 0) { return; } // Reduce entityIds by already loaded collections. var ids = new List<int>(entityIds.Length); foreach (var id in entityIds.Distinct().OrderBy(x => x)) { if (!_collectionCache.ContainsKey((entityName.ToLowerInvariant(), id))) { ids.Add(id); } } var storeId = _storeContext.CurrentStore.Id; var attributes = await _db.GenericAttributes .Where(x => ids.Contains(x.EntityId) && x.KeyGroup == entityName) .ToListAsync(); var groupedAttributes = attributes .GroupBy(x => x.EntityId) .ToList(); foreach (var group in groupedAttributes) { var entityId = group.Key; var collection = new GenericAttributeCollection( _db.GenericAttributes.Where(x => x.EntityId == entityId && x.KeyGroup == entityName), entityName, entityId, storeId, group.ToList()); _collectionCache[(entityName.ToLowerInvariant(), entityId)] = collection; } } } }
GenericAttributeService
csharp
CommunityToolkit__WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.Notifications/Toasts/Compat/Desktop/ManifestHelper.cs
{ "start": 2973, "end": 4264 }
class ____ matching their current process executable var comExeServerNode = comClassNode.ParentNode; var specifiedExeRelativePath = comExeServerNode.Attributes["Executable"].Value; var specifiedExeFullPath = Path.Combine(Package.Current.InstalledLocation.Path, specifiedExeRelativePath); var actualExeFullPath = Process.GetCurrentProcess().MainModule.FileName; if (specifiedExeFullPath != actualExeFullPath) { var correctExeRelativePath = actualExeFullPath.Substring(Package.Current.InstalledLocation.Path.Length + 1); throw new InvalidOperationException($"Your app manifest's comServer extension's Executable value is incorrect. It should be \"{correctExeRelativePath}\"."); } // Make sure their arguments are set correctly var argumentsNode = comExeServerNode.Attributes.GetNamedItem("Arguments"); if (argumentsNode == null || argumentsNode.Value != "-ToastActivated") { throw new InvalidOperationException("Your app manifest's comServer extension for toast activation must have its Arguments set exactly to \"-ToastActivated\""); } return clsid; } } } #endif
registration
csharp
abpframework__abp
modules/docs/test/Volo.Docs.EntityFrameworkCore.Tests/Volo/Docs/EntityFrameworkCore/ProjectRepository_Tests.cs
{ "start": 47, "end": 160 }
public class ____ : ProjectRepository_Tests<DocsEntityFrameworkCoreTestModule> { } }
ProjectRepository_Tests
csharp
microsoft__semantic-kernel
dotnet/test/VectorData/Pinecone.ConformanceTests/PineconeAllSupportedTypesTests.cs
{ "start": 224, "end": 2893 }
public class ____(PineconeFixture fixture) : IClassFixture<PineconeFixture> { [ConditionalFact] public async Task AllTypesBatchGetAsync() { var collection = fixture.TestStore.DefaultVectorStore.GetCollection<string, PineconeAllTypes>("all-types", PineconeAllTypes.GetRecordDefinition()); await collection.EnsureCollectionExistsAsync(); List<PineconeAllTypes> records = [ new() { Id = "all-types-1", BoolProperty = true, NullableBoolProperty = false, StringProperty = "string prop 1", NullableStringProperty = "nullable prop 1", IntProperty = 1, NullableIntProperty = 10, LongProperty = 100L, NullableLongProperty = 1000L, FloatProperty = 10.5f, NullableFloatProperty = 100.5f, DoubleProperty = 23.75d, NullableDoubleProperty = 233.75d, StringArray = ["one", "two"], NullableStringArray = ["five", "six"], StringList = ["eleven", "twelve"], NullableStringList = ["fifteen", "sixteen"], Embedding = new ReadOnlyMemory<float>([1.5f, 2.5f, 3.5f, 4.5f, 5.5f, 6.5f, 7.5f, 8.5f]) }, new() { Id = "all-types-2", BoolProperty = false, NullableBoolProperty = null, StringProperty = "string prop 2", NullableStringProperty = null, IntProperty = 2, NullableIntProperty = null, LongProperty = 200L, NullableLongProperty = null, FloatProperty = 20.5f, NullableFloatProperty = null, DoubleProperty = 43.75, NullableDoubleProperty = null, StringArray = [], NullableStringArray = null, StringList = [], NullableStringList = null, Embedding = new ReadOnlyMemory<float>([10.5f, 20.5f, 30.5f, 40.5f, 50.5f, 60.5f, 70.5f, 80.5f]) } ]; await collection.UpsertAsync(records); var allTypes = await collection.GetAsync(records.Select(r => r.Id), new RecordRetrievalOptions { IncludeVectors = true }).ToListAsync(); var allTypes1 = allTypes.Single(x => x.Id == records[0].Id); var allTypes2 = allTypes.Single(x => x.Id == records[1].Id); records[0].AssertEqual(allTypes1); records[1].AssertEqual(allTypes2); } }
PineconeAllSupportedTypesTests
csharp
dotnet__maui
src/Controls/tests/DeviceTests/Elements/Shell/ShellTests.iOS.cs
{ "start": 13234, "end": 13522 }
class ____ : ShellRenderer { protected override IShellNavBarAppearanceTracker CreateNavBarAppearanceTracker() => new CustomShellNavBarAppearanceTracker(this, base.CreateNavBarAppearanceTracker()) { handler = this }; public CGRect PreviousFrame { get; set; } }
CustomShellHandler
csharp
nuke-build__nuke
source/Nuke.Tooling.Generator/Model/RegexPatterns.cs
{ "start": 209, "end": 306 }
internal static class ____ { public const string Name = "^[0-9A-Z][A-Za-z0-9]*$"; }
RegexPatterns
csharp
Testably__Testably.Abstractions
Tests/Testably.Abstractions.AccessControl.Tests/Internal/AccessControlHelperTests.cs
{ "start": 2621, "end": 2707 }
private sealed class ____() : FileSystemStream(Null, ".", false); }
CustomFileSystemStream
csharp
NSubstitute__NSubstitute
src/NSubstitute/Core/IMethodInfoFormatter.cs
{ "start": 56, "end": 222 }
public interface ____ { bool CanFormat(MethodInfo methodInfo); string Format(MethodInfo methodInfo, IEnumerable<string> formattedArguments); }
IMethodInfoFormatter
csharp
dotnet__machinelearning
src/Microsoft.Data.Analysis/DataFrame.cs
{ "start": 939, "end": 31078 }
public partial class ____ { internal const int DefaultMaxRowsToShowInPreview = 25; private readonly DataFrameColumnCollection _columnCollection; private readonly DataFrameRowCollection _rowCollection; /// <summary> /// Constructs a <see cref="DataFrame"/> with <paramref name="columns"/>. /// </summary> /// <param name="columns">The columns of this <see cref="DataFrame"/>.</param> public DataFrame(IEnumerable<DataFrameColumn> columns) { _columnCollection = new DataFrameColumnCollection(columns, OnColumnsChanged); _rowCollection = new DataFrameRowCollection(this); } public DataFrame(params DataFrameColumn[] columns) { _columnCollection = new DataFrameColumnCollection(columns, OnColumnsChanged); _rowCollection = new DataFrameRowCollection(this); } /// <summary> /// Returns the columns contained in the <see cref="DataFrame"/> as a <see cref="DataFrameColumnCollection"/> /// </summary> public DataFrameColumnCollection Columns => _columnCollection; /// <summary> /// Returns a <see cref="DataFrameRowCollection"/> that contains a view of the rows in this <see cref="DataFrame"/> /// </summary> public DataFrameRowCollection Rows => _rowCollection; internal IReadOnlyList<string> GetColumnNames() => _columnCollection.GetColumnNames(); #region Operators /// <summary> /// An Indexer to get or set values. /// </summary> /// <param name="rowIndex">Zero based row index</param> /// <param name="columnIndex">Zero based column index</param> /// <returns>The value stored at the intersection of <paramref name="rowIndex"/> and <paramref name="columnIndex"/></returns> public object this[long rowIndex, int columnIndex] { get => _columnCollection[columnIndex][rowIndex]; set => _columnCollection[columnIndex][rowIndex] = value; } /// <summary> /// Returns a new DataFrame using the boolean values in <paramref name="filter"/> /// </summary> /// <param name="filter">A column of booleans</param> public DataFrame Filter(PrimitiveDataFrameColumn<bool> filter) => Clone(filter); /// <summary> /// Returns a new DataFrame using the row indices in <paramref name="rowIndices"/> /// </summary> /// <param name="rowIndices">A column of row indices</param> public DataFrame Filter(PrimitiveDataFrameColumn<int> rowIndices) => Clone(rowIndices); /// <summary> /// Returns a new DataFrame using the row indices in <paramref name="rowIndices"/> /// </summary> /// <param name="rowIndices">A column of row indices</param> public DataFrame Filter(PrimitiveDataFrameColumn<long> rowIndices) => Clone(rowIndices); /// <summary> /// Returns a new DataFrame using the boolean values in filter /// </summary> /// <param name="rowFilter">A column of booleans</param> public DataFrame this[PrimitiveDataFrameColumn<bool> rowFilter] => Filter(rowFilter); /// <summary> /// Returns a new DataFrame using the row indices in <paramref name="rowIndices"/> /// </summary> /// <param name="rowIndices">A column of row indices</param> public DataFrame this[PrimitiveDataFrameColumn<int> rowIndices] => Filter(rowIndices); /// <summary> /// Returns a new DataFrame using the row indices in <paramref name="rowIndices"/> /// </summary> /// <param name="rowIndices">A column of row indices</param> public DataFrame this[PrimitiveDataFrameColumn<long> rowIndices] => Filter(rowIndices); /// <summary> /// Returns a new DataFrame using the row indices in <paramref name="rowIndices"/> /// </summary> public DataFrame this[IEnumerable<int> rowIndices] { get { PrimitiveDataFrameColumn<int> filterColumn = new PrimitiveDataFrameColumn<int>("Filter", rowIndices); return Clone(filterColumn); } } /// <summary> /// Returns a new DataFrame using the row indices in <paramref name="rowIndices"/> /// </summary> public DataFrame this[IEnumerable<long> rowIndices] { get { PrimitiveDataFrameColumn<long> filterColumn = new PrimitiveDataFrameColumn<long>("Filter", rowIndices); return Clone(filterColumn); } } /// <summary> /// Returns a new DataFrame using the boolean values in <paramref name="rowFilter"/> /// </summary> public DataFrame this[IEnumerable<bool> rowFilter] { get { PrimitiveDataFrameColumn<bool> filterColumn = new PrimitiveDataFrameColumn<bool>("Filter", rowFilter); return Clone(filterColumn); } } /// <summary> /// An indexer based on <see cref="DataFrameColumn.Name"/> /// </summary> /// <param name="columnName">The name of a <see cref="DataFrameColumn"/></param> /// <returns>A <see cref="DataFrameColumn"/> if it exists.</returns> /// <exception cref="ArgumentException">Throws if <paramref name="columnName"/> is not present in this <see cref="DataFrame"/></exception> public DataFrameColumn this[string columnName] { get => Columns[columnName]; set => Columns[columnName] = value; } /// <summary> /// Returns the first <paramref name="numberOfRows"/> rows /// </summary> /// <param name="numberOfRows"></param> public DataFrame Head(int numberOfRows) { return Clone(new PrimitiveDataFrameColumn<int>("Filter", Enumerable.Range(0, numberOfRows))); } /// <summary> /// Returns the last <paramref name="numberOfRows"/> rows /// </summary> /// <param name="numberOfRows"></param> public DataFrame Tail(int numberOfRows) { PrimitiveDataFrameColumn<long> filter = new PrimitiveDataFrameColumn<long>("Filter", numberOfRows); for (long i = Rows.Count - numberOfRows; i < Rows.Count; i++) { filter[i - (Rows.Count - numberOfRows)] = i; } return Clone(filter); } // TODO: Add strongly typed versions of these APIs #endregion /// <summary> /// Returns a full copy /// </summary> public DataFrame Clone() { return Clone(mapIndices: null); } private DataFrame Clone(DataFrameColumn mapIndices = null) { List<DataFrameColumn> newColumns = new List<DataFrameColumn>(Columns.Count); for (int i = 0; i < Columns.Count; i++) { newColumns.Add(Columns[i].Clone(mapIndices)); } return new DataFrame(newColumns); } /// <summary> /// Generates a concise summary of each column in the DataFrame /// </summary> public DataFrame Info() { DataFrame ret = new DataFrame(); bool firstColumn = true; foreach (DataFrameColumn column in Columns) { if (firstColumn) { firstColumn = false; StringDataFrameColumn strColumn = new StringDataFrameColumn("Info", 2); strColumn[0] = Strings.DataType; strColumn[1] = Strings.DescriptionMethodLength; ret.Columns.Add(strColumn); } ret.Columns.Add(column.Info()); } return ret; } /// <summary> /// Generates descriptive statistics that summarize each numeric column /// </summary> public DataFrame Description() { DataFrame ret = new DataFrame(); bool firstDescriptionColumn = true; foreach (DataFrameColumn column in Columns) { if (!column.HasDescription()) { continue; } if (firstDescriptionColumn) { firstDescriptionColumn = false; StringDataFrameColumn stringColumn = new StringDataFrameColumn("Description", 0); stringColumn.Append(Strings.DescriptionMethodLength); stringColumn.Append("Max"); stringColumn.Append("Min"); stringColumn.Append("Mean"); ret.Columns.Add(stringColumn); } ret.Columns.Add(column.Description()); } return ret; } /// <summary> /// Orders the data frame by a specified column. /// </summary> /// <param name="columnName">The column name to order by.</param> /// <param name="ascending">Sorting order.</param> /// <param name="putNullValuesLast">If true, null values are always put at the end.</param> public DataFrame OrderBy(string columnName, bool ascending = true, bool putNullValuesLast = true) { return Sort(columnName, ascending, putNullValuesLast); } /// <summary> /// Orders the data frame by a specified column in descending order. /// </summary> /// <param name="columnName">The column name to order by.</param> /// <param name="putNullValuesLast">If true, null values are always put at the end.</param> public DataFrame OrderByDescending(string columnName, bool putNullValuesLast = true) { return Sort(columnName, false, putNullValuesLast); } /// <summary> /// Clamps values beyond the specified thresholds on numeric columns /// </summary> /// <typeparam name="U"></typeparam> /// <param name="min">Minimum value. All values below this threshold will be set to it</param> /// <param name="max">Maximum value. All values above this threshold will be set to it</param> /// <param name="inPlace">Indicates if the operation should be performed in place</param> public DataFrame Clamp<U>(U min, U max, bool inPlace = false) { DataFrame ret = inPlace ? this : Clone(); for (int i = 0; i < ret.Columns.Count; i++) { DataFrameColumn column = ret.Columns[i]; if (column.IsNumericColumn()) column.Clamp(min, max, inPlace: true); } return ret; } /// <summary> /// Adds a prefix to the column names /// </summary> public DataFrame AddPrefix(string prefix, bool inPlace = false) { DataFrame df = inPlace ? this : Clone(); for (int i = 0; i < df.Columns.Count; i++) { DataFrameColumn column = df.Columns[i]; column.SetName(prefix + column.Name); df.OnColumnsChanged(); } return df; } /// <summary> /// Adds a suffix to the column names /// </summary> public DataFrame AddSuffix(string suffix, bool inPlace = false) { DataFrame df = inPlace ? this : Clone(); for (int i = 0; i < df.Columns.Count; i++) { DataFrameColumn column = df.Columns[i]; column.SetName(column.Name + suffix); df.OnColumnsChanged(); } return df; } /// <summary> /// Returns a random sample of rows /// </summary> /// <param name="numberOfRows">Number of rows in the returned DataFrame</param> public DataFrame Sample(int numberOfRows) { if (numberOfRows > Rows.Count) { throw new ArgumentException(string.Format(Strings.ExceedsNumberOfRows, Rows.Count), nameof(numberOfRows)); } int shuffleLowerLimit = 0; int shuffleUpperLimit = (int)Math.Min(Int32.MaxValue, Rows.Count); int[] shuffleArray = Enumerable.Range(0, shuffleUpperLimit).ToArray(); Random rand = new Random(); while (shuffleLowerLimit < numberOfRows) { int randomIndex = rand.Next(shuffleLowerLimit, shuffleUpperLimit); int temp = shuffleArray[shuffleLowerLimit]; shuffleArray[shuffleLowerLimit] = shuffleArray[randomIndex]; shuffleArray[randomIndex] = temp; shuffleLowerLimit++; } ArraySegment<int> segment = new ArraySegment<int>(shuffleArray, 0, shuffleLowerLimit); PrimitiveDataFrameColumn<int> indices = new PrimitiveDataFrameColumn<int>("indices", segment); return Clone(indices); } /// <summary> /// Groups the rows of the <see cref="DataFrame"/> by unique values in the <paramref name="columnName"/> column. /// </summary> /// <param name="columnName">The column used to group unique values</param> /// <returns>A GroupBy object that stores the group information.</returns> public GroupBy GroupBy(string columnName) { int columnIndex = _columnCollection.IndexOf(columnName); if (columnIndex == -1) throw new ArgumentException(String.Format(Strings.InvalidColumnName, columnName), nameof(columnName)); DataFrameColumn column = _columnCollection[columnIndex]; return column.GroupBy(columnIndex, this); } /// <summary> /// Groups the rows of the <see cref="DataFrame"/> by unique values in the <paramref name="columnName"/> column. /// </summary> /// <typeparam name="TKey">Type of column used for grouping</typeparam> /// <param name="columnName">The column used to group unique values</param> /// <returns>A GroupBy object that stores the group information.</returns> public GroupBy<TKey> GroupBy<TKey>(string columnName) { GroupBy<TKey> group = GroupBy(columnName) as GroupBy<TKey>; if (group == null) { DataFrameColumn column = this[columnName]; throw new InvalidCastException(String.Format(Strings.BadColumnCastDuringGrouping, columnName, column.DataType, typeof(TKey))); } return group; } // In GroupBy and ReadCsv calls, columns get resized. We need to set the RowCount to reflect the true Length of the DataFrame. This does internal validation internal void SetTableRowCount(long rowCount) { // Even if current RowCount == rowCount, do the validation for (int i = 0; i < Columns.Count; i++) { if (Columns[i].Length != rowCount) throw new ArgumentException(String.Format("{0} {1}", Strings.MismatchedRowCount, Columns[i].Name)); } _columnCollection.RowCount = rowCount; } /// <summary> /// Returns a DataFrame with no missing values /// </summary> /// <param name="options"></param> public DataFrame DropNulls(DropNullOptions options = DropNullOptions.Any) { var filter = new BooleanDataFrameColumn("Filter"); if (options == DropNullOptions.Any) { filter.AppendMany(true, Rows.Count); var buffers = filter.ColumnContainer.Buffers; foreach (var column in Columns) { long index = 0; for (int b = 0; b < buffers.Count; b++) { var span = buffers.GetOrCreateMutable(b).Span; for (int i = 0; i < span.Length; i++) { span[i] = span[i] && column.IsValid(index); index++; } } } } else { filter.AppendMany(false, Rows.Count); var buffers = filter.ColumnContainer.Buffers; foreach (var column in Columns) { long index = 0; for (int b = 0; b < buffers.Count; b++) { var span = buffers.GetOrCreateMutable(b).Span; for (int i = 0; i < span.Length; i++) { span[i] = span[i] || column.IsValid(index); index++; } } } } return this[filter]; } /// <summary> /// Fills <see langword="null" /> values with <paramref name="value"/>. /// </summary> /// <param name="value">The value to replace <see langword="null" /> with.</param> /// <param name="inPlace">A boolean flag to indicate if the operation should be in place</param> /// <returns>A new <see cref="DataFrame"/> if <paramref name="inPlace"/> is not set. Returns this <see cref="DataFrame"/> otherwise.</returns> public DataFrame FillNulls(object value, bool inPlace = false) { DataFrame ret = inPlace ? this : Clone(); for (int i = 0; i < ret.Columns.Count; i++) { ret.Columns[i].FillNulls(value, inPlace: true); } return ret; } /// <summary> /// Fills <see langword="null" /> values in each column with values from <paramref name="values"/>. /// </summary> /// <param name="values">The values to replace <see langword="null" /> with, one value per column. Should be equal to the number of columns in this <see cref="DataFrame"/>. </param> /// <param name="inPlace">A boolean flag to indicate if the operation should be in place</param> /// <returns>A new <see cref="DataFrame"/> if <paramref name="inPlace"/> is not set. Returns this <see cref="DataFrame"/> otherwise.</returns> public DataFrame FillNulls(IList<object> values, bool inPlace = false) { if (values.Count != Columns.Count) throw new ArgumentException(Strings.MismatchedColumnLengths, nameof(values)); DataFrame ret = inPlace ? this : Clone(); for (int i = 0; i < ret.Columns.Count; i++) { Columns[i].FillNulls(values[i], inPlace: true); } return ret; } private void ResizeByOneAndAppend(DataFrameColumn column, object value) { long length = column.Length; column.Resize(length + 1); column[length] = value; } /// <summary> /// Appends rows to the DataFrame /// </summary> /// <remarks>If an input column's value doesn't match a DataFrameColumn's data type, a conversion will be attempted</remarks> /// <remarks>If a <seealso cref="DataFrameRow"/> in <paramref name="rows"/> is null, a null value is appended to each column</remarks> /// <remarks> Values are appended based on the column names</remarks> /// <param name="rows">The rows to be appended to this DataFrame </param> /// <param name="inPlace">If set, appends <paramref name="rows"/> in place. Otherwise, a new DataFrame is returned with the <paramref name="rows"/> appended</param> /// <param name="cultureInfo">culture info for formatting values</param> public DataFrame Append(IEnumerable<DataFrameRow> rows, bool inPlace = false, CultureInfo cultureInfo = null) { DataFrame ret = inPlace ? this : Clone(); foreach (DataFrameRow row in rows) { ret.Append(row.GetValues(), inPlace: true, cultureInfo: cultureInfo); } return ret; } /// <summary> /// Appends a row to the DataFrame /// </summary> /// <remarks>If a column's value doesn't match its column's data type, a conversion will be attempted</remarks> /// <remarks>If <paramref name="row"/> is null, a null value is appended to each column</remarks> /// <param name="row"></param> /// <param name="inPlace">If set, appends a <paramref name="row"/> in place. Otherwise, a new DataFrame is returned with an appended <paramref name="row"/> </param> /// <param name="cultureInfo">Culture info for formatting values</param> public DataFrame Append(IEnumerable<object> row = null, bool inPlace = false, CultureInfo cultureInfo = null) { if (cultureInfo == null) { cultureInfo = CultureInfo.CurrentCulture; } DataFrame ret = inPlace ? this : Clone(); IEnumerator<DataFrameColumn> columnEnumerator = ret.Columns.GetEnumerator(); bool columnMoveNext = columnEnumerator.MoveNext(); if (row != null) { // Go through row first to make sure there are no data type incompatibilities IEnumerator<object> rowEnumerator = row.GetEnumerator(); bool rowMoveNext = rowEnumerator.MoveNext(); List<object> cachedObjectConversions = new List<object>(); while (columnMoveNext && rowMoveNext) { DataFrameColumn column = columnEnumerator.Current; object value = rowEnumerator.Current; // StringDataFrameColumn can accept empty strings. The other columns interpret empty values as nulls if (value is string stringValue) { if (stringValue.Length == 0 && column.DataType != typeof(string)) { value = null; } else if (stringValue.Equals("null", StringComparison.OrdinalIgnoreCase)) { value = null; } } if (value != null) { value = Convert.ChangeType(value, column.DataType, cultureInfo); if (value is null) { throw new ArgumentException(string.Format(Strings.MismatchedValueType, column.DataType), column.Name); } } cachedObjectConversions.Add(value); columnMoveNext = columnEnumerator.MoveNext(); rowMoveNext = rowEnumerator.MoveNext(); } if (rowMoveNext) { throw new ArgumentException(string.Format(Strings.ExceedsNumberOfColumns, Columns.Count), nameof(row)); } // Reset the enumerators columnEnumerator = ret.Columns.GetEnumerator(); columnMoveNext = columnEnumerator.MoveNext(); rowEnumerator = row.GetEnumerator(); rowMoveNext = rowEnumerator.MoveNext(); int cacheIndex = 0; while (columnMoveNext && rowMoveNext) { DataFrameColumn column = columnEnumerator.Current; object value = cachedObjectConversions[cacheIndex]; ret.ResizeByOneAndAppend(column, value); columnMoveNext = columnEnumerator.MoveNext(); rowMoveNext = rowEnumerator.MoveNext(); cacheIndex++; } } while (columnMoveNext) { // Fill the remaining columns with null DataFrameColumn column = columnEnumerator.Current; ret.ResizeByOneAndAppend(column, null); columnMoveNext = columnEnumerator.MoveNext(); } ret.Columns.RowCount++; return ret; } /// <summary> /// Appends a row by enumerating column names and values from <paramref name="row"/> /// </summary> /// <remarks>If a column's value doesn't match its column's data type, a conversion will be attempted</remarks> /// <param name="row">An enumeration of column name and value to be appended</param> /// <param name="inPlace">If set, appends <paramref name="row"/> in place. Otherwise, a new DataFrame is returned with an appended <paramref name="row"/> </param> /// <param name="cultureInfo">Culture info for formatting values</param> public DataFrame Append(IEnumerable<KeyValuePair<string, object>> row, bool inPlace = false, CultureInfo cultureInfo = null) { if (cultureInfo == null) { cultureInfo = CultureInfo.CurrentCulture; } DataFrame ret = inPlace ? this : Clone(); if (row == null) { throw new ArgumentNullException(nameof(row)); } List<object> cachedObjectConversions = new List<object>(); foreach (KeyValuePair<string, object> columnAndValue in row) { string columnName = columnAndValue.Key; int index = ret.Columns.IndexOf(columnName); if (index == -1) { throw new ArgumentException(String.Format(Strings.InvalidColumnName, columnName), nameof(columnName)); } DataFrameColumn column = ret.Columns[index]; object value = columnAndValue.Value; if (value != null) { value = Convert.ChangeType(value, column.DataType, cultureInfo); if (value is null) { throw new ArgumentException(string.Format(Strings.MismatchedValueType, column.DataType), column.Name); } } cachedObjectConversions.Add(value); } int cacheIndex = 0; foreach (KeyValuePair<string, object> columnAndValue in row) { string columnName = columnAndValue.Key; int index = ret.Columns.IndexOf(columnName); DataFrameColumn column = ret.Columns[index]; object value = cachedObjectConversions[cacheIndex]; ret.ResizeByOneAndAppend(column, value); cacheIndex++; } foreach (DataFrameColumn column in ret.Columns) { if (column.Length == Rows.Count) { ret.ResizeByOneAndAppend(column, null); } } ret.Columns.RowCount++; return ret; } /// <summary> /// Invalidates any cached data after a column has changed. /// </summary> private void OnColumnsChanged() { _schema = null; } private DataFrame Sort(string columnName, bool ascending, bool putNullValuesLast) { DataFrameColumn column = Columns[columnName]; PrimitiveDataFrameColumn<long> sortIndices = column.GetSortIndices(ascending, putNullValuesLast); List<DataFrameColumn> newColumns = new List<DataFrameColumn>(Columns.Count); for (int i = 0; i < Columns.Count; i++) { DataFrameColumn oldColumn = Columns[i]; DataFrameColumn newColumn = oldColumn.Clone(sortIndices); Debug.Assert(newColumn.NullCount == oldColumn.NullCount); newColumns.Add(newColumn); } return new DataFrame(newColumns); } /// <summary> /// A preview of the contents of this <see cref="DataFrame"/> as a string. /// </summary> /// <returns>A preview of the contents of this <see cref="DataFrame"/>.</returns> public override string ToString() => ToString(DefaultMaxRowsToShowInPreview); /// <summary> /// A preview of the contents of this <see cref="DataFrame"/> as a string. /// </summary> /// <param name="rowsToShow">Max amount of rows to show in preview.</param> /// <returns></returns> public string ToString(long rowsToShow) { StringBuilder sb = new StringBuilder(); int longestColumnName = 0; for (int i = 0; i < Columns.Count; i++) { longestColumnName = Math.Max(longestColumnName, Columns[i].Name.Length); } int padding = Math.Max(10, longestColumnName + 1); for (int i = 0; i < Columns.Count; i++) { // Left align by 10 or more (in case of longer column names) sb.Append(string.Format(Columns[i].Name.PadRight(padding))); } sb.AppendLine(); long numberOfRows = Math.Min(Rows.Count, rowsToShow); for (long i = 0; i < numberOfRows; i++) { foreach (object obj in Rows[i]) { sb.Append((obj ?? "null").ToString().PadRight(padding)); } sb.AppendLine(); } if (numberOfRows < Rows.Count) { sb.Append(String.Format(Strings.AmountOfRowsShown, rowsToShow, Rows.Count)); sb.AppendLine(); } return sb.ToString(); } } }
DataFrame
csharp
nuke-build__nuke
source/Nuke.Common/Tools/NSwag/NSwag.Generated.cs
{ "start": 2337, "end": 8559 }
interface ____.</p><p>For more details, visit the <a href="https://github.com/RSuter/NSwag">official website</a>.</p></summary> public static IReadOnlyCollection<Output> NSwag(ArgumentStringHandler arguments, string workingDirectory = null, IReadOnlyDictionary<string, string> environmentVariables = null, int? timeout = null, bool? logOutput = null, bool? logInvocation = null, Action<OutputType, string> logger = null, Func<IProcess, object> exitHandler = null) => new NSwagTasks().Run(arguments, workingDirectory, environmentVariables, timeout, logOutput, logInvocation, logger, exitHandler); /// <summary><p>Prints the toolchain version.</p><p>For more details, visit the <a href="https://github.com/RSuter/NSwag">official website</a>.</p></summary> /// <remarks><p>This is a <a href="https://www.nuke.build/docs/common/cli-tools/#fluent-api">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p></remarks> public static IReadOnlyCollection<Output> NSwagVersion(NSwagVersionSettings options = null) => new NSwagTasks().Run<NSwagVersionSettings>(options); /// <inheritdoc cref="NSwagTasks.NSwagVersion(Nuke.Common.Tools.NSwag.NSwagVersionSettings)"/> public static IReadOnlyCollection<Output> NSwagVersion(Configure<NSwagVersionSettings> configurator) => new NSwagTasks().Run<NSwagVersionSettings>(configurator.Invoke(new NSwagVersionSettings())); /// <inheritdoc cref="NSwagTasks.NSwagVersion(Nuke.Common.Tools.NSwag.NSwagVersionSettings)"/> public static IEnumerable<(NSwagVersionSettings Settings, IReadOnlyCollection<Output> Output)> NSwagVersion(CombinatorialConfigure<NSwagVersionSettings> configurator, int degreeOfParallelism = 1, bool completeOnFailure = false) => configurator.Invoke(NSwagVersion, degreeOfParallelism, completeOnFailure); /// <summary><p>List all types for the given assembly and settings.</p><p>For more details, visit the <a href="https://github.com/RSuter/NSwag">official website</a>.</p></summary> /// <remarks><p>This is a <a href="https://www.nuke.build/docs/common/cli-tools/#fluent-api">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p><ul><li><c>/Assembly</c> via <see cref="NSwagListTypesSettings.Assembly"/></li><li><c>/AssemblyConfig</c> via <see cref="NSwagListTypesSettings.AssemblyConfig"/></li><li><c>/File</c> via <see cref="NSwagListTypesSettings.File"/></li><li><c>/ReferencePaths</c> via <see cref="NSwagListTypesSettings.ReferencePaths"/></li><li><c>/UseNuGetCache</c> via <see cref="NSwagListTypesSettings.UseNuGetCache"/></li><li><c>/Variables</c> via <see cref="NSwagListTypesSettings.Variables"/></li></ul></remarks> public static IReadOnlyCollection<Output> NSwagListTypes(NSwagListTypesSettings options = null) => new NSwagTasks().Run<NSwagListTypesSettings>(options); /// <inheritdoc cref="NSwagTasks.NSwagListTypes(Nuke.Common.Tools.NSwag.NSwagListTypesSettings)"/> public static IReadOnlyCollection<Output> NSwagListTypes(Configure<NSwagListTypesSettings> configurator) => new NSwagTasks().Run<NSwagListTypesSettings>(configurator.Invoke(new NSwagListTypesSettings())); /// <inheritdoc cref="NSwagTasks.NSwagListTypes(Nuke.Common.Tools.NSwag.NSwagListTypesSettings)"/> public static IEnumerable<(NSwagListTypesSettings Settings, IReadOnlyCollection<Output> Output)> NSwagListTypes(CombinatorialConfigure<NSwagListTypesSettings> configurator, int degreeOfParallelism = 1, bool completeOnFailure = false) => configurator.Invoke(NSwagListTypes, degreeOfParallelism, completeOnFailure); /// <summary><p>List all controllers classes for the given assembly and settings.</p><p>For more details, visit the <a href="https://github.com/RSuter/NSwag">official website</a>.</p></summary> /// <remarks><p>This is a <a href="https://www.nuke.build/docs/common/cli-tools/#fluent-api">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p><ul><li><c>/Assembly</c> via <see cref="NSwagListWebApiControllersSettings.Assembly"/></li><li><c>/AssemblyConfig</c> via <see cref="NSwagListWebApiControllersSettings.AssemblyConfig"/></li><li><c>/File</c> via <see cref="NSwagListWebApiControllersSettings.File"/></li><li><c>/ReferencePaths</c> via <see cref="NSwagListWebApiControllersSettings.ReferencePaths"/></li><li><c>/UseNuGetCache</c> via <see cref="NSwagListWebApiControllersSettings.UseNuGetCache"/></li><li><c>/Variables</c> via <see cref="NSwagListWebApiControllersSettings.Variables"/></li></ul></remarks> public static IReadOnlyCollection<Output> NSwagListWebApiControllers(NSwagListWebApiControllersSettings options = null) => new NSwagTasks().Run<NSwagListWebApiControllersSettings>(options); /// <inheritdoc cref="NSwagTasks.NSwagListWebApiControllers(Nuke.Common.Tools.NSwag.NSwagListWebApiControllersSettings)"/> public static IReadOnlyCollection<Output> NSwagListWebApiControllers(Configure<NSwagListWebApiControllersSettings> configurator) => new NSwagTasks().Run<NSwagListWebApiControllersSettings>(configurator.Invoke(new NSwagListWebApiControllersSettings())); /// <inheritdoc cref="NSwagTasks.NSwagListWebApiControllers(Nuke.Common.Tools.NSwag.NSwagListWebApiControllersSettings)"/> public static IEnumerable<(NSwagListWebApiControllersSettings Settings, IReadOnlyCollection<Output> Output)> NSwagListWebApiControllers(CombinatorialConfigure<NSwagListWebApiControllersSettings> configurator, int degreeOfParallelism = 1, bool completeOnFailure = false) => configurator.Invoke(NSwagListWebApiControllers, degreeOfParallelism, completeOnFailure); /// <summary><p>The project combines the functionality of Swashbuckle (Swagger generation) and AutoRest (client generation) in one toolchain. This way a lot of incompatibilites can be avoided and features which are not well described by the Swagger specification or JSON Schema are better supported (e.g. <a href="https://github.com/NJsonSchema/NJsonSchema/wiki/Inheritance">inheritance</a>, <a href="https://github.com/NJsonSchema/NJsonSchema/wiki/Enums">enum</a> and reference handling). The NSwag project heavily uses <a href="http://njsonschema.org/">NJsonSchema for .NET</a> for JSON Schema handling and C#/TypeScript class/
generation
csharp
dotnet__aspnetcore
src/Security/CookiePolicy/src/HttpOnlyPolicy.cs
{ "start": 262, "end": 671 }
public enum ____ { /// <summary> /// The cookie does not have a configured HttpOnly behavior. This cookie can be accessed by /// JavaScript <c>document.cookie</c> API. /// </summary> None, /// <summary> /// The cookie is configured with a HttpOnly attribute. This cookie inaccessible to the /// JavaScript <c>document.cookie</c> API. /// </summary> Always }
HttpOnlyPolicy