Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code style upgrade #900

Merged
merged 1 commit into from
Nov 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 23 additions & 16 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -446,12 +446,34 @@ dotnet_diagnostic.CA1032.severity = none # We're using RCS1194 which seems to co
dotnet_diagnostic.CA1034.severity = none # Do not nest type. Alternatively, change its accessibility so that it is not externally visible
dotnet_diagnostic.CA1054.severity = none # URI parameters should not be strings
dotnet_diagnostic.CA1062.severity = none # Disable null check, C# already does it for us
dotnet_diagnostic.CS1591.severity = none # Missing XML comment for publicly visible type or member
dotnet_diagnostic.CA1515.severity = none # Because an application's API isn't typically referenced from outside the assembly, types can be made internal
dotnet_diagnostic.CA1805.severity = none # Member is explicitly initialized to its default value
dotnet_diagnostic.CA1822.severity = none # Member does not access instance data and can be marked as static
dotnet_diagnostic.CA1848.severity = none # For improved performance, use the LoggerMessage delegates
dotnet_diagnostic.CA2227.severity = none # Change to be read-only by removing the property setter
dotnet_diagnostic.CA2253.severity = none # Named placeholders in the logging message template should not be comprised of only numeric characters
dotnet_diagnostic.CS1591.severity = none # Missing XML comment for publicly visible type or member
dotnet_diagnostic.IDE0001.severity = none # Simplify name
dotnet_diagnostic.IDE0002.severity = none # Simplify member access
dotnet_diagnostic.IDE0004.severity = none # Remove unnecessary cast
dotnet_diagnostic.IDE0010.severity = none # Populate switch
dotnet_diagnostic.IDE0032.severity = none # Use auto property
dotnet_diagnostic.IDE0035.severity = none # Remove unreachable code
dotnet_diagnostic.IDE0051.severity = none # Remove unused private member
dotnet_diagnostic.IDE0052.severity = none # Remove unread private member
dotnet_diagnostic.IDE0056.severity = none # Indexing can be simplified
dotnet_diagnostic.IDE0057.severity = none # Substring can be simplified
dotnet_diagnostic.IDE0058.severity = none # Remove unused expression value
dotnet_diagnostic.IDE0059.severity = none # Unnecessary assignment of a value
dotnet_diagnostic.IDE0060.severity = none # Remove unused parameter
dotnet_diagnostic.IDE0066.severity = none # Use 'switch' expression
dotnet_diagnostic.IDE0072.severity = none # Populate switch
dotnet_diagnostic.IDE0080.severity = none # Remove unnecessary suppression operator
dotnet_diagnostic.IDE0100.severity = none # Remove unnecessary equality operator
dotnet_diagnostic.IDE0110.severity = none # Remove unnecessary discards
dotnet_diagnostic.IDE0160.severity = none # Use block-scoped namespace
dotnet_diagnostic.IDE0290.severity = none # Use primary constructor
dotnet_diagnostic.IDE0305.severity = none # Collection initialization can be simplified
dotnet_diagnostic.RCS1021.severity = none # Use expression-bodied lambda.
dotnet_diagnostic.RCS1061.severity = none # Merge 'if' with nested 'if'.
dotnet_diagnostic.RCS1069.severity = none # Remove unnecessary case label.
Expand Down Expand Up @@ -480,26 +502,11 @@ dotnet_diagnostic.RCS1226.severity = none # Add paragraph to documentation comme
dotnet_diagnostic.RCS1234.severity = none # Enum duplicate value
dotnet_diagnostic.RCS1238.severity = none # Avoid nested ?: operators.
dotnet_diagnostic.RCS1241.severity = none # Implement IComparable when implementing IComparable<T><T>.
dotnet_diagnostic.IDE0001.severity = none # Simplify name
dotnet_diagnostic.IDE0002.severity = none # Simplify member access
dotnet_diagnostic.IDE0004.severity = none # Remove unnecessary cast
dotnet_diagnostic.IDE0035.severity = none # Remove unreachable code
dotnet_diagnostic.IDE0051.severity = none # Remove unused private member
dotnet_diagnostic.IDE0052.severity = none # Remove unread private member
dotnet_diagnostic.IDE0058.severity = none # Remove unused expression value
dotnet_diagnostic.IDE0059.severity = none # Unnecessary assignment of a value
dotnet_diagnostic.IDE0060.severity = none # Remove unused parameter
dotnet_diagnostic.IDE0080.severity = none # Remove unnecessary suppression operator
dotnet_diagnostic.IDE0100.severity = none # Remove unnecessary equality operator
dotnet_diagnostic.IDE0110.severity = none # Remove unnecessary discards
dotnet_diagnostic.IDE0032.severity = none # Use auto property
dotnet_diagnostic.IDE0160.severity = none # Use block-scoped namespace
dotnet_diagnostic.VSTHRD111.severity = none # Use .ConfigureAwait(bool) is hidden by default, set to none to prevent IDE from changing on autosave
dotnet_diagnostic.xUnit1004.severity = none # Test methods should not be skipped. Remove the Skip property to start running the test again.

dotnet_diagnostic.SKEXP0003.severity = none # XYZ is for evaluation purposes only
dotnet_diagnostic.SKEXP0010.severity = none
dotnet_diagnostic.SKEXP0010.severity = none
dotnet_diagnostic.SKEXP0011.severity = none
dotnet_diagnostic.SKEXP0052.severity = none
dotnet_diagnostic.SKEXP0101.severity = none
Expand Down
7 changes: 5 additions & 2 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,11 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageVersion>
<PackageVersion Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="8.0.0" />
<PackageVersion Include="Microsoft.VisualStudio.Threading.Analyzers" Version="17.11.20">
<PackageVersion Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="9.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageVersion>
<PackageVersion Include="Microsoft.VisualStudio.Threading.Analyzers" Version="17.12.19">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageVersion>
Expand Down
15 changes: 7 additions & 8 deletions applications/evaluation/Distribution.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@ public struct Distribution : IEquatable<Distribution>
public Distribution() { }

// TODO: use tolerance when comparing floating numbers for equality
public override bool Equals(object? obj) => obj is Distribution distribution &&
this.Simple == distribution.Simple &&
this.Reasoning == distribution.Reasoning &&
this.MultiContext == distribution.MultiContext &&
this.Conditioning == distribution.Conditioning;
public override readonly bool Equals(object? obj) => obj is Distribution distribution &&
this.Simple == distribution.Simple &&
this.Reasoning == distribution.Reasoning &&
this.MultiContext == distribution.MultiContext &&
this.Conditioning == distribution.Conditioning;

public override int GetHashCode()
public override readonly int GetHashCode()
{
return HashCode.Combine(this.Simple, this.Reasoning, this.MultiContext, this.Conditioning);
}
Expand All @@ -38,9 +38,8 @@ public override int GetHashCode()
return !(left == right);
}

public bool Equals(Distribution other)
public readonly bool Equals(Distribution other)
{
return this == other;
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ internal sealed class StatementExtraction
#pragma warning restore CA1812 // 'StatementExtraction' is an internal class that is apparently never instantiated. If so, remove the code from the assembly. If this class is intended to contain only static members, make it 'static' (Module in Visual Basic). (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1812)
{
[JsonPropertyName("statements")]
public List<string> Statements { get; set; } = new List<string>();
public List<string> Statements { get; set; } = [];
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ internal sealed class GroundTruthClassifications
#pragma warning restore CA1812 // 'GroundTruthClassifications' is an internal class that is apparently never instantiated. If so, remove the code from the assembly. If this class is intended to contain only static members, make it 'static' (Module in Visual Basic). (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1812)
{
[JsonPropertyName("evaluations")]
public List<GroundTruthClassification> Evaluations { get; set; } = new();
public List<GroundTruthClassification> Evaluations { get; set; } = [];
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ internal sealed class FaithfulnessEvaluations
#pragma warning restore CA1812 // 'FaithfulnessEvaluations' is an internal class that is apparently never instantiated. If so, remove the code from the assembly. If this class is intended to contain only static members, make it 'static' (Module in Visual Basic). (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1812)
{
[JsonPropertyName("evaluations")]
public List<StatementEvaluation> Evaluations { get; set; } = new();
public List<StatementEvaluation> Evaluations { get; set; } = [];
}
2 changes: 1 addition & 1 deletion applications/evaluation/TestSet/TestSetItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public sealed class TestSetItem

public int GroundTruthVerdict { get; set; }

public IEnumerable<string> Context { get; set; } = Array.Empty<string>();
public IEnumerable<string> Context { get; set; } = [];

public ICollection<MemoryFilter> Filters { get; set; } = Array.Empty<MemoryFilter>();

Expand Down
4 changes: 2 additions & 2 deletions applications/evaluation/TestSetEvaluator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ public class QuestionEvaluation

public MemoryAnswer MemoryAnswer { get; set; } = null!;

public EvaluationMetrics Metrics { get; set; } = new EvaluationMetrics();
public EvaluationMetrics Metrics { get; set; } = new();

public Dictionary<string, object?> Metadata { get; set; } = new();
public Dictionary<string, object?> Metadata { get; set; } = [];
}
6 changes: 3 additions & 3 deletions applications/evaluation/TestSetGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public async IAsyncEnumerable<TestSetItem> GenerateTestSetsAsync(

var documentIds = new List<string>();

await foreach (var record in this._memory.GetListAsync(index, limit: int.MaxValue))
await foreach (var record in this._memory.GetListAsync(index, limit: int.MaxValue).ConfigureAwait(false))
{
if (documentIds.Contains(record.GetDocumentId()))
{
Expand All @@ -110,7 +110,7 @@ public async IAsyncEnumerable<TestSetItem> GenerateTestSetsAsync(
foreach (var documentId in documentIds)
{
var partitionRecords = await this._memory.GetListAsync(index,
filters: new[] { new MemoryFilter().ByDocument(documentId) },
filters: [new MemoryFilter().ByDocument(documentId)],
limit: int.MaxValue)
.ToArrayAsync()
.ConfigureAwait(false);
Expand All @@ -123,7 +123,7 @@ public async IAsyncEnumerable<TestSetItem> GenerateTestSetsAsync(
.Concat(this.GetMultiContextTestSetsAsync(nodes.Skip(simpleCount + reasoningCount).Take(multiContextCount), language: language, retryCount: retryCount))
.Concat(this.GetConditioningTestSetsAsync(nodes.Skip(simpleCount + reasoningCount + multiContextCount).Take(conditioningCount), language: language, retryCount: retryCount));

await foreach (var item in questions)
await foreach (var item in questions.ConfigureAwait(false))
{
yield return item;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,14 +81,13 @@ await this._memory
documentId: "file1-NASA-news",
steps: Constants.PipelineWithoutSummary);

var evaluation = await this._testSetEvaluator.EvaluateTestSetAsync("default4tests", new[]
{
var evaluation = await this._testSetEvaluator.EvaluateTestSetAsync("default4tests", [
new TestSetItem
{
Question = "What is the role of the Department of Defense in the recovery operations for the Artemis II mission?",
GroundTruth = "The Department of Defense personnel are involved in practicing recovery operations for the Artemis II mission. They use a crew module test article to help verify the recovery team's readiness to recover the Artemis II crew and the Orion spacecraft.",
}
}).ToArrayAsync();
]).ToArrayAsync();

Assert.NotEmpty(evaluation);
}
Expand Down
10 changes: 5 additions & 5 deletions clients/dotnet/WebClient/MemoryWebClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ public async Task<SearchResult> SearchAsync(
{
if (filter != null)
{
if (filters == null) { filters = new List<MemoryFilter>(); }
if (filters == null) { filters = []; }

filters.Add(filter);
}
Expand All @@ -321,7 +321,7 @@ public async Task<SearchResult> SearchAsync(
{
Index = index,
Query = query,
Filters = (filters is { Count: > 0 }) ? filters.ToList() : new(),
Filters = (filters is { Count: > 0 }) ? filters.ToList() : [],
MinRelevance = minRelevance,
Limit = limit,
ContextArguments = (context?.Arguments ?? new Dictionary<string, object?>()).ToDictionary(),
Expand All @@ -348,7 +348,7 @@ public async Task<MemoryAnswer> AskAsync(
{
if (filter != null)
{
if (filters == null) { filters = new List<MemoryFilter>(); }
if (filters == null) { filters = []; }

filters.Add(filter);
}
Expand All @@ -357,7 +357,7 @@ public async Task<MemoryAnswer> AskAsync(
{
Index = index,
Question = question,
Filters = (filters is { Count: > 0 }) ? filters.ToList() : new(),
Filters = (filters is { Count: > 0 }) ? filters.ToList() : [],
MinRelevance = minRelevance,
ContextArguments = (context?.Arguments ?? new Dictionary<string, object?>()).ToDictionary(),
};
Expand Down Expand Up @@ -425,7 +425,7 @@ private async Task<string> ImportInternalAsync(
CancellationToken cancellationToken)
{
// Populate form with values and files from disk
using MultipartFormDataContent formData = new();
using MultipartFormDataContent formData = [];

using StringContent indexContent = new(index);
using StringContent contextArgsContent = new(JsonSerializer.Serialize(context?.Arguments));
Expand Down
4 changes: 2 additions & 2 deletions examples/001-dotnet-WebClient/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@
* handlers are running to get the pipeline to complete,
* otherwise the web service might just upload the files
* without extracting memories. */
public static class Program
internal static class Program
{
private static MemoryWebClient? s_memory;
private static readonly List<string> s_toDelete = new();
private static readonly List<string> s_toDelete = [];

// Change this to True and configure Azure Document Intelligence to test OCR and support for images
private const bool ImageSupportDemoEnabled = true;
Expand Down
2 changes: 1 addition & 1 deletion examples/002-dotnet-Serverless/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
public static class Program
{
private static MemoryServerless? s_memory;
private static readonly List<string> s_toDelete = new();
private static readonly List<string> s_toDelete = [];

// Remember to configure Azure Document Intelligence to test OCR and support for images
private static bool s_imageSupportDemoEnabled = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<LangVersion>12</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<NoWarn>$(NoWarn);NU1900</NoWarn>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
public static class Program
{
private static MemoryWebClient? s_memory;
private static readonly List<string> s_toDelete = new();
private static readonly List<string> s_toDelete = [];

public static async Task Main()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
<LangVersion>12</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<NoWarn>$(NoWarn);NU1900</NoWarn>
</PropertyGroup>

<ItemGroup>
Expand Down
3 changes: 2 additions & 1 deletion extensions/Anthropic/AnthropicTextGeneration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.KernelMemory.AI.Anthropic.Client;
using Microsoft.KernelMemory.AI.OpenAI;
Expand Down Expand Up @@ -113,7 +114,7 @@ public async IAsyncEnumerable<string> GenerateTextAsync(

IAsyncEnumerable<StreamingResponseMessage> streamedResponse = this._client.CallClaudeStreamingAsync(parameters, cancellationToken);

await foreach (StreamingResponseMessage response in streamedResponse)
await foreach (StreamingResponseMessage response in streamedResponse.ConfigureAwait(false))
{
//now we simply yield the response
switch (response)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public enum AuthTypes
public string Endpoint { get; set; } = string.Empty;
public string APIKey { get; set; } = string.Empty;
public double GlobalSafetyThreshold { get; set; } = 0.0;
public List<string> IgnoredWords { get; set; } = new();
public List<string> IgnoredWords { get; set; } = [];

public void SetCredential(TokenCredential credential)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public async Task<bool> IsSafeAsync(string? text, double threshold, Cancellation

if (!isSafe)
{
IEnumerable<string> report = result.HasValue ? result.Value.CategoriesAnalysis.Select(x => $"{x.Category}: {x.Severity}") : Array.Empty<string>();
IEnumerable<string> report = result.HasValue ? result.Value.CategoriesAnalysis.Select(x => $"{x.Category}: {x.Severity}") : [];
this._log.LogWarning("Unsafe content detected, report: {0}", string.Join("; ", report));
this._log.LogSensitive("Unsafe content: {0}", text);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

namespace Microsoft.AzureAISearch.TestApplication;

public static class Program
internal static class Program
{
// Azure Search Index name
private const string Index = "test01";
Expand Down Expand Up @@ -124,7 +124,7 @@ private static async Task CreateIndexAsync(string name)

var indexSchema = new SearchIndex(name)
{
Fields = new List<SearchField>(),
Fields = [],
VectorSearch = new VectorSearch
{
Profiles =
Expand Down Expand Up @@ -285,7 +285,7 @@ private static async Task DeleteRecordAsync(string index, string recordId)

Console.WriteLine($"DELETING {recordId}\n");

Response<IndexDocumentsResult>? response = await client.DeleteDocumentsAsync("id", new List<string> { recordId });
Response<IndexDocumentsResult>? response = await client.DeleteDocumentsAsync("id", [recordId]);

Console.WriteLine("Status: " + response.GetRawResponse().Status);
Console.WriteLine("IsError: " + response.GetRawResponse().IsError);
Expand Down
Loading
Loading