content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using AirCC.Client;
using AirCC.Client.Modules;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using AirCCClient.Web.Apis;
using BCI.Extensions.IdentityClient.Token;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace AirCCClient.Web
{
public static class IHostBuilderExtensions
{
public static IHostBuilder ConfigureAirCCFile(this IHostBuilder hostBuilder)
{
hostBuilder.ConfigureServices(services => {
services.AddClientServices();
services.TryAddScoped<IUpdateAuthorizationService, UpdateAuthorizationService>();
services.TryAddTransient<IJwtTokenHandler,JwtTokenHandler>();
});
hostBuilder = hostBuilder.ConfigureAppConfiguration(configBuilder =>
{
var airccOptions = configBuilder.Build().GetSection(AirCCConfigOptions.SectionName).Get<AirCCConfigOptions>();
configBuilder.AddIniFile(airccOptions.FilePath, optional: true, reloadOnChange: true);
});
return hostBuilder;
}
}
}
| 35.294118 | 126 | 0.7075 | [
"MIT"
] | ellefry/AirCC | src/AirCCClient.Web/IHostBuilderExtensions.cs | 1,202 | C# |
using System;
using System.Collections.Generic;
using CinemaConstructor.Models;
using Microsoft.AspNetCore.Mvc;
namespace CinemaConstructor.Controllers
{
public class BaseController : Controller
{
internal void AddBreadcrumb(string displayName, string urlPath)
{
List<Message> messages;
if (ViewBag.Breadcrumb == null)
{
messages = new List<Message>();
}
else
{
messages = ViewBag.Breadcrumb as List<Message>;
}
messages.Add(new Message { DisplayName = displayName, URLPath = urlPath });
ViewBag.Breadcrumb = messages;
}
internal void AddPageHeader(string pageHeader = "", string pageDescription = "")
{
ViewBag.PageHeader = Tuple.Create(pageHeader, pageDescription);
}
internal enum PageAlertType
{
Error,
Info,
Warning,
Success
}
internal void AddPageAlerts(PageAlertType pageAlertType, string description)
{
List<Message> messages;
if (ViewBag.PageAlerts == null)
{
messages = new List<Message>();
}
else
{
messages = ViewBag.PageAlerts as List<Message>;
}
messages.Add(new Message { Type = pageAlertType.ToString().ToLower(), ShortDesc = description });
ViewBag.PageAlerts = messages;
}
}
} | 27.192982 | 109 | 0.545161 | [
"MIT"
] | dnskk/CinemaConstructor | CinemaConstructor/Controllers/BaseController.cs | 1,550 | C# |
using NCDK.Smiles;
using System;
using System.Runtime.InteropServices;
namespace ACDK
{
[Guid("8FB35828-51E6-4836-BB04-CCF1B05EB6C9")]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IObjectFactory
{
[DispId(0x1000)]
IChemObjectBuilder DefaultChemObjectBuilder { get; }
[DispId(0x1001)]
IChemObjectBuilder SilentChemObjectBuilder { get; }
[DispId(0x1002)]
SmilesParser NewSmilesParser(IChemObjectBuilder builder);
}
[Guid("FB5F852E-C71D-4C2B-ABB9-A4C4DFF433D8")]
[ComDefaultInterface(typeof(IObjectFactory))]
public class ObjectFactory
: IObjectFactory
{
public ObjectFactory()
{ }
[DispId(0x1000)]
public IChemObjectBuilder DefaultChemObjectBuilder { get; } = new W_IChemObjectBuilder(NCDK.Default.ChemObjectBuilder.Instance);
[DispId(0x1001)]
public IChemObjectBuilder SilentChemObjectBuilder { get; } = new W_IChemObjectBuilder(NCDK.Silent.ChemObjectBuilder.Instance);
[DispId(0x1002)]
public SmilesParser NewSmilesParser(IChemObjectBuilder builder)
=> new W_SmilesParser(new NCDK.Smiles.SmilesParser(((W_IChemObjectBuilder)builder).Object));
}
}
| 31.225 | 136 | 0.702162 | [
"MIT"
] | kazuyaujihara/ACDK | ACDK/ObjectFactory.cs | 1,251 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Insights.Diagnostics;
using Microsoft.Azure.Management.Monitor;
using Microsoft.Azure.Management.Monitor.Models;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Moq;
using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.Azure.Commands.Insights.Test.Diagnostics
{
public class GetDiagnosticSettingCommandTests
{
private readonly GetAzureRmDiagnosticSettingCommand cmdlet;
private readonly Mock<MonitorManagementClient> insightsManagementClientMock;
private readonly Mock<IDiagnosticSettingsOperations> insightsDiagnosticsOperationsMock;
private Mock<ICommandRuntime> commandRuntimeMock;
private Microsoft.Rest.Azure.AzureOperationResponse<DiagnosticSettingsResource> response;
private const string resourceId = "/subscriptions/123/resourcegroups/rg/providers/rp/resource/myresource";
private string calledResourceId;
private string diagnosticSettingName;
public GetDiagnosticSettingCommandTests(Xunit.Abstractions.ITestOutputHelper output)
{
ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output));
insightsDiagnosticsOperationsMock = new Mock<IDiagnosticSettingsOperations>();
insightsManagementClientMock = new Mock<MonitorManagementClient>();
commandRuntimeMock = new Mock<ICommandRuntime>();
cmdlet = new GetAzureRmDiagnosticSettingCommand()
{
CommandRuntime = commandRuntimeMock.Object,
MonitorManagementClient = insightsManagementClientMock.Object
};
response = new Microsoft.Rest.Azure.AzureOperationResponse<DiagnosticSettingsResource>()
{
Body = new DiagnosticSettingsResource
{
EventHubName = "",
EventHubAuthorizationRuleId = "",
StorageAccountId = "/subscriptions/123/resourcegroups/rg/providers/microsoft.storage/accounts/myaccount",
WorkspaceId = "",
Logs = new List<LogSettings>
{
new LogSettings
{
RetentionPolicy = new RetentionPolicy()
{
Days = 10,
Enabled = true
},
Category = "TestCategory1",
Enabled = true
},
new LogSettings
{
RetentionPolicy = new RetentionPolicy()
{
Days = 5,
Enabled = false
},
Category = "TestCategory2",
Enabled = false
}
},
Metrics = new List<MetricSettings>
{
new MetricSettings
{
Category = "MetricCat1",
RetentionPolicy = new RetentionPolicy()
{
Days = 7,
Enabled = false
},
TimeGrain = TimeSpan.FromMinutes(1),
Enabled = false
},
new MetricSettings
{
Category = "MetricCat2",
RetentionPolicy = new RetentionPolicy()
{
Days = 3,
Enabled = true
},
TimeGrain = TimeSpan.FromHours(1)
}
}
}
};
insightsDiagnosticsOperationsMock.Setup(f => f.GetWithHttpMessagesAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult<Microsoft.Rest.Azure.AzureOperationResponse<DiagnosticSettingsResource>>(response))
.Callback((string resourceId, string name, Dictionary<string, List<string>> headers, CancellationToken cancellationToken) =>
{
this.calledResourceId = resourceId;
this.diagnosticSettingName = name;
});
insightsManagementClientMock.SetupGet(f => f.DiagnosticSettings).Returns(this.insightsDiagnosticsOperationsMock.Object);
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void GetDiagnosticSettingCommandParametersProcessing()
{
cmdlet.ResourceId = resourceId;
cmdlet.ExecuteCmdlet();
Assert.Equal(resourceId, this.calledResourceId);
Assert.Equal("service", this.diagnosticSettingName);
}
}
}
| 46.864662 | 202 | 0.530884 | [
"MIT"
] | PrakharSaxena-31/azure-powershell | src/ResourceManager/Insights/Commands.Insights.Test/Diagnostics/GetDiagnosticSettingCommandTests.cs | 6,103 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using SourceGenerators.Tests;
using Xunit;
namespace Microsoft.Extensions.Logging.Generators.Tests
{
[ActiveIssue("https://github.com/dotnet/runtime/issues/32743", TestRuntimes.Mono)]
public class LoggerMessageGeneratorParserTests
{
[Fact]
public async Task InvalidMethodName()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1"")]
static partial void __M1(ILogger logger);
}
");
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.InvalidLoggingMethodName.Id, diagnostics[0].Id);
}
[Fact]
public async Task MissingLogLevel()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 0, Message = ""M1"")]
static partial void M1(ILogger logger);
}
");
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.MissingLogLevel.Id, diagnostics[0].Id);
}
[Fact]
public async Task InvalidMethodBody()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
static partial void M1(ILogger logger);
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1"")]
static partial void M1(ILogger logger)
{
}
}
");
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.LoggingMethodHasBody.Id, diagnostics[0].Id);
}
[Fact]
public async Task MissingTemplate()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""This is a message without foo"")]
static partial void M1(ILogger logger, string foo);
}
");
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.ArgumentHasNoCorrespondingTemplate.Id, diagnostics[0].Id);
Assert.Contains("Argument 'foo' is not referenced from the logging message", diagnostics[0].GetMessage(), StringComparison.InvariantCulture);
}
[Fact]
public async Task MissingArgument()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""{foo}"")]
static partial void M1(ILogger logger);
}
");
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.TemplateHasNoCorrespondingArgument.Id, diagnostics[0].Id);
Assert.Contains("Template 'foo' is not provided as argument to the logging method", diagnostics[0].GetMessage(), StringComparison.InvariantCulture);
}
[Fact]
public async Task NeedlessQualifierInMessage()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 0, Level = LogLevel.Information, Message = ""INFO: this is an informative message"")]
static partial void M1(ILogger logger);
}
");
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.RedundantQualifierInMessage.Id, diagnostics[0].Id);
}
[Fact]
public async Task NeedlessExceptionInMessage()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1 {ex} {ex2}"")]
static partial void M1(ILogger logger, System.Exception ex, System.Exception ex2);
}
");
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.ShouldntMentionExceptionInMessage.Id, diagnostics[0].Id);
}
[Fact]
public async Task NeedlessLogLevelInMessage()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 0, Message = ""M1 {l1} {l2}"")]
static partial void M1(ILogger logger, LogLevel l1, LogLevel l2);
}
");
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.ShouldntMentionLogLevelInMessage.Id, diagnostics[0].Id);
}
[Fact]
public async Task NeedlessLoggerInMessage()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1 {logger}"")]
static partial void M1(ILogger logger);
}
");
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.ShouldntMentionLoggerInMessage.Id, diagnostics[0].Id);
}
[Fact]
public async Task DoubleLogLevel_InAttributeAndAsParameterButMissingInTemplate_ProducesDiagnostic()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1"")]
static partial void M1(ILogger logger, LogLevel levelParam);
}
");
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.ArgumentHasNoCorrespondingTemplate.Id, diagnostics[0].Id);
}
[Fact]
public async Task LogLevelDoublySet_AndInMessageTemplate_ProducesDiagnostic()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1 {level2}"")]
static partial void M1(ILogger logger, LogLevel level1, LogLevel level2);
}
");
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.ArgumentHasNoCorrespondingTemplate.Id, diagnostics[0].Id);
}
[Fact]
public async Task DoubleLogLevel_FirstOneSetAsMethodParameter_SecondOneInMessageTemplate_Supported()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 0, Message = ""M1 {level2}"")]
static partial void M1(ILogger logger, LogLevel level1, LogLevel level2);
}
");
Assert.Empty(diagnostics);
}
#if false
// TODO: can't have the same template with different casing
[Fact]
public async Task InconsistentTemplateCasing()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1 {p1} {P1}"")]
static partial void M1(ILogger logger, int p1, int P1);
}
");
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.InconsistentTemplateCasing.Id, diagnostics[0].Id);
}
// TODO: can't have malformed format strings (like dangling {, etc)
[Fact]
public async Task MalformedFormatString()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1 {p1} {P1}"")]
static partial void M1(ILogger logger, int p1, int P1);
}
");
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.MalformedFormatStrings.Id, diagnostics[0].Id);
}
#endif
[Fact]
public async Task InvalidParameterName()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1 {__foo}"")]
static partial void M1(ILogger logger, string __foo);
}
");
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.InvalidLoggingMethodParameterName.Id, diagnostics[0].Id);
}
[Fact]
public async Task NestedTypeOK()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
public partial class Nested
{
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1"")]
static partial void M1(ILogger logger);
}
}
");
Assert.Empty(diagnostics);
}
[Fact]
public async Task MissingExceptionType()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
namespace System
{
public class Object {}
public class Void {}
public class String {}
public struct DateTime {}
}
namespace System.Collections
{
public interface IEnumerable {}
}
namespace Microsoft.Extensions.Logging
{
public enum LogLevel {}
public interface ILogger {}
}
namespace Microsoft.Extensions.Logging
{
public class LoggerMessageAttribute {}
}
partial class C
{
}
", false, includeBaseReferences: false, includeLoggingReferences: false);
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.MissingRequiredType.Id, diagnostics[0].Id);
}
[Fact]
public async Task MissingLoggerMessageAttributeType()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
}
", false, includeLoggingReferences: false);
Assert.Empty(diagnostics);
}
[Fact]
public async Task MissingILoggerType()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
namespace Microsoft.Extensions.Logging
{
public sealed class LoggerMessageAttribute : System.Attribute {}
}
partial class C
{
}
", false, includeLoggingReferences: false);
Assert.Empty(diagnostics);
}
[Fact]
public async Task MissingLogLevelType()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
namespace Microsoft.Extensions.Logging
{
public sealed class LoggerMessageAttribute : System.Attribute {}
}
namespace Microsoft.Extensions.Logging
{
public interface ILogger {}
}
partial class C
{
}
", false, includeLoggingReferences: false);
Assert.Empty(diagnostics);
}
[Fact]
public async Task EventIdReuse()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class MyClass
{
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1"")]
static partial void M1(ILogger logger);
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1"")]
static partial void M2(ILogger logger);
}
");
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.ShouldntReuseEventIds.Id, diagnostics[0].Id);
Assert.Contains("in class MyClass", diagnostics[0].GetMessage(), StringComparison.InvariantCulture);
}
[Fact]
public async Task MethodReturnType()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1"")]
public static partial int M1(ILogger logger);
public static partial int M1(ILogger logger) { return 0; }
}
");
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.LoggingMethodMustReturnVoid.Id, diagnostics[0].Id);
}
[Fact]
public async Task MissingILogger()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1 {p1}"")]
static partial void M1(int p1);
}
");
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.MissingLoggerArgument.Id, diagnostics[0].Id);
Assert.Contains("One of the arguments to the static logging method 'M1' must implement the Microsoft.Extensions.Logging.ILogger interface", diagnostics[0].GetMessage(), StringComparison.InvariantCulture);
}
[Fact]
public async Task NotStatic()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1"")]
partial void M1(ILogger logger);
}
");
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.LoggingMethodShouldBeStatic.Id, diagnostics[0].Id);
}
[Fact]
public async Task NoILoggerField()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1"")]
public partial void M1();
}
");
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.MissingLoggerField.Id, diagnostics[0].Id);
}
[Fact]
public async Task MultipleILoggerFields()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
public ILogger _logger1;
public ILogger _logger2;
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1"")]
public partial void M1();
}
");
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.MultipleLoggerFields.Id, diagnostics[0].Id);
}
[Fact]
public async Task NotPartial()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1"")]
static void M1(ILogger logger) {}
}
");
Assert.Equal(2, diagnostics.Count);
Assert.Equal(DiagnosticDescriptors.LoggingMethodMustBePartial.Id, diagnostics[0].Id);
Assert.Equal(DiagnosticDescriptors.LoggingMethodHasBody.Id, diagnostics[1].Id);
}
[Fact]
public async Task MethodGeneric()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1"")]
static partial void M1<T>(ILogger logger);
}
");
Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.LoggingMethodIsGeneric.Id, diagnostics[0].Id);
}
[Fact]
public async Task Templates()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 1, Level = LogLevel.Debug, Message = ""M1"")]
static partial void M1(ILogger logger);
[LoggerMessage(EventId = 2, Level = LogLevel.Debug, Message = ""M2 {arg1} {arg2}"")]
static partial void M2(ILogger logger, string arg1, string arg2);
[LoggerMessage(EventId = 3, Level = LogLevel.Debug, Message = ""M3 {arg1"")]
static partial void M3(ILogger logger);
[LoggerMessage(EventId = 4, Level = LogLevel.Debug, Message = ""M4 arg1}"")]
static partial void M4(ILogger logger);
[LoggerMessage(EventId = 5, Level = LogLevel.Debug, Message = ""M5 {"")]
static partial void M5(ILogger logger);
[LoggerMessage(EventId = 6, Level = LogLevel.Debug, Message = ""}M6 "")]
static partial void M6(ILogger logger);
[LoggerMessage(EventId = 7, Level = LogLevel.Debug, Message = ""M7 {{arg1}}"")]
static partial void M7(ILogger logger);
}
");
Assert.Empty(diagnostics);
}
[Fact]
public async Task Cancellation()
{
await Assert.ThrowsAsync<OperationCanceledException>(async () =>
await RunGenerator(@"
partial class C
{
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1"")]
static partial void M1(ILogger logger);
}
", cancellationToken: new CancellationToken(true)));
}
[Fact]
public async Task SourceErrors()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
static partial class C
{
// bogus argument type
[LoggerMessage(EventId = 0, Level = "", Message = ""Hello"")]
static partial void M1(ILogger logger);
// missing parameter name
[LoggerMessage(EventId = 1, Level = LogLevel.Debug, Message = ""Hello"")]
static partial void M2(ILogger);
// bogus parameter type
[LoggerMessage(EventId = 2, Level = LogLevel.Debug, Message = ""Hello"")]
static partial void M3(XILogger logger);
// attribute applied to something other than a method
[LoggerMessage(EventId = 4, Message = ""Hello"")]
int M5;
}
");
Assert.Empty(diagnostics); // should fail quietly on broken code
}
private static async Task<IReadOnlyList<Diagnostic>> RunGenerator(
string code,
bool wrap = true,
bool inNamespace = true,
bool includeBaseReferences = true,
bool includeLoggingReferences = true,
CancellationToken cancellationToken = default)
{
var text = code;
if (wrap)
{
var nspaceStart = "namespace Test {";
var nspaceEnd = "}";
if (!inNamespace)
{
nspaceStart = "";
nspaceEnd = "";
}
text = $@"
{nspaceStart}
using Microsoft.Extensions.Logging;
{code}
{nspaceEnd}
";
}
Assembly[]? refs = null;
if (includeLoggingReferences)
{
refs = new[] { typeof(ILogger).Assembly, typeof(LoggerMessageAttribute).Assembly };
}
var (d, r) = await RoslynTestUtils.RunGenerator(
new LoggerMessageGenerator(),
refs,
new[] { text },
includeBaseReferences: includeBaseReferences,
cancellationToken: cancellationToken).ConfigureAwait(false);
return d;
}
}
}
| 36.698492 | 216 | 0.526405 | [
"MIT"
] | JanDeDobbeleer/runtime | src/libraries/Microsoft.Extensions.Logging.Abstractions/tests/Microsoft.Extensions.Logging.Generators.Tests/LoggerMessageGeneratorParserTests.cs | 21,909 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Models.Api20210401Preview
{
using static Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Extensions;
/// <summary>Response properties for iSCSI Target operations.</summary>
public partial class IscsiTargetProperties :
Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Models.Api20210401Preview.IIscsiTargetProperties,
Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Models.Api20210401Preview.IIscsiTargetPropertiesInternal
{
/// <summary>Backing field for <see cref="AclMode" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Support.IscsiTargetAclMode _aclMode;
/// <summary>Mode for Target connectivity.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Origin(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.PropertyOrigin.Owned)]
public Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Support.IscsiTargetAclMode AclMode { get => this._aclMode; set => this._aclMode = value; }
/// <summary>Backing field for <see cref="Endpoint" /> property.</summary>
private string[] _endpoint;
/// <summary>List of private IPv4 addresses to connect to the iSCSI Target.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Origin(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.PropertyOrigin.Owned)]
public string[] Endpoint { get => this._endpoint; set => this._endpoint = value; }
/// <summary>Backing field for <see cref="Lun" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Models.Api20210401Preview.IIscsiLun[] _lun;
/// <summary>List of LUNs to be exposed through iSCSI Target.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Origin(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.PropertyOrigin.Owned)]
public Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Models.Api20210401Preview.IIscsiLun[] Lun { get => this._lun; set => this._lun = value; }
/// <summary>Internal Acessors for ProvisioningState</summary>
Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Support.ProvisioningStates Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Models.Api20210401Preview.IIscsiTargetPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } }
/// <summary>Backing field for <see cref="Port" /> property.</summary>
private int? _port;
/// <summary>The port used by iSCSI Target portal group.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Origin(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.PropertyOrigin.Owned)]
public int? Port { get => this._port; set => this._port = value; }
/// <summary>Backing field for <see cref="ProvisioningState" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Support.ProvisioningStates _provisioningState;
/// <summary>State of the operation on the resource.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Origin(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.PropertyOrigin.Owned)]
public Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Support.ProvisioningStates ProvisioningState { get => this._provisioningState; }
/// <summary>Backing field for <see cref="StaticAcls" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Models.Api20210401Preview.IAcl[] _staticAcls;
/// <summary>Access Control List (ACL) for an iSCSI Target; defines LUN masking policy</summary>
[Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Origin(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.PropertyOrigin.Owned)]
public Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Models.Api20210401Preview.IAcl[] StaticAcls { get => this._staticAcls; set => this._staticAcls = value; }
/// <summary>Backing field for <see cref="Status" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Support.OperationalStatus _status;
/// <summary>Operational status of the iSCSI Target.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Origin(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.PropertyOrigin.Owned)]
public Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Support.OperationalStatus Status { get => this._status; set => this._status = value; }
/// <summary>Backing field for <see cref="TargetIqn" /> property.</summary>
private string _targetIqn;
/// <summary>
/// iSCSI Target IQN (iSCSI Qualified Name); example: "iqn.2005-03.org.iscsi:server".
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Origin(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.PropertyOrigin.Owned)]
public string TargetIqn { get => this._targetIqn; set => this._targetIqn = value; }
/// <summary>Creates an new <see cref="IscsiTargetProperties" /> instance.</summary>
public IscsiTargetProperties()
{
}
}
/// Response properties for iSCSI Target operations.
public partial interface IIscsiTargetProperties :
Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.IJsonSerializable
{
/// <summary>Mode for Target connectivity.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"Mode for Target connectivity.",
SerializedName = @"aclMode",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Support.IscsiTargetAclMode) })]
Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Support.IscsiTargetAclMode AclMode { get; set; }
/// <summary>List of private IPv4 addresses to connect to the iSCSI Target.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"List of private IPv4 addresses to connect to the iSCSI Target.",
SerializedName = @"endpoints",
PossibleTypes = new [] { typeof(string) })]
string[] Endpoint { get; set; }
/// <summary>List of LUNs to be exposed through iSCSI Target.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"List of LUNs to be exposed through iSCSI Target.",
SerializedName = @"luns",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Models.Api20210401Preview.IIscsiLun) })]
Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Models.Api20210401Preview.IIscsiLun[] Lun { get; set; }
/// <summary>The port used by iSCSI Target portal group.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The port used by iSCSI Target portal group.",
SerializedName = @"port",
PossibleTypes = new [] { typeof(int) })]
int? Port { get; set; }
/// <summary>State of the operation on the resource.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Info(
Required = true,
ReadOnly = true,
Description = @"State of the operation on the resource.",
SerializedName = @"provisioningState",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Support.ProvisioningStates) })]
Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Support.ProvisioningStates ProvisioningState { get; }
/// <summary>Access Control List (ACL) for an iSCSI Target; defines LUN masking policy</summary>
[Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Access Control List (ACL) for an iSCSI Target; defines LUN masking policy",
SerializedName = @"staticAcls",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Models.Api20210401Preview.IAcl) })]
Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Models.Api20210401Preview.IAcl[] StaticAcls { get; set; }
/// <summary>Operational status of the iSCSI Target.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"Operational status of the iSCSI Target.",
SerializedName = @"status",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Support.OperationalStatus) })]
Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Support.OperationalStatus Status { get; set; }
/// <summary>
/// iSCSI Target IQN (iSCSI Qualified Name); example: "iqn.2005-03.org.iscsi:server".
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"iSCSI Target IQN (iSCSI Qualified Name); example: ""iqn.2005-03.org.iscsi:server"".",
SerializedName = @"targetIqn",
PossibleTypes = new [] { typeof(string) })]
string TargetIqn { get; set; }
}
/// Response properties for iSCSI Target operations.
internal partial interface IIscsiTargetPropertiesInternal
{
/// <summary>Mode for Target connectivity.</summary>
Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Support.IscsiTargetAclMode AclMode { get; set; }
/// <summary>List of private IPv4 addresses to connect to the iSCSI Target.</summary>
string[] Endpoint { get; set; }
/// <summary>List of LUNs to be exposed through iSCSI Target.</summary>
Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Models.Api20210401Preview.IIscsiLun[] Lun { get; set; }
/// <summary>The port used by iSCSI Target portal group.</summary>
int? Port { get; set; }
/// <summary>State of the operation on the resource.</summary>
Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Support.ProvisioningStates ProvisioningState { get; set; }
/// <summary>Access Control List (ACL) for an iSCSI Target; defines LUN masking policy</summary>
Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Models.Api20210401Preview.IAcl[] StaticAcls { get; set; }
/// <summary>Operational status of the iSCSI Target.</summary>
Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Support.OperationalStatus Status { get; set; }
/// <summary>
/// iSCSI Target IQN (iSCSI Qualified Name); example: "iqn.2005-03.org.iscsi:server".
/// </summary>
string TargetIqn { get; set; }
}
} | 62.212644 | 272 | 0.687113 | [
"MIT"
] | AndriiKalinichenko/azure-powershell | src/DiskPool/generated/api/Models/Api20210401Preview/IscsiTargetProperties.cs | 10,652 | C# |
[SoftUni("Ventsi")]
public class Program
{
[SoftUni("Gosho")]
public static void Main()
{
var tracker = new Tracker();
tracker.PrintMethodsByAuthor();
}
} | 18.7 | 39 | 0.588235 | [
"MIT"
] | mayapeneva/C-Sharp-OOP-Advanced | 04-05.ReflectionAndAttributesCORE/CodeTracker_Lab/Program.cs | 189 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
namespace AJTaskManagerMobile.Views.Controls
{
public sealed partial class AddItemControl : UserControl
{
public AddItemControl()
{
this.InitializeComponent();
}
}
}
| 26.178571 | 96 | 0.757162 | [
"Apache-2.0"
] | qbasko/AJTaskManager | AJTaskManagerService/AJTaskManagerMobile/Views/Controls/AddItemControl.xaml.cs | 735 | C# |
// Copyright (c) 2016 Framefield. All rights reserved.
// Released under the MIT license. (see LICENSE.txt)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Framefield.Core
{
public static class OperatorPartUtilities
{
public static float GetInputFloatValue(OperatorPart opPart)
{
if (opPart.Connections.Count == 0)
{
float newValue = 0;
var floatValue = ((opPart.Func as Utilities.ValueFunction).Value as Float);
if (floatValue != null)
newValue = floatValue.Val;
return newValue;
}
else
{
return opPart.Connections[0].Eval(new OperatorPartContext()).Value;
}
}
public static string GetInputTextValue(OperatorPart opPart)
{
if (opPart.Connections.Count == 0)
{
string text = "";
var textValue = ((opPart.Func as Utilities.ValueFunction).Value as Text);
if (textValue != null)
text = textValue.Val;
return text;
}
else
{
return opPart.Connections[0].Eval(new OperatorPartContext()).Text;
}
}
public static OperatorPart FindLowestUnconnectedOpPart(OperatorPart opPart, int maxDepth)
{
if (opPart == null)
return null;
if (maxDepth < 0)
return null;
if (opPart.Connections.Count == 0)
return opPart;
foreach (var input in opPart.Connections)
{
OperatorPart foundElement = FindLowestUnconnectedOpPart(input, maxDepth - 1);
if (foundElement != null)
return foundElement;
}
return null;
}
}
}
| 31.046154 | 98 | 0.505946 | [
"MIT"
] | kajott/tooll | Core/OperatorPartUtilities.cs | 2,020 | C# |
using Draughts.Common.Utilities;
using Draughts.Domain.GameContext.Models;
using Draughts.Domain.UserContext.Models;
using NodaTime;
using System;
namespace Draughts.Domain.GameContext.Services {
public class PlayGameDomainService : IPlayGameDomainService {
private readonly IClock _clock;
public PlayGameDomainService(IClock clock) {
_clock = clock;
}
public void DoMove(Game game, GameState gameState, UserId currentUserId, SquareId from, SquareId to) {
game.ValidateCanDoMove(currentUserId);
var moveResult = gameState.AddMove(from, to, game.Turn!.Player.Color, game.Settings);
switch (moveResult) {
case GameState.MoveResult.NextTurn:
game.NextTurn(currentUserId, _clock.UtcNow());
break;
case GameState.MoveResult.MoreCapturesAvailable:
break; // No need to do anything, the user will do the next move.
case GameState.MoveResult.GameOver:
game.WinGame(currentUserId, _clock.UtcNow());
break;
default:
throw new InvalidOperationException("Unknown MoveResult");
}
}
}
}
| 36.285714 | 110 | 0.620472 | [
"MIT"
] | Mattias1/ddd-draughts | Draughts/Domain/GameContext/Services/PlayGameDomainService.cs | 1,270 | C# |
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Abstractions;
using Abstractions.Stores;
using DataObjects;
using DataObjects.DAOS;
using DataObjects.DTOS.ManagementPlans.SearchScreens;
using EDCORE.ViewModel;
using MvvmHelpers;
using Stores;
namespace SQLite
{
public class SummaryStore : BaseStore, ISummaryStore
{
public SummaryStore(IDBPlatformSettings platform, ISQLiteCache iCache, ILookupStore iLookupStore)
{
_platform = platform;
_iCache = iCache;
_iLookupStore = iLookupStore;
_sqLiteAsyncConnection = GetConnection();
_sqLiteSyncConnection = GetSynchConnection();
}
public List<SummaryDescriptiontListDTO> GetSummaryDescriptiontListDtos()
{
Stopwatch stopwatch = Stopwatch.StartNew();
Debug.WriteLine("GetSummaryDescriptiontListDtos started");
var retData = new List<SummaryDescriptiontListDTO>();
string magicString = "SELECT mau.MainAcquisitionUnitID AS AcquisitionUnitID, " +
"mu.ID AS ManagementUnitID," +
" SUM(CASE dt.Reference WHEN \'SSSI\' THEN 1 ELSE 0 END) AS CountSSSI," +
" CAST(MAX(CASE dt.Reference WHEN \'SSSI\' THEN 1 ELSE 0 END) \r\n AS BIT) AS IsSSSI," +
" SUM(CASE dt.Reference WHEN \'TPO\' THEN 1 ELSE 0 END) AS CountTPO, CAST(MAX(CASE dt.Reference WHEN \'TPO\' THEN 1 ELSE 0 END) AS BIT) AS IsTPO," +
" \r\n SUM(CASE dt.Reference WHEN \'AWS\' THEN 1 ELSE 0 END) AS CountAWS, " +
"CAST(MAX(CASE dt.Reference WHEN \'AWS\' THEN 1 ELSE 0 END) AS BIT) AS IsAWS, " +
"\r\n SUM(CASE dt.Reference WHEN \'AONB\' THEN 1 ELSE 0 END) AS CountAONB, " +
"CAST(MAX(CASE dt.Reference WHEN \'AONB\' THEN 1 ELSE 0 END) AS BIT) AS IsAONB, \r\n " +
"SUM(CASE dt.Reference WHEN \'NP\' THEN 1 ELSE 0 END) AS CountNP, " +
"CAST(MAX(CASE dt.Reference WHEN \'NP\' THEN 1 ELSE 0 END) AS BIT) AS IsNP, " +
"SUM(CASE dt.Reference WHEN \'SAM\' THEN 1 ELSE 0 END)\r\n AS CountSAM, " +
"CAST(MAX(CASE dt.Reference WHEN \'SAM\' THEN 1 ELSE 0 END) AS BIT) AS IsSAM, " +
"intDesignStats.AWR, " +
"intDesignStats.[DEMO W/C], " +
"intDesignStats.[DEMO AWR], " +
"intDesignStats.DIO, \r\n " +
"intDesignStats.DEST," +
" intDesignStats.FA, " +
"intDesignStats.FWW, " +
"intDesignStats.LTM, " +
"intDesignStats.PPP, " +
"intDesignStats.PRP, " +
"intDesignStats.T4A, " +
"intDesignStats.TRAF AS Trafalgar," +
" intDesignStats.WOYD," +
" \r\n intDesignStats.WSP," +
" MAX(sc.PAWSStatus) AS PAWSStatus, " +
"CAST(CASE WHEN COUNT(dt.ID) > 7 THEN 1 ELSE 0 END AS BIT) AS MoreDesignations\r\n" +
"FROM (seLECT ID AS MainAcquisitionUnitID, ManagementUnitID\r\n" +
"FROM AcquisitionUnit) AS mau INNER JOIN\r\n ManagementUnit AS mu ON mu.ID = mau.ManagementUnitID INNER JOIN \r\n\t\t\t\t\t\t (SELECT au.ManagementUnitID AS [Cost Centre], CAST(SUM(CASE WHEN d .TypeID = 1 THEN 1 ELSE 0 END) AS BIT) AS AWR, CAST(SUM(CASE WHEN d .TypeID = 2 THEN 1 ELSE 0 END) AS BIT) AS [DEMO W/C], \r\n CAST(SUM(CASE WHEN d .TypeID = 3 THEN 1 ELSE 0 END) AS BIT) AS [DEMO AWR], CAST(SUM(CASE WHEN d .TypeID = 4 THEN 1 ELSE 0 END) AS BIT) AS DIO, \r\n CAST(SUM(CASE WHEN d .TypeID = 5 THEN 1 ELSE 0 END) AS BIT) AS DEST, CAST(SUM(CASE WHEN d .TypeID = 6 THEN 1 ELSE 0 END) AS BIT) AS FA, CAST(SUM(CASE WHEN d .TypeID = 7 THEN 1 ELSE 0 END)\r\n AS BIT) AS FWW, CAST(SUM(CASE WHEN d .TypeID = 8 THEN 1 ELSE 0 END) AS BIT) AS LTM, CAST(SUM(CASE WHEN d .TypeID = 9 THEN 1 ELSE 0 END) AS BIT) AS PPP, \r\n CAST(SUM(CASE WHEN d .TypeID = 10 THEN 1 ELSE 0 END) AS BIT) AS PRP, CAST(SUM(CASE WHEN d .TypeID = 11 THEN 1 ELSE 0 END) AS BIT) AS T4A, \r\n CAST(SUM(CASE WHEN d .TypeID = 12 THEN 1 ELSE 0 END) AS BIT) AS TRAF, CAST(SUM(CASE WHEN d .TypeID = 13 THEN 1 ELSE 0 END) AS BIT) AS WOYD, \r\n CAST(SUM(CASE WHEN d .TypeID = 14 THEN 1 ELSE 0 END) AS BIT) AS WSP\r\nFROM AcquisitionUnit AS au LEFT OUTER JOIN\r\n InternalDesignation AS d ON d.AcquisitionUnitID = au.ID\r\nGROUP BY au.ManagementUnitID) AS intDesignStats \t\t\t\t\t\t \t\t\t\t\t\t \r\n\t\t\t\t\t\t ON intDesignStats.[Cost Centre] = mu.ID LEFT OUTER JOIN\r\n SubCompartment AS sc ON sc.ManagementUnitID = mu.ID AND sc.Deleted = 0 LEFT OUTER JOIN\r\n AcquisitionUnit AS au ON au.ManagementUnitID = mu.ID AND au.Deleted = 0 LEFT OUTER JOIN\r\n Designation AS ds ON ds.AcquisitionUnitID = au.ID AND ds.Deleted = 0 LEFT OUTER JOIN\r\n DesignationType AS dt ON dt.ID = ds.TypeID AND dt.Deleted = 0\r\nGROUP BY mau.MainAcquisitionUnitID, mu.ID, intDesignStats.AWR, intDesignStats.[DEMO W/C], intDesignStats.[DEMO AWR], intDesignStats.DIO, intDesignStats.DEST, intDesignStats.FA, intDesignStats.FWW, \r\n intDesignStats.LTM, intDesignStats.PPP, intDesignStats.PRP, intDesignStats.T4A, intDesignStats.TRAF, intDesignStats.WOYD, intDesignStats.WSP";
var data = _sqLiteSyncConnection.Query<SummaryDescriptiont>(magicString).ToList();
//hack alert!!!
List<int> addedAcqs = new List<int>();
foreach (var v in data)
{
if (addedAcqs.Contains(v.ManagementUnitID)) continue;
addedAcqs.Add(v.ManagementUnitID);
var areaTotal =
_iCache.AcquisitionUnits.Where(a => a.ManagementUnitID == v.ManagementUnitID).Sum(s => s.GISAreaInHectares.GetValueOrDefault());
var manu = _iCache.ManagementUnits.FirstOrDefault(p => p.Id == v.ManagementUnitID);
var locat = _iCache.AcquisitionUnits.FirstOrDefault(a => a.ID == v.AcquisitionUnitID);
var sum = new SummaryDescriptiontListDTO
{
ManagementUnitID = v.ManagementUnitID,
CostCentre = v.ManagementUnitID,
Region = _iCache.RegionLookup[manu.RegionId.GetValueOrDefault()],
Manager = _iCache.UserLookup[manu.WoodlandOfficerId],
Name = manu.Name,
Location = locat?.Location,
AONB = v.IsAONB.GetValueOrDefault(),
Ancient = v.AWR.GetValueOrDefault(),
AreaHa = areaTotal,
MoreDesignations = v.MoreDesignations.GetValueOrDefault(),
NP = v.IsNP.GetValueOrDefault(),
PAWS = v.PPP.GetValueOrDefault(),
PAWStatus = v.PAWSStatus.GetValueOrDefault().ToString(),
SAM = v.IsSAM.GetValueOrDefault(),
SSSI = v.IsSSSI.GetValueOrDefault(),
TPO = v.IsTPO.GetValueOrDefault()
};
retData.Add(sum);
}
stopwatch.Stop();
Debug.WriteLine("GetSummaryDescriptiontListDtos ended in: " + stopwatch.ElapsedMilliseconds);
return retData.OrderBy(p=>p.Name).ToList();
}
public SummaryOverviewDto GetSummaryDescriptionContainerEditDto(int managementUnitID)
{
managementUnitID = 4354;
var mainSpeciesLookup = _iLookupStore.GetMainSpeciesDTOs();
var managementRegionsLookup = _iLookupStore.GetManagementRegimeDTOs();
var managementConstraintTypesLookup = _iLookupStore.GetManagementConstraints(0);
var conservationTypesLookup = _iLookupStore.GetConservationFeatures(0);
var designationsLookup = _iLookupStore.GetDesignations(0);
var yearsLookup = _iLookupStore.GetYears();
var acqu = _iCache.AcquisitionUnits.FirstOrDefault(
a => a.ManagementUnitID == managementUnitID && a.SummaryDescription != null);
var summaryDescriptiontEditContainerDto =
new SummaryOverviewDto
{
// SummariesList = new ObservableRangeCollection<SummaryDto>(),
SummaryDescription = acqu.SummaryDescription,
LongTermPolicyConclusions = _iCache.ManagementUnits.First(f=>f.Id == managementUnitID).LongTermIntentions
};
var magicString = @"SELECT ID,Year, AreaInHectares,Compartment,Description,MainSpeciesID,SecondSpeciesID,ManagementRegimeID,Reference FROM SubCompartment WHERE ManagementUnitID = " + managementUnitID;
var conditions = _sqLiteSyncConnection.Query<SubCompartment>(magicString).ToList();
//select d.TypeID from SubCompartment sc join SubCompartmentDesignationMap sm on sc.ID = sm.SubCompartmentID join Designation d on sm.DesignationID = d.ID where sc.ID = 4262
foreach (var sc in conditions)
{
Debug.WriteLine(sc.ID + " IDs ");
var designations = new ObservableRangeCollection<SummaryDesignationDto>();
designations.AddRange(_sqLiteSyncConnection.Query<SummaryDesignationDto>(@"select d.TypeID AS ID from SubCompartment sc join SubCompartmentDesignationMap sm on sc.ID = sm.SubCompartmentID join Designation d on sm.DesignationID = d.ID where sc.ID = " + sc.ID).ToList());
var conservationFeatures = new ObservableRangeCollection<SummaryFeatureDto>();
conservationFeatures.AddRange(_sqLiteSyncConnection.Query<SummaryFeatureDto>(@"SELECT sm.ID, FeatureID, sm.[Description], Confidential, MapRef from SubCompartment sc join SubCompartmentFeatureMap sm on sc.ID = sm.SubCompartmentID WHERE sc.ID = " + sc.ID).ToList());
//ManagementConstraintLookupDTO
var managementConstraintLookupDTOs = new ObservableRangeCollection<SummaryConstraintDto>();
managementConstraintLookupDTOs.AddRange(_sqLiteSyncConnection.Query<SummaryConstraintDto>(@"select mm.ID, TypeID, mm.Confidential, mm.OtherDescription from SubCompartment sc
join MajorManagementConstraintMap mmc
on sc.ID = mmc.SubCompartmentID
join MajorManagementConstraint mm
on mmc.MajorManagementConstraintTypeID = mm.ID WHERE sc.ID = " + sc.ID).ToList());
foreach (var cf in conservationFeatures)
{
cf.Feature = conservationTypesLookup.FirstOrDefault(f => f.ID == cf.FeatureId);
}
foreach (var mc in managementConstraintLookupDTOs)
{
mc.Type = managementConstraintTypesLookup.FirstOrDefault(f => f.ID == mc.TypeID);
}
foreach (var des in designations)
{
des.Description = designationsLookup.FirstOrDefault(f => f.ID == des.Id);
}
//summaryDescriptiontEditContainerDto.SummariesList.Add(new SummaryDto()
//{
// Year = sc.Year.GetValueOrDefault(),
// YearLookup = yearsLookup.FirstOrDefault(f=>f.ID == sc.Year.GetValueOrDefault()),
// AreaHa = sc.AreaInHectares,
// Compartment = sc.Compartment,
// CompartmentDescription = sc.Description,
// MainSpeciesID = sc.MainSpeciesID.GetValueOrDefault(),
// MainSpecies = mainSpeciesLookup.FirstOrDefault(i=>i.ID == sc.MainSpeciesID.GetValueOrDefault()),
// SecondarySpeciesID = sc.SecondSpeciesID.GetValueOrDefault(),
// SecondarySpecies = mainSpeciesLookup.FirstOrDefault(i => i.ID == sc.SecondSpeciesID.GetValueOrDefault()),
// ManagementRegimeID = sc.ManagementRegimeID.GetValueOrDefault(),
// ManagementRegime = managementRegionsLookup.FirstOrDefault(i => i.ID == sc.ManagementRegimeID.GetValueOrDefault()),
// SubCompartmentID = sc.ID,
// SubCompartmentRef = sc.Reference,
// Designations = designations,
// ConservationFeatures = conservationFeatures,
// MajorManagementConstraints = managementConstraintLookupDTOs
//});
}
return summaryDescriptiontEditContainerDto;
}
public List<SummaryDto> GetSummaries(int managementUnitId)
{
throw new System.NotImplementedException();
}
public List<SummaryConstraintDto> GetSummaryConstraints(int subCompartmentId)
{
throw new System.NotImplementedException();
}
public List<SummaryFeatureDto> GetSummaryFeatures(int subCompartmentId)
{
throw new System.NotImplementedException();
}
public List<SummaryDesignationDto> GetSummaryDesignations(int subCompartmentId)
{
throw new System.NotImplementedException();
}
public void UpdateSummaryDescriptionOverview(SummaryOverviewDto editSet, int managementId)
{
throw new System.NotImplementedException();
}
public void UpdateSummaries(List<SummaryDto> editSet, int managementId)
{
throw new System.NotImplementedException();
}
public void UpdateSummaryConstraints(List<SummaryConstraintDto> editSet, int subCompartmentId)
{
throw new System.NotImplementedException();
}
public void UpdateSummaryFeatures(List<SummaryFeatureDto> editSet, int subCompartmentId)
{
throw new System.NotImplementedException();
}
public void UpdateSummaryDesignations(List<SummaryDesignationDto> editSet, int subCompartmentId)
{
throw new System.NotImplementedException();
}
public List<SummaryDescriptiontListDTO> GetSummaryDescriptiontListDtos(List<UserRoleSmallDto> userRole, int userId, int application, int regionId)
{
throw new System.NotImplementedException();
}
}
} | 54.392361 | 2,513 | 0.569167 | [
"MIT"
] | GeorgeThackrayWT/GraphQLSample | ED/SQLite/Content/ManagementPlans/SummaryDescription/SummaryStore.cs | 15,665 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Threading.Tasks;
namespace Microsoft.Its.Domain
{
/// <summary>
/// Handles commands that have passed authorization and validation checks.
/// </summary>
/// <typeparam name="TTarget">The type of the target.</typeparam>
/// <typeparam name="TCommand">The type of the command.</typeparam>
public interface ICommandHandler<in TTarget, TCommand>
where TCommand : class, ICommand<TTarget>
{
/// <summary>
/// Called when a command has passed validation and authorization checks.
/// </summary>
/// <param name="target">The target to which the command was applied.</param>
/// <param name="command">The command.</param>
Task EnactCommand(TTarget target, TCommand command);
/// <summary>
/// Handles any exception that occurs during delivery of a scheduled command.
/// </summary>
/// <param name="target">The target of the command.</param>
/// <param name="command">The command.</param>
/// <remarks>
/// The aggregate can use this method to control retry and cancelation of the command.
/// </remarks>
Task HandleScheduledCommandException(TTarget target, CommandFailed<TCommand> command);
}
}
| 41.676471 | 101 | 0.656316 | [
"MIT"
] | jonsequitur/Its.Cqrs | Domain/ICommandHandler{T,TCommand}.cs | 1,417 | C# |
namespace Milou.Deployer.Core.Deployment.Configuration
{
public class WebDeployRulesConfig
{
public WebDeployRulesConfig(
bool doNotDeleteRuleEnabled,
bool appOfflineRuleEnabled,
bool useChecksumRuleEnabled,
bool appDataSkipDirectiveEnabled,
bool applicationInsightsProfiler2SkipDirectiveEnabled)
{
DoNotDeleteRuleEnabled = doNotDeleteRuleEnabled;
AppOfflineRuleEnabled = appOfflineRuleEnabled;
UseChecksumRuleEnabled = useChecksumRuleEnabled;
AppDataSkipDirectiveEnabled = appDataSkipDirectiveEnabled;
ApplicationInsightsProfiler2SkipDirectiveEnabled = applicationInsightsProfiler2SkipDirectiveEnabled;
}
public bool DoNotDeleteRuleEnabled { get; }
public bool AppOfflineRuleEnabled { get; }
public bool UseChecksumRuleEnabled { get; }
public bool AppDataSkipDirectiveEnabled { get; }
public bool ApplicationInsightsProfiler2SkipDirectiveEnabled { get; }
}
}
| 35.4 | 112 | 0.707156 | [
"MIT"
] | bjorkblom/milou.deployer | src/Milou.Deployer.Core/Deployment/Configuration/WebDeployRulesConfig.cs | 1,064 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Text.RegularExpressions;
using System.Collections.ObjectModel;
using LogProc.Definitions;
using LogProc.Utilities;
namespace LogProc {
public partial class ContestNo : Window {
private ObservableCollection<ScnData> scn { get; set; }
public string retEx = null;
public ContestNo() { }
public ContestNo(string extra) {
InitializeComponent();
scn = new ObservableCollection<ScnData>(GetScnList(extra));
this.dgRcn.ItemsSource = new ObservableCollection<ScnData>(scn.ToList());
foreach(FreqStr fs in Enum.GetValues(typeof(FreqStr))) {
cbFreq.Items.Add(Freq.CnvTostr(fs));
}
}
public static List<ScnData> GetScnList(string ex) {
return Regex.Matches(ex, @"([\w\d\.]+), ([^:,]+): ").Cast<Match>().Select(x => new ScnData() { Freq = x.Groups[1].Value, SentCn = x.Groups[2].Value }).ToList();
}
public static string GetVal(string ex, string freq) {
var list = GetScnList(ex);
if (list.Count == 0) return null;
var litmp = list.Where(x => x.Freq == freq).FirstOrDefault();
return litmp != null ? litmp.SentCn : null;
}
private void btCancel_Click(object sender, RoutedEventArgs e) {
this.Close();
}
private void btConfirm_Click(object sender, RoutedEventArgs e) {
retEx = "";
scn.ToList().ForEach(s => {
retEx += s.Freq + ", " + s.SentCn + ": ";
});
this.Close();
}
private void btAdd_Click(object sender, RoutedEventArgs e) {
scn.Add(new ScnData() { Freq = cbFreq.Text, SentCn = tbScn.Text, });
scn = new ObservableCollection<ScnData>(scn);
dgRcn.ItemsSource = scn;
}
}
}
| 30.327273 | 163 | 0.679856 | [
"MIT"
] | JI1LDG/LogProc | LogProc/ContestNo.xaml.cs | 1,670 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("LibBili.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LibBili.Test")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("7db4d5ce-bf02-4eed-8332-4e47529ffe0b")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 25.378378 | 56 | 0.71459 | [
"MIT"
] | shabby2333/LibBili | LibBili.Test/Properties/AssemblyInfo.cs | 1,280 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using PrtgAPI.PowerShell.Progress;
using PrtgAPI.Utilities;
namespace PrtgAPI.PowerShell.Base
{
/// <summary>
/// Base class for all cmdlets that return a list of objects.
/// </summary>
/// <typeparam name="T">The type of objects that will be retrieved.</typeparam>
public abstract class PrtgObjectCmdlet<T> : PrtgProgressCmdlet
{
/// <summary>
/// Initializes a new instance of the <see cref="PrtgObjectCmdlet{T}"/> class.
/// </summary>
protected PrtgObjectCmdlet() : base(IObjectExtensions.GetTypeDescription(typeof(T)))
{
}
/// <summary>
/// Retrieves all records of a specified type from a PRTG Server. Implementors can call different methods of a
/// <see cref="PrtgClient"/> based on the type of object they wish to retrieve.
/// </summary>
/// <returns>A list of records relevant to the caller.</returns>
protected abstract IEnumerable<T> GetRecords();
/// <summary>
/// Performs enhanced record-by-record processing functionality for the cmdlet.
/// </summary>
protected override void ProcessRecordEx()
{
IEnumerable<T> records;
if (ProgressManager.GetRecordsWithVariableProgress)
records = GetResultsWithVariableProgress(GetRecords);
else if (ProgressManager.GetResultsWithProgress)
records = GetResultsWithProgress(GetRecords);
else
records = GetRecords();
WriteList(records);
}
/// <summary>
/// Retrieve results from a PRTG server while displaying progress for objects that have been piped from a variable.
/// </summary>
/// <param name="getResults">The function to execute to retrieve this cmdlet's results.</param>
/// <returns>A collection of objects returned from a PRTG Server. that match the specified search criteria.</returns>
protected IEnumerable<T> GetResultsWithVariableProgress(Func<IEnumerable<T>> getResults)
{
UpdatePreviousAndCurrentVariableProgressOperations();
var records = getResults().ToList();
ProgressManager.TotalRecords = records.Count;
return records;
}
/// <summary>
/// Retrieve results from a PRTG server while displaying progress for objects that have been piped between cmdlets.
/// </summary>
/// <param name="getResults">The function to execute to retrieve this cmdlet's results.</param>
/// <returns>A collection of objects returned from a PRTG Server. that match the specified search criteria.</returns>
protected IEnumerable<T> GetResultsWithProgress(Func<IEnumerable<T>> getResults)
{
//May return the count of records we'll be retrieving if we're streaming (for example)
int count = DisplayInitialProgress();
var records = getResults();
return UpdatePreviousProgressAndGetCount(records, count);
}
private int DisplayInitialProgress()
{
int count = -1;
if (ProgressManager.FirstInChain)
{
//If DisplayFirstInChainMessage is overridden, count _may_ be set (e.g. if we are streaming records,
//in which case we will get the total number of records we _will_ retrieve before returning)
count = DisplayFirstInChainMessage();
}
else
{
if (ProgressManager.PreviousContainsProgress)
{
ProgressManager.SetPreviousOperation($"Retrieving all {TypeDescription.ToLower().ForcePlural()}");
}
}
return count;
}
private IEnumerable<T> UpdatePreviousProgressAndGetCount(IEnumerable<T> records, int count)
{
records = GetCount(records, ref count);
UpdatePreviousProgressAndSetCount(count);
return records;
}
/// <summary>
/// Display the initial progress message for the first cmdlet in the chain.<para/>
/// Returns an integer so that overridden instances of this method may support progress scenarios such as streaming
/// (where a "detecting total number of items" message is displayed before requesting the object totals.
/// </summary>
/// <returns>-1. Override this method in a derived class to optionally return the total number of objects that will be retrieved.</returns>
protected virtual int DisplayFirstInChainMessage()
{
int count = -1;
SetObjectSearchProgress(ProcessingOperation.Retrieving);
ProgressManager.DisplayInitialProgress();
return count;
}
/// <summary>
/// Retrieves the number of elements returned from a request. Generally the collection of records should internally be a <see cref="List{T}"/>.<para/>
/// For scenarios where this is not the case, this method can be overridden in derived classes.
/// </summary>
/// <param name="records">The collection of records to count.Should be a <see cref="List{T}"/></param>
/// <param name="count">The count of records to be returned from this method.</param>
/// <returns>The number of elements returned from the request.</returns>
protected virtual IEnumerable<T> GetCount(IEnumerable<T> records, ref int count)
{
var list = records as List<T> ?? records.ToList();
count = list.Count;
return list;
}
/// <summary>
/// Filter a response with a wildcard expression on a specified property.
/// </summary>
/// <param name="records">The records to filter.</param>
/// <param name="pattern">The wildcard expression to filter with.</param>
/// <param name="getProperty">A function that yields the property to filter by.</param>
/// <returns>A list of records that match the specified filter.</returns>
protected IEnumerable<T> FilterResponseRecords(IEnumerable<T> records, string pattern, Func<T, string> getProperty)
{
if (pattern != null)
{
var filter = new WildcardPattern(pattern.ToLower());
records = records.Where(r => filter.IsMatch(getProperty(r).ToLower()));
}
return records;
}
/// <summary>
/// Filter a response on a specified property.
/// </summary>
/// <typeparam name="TObject">The type of object to filter.</typeparam>
/// <typeparam name="TProperty">The type of property to filter on.</typeparam>
/// <param name="filters">A list of values to filter based on.</param>
/// <param name="getProperty">A function that yields the property to filter by.</param>
/// <param name="records">The records to filter.</param>
/// <returns>A list of records that matched any of the specified filters.</returns>
protected IEnumerable<TObject> FilterResponseRecords<TObject, TProperty>(TProperty[] filters, Func<TObject, TProperty> getProperty, IEnumerable<TObject> records)
{
if (filters != null)
records = records.Where(r => filters.Contains(getProperty(r)));
return records;
}
/// <summary>
/// Filter a response by either a wildcard expression or an object contained in a <see cref="NameOrObject{T}"/> value.
/// </summary>
/// <typeparam name="TProperty">The type of property to filter on.</typeparam>
/// <param name="filters">A list of values to filter based on.</param>
/// <param name="getProperty">A function that yields the property to filter by.</param>
/// <param name="records">The records to filter.</param>
/// <returns>A list of records that matched any of the specified filters.</returns>
protected IEnumerable<T> FilterResponseRecordsByPropertyNameOrObjectId<TProperty>(
NameOrObject<TProperty>[] filters,
Func<T, TProperty> getProperty,
IEnumerable<T> records) where TProperty : PrtgObject
{
if (filters == null)
return records;
return records.Where(
record =>
{
return filters.Any(filter =>
{
var action = getProperty(record);
if (action == null)
return false;
if (filter.IsObject)
return action.Id == filter.Object.Id;
else
{
var wildcard = new WildcardPattern(filter.Name, WildcardOptions.IgnoreCase);
return wildcard.IsMatch(action.Name);
}
});
}
);
}
/// <summary>
/// Filter records returned from PRTG by one or more wildcards.
/// </summary>
/// <param name="arr">The array of wildcards to filter against.</param>
/// <param name="getProperty">A function that yields the property to filter by.</param>
/// <param name="records">The records to filter.</param>
/// <returns>A collection of filtered records.</returns>
protected IEnumerable<T> FilterResponseRecordsByWildcardArray(string[] arr, Func<T, string> getProperty, IEnumerable<T> records)
{
if (arr != null)
{
records = records.Where(
record => arr
.Select(a => new WildcardPattern(a, WildcardOptions.IgnoreCase))
.Any(filter => filter.IsMatch(getProperty(record))
)
);
}
return records;
}
}
}
| 42.609244 | 169 | 0.595898 | [
"MIT"
] | ericsp59/PrtgAPI | src/PrtgAPI.PowerShell/PowerShell/Base/PrtgObjectCmdlet.cs | 10,143 | C# |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Novell.Directory.Ldap.Asn1.Asn1Set.cs
//
// Author:
// Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
namespace Novell.Directory.Ldap.Asn1
{
/// <summary> The Asn1Set class can hold an unordered collection of components with
/// distinct type. This class inherits from the Asn1Structured class
/// which already provides functionality to hold multiple Asn1 components.
/// </summary>
public class Asn1Set:Asn1Structured
{
/// <summary> ASN.1 SET tag definition.</summary>
public const int TAG = 0x11;
/// <summary> ID is added for Optimization.</summary>
/// <summary> ID needs only be one Value for every instance,
/// thus we create it only once.
/// </summary>
public static readonly Asn1Identifier ID = new Asn1Identifier(Asn1Identifier.UNIVERSAL, true, TAG);
/* Constructors for Asn1Set
*/
/// <summary> Constructs an Asn1Set object with no actual
/// Asn1Objects in it. Assumes a default size of 5 elements.
/// </summary>
public Asn1Set():base(ID)
{
return ;
}
/// <summary> Constructs an Asn1Set object with the specified
/// number of placeholders for Asn1Objects. However there
/// are no actual Asn1Objects in this SequenceOf object.
///
/// </summary>
/// <param name="size">Specifies the initial size of the collection.
/// </param>
public Asn1Set(int size):base(ID, size)
{
return ;
}
/// <summary> Constructs an Asn1Set object by decoding data from an
/// input stream.
///
/// </summary>
/// <param name="dec">The decoder object to use when decoding the
/// input stream. Sometimes a developer might want to pass
/// in his/her own decoder object
///
/// </param>
/// <param name="in">A byte stream that contains the encoded ASN.1
///
/// </param>
[CLSCompliantAttribute(false)]
public Asn1Set(Asn1Decoder dec, System.IO.Stream in_Renamed, int len):base(ID)
{
decodeStructured(dec, in_Renamed, len);
return ;
}
/* Asn1Set specific methods
*/
/// <summary> Returns a String representation of this Asn1Set.</summary>
[CLSCompliantAttribute(false)]
public override System.String ToString()
{
return base.toString("SET: { ");
}
}
}
| 33.481132 | 101 | 0.673429 | [
"Apache-2.0"
] | 121468615/mono | mcs/class/Novell.Directory.Ldap/Novell.Directory.Ldap.Asn1/Asn1Set.cs | 3,549 | C# |
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server
* for more information concerning the license and the contributors participating to this project.
*/
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Http;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace AspNet.Security.OpenIdConnect.Server {
/// <summary>
/// Provides context information when processing an Authorization Response
/// </summary>
public sealed class AuthorizationEndpointResponseNotification : BaseNotification<OpenIdConnectServerOptions> {
/// <summary>
/// Initializes a new instance of the <see cref="AuthorizationEndpointResponseNotification"/> class
/// </summary>
/// <param name="context"></param>
/// <param name="options"></param>
/// <param name="ticket"></param>
/// <param name="request"></param>
/// <param name="response"></param>
internal AuthorizationEndpointResponseNotification(
HttpContext context,
OpenIdConnectServerOptions options,
OpenIdConnectMessage request,
OpenIdConnectMessage response)
: base(context, options) {
Request = request;
Response = response;
}
/// <summary>
/// Gets the authorization request.
/// </summary>
public new OpenIdConnectMessage Request { get; }
/// <summary>
/// Gets the authorization response.
/// </summary>
public new OpenIdConnectMessage Response { get; }
/// <summary>
/// Get the access code expected to
/// be returned to the client application.
/// Depending on the flow, it can be null.
/// </summary>
public string AccessToken => Response.AccessToken;
/// <summary>
/// Get the authorization code expected to
/// be returned to the client application.
/// Depending on the flow, it can be null.
/// </summary>
public string AuthorizationCode => Response.Code;
}
}
| 37.389831 | 114 | 0.63418 | [
"Apache-2.0"
] | bigfont/AspNet.Security.OpenIdConnect.Server | src/AspNet.Security.OpenIdConnect.Server/Notifications/AuthorizationEndpointResponseNotification.cs | 2,208 | C# |
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
namespace UnityChan
{
[ExecuteInEditMode]
public class SplashScreen : MonoBehaviour
{
void NextLevel ()
{
//SceneManager.LoadScene();
}
}
} | 16 | 43 | 0.679688 | [
"MIT"
] | chunibyo-wly/openpose-unity-game | Assets/unity-chan!/Unity-chan! Model/SplashScreen/Scripts/SplashScreen.cs | 258 | C# |
using Newtonsoft.Json;
namespace NIMChatRoom
{
/// <summary>
/// 聊天室信息
/// </summary>
public class ChatRoomInfo : NimUtility.NimJsonObject<ChatRoomInfo>
{
/// <summary>
///聊天室ID
/// </summary>
[JsonProperty("id")]
public long RoomId { get; set; }
/// <summary>
///聊天室名称
/// </summary>
[JsonProperty("name")]
public string RoomName { get; set; }
/// <summary>
///聊天室公告
/// </summary>
[JsonProperty("announcement")]
public string Announcement { get; set; }
/// <summary>
///视频直播流地址
/// </summary>
[JsonProperty("broadcast_url")]
public string BroadcastUrl { get; set; }
/// <summary>
///聊天室创建者账号
/// </summary>
[JsonProperty("creator_id")]
public string CreatorId { get; set; }
/// <summary>
///聊天室有效标记, 1:有效,0:无效
/// </summary>
[JsonProperty("valid_flag")]
public int Valid { get; set; }
/// <summary>
///第三方扩展字段, 必须为可以解析为Json的非格式化的字符串, 长度4k
/// </summary>
[JsonProperty("ext")]
public string Extension { get; set; }
/// <summary>
/// 在线人数
/// </summary>
[JsonProperty("online_count")]
public int OnlineMembersCount { get; set; }
[JsonProperty("mute_all")]
public int _isMuted { get; set; }
/// <summary>
/// 聊天室禁言标志
/// </summary>
[JsonIgnore]
public bool IsMuted
{
get { return _isMuted == 1; }
set { _isMuted = 0; }
}
public ChatRoomInfo()
{
RoomId = 0;
Valid = 0;
}
}
}
| 22.807692 | 70 | 0.469927 | [
"Apache-2.0"
] | YANGQUNGONGSHE/jesusYQ_U3d | Assets/nim/ChatRoom/ChatRoomInfo.cs | 1,943 | C# |
using System;
using ServiceStack.ServiceHost;
namespace ServiceStack.WebHost.Endpoints.Support
{
public class ContentType
{
public const string HeaderContentType = "Content-Type";
public const string FormUrlEncoded = "application/x-www-form-urlencoded";
public const string MultiPartFormData = "multipart/form-data";
public const string Html = "text/html";
public const string Xml = "application/xml";
public const string XmlText = "text/xml";
public const string Soap11 = " text/xml; charset=utf-8";
public const string Soap12 = " application/soap+xml";
public const string Json = "application/json";
public const string JsonText = "text/json";
public const string Jsv = "application/jsv";
public const string JsvText = "text/jsv";
public const string Csv = "text/csv";
public const string Yaml = "application/yaml";
public const string YamlText = "text/yaml";
public const string PlainText = "text/plain";
public const string ProtoBuf = "application/x-protobuf";
public static EndpointAttributes GetEndpointAttributes(string contentType)
{
switch (contentType)
{
case Json:
case JsonText:
return EndpointAttributes.Json;
case Xml:
case XmlText:
return EndpointAttributes.Xml;
case Html:
return EndpointAttributes.Html;
case Jsv:
case JsvText:
return EndpointAttributes.Jsv;
case Yaml:
case YamlText:
return EndpointAttributes.Yaml;
case Csv:
return EndpointAttributes.Csv;
}
throw new NotSupportedException(contentType);
}
public static string GetContentType(EndpointType endpointType)
{
switch (endpointType)
{
case EndpointType.Soap11:
case EndpointType.Soap12:
case EndpointType.Xml:
return Xml;
case EndpointType.Json:
return Json;
case EndpointType.Jsv:
return JsvText;
case EndpointType.ProtoBuf:
return ProtoBuf;
default:
throw new NotSupportedException(endpointType.ToString());
}
}
}
} | 22.231579 | 77 | 0.677083 | [
"BSD-3-Clause"
] | bcuff/ServiceStack | src/ServiceStack.MonoTouch/ContentType.cs | 2,112 | C# |
// ****************************************************************
// Copyright 2007, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org/?p=license&r=2.4
// ****************************************************************
using System;
using NUnit.Framework;
namespace NUnit.TestData.PropertyAttributeTests
{
[TestFixture, Property("ClassUnderTest","SomeClass" )]
public class FixtureWithProperties
{
[Test, Property("user","Charlie")]
public void Test1() { }
[Test, Property("X",10.0), Property("Y",17.0)]
public void Test2() { }
[Test, Priority(5)]
public void Test3() { }
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple=false)]
public class PriorityAttribute : PropertyAttribute
{
public PriorityAttribute( int level ) : base( level ) { }
}
}
| 28.870968 | 69 | 0.582123 | [
"Apache-2.0"
] | assessorgeneral/ConQAT | org.conqat.engine.dotnet/test-data/org.conqat.engine.dotnet.scope/NUnit_Folder/tests/test-assembly/PropertyAttributeTests.cs | 895 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Http;
using System.Web.Routing;
namespace DSETrending
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
}
}
}
| 34.642857 | 159 | 0.749485 | [
"MIT"
] | nazmoonnoor/trending | DSETrending/Global.asax.cs | 972 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: ReferenceAssembly]
[assembly: AssemblyTitle("System.Console")]
[assembly: AssemblyDescription("System.Console")]
[assembly: AssemblyDefaultAlias("System.Console")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Microsoft® .NET Framework")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyFileVersion("4.6.24705.01")]
[assembly: AssemblyInformationalVersion("4.6.24705.01 built by: SOURCEBUILD")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("", "")]
[assembly: AssemblyVersion("4.0.1.0")]
[assembly: TypeForwardedTo(typeof(System.Console))]
[assembly: TypeForwardedTo(typeof(System.ConsoleCancelEventArgs))]
[assembly: TypeForwardedTo(typeof(System.ConsoleCancelEventHandler))]
[assembly: TypeForwardedTo(typeof(System.ConsoleColor))]
[assembly: TypeForwardedTo(typeof(System.ConsoleKey))]
[assembly: TypeForwardedTo(typeof(System.ConsoleKeyInfo))]
[assembly: TypeForwardedTo(typeof(System.ConsoleModifiers))]
[assembly: TypeForwardedTo(typeof(System.ConsoleSpecialKey))]
| 44.7 | 90 | 0.728188 | [
"MIT"
] | MichaelSimons/source-build-reference-packages | src/referencePackages/src/system.console/4.3.0/ref/net46/System.Console.cs | 1,790 | C# |
namespace BoundlessProxyUi.Util
{
/// <summary>
/// Constants for the whole application
/// </summary>
class Constants
{
/// <summary>
/// Discovery server name to connect to
/// </summary>
public const string DiscoveryServer = "ds.playboundless.com";
//public const string DiscoveryServer = "ds-testing.playboundless.com";
/// <summary>
/// Account server name to connect to
/// </summary>
public const string AccountServer = "account.playboundless.com";
/// <summary>
/// Domain for Boundlexx
/// </summary>
public const string BoundlexxApi = "api.boundlexx.app";
/// <summary>
/// Server Prefix for Game Servers
/// </summary>
public const string ServerPrefix = "gs-live";
}
}
| 27.258065 | 79 | 0.573964 | [
"MIT"
] | AngellusMortis/BoundlessProxyUi | BoundlessProxyUi/Util/Constants.cs | 847 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Volo.Abp.EntityFrameworkCore;
using wf.abp.EntityFrameworkCore.DbMigrations;
namespace wf.abp.EntityFrameworkCore.DbMigrations.Migrations
{
[DbContext(typeof(ProductsMigrationsDbContext))]
[Migration("20201130084947_01")]
partial class _01
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("_Abp_DatabaseProvider", EfCoreDatabaseProvider.MySql)
.HasAnnotation("ProductVersion", "3.1.10")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("wf.abp.Domain.Books.Book", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnName("ConcurrencyStamp")
.HasColumnType("varchar(40) CHARACTER SET utf8mb4")
.HasMaxLength(40);
b.Property<DateTime>("CreationTime")
.HasColumnName("CreationTime")
.HasColumnType("datetime(6)");
b.Property<Guid?>("CreatorId")
.HasColumnName("CreatorId")
.HasColumnType("char(36)");
b.Property<string>("ExtraProperties")
.HasColumnName("ExtraProperties")
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.Property<DateTime?>("LastModificationTime")
.HasColumnName("LastModificationTime")
.HasColumnType("datetime(6)");
b.Property<Guid?>("LastModifierId")
.HasColumnName("LastModifierId")
.HasColumnType("char(36)");
b.Property<string>("Name")
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.Property<float>("Price")
.HasColumnType("float");
b.Property<DateTime>("PublishDate")
.HasColumnType("datetime(6)");
b.Property<int>("Type")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Book");
});
#pragma warning restore 612, 618
}
}
}
| 36.921053 | 85 | 0.534212 | [
"MIT"
] | iwangfeng7/AbpvNextDemo | wf.abpDemo/wf.abp.EntityFrameworkCore.DbMigrations/Migrations/20201130084947_01.Designer.cs | 2,808 | C# |
using dnlib.DotNet;
using dnlib.DotNet.Emit;
using Uskr.Attributes;
using Uskr.Core;
using Uskr.IR;
namespace Uskr.Opcodes
{
[Handler(Code.Ldelem)]
public class Ldelem : IOpcodeProcessor
{
public void Handel(IRAssembly assembly, IRMethod meth, UskrContext context, Instruction instruction)
{
context.Asm($"pop eax"); //index
context.Asm($"pop ecx"); //array
context.Asm($"add ecx, 4"); //array
context.Asm($"mov edx, 4"); //array
context.Asm($"mul edx");
context.Asm($"add ecx, eax");
context.Asm($"mov ebx, [ecx]"); //array
context.Asm("push ebx");
}
}
} | 27.192308 | 108 | 0.561528 | [
"MIT"
] | Myvar/Uskr | Uskr/Opcodes/Ldelem.cs | 707 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace ForYou.CodingInterviews.Account.Windows
{
/// <summary>
/// Interaction logic for ModePaymentWindow.xaml
/// </summary>
public partial class ModePaymentWindow : Window
{
public ModePaymentWindow()
{
InitializeComponent();
}
int _selectedIndex = -1;
private void ModePaymentLBMouseLeftClick(object sender, MouseButtonEventArgs e)
{
var lb = sender as ListBox;
if(lb.SelectedIndex == _selectedIndex)
{
lb.SelectedItem = null;
}
_selectedIndex = lb.SelectedIndex;
}
int _accountSelectedIndex = -1;
private void AccountPaymentLBMouseLeftClick(object sender, MouseButtonEventArgs e)
{
var lb = sender as ListBox;
if (lb.SelectedIndex == _accountSelectedIndex)
{
lb.SelectedItem = null;
}
_accountSelectedIndex = lb.SelectedIndex;
}
}
}
| 27.4 | 90 | 0.633577 | [
"MIT"
] | Gun-Killer/CodingInterviews | ForYou.CodingInterviews/WPF/Projects/Account/ForYou.CodingInterviews.Account/Windows/ModePaymentWindow.xaml.cs | 1,372 | C# |
using System;
using System.Linq.Expressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Lambda2Js.Tests
{
[TestClass]
public class StaticMathMethodTests
{
[TestMethod]
public void MathPow()
{
Expression<Func<MyClass, double>> expr = o => Math.Pow(o.Age, 2.0);
var js = expr.CompileToJavascript(
new JavascriptCompilationOptions(
JsCompilationFlags.BodyOnly | JsCompilationFlags.ScopeParameter,
new[] { new StaticMathMethods() }));
Assert.AreEqual("Math.pow(Age,2)", js);
}
[TestMethod]
public void MathLog()
{
Expression<Func<MyClass, double>> expr = o => Math.Log(o.Age) + 1;
var js = expr.CompileToJavascript(
new JavascriptCompilationOptions(
JsCompilationFlags.BodyOnly | JsCompilationFlags.ScopeParameter,
new[] { new StaticMathMethods(), }));
Assert.AreEqual("Math.log(Age)+1", js);
}
[TestMethod]
public void MathLog2Args()
{
Expression<Func<MyClass, double>> expr = o => Math.Log(o.Age, 2.0) + 1;
var js = expr.CompileToJavascript(
new JavascriptCompilationOptions(
JsCompilationFlags.BodyOnly | JsCompilationFlags.ScopeParameter,
new[] { new StaticMathMethods(), }));
Assert.AreEqual("Math.log(Age)/Math.log(2)+1", js);
}
[TestMethod]
public void MathRound()
{
Expression<Func<MyClass, double>> expr = o => Math.Round(o.Age / 0.7);
var js = expr.CompileToJavascript(
new JavascriptCompilationOptions(
JsCompilationFlags.BodyOnly | JsCompilationFlags.ScopeParameter,
new[] { new StaticMathMethods(true) }));
Assert.AreEqual("Math.round(Age/0.7)", js);
}
[TestMethod]
public void MathRound2Args()
{
Expression<Func<MyClass, double>> expr = o => Math.Round(o.Age / 0.7, 2);
var js = expr.CompileToJavascript(
new JavascriptCompilationOptions(
JsCompilationFlags.BodyOnly | JsCompilationFlags.ScopeParameter,
new[] { new StaticMathMethods(true) }));
Assert.AreEqual("(function(a,b){return Math.round(a*b)/b;})(Age/0.7,Math.pow(10,2))", js);
}
[TestMethod]
public void MathE()
{
Expression<Func<MyClass, double>> expr = o => Math.E;
var js = expr.CompileToJavascript(
new JavascriptCompilationOptions(
JsCompilationFlags.BodyOnly | JsCompilationFlags.ScopeParameter,
new[] { new StaticMathMethods() }));
Assert.AreEqual("Math.E", js);
}
[TestMethod]
public void MathPI()
{
Expression<Func<MyClass, double>> expr = o => Math.PI;
var js = expr.CompileToJavascript(
new JavascriptCompilationOptions(
JsCompilationFlags.BodyOnly | JsCompilationFlags.ScopeParameter,
new[] { new StaticMathMethods() }));
Assert.AreEqual("Math.PI", js);
}
}
} | 33.306931 | 102 | 0.55321 | [
"MIT"
] | ganezh/lambda2js | Lambda2Js.Tests/StaticMathMethodTests.cs | 3,364 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227
namespace GradientBrushMarkup
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used when the application is launched to open a specific file, to display
/// search results, and so forth.
/// </summary>
/// <param name="args">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
if (!rootFrame.Navigate(typeof(MainPage), args.Arguments))
{
throw new Exception("Failed to create initial page");
}
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
| 39.824176 | 100 | 0.605684 | [
"MIT"
] | nnaabbcc/exercise | windows/pw6e.official/CSharp/Chapter02/GradientBrushMarkup/GradientBrushMarkup/App.xaml.cs | 3,624 | C# |
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace apislice.Controllers
{
public class TagsController : ControllerBase
{
}
}
| 16.285714 | 48 | 0.763158 | [
"MIT"
] | microsoftgraph/msgraph-openapi-introspection | graphslice/Controllers/TagsController.cs | 230 | C# |
using DatabaseBenchmark.Core;
using DatabaseBenchmark.Core.Interfaces;
using DatabaseBenchmark.Databases.Interfaces;
using DatabaseBenchmark.Model;
using System.Data;
namespace DatabaseBenchmark.Databases.Sql
{
public class SqlRawQueryExecutorFactory<TConnection> : IQueryExecutorFactory
where TConnection: IDbConnection, new()
{
private readonly string _connectionString;
private readonly RawQuery _query;
private readonly IExecutionEnvironment _environment;
private readonly RandomGenerator _randomGenerator;
public SqlRawQueryExecutorFactory(
string connectionString,
RawQuery query,
IExecutionEnvironment environment)
{
_connectionString = connectionString;
_query = query;
_environment = environment;
_randomGenerator = new RandomGenerator();
}
public IQueryExecutor Create()
{
var connection = new TConnection
{
ConnectionString = _connectionString
};
var parametersBuilder = new SqlParametersBuilder();
var columnPropertiesProvider = new RawQueryColumnPropertiesProvider(_query);
var distinctValuesProvider = new SqlDistinctValuesProvider(connection, _environment);
var randomValueProvider = new RandomValueProvider(_randomGenerator, columnPropertiesProvider, distinctValuesProvider);
var queryBuilder = new SqlRawQueryBuilder(_query, parametersBuilder, randomValueProvider);
return new SqlQueryExecutor(connection, queryBuilder, parametersBuilder, _environment);
}
}
}
| 38.555556 | 131 | 0.678386 | [
"Apache-2.0"
] | YuriyIvon/DatabaseBenchmark | src/DatabaseBenchmark/Databases/Sql/SqlRawQueryExecutorFactory.cs | 1,737 | C# |
namespace TraktNet.Objects.Post.Syncs.History.Json.Writer
{
internal class SyncHistoryPostObjectJsonWriter : ASyncHistoryPostObjectJsonWriter<ITraktSyncHistoryPost>
{
}
}
| 26.285714 | 108 | 0.798913 | [
"MIT"
] | henrikfroehling/Trakt.NET | Source/Lib/Trakt.NET/Objects/Post/Syncs/History/Json/Writer/SyncHistoryPostObjectJsonWriter.cs | 186 | C# |
using System.Collections.Generic;
using Abp.Application.Services.Dto;
using GYISMS.Employees;
namespace GYISMS.Employees.Dtos
{
public class GetEmployeeForEditOutput
{
public EmployeeEditDto Employee { get; set; }
//// custom codes
//// custom codes end
}
} | 15.526316 | 53 | 0.684746 | [
"MIT"
] | DonaldTdz/GYISMS | aspnet-core/src/GYISMS.Application/Employees/Dtos/GetEmployeeForEditOutput.cs | 295 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using FFImageLoading.Transformations;
using FFImageLoading.Work;
using MvvmCross.Core.ViewModels;
using RoomMateExpress.Core.ViewModels.BaseViewModels;
namespace RoomMateExpress.Core.ViewModels
{
public class PostPictureItemViewModel : MvxViewModel
{
private BasePostPictureViewModel _postPicture;
private bool _isChecked;
public PostPictureItemViewModel(BasePostPictureViewModel postPicture)
{
PostPicture = postPicture;
}
public BasePostPictureViewModel PostPicture
{
get => _postPicture;
set => SetProperty(ref _postPicture, value);
}
public bool IsChecked
{
get => _isChecked;
set => SetProperty(ref _isChecked, value);
}
public List<ITransformation> Transformations => new List<ITransformation>
{
new RoundedTransformation()
};
public IMvxCommand CheckCommand => new MvxCommand(() => IsChecked = !IsChecked);
}
}
| 26.309524 | 88 | 0.655204 | [
"Apache-2.0"
] | Dorianxxxx/RoomMateExpress | RoomMateExpress.Core/ViewModels/PostPictureItemViewModel.cs | 1,107 | C# |
#region Sharp3D.Math, Copyright(C) 2004 Eran Kampf, Licensed under LGPL.
// Sharp3D.Math math library
// Copyright (C) 2003-2004
// Eran Kampf
// eran@ekampf.com
// http://www.ekampf.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#endregion
#region Using directives
using System;
using System.ComponentModel;
using System.Collections.Generic;
using Sharp3D.Math.Core;
#endregion
namespace Sharp3D.Math.Geometry2D
{
public enum Ordering
{
Clockwise,
Counterclockwise,
None
}
}
| 31.384615 | 77 | 0.729575 | [
"Unlicense",
"MIT"
] | siranen/PalletBuilder | Sharp3D.Math/Geometry2D/Enums.cs | 1,226 | C# |
using SX.WebCore.MvcControllers;
namespace goldfish.WebUI.Areas.Admin.Controllers
{
public sealed class VideosController : SxVideosController
{
}
} | 18.888889 | 61 | 0.717647 | [
"MIT"
] | simlex-titul2005/goldfish.pro | goldfish.WebUI/Areas/Admin/Controllers/VideosController.cs | 172 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OSGeo.GDAL;
using System.Drawing.Imaging;
namespace CropMonitoring.SetelliteImageProcessor
{
class LandsatBitmapPaletteWriter : LandsatImageProcessor
{
protected override void SaveBitmapGrayBuffered(Dataset ds, Dataset nirDataset, string filename, int iOverview)
{
filename = GetOutImageName(filename);
ThresholdReachedEventArgs args = new ThresholdReachedEventArgs();
Band band = ds.GetRasterBand(1);
Band nirBand = nirDataset.GetRasterBand(1);
if (iOverview >= 0 && band.GetOverviewCount() > iOverview)
band = band.GetOverview(iOverview);
int width = band.XSize;
int height = band.YSize;
Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb);
byte[] r = new byte[width * height];
byte[] nir = new byte[width * height];
//byte[] r1 = new byte[width * height];
//byte[] b1 = new byte[width * height];
//byte[] g1 = new byte[width * height];
band.ReadRaster(0, 0, width, height, r, width, height, 0, 0);
nirBand.ReadRaster(0, 0, width, height, nir, width, height, 0, 0);
int i, j;
double ndvi = 0;
int progressScale = width / 100;
int progressCounter = 0;
try
{
for (i = 0; i < width; i++)
{
CheckStatus(progressScale, args, ref progressCounter);
for (j = 0; j < height; j++)
{
double low = nir[i + j * width] + r[i + j * width];
double up = nir[i + j * width] - r[i + j * width];
if (low == 0)
ndvi = 0;
else
{
ndvi = up / low;
}
//Color color = SetColor2(ndvi);
//r1[i + j * width] = color.R;
//b1[i + j * width] = color.B;
//g1[i + j + width] = color.G;
//bitmap.SetPixel(i, j, SetColor(ndvi));
bitmap.SetPixel(i, j, SetColor(ndvi));
}
}
//Dataset outRaster = Gdal.GetDriverByName("GTiff").Create(filename, width, height, 3, DataType.GDT_Byte, null);
//double[] geoTransformerData = new double[6];
//ds.GetGeoTransform(geoTransformerData);
//outRaster.SetGeoTransform(geoTransformerData);
//outRaster.SetProjection(ds.GetProjection());
//outRaster.GetRasterBand(1).WriteRaster(0, 0, width, height, r1, width, height, 0, 0);
//outRaster.GetRasterBand(2).WriteRaster(0, 0, width, height, b1, width, height, 0, 0);
//outRaster.GetRasterBand(3).WriteRaster(0, 0, width, height, g1, width, height, 0, 0);
//outRaster.FlushCache();
}
catch (Exception e)
{
}
bitmap.Save(filename);
}
protected override Color SetColor(double ndvi)
{
if (ndvi <= -0.2)
{
return Color.DarkCyan;
}
else if (ndvi == 0)
{
return Color.Black;
}
else if (ndvi > -0.2 && ndvi <= -0.1)
{
return Color.White;
}
else if (ndvi > -0.1 && ndvi <= 0)
{
return Color.Gray;
}
else if (ndvi > 0 && ndvi <= 0.1)
{
return Color.DarkBlue;
}
else if (ndvi > 0.1 && ndvi <= 0.2)
{
return Color.Blue;
}
else if (ndvi > 0.2 && ndvi <= 0.3)
{
return Color.DarkGreen;
}
else if (ndvi > 0.3 && ndvi <= 0.4)
{
return Color.Green;
}
else if (ndvi > 0.4 && ndvi <= 0.5)
{
return Color.LightGreen;
}
else if (ndvi > 0.5 && ndvi <= 0.6)
{
return Color.Yellow;
}
else if (ndvi > 0.6 && ndvi <= 0.7)
{
return Color.LightYellow;
}
else if (ndvi > 0.7 && ndvi <= 0.8)
{
return Color.OrangeRed;
}
else if (ndvi > 0.8 && ndvi <= 0.9)
{
return Color.Red;
}
else if (ndvi > 0.9 && ndvi <= 1)
{
return Color.Red;
}
return Color.Black;
}
protected override string GetOutImageName(string filename)
{
int index = filename.LastIndexOf('\\');
string oldName = filename.Substring(index + 1);
string newName = "P1_" + filename.Substring(index + 1);
return filename.Replace(oldName, newName);
}
}
}
| 34.089744 | 128 | 0.448853 | [
"MIT"
] | EtherealArd/CropMonitoring | CropMonitoring/SetelliteImageProcessor/LandsatBitmapPaletteWriter.cs | 5,320 | C# |
namespace SimpleIdentityServer.Core.Services
{
public interface IClientPasswordService
{
string Encrypt(string password);
}
}
| 16.444444 | 44 | 0.709459 | [
"Apache-2.0"
] | appkins/SimpleIdentityServer | SimpleIdentityServer/src/Apis/SimpleIdServer/SimpleIdentityServer.Core/Services/IClientPasswordService.cs | 150 | C# |
using Dock.Model.Controls;
namespace AvaloniaDemo.ViewModels.Tools
{
public class RightTopTool3 : ToolTab
{
}
}
| 14 | 40 | 0.706349 | [
"MIT"
] | PurpleGray/Dock | samples/AvaloniaDemo/ViewModels/Tools/RightTopTool3.cs | 128 | C# |
//CHANGED
//
// System.Threading.Interlocked.cs
//
// Author:
// Patrik Torstensson (patrik.torstensson@labs2.com)
// Dick Porter (dick@ximian.com)
//
// (C) Ximian, Inc. http://www.ximian.com
//
//
// Copyright (C) 2004, 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Threading
{
public
#if NET_2_0
static
#else
sealed
#endif
class Interlocked
{
#if !NET_2_0
private Interlocked () {}
#endif
public static int CompareExchange(ref int location, int value, int comparand)
{
int old = location;
if (old == comparand)
location = value;
return old;
}
internal static object CompareExchange(ref object location, object value, object comparand)
{
object old = location;
if (Equals(old, comparand))
location = value;
return old;
}
internal static float CompareExchange(ref float location, float value, float comparand)
{
float old = location;
if (old == comparand)
location = value;
return old;
}
public static int Decrement(ref int location)
{
--location;
return location;
}
public static long Decrement(ref long location)
{
--location;
return location;
}
public static int Increment(ref int location)
{
--location;
return location;
}
public static long Increment(ref long location)
{
--location;
return location;
}
public static int Exchange(ref int location, int value)
{
int old = location;
location = value;
return old;
}
internal static object Exchange(ref object location, object value)
{
object old = location;
location = value;
return old;
}
internal static float Exchange(ref float location, float value)
{
float old = location;
location = value;
return old;
}
//#if NET_2_0
public static long CompareExchange(ref long location, long value, long comparand)
{
long old = location;
if (old == comparand)
location = value;
return old;
}
#if NOT_PFX
#if NET_2_0
[ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
#endif
public static IntPtr CompareExchange(ref IntPtr location, IntPtr value, IntPtr comparand)
{
throw new NotSupportedException();
}
#endif
internal static double CompareExchange(ref double location, double value, double comparand)
{
double old = location;
if (old == comparand)
location = value;
return old;
}
[ComVisible (false)]
public static T CompareExchange<T> (ref T location, T value, T comparand) where T:class
{
T old = location;
if (Equals(old, comparand))
location = value;
return old;
}
public static long Exchange(ref long location, long value)
{
long old = location;
location = value;
return old;
}
#if NOT_PFX
#if NET_2_0
[ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
#endif
public static IntPtr Exchange(ref IntPtr location, IntPtr value)
{
throw new NotSupportedException();
}
#endif
internal static double Exchange(ref double location, double value)
{
double old = location;
location = value;
return old;
}
[ComVisible (false)]
public static T Exchange<T> (ref T location, T value) where T:class
{
T old = location;
location = value;
return old;
}
internal static long Read(ref long location)
{
return location;
}
public static int Add(ref int location, int add)
{
location += add;
return location;
}
public static long Add(ref long location, long add)
{
location += add;
return location;
}
//#endif
}
}
| 25.014286 | 96 | 0.631258 | [
"MIT"
] | GrapeCity/pagefx | mono/mcs/class/corlib/System.Threading/Interlocked.cs | 5,253 | C# |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using PureCloudPlatform.Client.V2.Client;
namespace PureCloudPlatform.Client.V2.Model
{
/// <summary>
/// OAuthAuthorizationListing
/// </summary>
[DataContract]
public partial class OAuthAuthorizationListing : IEquatable<OAuthAuthorizationListing>
{
/// <summary>
/// Initializes a new instance of the <see cref="OAuthAuthorizationListing" /> class.
/// </summary>
/// <param name="Total">Total.</param>
/// <param name="Entities">Entities.</param>
/// <param name="SelfUri">SelfUri.</param>
public OAuthAuthorizationListing(long? Total = null, List<OAuthAuthorization> Entities = null, string SelfUri = null)
{
this.Total = Total;
this.Entities = Entities;
this.SelfUri = SelfUri;
}
/// <summary>
/// Gets or Sets Total
/// </summary>
[DataMember(Name="total", EmitDefaultValue=false)]
public long? Total { get; set; }
/// <summary>
/// Gets or Sets Entities
/// </summary>
[DataMember(Name="entities", EmitDefaultValue=false)]
public List<OAuthAuthorization> Entities { get; set; }
/// <summary>
/// Gets or Sets SelfUri
/// </summary>
[DataMember(Name="selfUri", EmitDefaultValue=false)]
public string SelfUri { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class OAuthAuthorizationListing {\n");
sb.Append(" Total: ").Append(Total).Append("\n");
sb.Append(" Entities: ").Append(Entities).Append("\n");
sb.Append(" SelfUri: ").Append(SelfUri).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
Formatting = Formatting.Indented
});
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as OAuthAuthorizationListing);
}
/// <summary>
/// Returns true if OAuthAuthorizationListing instances are equal
/// </summary>
/// <param name="other">Instance of OAuthAuthorizationListing to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(OAuthAuthorizationListing other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return true &&
(
this.Total == other.Total ||
this.Total != null &&
this.Total.Equals(other.Total)
) &&
(
this.Entities == other.Entities ||
this.Entities != null &&
this.Entities.SequenceEqual(other.Entities)
) &&
(
this.SelfUri == other.SelfUri ||
this.SelfUri != null &&
this.SelfUri.Equals(other.SelfUri)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Total != null)
hash = hash * 59 + this.Total.GetHashCode();
if (this.Entities != null)
hash = hash * 59 + this.Entities.GetHashCode();
if (this.SelfUri != null)
hash = hash * 59 + this.SelfUri.GetHashCode();
return hash;
}
}
}
}
| 30.390805 | 125 | 0.501513 | [
"MIT"
] | F-V-L/platform-client-sdk-dotnet | build/src/PureCloudPlatform.Client.V2/Model/OAuthAuthorizationListing.cs | 5,288 | C# |
using Convey.CQRS.Commands;
using System;
namespace Lapka.Identity.Application.Commands
{
public class CreateValue : ICommand
{
public Guid Id { get; }
public string Name { get; }
public string Description { get; }
public CreateValue(string name, string description, Guid guid )
{
Id = guid;
Name = name;
Description = description;
}
}
} | 22.894737 | 71 | 0.581609 | [
"MIT"
] | MobiCommunity/Lapka.Identity | Lapka.Identity.Application/Commands/CreateValue.cs | 435 | C# |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.EventSystems;
namespace UnityUI
{
public enum UIEventType
{
onSubmit,
onClick,
onHover,
onToggleChanged,
onSliderChanged,
onScrollbarChanged,
onDrapDownChanged,
onInputFieldChanged,
}
public class UIEventListener : EventTrigger
{
public System.Action<GameObject> onSubmit { get; set; }
public System.Action<GameObject> onClick { get; set; }
public System.Action<GameObject, bool> onHover { get; set; }
public System.Action<GameObject, bool> onToggleChanged { get; set; }
public System.Action<GameObject, float> onSliderChanged { get; set; }
public System.Action<GameObject, float> onScrollbarChanged { get; set; }
public System.Action<GameObject, int> onDrapDownChanged { get; set; }
public System.Action<GameObject, string> onInputFieldChanged { get; set; }
public object m_UserData { get; set; }
public override void OnSubmit(BaseEventData eventData)
{
if (onSubmit != null)
onSubmit(gameObject);
}
public override void OnPointerEnter(PointerEventData eventData)
{
if (onHover != null)
onHover(gameObject, true);
}
public override void OnPointerClick(PointerEventData eventData)
{
if (onClick != null)
onClick(gameObject);
if (onToggleChanged != null)
onToggleChanged(gameObject, gameObject.GetComponent<Toggle>().isOn);
}
public override void OnPointerExit(PointerEventData eventData)
{
if (onHover != null)
onHover(gameObject, false);
}
public override void OnDrag(PointerEventData eventData)
{
if (onSliderChanged != null)
onSliderChanged(gameObject, gameObject.GetComponent<Slider>().value);
if (onScrollbarChanged != null)
onScrollbarChanged(gameObject, gameObject.GetComponent<Scrollbar>().value);
}
public override void OnSelect(BaseEventData eventData)
{
if (onDrapDownChanged != null)
onDrapDownChanged(gameObject, gameObject.GetComponent<Dropdown>().value);
}
public override void OnUpdateSelected(BaseEventData eventData)
{
if (onInputFieldChanged != null)
onInputFieldChanged(gameObject, gameObject.GetComponent<InputField>().text);
}
public override void OnDeselect(BaseEventData eventData)
{
if (onInputFieldChanged != null)
onInputFieldChanged(gameObject, gameObject.GetComponent<InputField>().text);
}
//----------------------------------------------------------------------------------------
public static void AddListener(Component com, UIEventType et, System.Action<GameObject> func, object userdata = null)
{
UIEventListener listener = GetOrAdd(com);
if (listener == null)
{
Debug.LogError("设置事件的组件为空");
return;
}
if (et == UIEventType.onSubmit)
{
listener.onSubmit = func;
}
else if (et == UIEventType.onClick)
{
listener.onClick = func;
}
if (listener != null)
{
listener.m_UserData = userdata;
}
}
public static void RemoveListener(Component com, UIEventType et)
{
UIEventListener listener = GetOrAdd(com);
if (listener == null)
{
Debug.LogError("设置事件的组件为空");
return;
}
if (et == UIEventType.onSubmit)
{
listener.onSubmit = null;
}
else if (et == UIEventType.onClick)
{
listener.onClick = null;
}
else if (et == UIEventType.onSliderChanged)
{
listener.onSliderChanged = null;
}
else if (et == UIEventType.onScrollbarChanged)
{
listener.onScrollbarChanged = null;
}
else if (et == UIEventType.onHover)
{
listener.onHover = null;
}
else if (et == UIEventType.onToggleChanged)
{
listener.onToggleChanged = null;
}
else if (et == UIEventType.onDrapDownChanged)
{
listener.onDrapDownChanged = null;
}
else if (et == UIEventType.onInputFieldChanged)
{
listener.onInputFieldChanged = null;
}
if (listener != null)
{
listener.m_UserData = null;
}
}
public static void AddListener(Component com, UIEventType et, System.Action<GameObject, bool> func, object userdata = null)
{
UIEventListener listener = GetOrAdd(com);
if (listener == null)
{
Debug.LogError("设置事件的组件为空");
return;
}
if (et == UIEventType.onHover)
{
listener.onHover = func;
}
else if (et == UIEventType.onToggleChanged)
{
listener.onToggleChanged = func;
}
if (listener != null)
{
listener.m_UserData = userdata;
}
}
public static void AddListener(Component com, UIEventType et, System.Action<GameObject, float> func, object userdata)
{
UIEventListener listener = GetOrAdd(com);
if (listener == null)
{
Debug.LogError("设置事件的组件为空");
return;
}
if (et == UIEventType.onSliderChanged)
{
listener.onSliderChanged = func;
}
else if (et == UIEventType.onScrollbarChanged)
{
listener.onScrollbarChanged = func;
}
if (listener != null)
{
listener.m_UserData = userdata;
}
}
public static void AddListener(Component com, UIEventType et, System.Action<GameObject, int> func, object userdata)
{
UIEventListener listener = GetOrAdd(com);
if (listener == null)
{
Debug.LogError("设置事件的组件为空");
return;
}
if (et == UIEventType.onDrapDownChanged)
{
listener.onDrapDownChanged = func;
}
if (listener != null)
{
listener.m_UserData = userdata;
}
}
public static void AddListener(Component com, UIEventType et, System.Action<GameObject, string> func, object userdata)
{
UIEventListener listener = GetOrAdd(com);
if (listener == null)
{
Debug.LogError("设置事件的组件为空");
return;
}
if (et == UIEventType.onInputFieldChanged)
{
listener.onInputFieldChanged = func;
}
if (listener != null)
{
listener.m_UserData = userdata;
}
}
public static UIEventListener Get(Component com)
{
if (com == null)
{
return null;
}
UIEventListener listener = com.GetComponent<UIEventListener>();
return listener;
}
public static UIEventListener Get(GameObject go)
{
if (go == null)
{
return null;
}
UIEventListener listener = go.GetComponent<UIEventListener>();
return listener;
}
private static UIEventListener GetOrAdd(Component com)
{
if (com == null)
{
return null;
}
else
{
if (com.gameObject == null || com.gameObject.Equals(null))
{
return null;
}
else
{
GameObject go = com.gameObject;
UIEventListener listener = go.GetComponent<UIEventListener>();
if (listener == null)
{
listener = go.AddComponent<UIEventListener>();
}
return listener;
}
}
}
}
} | 33.947955 | 132 | 0.483136 | [
"MIT"
] | 591094733/cshotfix | CSHotFix_SimpleFramework/Assets/Scripts/ThirdParty/UnityUI/Others/UIEventListener.cs | 9,242 | C# |
namespace LuduStack.Domain.Core.Enums
{
public enum VoteValue
{
Neutral = 0,
Positive = 1,
Negative = -1
}
} | 16.111111 | 38 | 0.537931 | [
"MIT"
] | DJJones66/ludustack-code | LuduStack.Domain.Core/Enums/VoteValue.cs | 147 | C# |
using System;
using System.Reflection;
namespace SEAQ.Tests
{
public static class TestExtensions
{
internal static bool IsPropertyEmpty(this PropertyInfo p, string val)
{
var res = true;
if (val == null)
return true;
var t = p.PropertyType;
if (t == typeof(DateTime))
{
res = DateTime.Parse(val) == DateTime.MinValue;
}
else if (t == typeof(DateTime?))
{
res = DateTime.Parse(val) == DateTime.MinValue;
}
else
{
res = val == null;
}
return res;
}
}
}
| 20.970588 | 77 | 0.4446 | [
"MIT"
] | oklacoder/seaq | src/SEAQ.Tests/TestExtensions.cs | 715 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.WindowsRuntime;
using Template10.Mvvm;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
namespace MonocleGiraffe.Controls.TreeView
{
public sealed partial class CommentsPanel : UserControl, INotifyPropertyChanged
{
public CommentsPanel()
{
this.InitializeComponent();
//InitDesign();
}
public IEnumerable<ITreeItem> ItemsSource
{
get { return (IEnumerable<ITreeItem>)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
// Using a DependencyProperty as the backing store for ItemsSource. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(IEnumerable<ITreeItem>), typeof(CommentsPanel), new PropertyMetadata(null, new PropertyChangedCallback(ItemsSourceChanged)));
private static void ItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue == null)
return;
var newValue = e.NewValue as IEnumerable<ITreeItem>;
var panel = (CommentsPanel)d;
panel.Items = new ObservableCollection<TreeViewItem>(Translate(newValue.ToList(), 0, new List<int>()));
}
ObservableCollection<TreeViewItem> items = default(ObservableCollection<TreeViewItem>);
public ObservableCollection<TreeViewItem> Items { get { return items; } set { Set(ref items, value); } }
private static List<TreeViewItem> Translate<T>(List<T> input, int depth, List<int> address) where T : ITreeItem
{
List<TreeViewItem> ret = new List<TreeViewItem>();
for (int i = 0; i < input.Count(); i++)
{
var item = input[i];
TreeViewItem t = new TreeViewItem();
t.Content = item.Content;
t.Depth = depth;
t.Address = new List<int>(address);
t.Address.Add(i);
if (item.Children != null)
{
t.Children = Translate(item.Children, t.Depth + 1, t.Address);
}
ret.Add(t);
}
return ret;
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
public void Set<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (!Equals(storage, value))
{
storage = value;
RaisePropertyChanged(propertyName);
}
}
public void RaisePropertyChanged([CallerMemberName] string propertyName = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
#endregion
private void Grid_Tapped(object sender, TappedRoutedEventArgs e)
{
TreeViewItem tappedItem = (sender as FrameworkElement).Tag as TreeViewItem;
int index = Items.IndexOf(tappedItem);
if (tappedItem.IsExpanded)
{
foreach (var item in tappedItem.Children)
{
Items.Remove(item);
}
tappedItem.IsExpanded = false;
}
else
{
foreach (var item in tappedItem.Children)
{
Items.Insert(++index, item);
}
tappedItem.IsExpanded = true;
}
}
}
public class TreeViewItem
{
public object Content { get; set; }
public List<int> Address { get; set; }
public int Depth { get; set; }
public List<TreeViewItem> Children { get; set; }
public bool IsExpanded { get; set; }
}
public class DepthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
int multiplier = int.Parse((string)parameter);
return new GridLength((int)value * multiplier);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
public class RangeObservableCollection<T> : ObservableCollection<T>
{
private bool _suppressNotification = false;
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (!_suppressNotification)
base.OnCollectionChanged(e);
}
public void AddRange(IEnumerable<T> list)
{
if (list == null)
throw new ArgumentNullException("list");
_suppressNotification = true;
foreach (T item in list)
{
Add(item);
}
_suppressNotification = false;
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
public void InsertRange(int index, IEnumerable<T> list)
{
if (list == null)
throw new ArgumentNullException("list");
_suppressNotification = true;
foreach (T item in list)
{
Insert(++index, item);
}
_suppressNotification = false;
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
public interface ITreeItem
{
object Content { get; set; }
List<ITreeItem> Children { get; set; }
}
}
| 32.973958 | 187 | 0.601011 | [
"Apache-2.0"
] | akshay2000/MonocleGiraffe | MonocleGiraffe/MonocleGiraffe/Controls/TreeView/CommentsPanel.xaml.cs | 6,333 | C# |
using Disqord.Serialization.Json;
namespace Disqord.Models
{
public class GuildPreviewJsonModel : JsonModel
{
[JsonProperty("id")]
public Snowflake Id;
[JsonProperty("name")]
public string Name;
[JsonProperty("icon")]
public string Icon;
[JsonProperty("splash")]
public string Splash;
[JsonProperty("discovery_splash")]
public Optional<string> DiscoverySplash;
[JsonProperty("emojis")]
public EmojiJsonModel[] Emojis;
[JsonProperty("features")]
public string[] Features;
[JsonProperty("approximate_member_count")]
public int ApproximateMemberCount;
[JsonProperty("approximate_presence_count")]
public int ApproximatePresenceCount;
[JsonProperty("description")]
public string Description;
}
}
| 24 | 53 | 0.607456 | [
"MIT"
] | Neuheit/Diqnod | src/Disqord.Core/Models/GuildPreviewJsonModel.cs | 914 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SAI.GA
{
public class NumericCrossOver : ICrossOver<NumericChromosome>
{
public IList<NumericChromosome> CrossOver(IList<NumericChromosome> population)
{
throw new NotImplementedException();
}
}
}
| 22.882353 | 87 | 0.676093 | [
"MIT"
] | sgago/sai | NumericCrossOver.cs | 391 | C# |
using NHapi.Base.Parser;
using NHapi.Base;
using NHapi.Base.Log;
using System;
using System.Collections.Generic;
using NHapi.Model.V24.Segment;
using NHapi.Model.V24.Datatype;
using NHapi.Base.Model;
namespace NHapi.Model.V24.Group
{
///<summary>
///Represents the PPG_PCG_ORDER_DETAIL Group. A Group is an ordered collection of message
/// segments that can repeat together or be optionally in/excluded together.
/// This Group contains the following elements:
///<ol>
///<li>0: OBR (Observation Request) </li>
///<li>1: RXO (Pharmacy/Treatment Order) </li>
///<li>2: NTE (Notes and Comments) optional repeating</li>
///<li>3: VAR (Variance) optional repeating</li>
///<li>4: PPG_PCG_ORDER_OBSERVATION (a Group object) optional repeating</li>
///</ol>
///</summary>
[Serializable]
public class PPG_PCG_ORDER_DETAIL : AbstractGroup {
///<summary>
/// Creates a new PPG_PCG_ORDER_DETAIL Group.
///</summary>
public PPG_PCG_ORDER_DETAIL(IGroup parent, IModelClassFactory factory) : base(parent, factory){
try {
this.add(typeof(OBR), true, false);
this.add(typeof(RXO), true, false);
this.add(typeof(NTE), false, true);
this.add(typeof(VAR), false, true);
this.add(typeof(PPG_PCG_ORDER_OBSERVATION), false, true);
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating PPG_PCG_ORDER_DETAIL - this is probably a bug in the source code generator.", e);
}
}
///<summary>
/// Returns OBR (Observation Request) - creates it if necessary
///</summary>
public OBR OBR {
get{
OBR ret = null;
try {
ret = (OBR)this.GetStructure("OBR");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns RXO (Pharmacy/Treatment Order) - creates it if necessary
///</summary>
public RXO RXO {
get{
RXO ret = null;
try {
ret = (RXO)this.GetStructure("RXO");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns first repetition of NTE (Notes and Comments) - creates it if necessary
///</summary>
public NTE GetNTE() {
NTE ret = null;
try {
ret = (NTE)this.GetStructure("NTE");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
///<summary>
///Returns a specific repetition of NTE
/// * (Notes and Comments) - creates it if necessary
/// throws HL7Exception if the repetition requested is more than one
/// greater than the number of existing repetitions.
///</summary>
public NTE GetNTE(int rep) {
return (NTE)this.GetStructure("NTE", rep);
}
/**
* Returns the number of existing repetitions of NTE
*/
public int NTERepetitionsUsed {
get{
int reps = -1;
try {
reps = this.GetAll("NTE").Length;
} catch (HL7Exception e) {
string message = "Unexpected error accessing data - this is probably a bug in the source code generator.";
HapiLogFactory.GetHapiLog(GetType()).Error(message, e);
throw new System.Exception(message);
}
return reps;
}
}
/**
* Enumerate over the NTE results
*/
public IEnumerable<NTE> NTEs
{
get
{
for (int rep = 0; rep < NTERepetitionsUsed; rep++)
{
yield return (NTE)this.GetStructure("NTE", rep);
}
}
}
///<summary>
///Adds a new NTE
///</summary>
public NTE AddNTE()
{
return this.AddStructure("NTE") as NTE;
}
///<summary>
///Removes the given NTE
///</summary>
public void RemoveNTE(NTE toRemove)
{
this.RemoveStructure("NTE", toRemove);
}
///<summary>
///Removes the NTE at the given index
///</summary>
public void RemoveNTEAt(int index)
{
this.RemoveRepetition("NTE", index);
}
///<summary>
/// Returns first repetition of VAR (Variance) - creates it if necessary
///</summary>
public VAR GetVAR() {
VAR ret = null;
try {
ret = (VAR)this.GetStructure("VAR");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
///<summary>
///Returns a specific repetition of VAR
/// * (Variance) - creates it if necessary
/// throws HL7Exception if the repetition requested is more than one
/// greater than the number of existing repetitions.
///</summary>
public VAR GetVAR(int rep) {
return (VAR)this.GetStructure("VAR", rep);
}
/**
* Returns the number of existing repetitions of VAR
*/
public int VARRepetitionsUsed {
get{
int reps = -1;
try {
reps = this.GetAll("VAR").Length;
} catch (HL7Exception e) {
string message = "Unexpected error accessing data - this is probably a bug in the source code generator.";
HapiLogFactory.GetHapiLog(GetType()).Error(message, e);
throw new System.Exception(message);
}
return reps;
}
}
/**
* Enumerate over the VAR results
*/
public IEnumerable<VAR> VARs
{
get
{
for (int rep = 0; rep < VARRepetitionsUsed; rep++)
{
yield return (VAR)this.GetStructure("VAR", rep);
}
}
}
///<summary>
///Adds a new VAR
///</summary>
public VAR AddVAR()
{
return this.AddStructure("VAR") as VAR;
}
///<summary>
///Removes the given VAR
///</summary>
public void RemoveVAR(VAR toRemove)
{
this.RemoveStructure("VAR", toRemove);
}
///<summary>
///Removes the VAR at the given index
///</summary>
public void RemoveVARAt(int index)
{
this.RemoveRepetition("VAR", index);
}
///<summary>
/// Returns first repetition of PPG_PCG_ORDER_OBSERVATION (a Group object) - creates it if necessary
///</summary>
public PPG_PCG_ORDER_OBSERVATION GetORDER_OBSERVATION() {
PPG_PCG_ORDER_OBSERVATION ret = null;
try {
ret = (PPG_PCG_ORDER_OBSERVATION)this.GetStructure("ORDER_OBSERVATION");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
///<summary>
///Returns a specific repetition of PPG_PCG_ORDER_OBSERVATION
/// * (a Group object) - creates it if necessary
/// throws HL7Exception if the repetition requested is more than one
/// greater than the number of existing repetitions.
///</summary>
public PPG_PCG_ORDER_OBSERVATION GetORDER_OBSERVATION(int rep) {
return (PPG_PCG_ORDER_OBSERVATION)this.GetStructure("ORDER_OBSERVATION", rep);
}
/**
* Returns the number of existing repetitions of PPG_PCG_ORDER_OBSERVATION
*/
public int ORDER_OBSERVATIONRepetitionsUsed {
get{
int reps = -1;
try {
reps = this.GetAll("ORDER_OBSERVATION").Length;
} catch (HL7Exception e) {
string message = "Unexpected error accessing data - this is probably a bug in the source code generator.";
HapiLogFactory.GetHapiLog(GetType()).Error(message, e);
throw new System.Exception(message);
}
return reps;
}
}
/**
* Enumerate over the PPG_PCG_ORDER_OBSERVATION results
*/
public IEnumerable<PPG_PCG_ORDER_OBSERVATION> ORDER_OBSERVATIONs
{
get
{
for (int rep = 0; rep < ORDER_OBSERVATIONRepetitionsUsed; rep++)
{
yield return (PPG_PCG_ORDER_OBSERVATION)this.GetStructure("ORDER_OBSERVATION", rep);
}
}
}
///<summary>
///Adds a new PPG_PCG_ORDER_OBSERVATION
///</summary>
public PPG_PCG_ORDER_OBSERVATION AddORDER_OBSERVATION()
{
return this.AddStructure("ORDER_OBSERVATION") as PPG_PCG_ORDER_OBSERVATION;
}
///<summary>
///Removes the given PPG_PCG_ORDER_OBSERVATION
///</summary>
public void RemoveORDER_OBSERVATION(PPG_PCG_ORDER_OBSERVATION toRemove)
{
this.RemoveStructure("ORDER_OBSERVATION", toRemove);
}
///<summary>
///Removes the PPG_PCG_ORDER_OBSERVATION at the given index
///</summary>
public void RemoveORDER_OBSERVATIONAt(int index)
{
this.RemoveRepetition("ORDER_OBSERVATION", index);
}
}
}
| 27.827476 | 158 | 0.671527 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | AMCN41R/nHapi | src/NHapi.Model.V24/Group/PPG_PCG_ORDER_DETAIL.cs | 8,710 | C# |
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
namespace Roslynator.CommandLine
{
internal readonly struct ProjectFilter
{
public ProjectFilter(
IEnumerable<string> names,
IEnumerable<string> ignoredNames,
string language)
{
if (names?.Any() == true
&& ignoredNames?.Any() == true)
{
throw new ArgumentException($"Cannot specify both '{nameof(names)}' and '{nameof(ignoredNames)}'.", nameof(names));
}
Names = names?.ToImmutableHashSet() ?? ImmutableHashSet<string>.Empty;
IgnoredNames = ignoredNames?.ToImmutableHashSet() ?? ImmutableHashSet<string>.Empty;
Language = language;
}
public ImmutableHashSet<string> Names { get; }
public ImmutableHashSet<string> IgnoredNames { get; }
public string Language { get; }
public bool IsDefault
{
get
{
return Names == null
&& IgnoredNames == null
&& Language == null;
}
}
public bool IsMatch(Project project)
{
if (Language != null
&& Language != project.Language)
{
return false;
}
if (Names?.Count > 0)
return Names.Contains(project.Name);
if (IgnoredNames?.Count > 0)
return !IgnoredNames.Contains(project.Name);
return true;
}
}
}
| 28.746032 | 160 | 0.552181 | [
"Apache-2.0"
] | ADIX7/Roslynator | src/CommandLine/ProjectFilter.cs | 1,813 | C# |
using System.Windows.Documents;
using System.Xml.Linq;
using DaveSexton.XmlGel.Maml.Documents.Visitors;
namespace DaveSexton.XmlGel.Maml.Documents
{
internal sealed class MamlQuote : MamlInline
{
public MamlQuote(XElement element)
: base(element)
{
}
public override TextElement Accept(MamlToFlowDocumentVisitor visitor, out TextElement contentContainer)
{
return visitor.Visit(this, out contentContainer);
}
}
} | 22.947368 | 105 | 0.775229 | [
"Apache-2.0"
] | RxDave/XMLGel | Source/DaveSexton.XmlGel/MAML/Documents/MamlQuote.cs | 438 | C# |
namespace Images.Services
{
using Images.Entities;
using Microsoft.Azure.Cosmos;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
public class ImageDbService : IImageDbService
{
private Container _container;
private IConfigurationSection _configurationSection;
private const string containerName = "Image";
public ImageDbService(
CosmosClient client,
IConfigurationSection configurationSection)
{
_configurationSection = configurationSection;
string databaseName = _configurationSection.GetSection("DatabaseName").Value;
this._container = client.GetContainer(databaseName, containerName);
DatabaseResponse database = client.CreateDatabaseIfNotExistsAsync(databaseName).Result;
database.Database.CreateContainerIfNotExistsAsync(containerName, "/id");
}
public async Task AddItemAsync(Image image)
{
await this._container.CreateItemAsync<Image>(image, new PartitionKey(image.Id));
}
public async Task DeleteItemAsync(string id)
{
await this._container.DeleteItemAsync<Image>(id, new PartitionKey(id));
}
public async Task<Image> GetItemAsync(string id)
{
try
{
ItemResponse<Image> response = await this._container.ReadItemAsync<Image>(id, new PartitionKey(id));
return response.Resource;
}
catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
}
}
public async Task<IEnumerable<Image>> GetItemsAsync(string queryString)
{
var query = this._container.GetItemQueryIterator<Image>(new QueryDefinition(queryString));
List<Image> results = new List<Image>();
while (query.HasMoreResults)
{
var response = await query.ReadNextAsync();
results.AddRange(response.ToList());
}
return results;
}
public async Task UpdateItemAsync(string id, Image image)
{
await this._container.UpsertItemAsync<Image>(image, new PartitionKey(id));
}
}
} | 33.164384 | 116 | 0.621644 | [
"MIT"
] | shifatullah/aspnetcore-cosmosdb-webjob-imageresizer-sample | src/Services/ImageDbService.cs | 2,423 | C# |
using System;
namespace Marten.Exceptions
{
public class SchemaValidationException: Exception
{
public SchemaValidationException(string ddl)
: base("Configuration to Schema Validation Failed! These changes detected:\n\n" + ddl)
{
}
#if SERIALIZE
protected SchemaValidationException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
#endif
}
}
| 23.315789 | 115 | 0.668172 | [
"MIT"
] | 0xced/marten | src/Marten/Exceptions/SchemaValidationException.cs | 443 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace Microsoft.AspNetCore.Identity.EntityFrameworkCore.Test
{
public class StringUser : IdentityUser
{
public StringUser()
{
Id = Guid.NewGuid().ToString();
UserName = Id;
}
}
public class StringRole : IdentityRole<string>
{
public StringRole()
{
Id = Guid.NewGuid().ToString();
Name = Id;
}
}
public class UserStoreStringKeyTest : SqlStoreTestBase<StringUser, StringRole, string>
{
public UserStoreStringKeyTest(ScratchDatabaseFixture fixture)
: base(fixture)
{ }
[Fact]
public void AddEntityFrameworkStoresCanInferKey()
{
var services = new ServiceCollection();
// This used to throw
var builder = services.AddIdentity<StringUser, StringRole>().AddEntityFrameworkStores<TestDbContext>();
}
[Fact]
public void AddEntityFrameworkStoresCanInferKeyWithGenericBase()
{
var services = new ServiceCollection();
// This used to throw
var builder = services.AddIdentity<IdentityUser<string>, IdentityRole<string>>().AddEntityFrameworkStores<TestDbContext>();
}
}
} | 29.54902 | 135 | 0.629728 | [
"Apache-2.0"
] | neyromant/Identity | test/Microsoft.AspNetCore.Identity.EntityFrameworkCore.Test/UserStoreStringKeyTest.cs | 1,507 | C# |
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace TodoWebApiV1.Entities
{
public class TodoContext : DbContext
{
public TodoContext(): base("name=DefaultConnection")
{
}
public TodoContext(DbConnection existingConnection, bool contextOwnsConnection): base(existingConnection, contextOwnsConnection)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new TodoMap());
}
public DbSet<Todo> Todos { get; set; }
}
} | 20.5 | 136 | 0.658537 | [
"MIT"
] | r0lan2/TodoWebApiV1 | TodoWebApiV1/Entities/TodoContext.cs | 740 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Drawing;
using Xamarin.Forms.Internals;
#if __UNIFIED__
using UIKit;
#else
using MonoTouch.UIKit;
#endif
#if __UNIFIED__
using RectangleF = CoreGraphics.CGRect;
using SizeF = CoreGraphics.CGSize;
using PointF = CoreGraphics.CGPoint;
#else
using nfloat = System.Single;
using nint = System.Int32;
using nuint = System.UInt32;
#endif
namespace Xamarin.Forms.Platform.iOS
{
public class CarouselPageRenderer : UIViewController, IVisualElementRenderer
{
bool _appeared;
Dictionary<Page, UIView> _containerMap;
bool _disposed;
EventTracker _events;
bool _ignoreNativeScrolling;
UIScrollView _scrollView;
VisualElementTracker _tracker;
public CarouselPageRenderer()
{
if (!Forms.IsiOS7OrNewer)
WantsFullScreenLayout = true;
}
IElementController ElementController => Element as IElementController;
protected CarouselPage Carousel
{
get { return (CarouselPage)Element; }
}
IPageController PageController => (IPageController)Element;
protected int SelectedIndex
{
get { return (int)(_scrollView.ContentOffset.X / _scrollView.Frame.Width); }
set { ScrollToPage(value); }
}
public VisualElement Element { get; private set; }
public event EventHandler<VisualElementChangedEventArgs> ElementChanged;
public SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint)
{
return NativeView.GetSizeRequest(widthConstraint, heightConstraint);
}
public UIView NativeView
{
get { return View; }
}
public void SetElement(VisualElement element)
{
VisualElement oldElement = Element;
Element = element;
_containerMap = new Dictionary<Page, UIView>();
OnElementChanged(new VisualElementChangedEventArgs(oldElement, element));
if (element != null)
element.SendViewInitialized(NativeView);
}
public void SetElementSize(Size size)
{
Element.Layout(new Rectangle(Element.X, Element.Y, size.Width, size.Height));
}
public UIViewController ViewController
{
get { return this; }
}
public override void DidRotate(UIInterfaceOrientation fromInterfaceOrientation)
{
_ignoreNativeScrolling = false;
View.SetNeedsLayout();
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
if (_appeared || _disposed)
return;
_appeared = true;
PageController.SendAppearing();
}
public override void ViewDidDisappear(bool animated)
{
base.ViewDidDisappear(animated);
if (!_appeared || _disposed)
return;
_appeared = false;
PageController.SendDisappearing();
}
public override void ViewDidLayoutSubviews()
{
base.ViewDidLayoutSubviews();
View.Frame = View.Superview.Bounds;
_scrollView.Frame = View.Bounds;
PositionChildren();
UpdateCurrentPage(false);
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
_tracker = new VisualElementTracker(this);
_events = new EventTracker(this);
_events.LoadEvents(View);
_scrollView = new UIScrollView { ShowsHorizontalScrollIndicator = false };
_scrollView.DecelerationEnded += OnDecelerationEnded;
UpdateBackground();
View.Add(_scrollView);
for (var i = 0; i < ElementController.LogicalChildren.Count; i++)
{
Element element = ElementController.LogicalChildren[i];
var child = element as ContentPage;
if (child != null)
InsertPage(child, i);
}
PositionChildren();
Carousel.PropertyChanged += OnPropertyChanged;
Carousel.PagesChanged += OnPagesChanged;
}
public override void ViewDidUnload()
{
base.ViewDidUnload();
if (_scrollView != null)
_scrollView.DecelerationEnded -= OnDecelerationEnded;
if (Carousel != null)
{
Carousel.PropertyChanged -= OnPropertyChanged;
Carousel.PagesChanged -= OnPagesChanged;
}
}
public override void WillRotate(UIInterfaceOrientation toInterfaceOrientation, double duration)
{
_ignoreNativeScrolling = true;
}
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
if (_scrollView != null)
_scrollView.DecelerationEnded -= OnDecelerationEnded;
if (Carousel != null)
{
Carousel.PropertyChanged -= OnPropertyChanged;
Carousel.PagesChanged -= OnPagesChanged;
}
Platform.SetRenderer(Element, null);
Clear();
if (_scrollView != null)
{
_scrollView.DecelerationEnded -= OnDecelerationEnded;
_scrollView.RemoveFromSuperview();
_scrollView = null;
}
if (_appeared)
{
_appeared = false;
PageController?.SendDisappearing();
}
if (_events != null)
{
_events.Dispose();
_events = null;
}
if (_tracker != null)
{
_tracker.Dispose();
_tracker = null;
}
Element = null;
_disposed = true;
}
base.Dispose(disposing);
}
protected virtual void OnElementChanged(VisualElementChangedEventArgs e)
{
EventHandler<VisualElementChangedEventArgs> changed = ElementChanged;
if (changed != null)
changed(this, e);
}
void Clear()
{
foreach (KeyValuePair<Page, UIView> kvp in _containerMap)
{
kvp.Value.RemoveFromSuperview();
IVisualElementRenderer renderer = Platform.GetRenderer(kvp.Key);
if (renderer != null)
{
renderer.ViewController.RemoveFromParentViewController();
renderer.NativeView.RemoveFromSuperview();
Platform.SetRenderer(kvp.Key, null);
}
}
_containerMap.Clear();
}
void InsertPage(ContentPage page, int index)
{
IVisualElementRenderer renderer = Platform.GetRenderer(page);
if (renderer == null)
{
renderer = Platform.CreateRenderer(page);
Platform.SetRenderer(page, renderer);
}
UIView container = new PageContainer(page);
container.AddSubview(renderer.NativeView);
_containerMap[page] = container;
AddChildViewController(renderer.ViewController);
_scrollView.InsertSubview(container, index);
if ((index == 0 && SelectedIndex == 0) || (index < SelectedIndex))
ScrollToPage(SelectedIndex + 1, false);
}
void OnDecelerationEnded(object sender, EventArgs eventArgs)
{
if (_ignoreNativeScrolling || SelectedIndex >= ElementController.LogicalChildren.Count)
return;
Carousel.CurrentPage = (ContentPage)ElementController.LogicalChildren[SelectedIndex];
}
void OnPagesChanged(object sender, NotifyCollectionChangedEventArgs e)
{
_ignoreNativeScrolling = true;
NotifyCollectionChangedAction action = e.Apply((o, i, c) => InsertPage((ContentPage)o, i), (o, i) => RemovePage((ContentPage)o, i), Reset);
PositionChildren();
_ignoreNativeScrolling = false;
if (action == NotifyCollectionChangedAction.Reset)
{
int index = Carousel.CurrentPage != null ? CarouselPage.GetIndex(Carousel.CurrentPage) : 0;
if (index < 0)
index = 0;
ScrollToPage(index);
}
}
void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "CurrentPage")
UpdateCurrentPage();
else if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName)
UpdateBackground();
else if (e.PropertyName == Page.BackgroundImageProperty.PropertyName)
UpdateBackground();
}
void PositionChildren()
{
nfloat x = 0;
RectangleF bounds = View.Bounds;
foreach (ContentPage child in ((CarouselPage)Element).Children)
{
UIView container = _containerMap[child];
container.Frame = new RectangleF(x, bounds.Y, bounds.Width, bounds.Height);
x += bounds.Width;
}
_scrollView.PagingEnabled = true;
_scrollView.ContentSize = new SizeF(bounds.Width * ((CarouselPage)Element).Children.Count, bounds.Height);
}
void RemovePage(ContentPage page, int index)
{
UIView container = _containerMap[page];
container.RemoveFromSuperview();
_containerMap.Remove(page);
IVisualElementRenderer renderer = Platform.GetRenderer(page);
if (renderer == null)
return;
renderer.ViewController.RemoveFromParentViewController();
renderer.NativeView.RemoveFromSuperview();
}
void Reset()
{
Clear();
for (var i = 0; i < ElementController.LogicalChildren.Count; i++)
{
Element element = ElementController.LogicalChildren[i];
var child = element as ContentPage;
if (child != null)
InsertPage(child, i);
}
}
void ScrollToPage(int index, bool animated = true)
{
if (_scrollView.ContentOffset.X == index * _scrollView.Frame.Width)
return;
_scrollView.SetContentOffset(new PointF(index * _scrollView.Frame.Width, 0), animated);
}
void UpdateBackground()
{
string bgImage = ((Page)Element).BackgroundImage;
if (!string.IsNullOrEmpty(bgImage))
{
View.BackgroundColor = UIColor.FromPatternImage(UIImage.FromBundle(bgImage));
return;
}
Color bgColor = Element.BackgroundColor;
if (bgColor.IsDefault)
View.BackgroundColor = UIColor.White;
else
View.BackgroundColor = bgColor.ToUIColor();
}
void UpdateCurrentPage(bool animated = true)
{
ContentPage current = Carousel.CurrentPage;
if (current != null)
ScrollToPage(CarouselPage.GetIndex(current), animated);
}
class PageContainer : UIView
{
public PageContainer(VisualElement element)
{
Element = element;
}
public VisualElement Element { get; }
public override void LayoutSubviews()
{
base.LayoutSubviews();
if (Subviews.Length > 0)
Subviews[0].Frame = new RectangleF(0, 0, (float)Element.Width, (float)Element.Height);
}
}
}
} | 23.9875 | 142 | 0.71037 | [
"MIT"
] | akihikodaki/Xamarin.Forms | Xamarin.Forms.Platform.iOS/Renderers/CarouselPageRenderer.cs | 9,595 | C# |
#region license
// Copyright (c) 2007-2010 Mauricio Scheffer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using MbUnit.Framework;
using SolrNet;
namespace Ninject.Integration.SolrNet.Tests {
[TestFixture]
public class Tests {
[Test]
[Category("Integration")]
public void Ping_And_Query() {
var c = new StandardKernel();
c.Load(new SolrNetModule("http://localhost:8983/solr"));
var solr = c.Get<ISolrOperations<Entity>>();
solr.Ping();
Console.WriteLine(solr.Query(SolrQuery.All).Count);
}
[Test]
public void ReplaceMapper() {
var c = new StandardKernel();
var mapper = new global::SolrNet.Tests.Mocks.MReadOnlyMappingManager();
c.Load(new SolrNetModule("http://localhost:8983/solr") {Mapper = mapper});
var m = c.Get<IReadOnlyMappingManager>();
Assert.AreSame(mapper, m);
}
[Test]
public void ResolveSolrOperations() {
var c = new StandardKernel();
c.Load(new SolrNetModule("http://localhost:8983/solr"));
var m = c.Get<ISolrOperations<Entity>>();
}
public class Entity {}
}
} | 34.25 | 86 | 0.633352 | [
"Apache-2.0"
] | AlexeyKozhemiakin/SolrNet | Ninject.Integration.SolrNet.Tests/Tests.cs | 1,783 | C# |
using System;
namespace GraduatedCylinder.Devices.Laser.Nmea
{
internal class CommandSentence
{
internal CommandSentence(string text) {
CommandText = text;
}
public string CommandText { get; set; }
public string GetCommand() {
return string.Format("${0}\r\n", CommandText);
}
}
internal class CommandSentence<T> : CommandSentence
{
internal CommandSentence(string text)
: base(text) { }
public T Decode(string line) {
throw new NotImplementedException();
}
public string GetSetCommand(T newValue) {
return string.Format("${0},{1}\r\n", CommandText, Convert.ToInt32(newValue));
}
}
} | 24.290323 | 89 | 0.584329 | [
"MIT"
] | EddieGarmon/GraduatedCylinder | Source/GraduatedCylinder.Geo/Devices/Laser/Nmea/CommandSentence.cs | 755 | C# |
using NUnit.Framework;
using System;
namespace DeltaTimer.FixedPoint.Tests
{
public class RandomExtensionsTests
{
// Run sufficient times, to make sure that the values keep in range
[Test]
public void RandomMaxTests()
{
Random random = new Random();
for (int i = 0; i < 1000000; i++)
{
FPFloat value = random.NextFloat(13);
if (value < FPFloat.Zero || value >= 13)
{
Assert.Fail();
}
}
}
// Run sufficient times, to make sure that the values keep in range
[Test]
public void RandomMinMaxTests()
{
Random random = new Random();
for (int i = 0; i < 1000000; i++)
{
FPFloat value = random.NextFloat(9, 13);
if (value < 9 || value >= 13)
{
Assert.Fail();
}
}
}
// Run sufficient times, to make sure that the values keep in range
[Test]
public void Random01Tests()
{
Random random = new Random();
for (int i = 0; i < 1000000; i++)
{
FPFloat value = random.NextFloat01();
if (value < FPFloat.Zero || value >= FPFloat.One)
{
Assert.Fail();
}
}
}
}
}
| 27.296296 | 75 | 0.436228 | [
"MIT"
] | daleth90/fixed-point-unity | Tests/RandomExtensionsTests.cs | 1,474 | C# |
using System.IO;
using System.Text;
using Microsoft.TemplateEngine.Core.Contracts;
using Microsoft.TemplateEngine.Core.Operations;
using Microsoft.TemplateEngine.Core.Util;
using Microsoft.TemplateEngine.TestHelper;
using Xunit;
namespace Microsoft.TemplateEngine.Core.UnitTests
{
public class ReplacementTests : TestBase
{
[Fact(DisplayName = nameof(VerifyReplacement))]
public void VerifyReplacement()
{
string value = @"test value test";
string expected = @"test foo test";
byte[] valueBytes = Encoding.UTF8.GetBytes(value);
MemoryStream input = new MemoryStream(valueBytes);
MemoryStream output = new MemoryStream();
IOperationProvider[] operations = {new Replacement("value", "foo", null)};
EngineConfig cfg = new EngineConfig(EnvironmentSettings, VariableCollection.Environment(EnvironmentSettings), "${0}$");
IProcessor processor = Processor.Create(cfg, operations);
//Changes should be made
bool changed = processor.Run(input, output);
Verify(Encoding.UTF8, output, changed, value, expected);
}
[Fact(DisplayName = nameof(VerifyNoReplacement))]
public void VerifyNoReplacement()
{
string value = @"test value test";
string expected = @"test value test";
byte[] valueBytes = Encoding.UTF8.GetBytes(value);
MemoryStream input = new MemoryStream(valueBytes);
MemoryStream output = new MemoryStream();
IOperationProvider[] operations = { new Replacement("value2", "foo", null) };
EngineConfig cfg = new EngineConfig(EnvironmentSettings, VariableCollection.Environment(EnvironmentSettings), "${0}$");
IProcessor processor = Processor.Create(cfg, operations);
//Changes should be made
bool changed = processor.Run(input, output);
Verify(Encoding.UTF8, output, changed, value, expected);
}
[Fact(DisplayName = nameof(VerifyTornReplacement))]
public void VerifyTornReplacement()
{
string value = @"test value test";
string expected = @"test foo test";
byte[] valueBytes = Encoding.UTF8.GetBytes(value);
MemoryStream input = new MemoryStream(valueBytes);
MemoryStream output = new MemoryStream();
IOperationProvider[] operations = { new Replacement("value", "foo", null) };
EngineConfig cfg = new EngineConfig(EnvironmentSettings, VariableCollection.Environment(EnvironmentSettings), "${0}$");
IProcessor processor = Processor.Create(cfg, operations);
//Changes should be made
bool changed = processor.Run(input, output, 6);
Verify(Encoding.UTF8, output, changed, value, expected);
}
[Fact(DisplayName = nameof(VerifyTinyPageReplacement))]
public void VerifyTinyPageReplacement()
{
string value = @"test value test";
string expected = @"test foo test";
byte[] valueBytes = Encoding.UTF8.GetBytes(value);
MemoryStream input = new MemoryStream(valueBytes);
MemoryStream output = new MemoryStream();
IOperationProvider[] operations = { new Replacement("value", "foo", null) };
EngineConfig cfg = new EngineConfig(EnvironmentSettings, VariableCollection.Environment(EnvironmentSettings), "${0}$");
IProcessor processor = Processor.Create(cfg, operations);
//Changes should be made
bool changed = processor.Run(input, output, 1);
Verify(Encoding.UTF8, output, changed, value, expected);
}
}
}
| 41.911111 | 131 | 0.637328 | [
"MIT"
] | codito/dotnet-templating | test/Microsoft.TemplateEngine.Core.UnitTests/ReplacementTests.cs | 3,774 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Discord.Commands;
namespace NadekoBot.Classes.ClashOfClans {
internal class Caller {
public string CallUser { get; }
public DateTime TimeAdded { get; private set; }
public bool BaseDestroyed { get; internal set; }
public Caller(string callUser, DateTime timeAdded, bool baseDestroyed) {
CallUser = callUser;
TimeAdded = timeAdded;
BaseDestroyed = baseDestroyed;
}
public void ResetTime() {
TimeAdded = DateTime.Now;
}
public void Destroy() {
BaseDestroyed = true;
}
}
internal class ClashWar {
private static TimeSpan callExpire => new TimeSpan(2, 0, 0);
private CommandEventArgs e;
public string EnemyClan { get; }
public int Size { get; }
private Caller[] bases { get; }
private CancellationTokenSource[] baseCancelTokens;
private CancellationTokenSource endTokenSource { get; } = new CancellationTokenSource();
public event Action<string> OnUserTimeExpired = delegate { };
public event Action OnWarEnded = delegate { };
public bool Started { get; set; } = false;
public ClashWar(string enemyClan, int size, CommandEventArgs e) {
this.EnemyClan = enemyClan;
this.Size = size;
this.bases = new Caller[size];
this.baseCancelTokens = new CancellationTokenSource[size];
}
internal void End() {
if (endTokenSource.Token.IsCancellationRequested) return;
endTokenSource.Cancel();
OnWarEnded();
}
internal void Call(string u, int baseNumber) {
if (baseNumber < 0 || baseNumber >= bases.Length)
throw new ArgumentException("Invalid base number");
if (bases[baseNumber] != null)
throw new ArgumentException("That base is already claimed.");
for (var i = 0; i < bases.Length; i++) {
if (bases[i]?.BaseDestroyed == false && bases[i]?.CallUser == u)
throw new ArgumentException($"@{u} You already claimed a base #{i + 1}. You can't claim a new one.");
}
bases[baseNumber] = new Caller(u.Trim(), DateTime.Now, false);
}
internal async Task Start() {
if (Started)
throw new InvalidOperationException();
try {
Started = true;
foreach (var b in bases.Where(b => b != null)) {
b.ResetTime();
}
Task.Run(async () => await ClearArray()).ConfigureAwait(false);
await Task.Delay(new TimeSpan(24, 0, 0), endTokenSource.Token);
} catch { } finally {
End();
}
}
internal int Uncall(string user) {
user = user.Trim();
for (var i = 0; i < bases.Length; i++) {
if (bases[i]?.CallUser != user) continue;
bases[i] = null;
return i;
}
throw new InvalidOperationException("You are not participating in that war.");
}
private async Task ClearArray() {
while (!endTokenSource.IsCancellationRequested) {
await Task.Delay(5000);
for (var i = 0; i < bases.Length; i++) {
if (bases[i] == null) continue;
if (!bases[i].BaseDestroyed && DateTime.Now - bases[i].TimeAdded >= callExpire) {
Console.WriteLine($"Removing user {bases[i].CallUser}");
OnUserTimeExpired(bases[i].CallUser);
bases[i] = null;
}
}
}
Console.WriteLine("Out of clear array");
}
public string ShortPrint() =>
$"`{EnemyClan}` ({Size} v {Size})";
public override string ToString() {
var sb = new StringBuilder();
sb.AppendLine($"🔰**WAR AGAINST `{EnemyClan}` ({Size} v {Size}) INFO:**");
if (!Started)
sb.AppendLine("`not started`");
for (var i = 0; i < bases.Length; i++) {
if (bases[i] == null) {
sb.AppendLine($"`{i + 1}.` ❌*unclaimed*");
} else {
if (bases[i].BaseDestroyed) {
sb.AppendLine($"`{i + 1}.` ✅ `{bases[i].CallUser}` ⭐ ⭐ ⭐");
} else {
var left = Started ? callExpire - (DateTime.Now - bases[i].TimeAdded) : callExpire;
sb.AppendLine($"`{i + 1}.` ✅ `{bases[i].CallUser}` {left.Hours}h {left.Minutes}m {left.Seconds}s left");
}
}
}
return sb.ToString();
}
internal int FinishClaim(string user) {
user = user.Trim();
for (var i = 0; i < bases.Length; i++) {
if (bases[i]?.BaseDestroyed != false || bases[i]?.CallUser != user) continue;
bases[i].BaseDestroyed = true;
return i;
}
throw new InvalidOperationException($"@{user} You are either not participating in that war, or you already destroyed a base.");
}
}
}
| 37.312925 | 139 | 0.516317 | [
"MIT"
] | IttyBittyNinja/AYYLMAO | NadekoBot/Classes/ClashOfClans/ClashOfClans.cs | 5,502 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.DevTestLab.V20180915.Outputs
{
[OutputType]
public sealed class WindowsOsInfoResponse
{
/// <summary>
/// The state of the Windows OS (i.e. NonSysprepped, SysprepRequested, SysprepApplied).
/// </summary>
public readonly string? WindowsOsState;
[OutputConstructor]
private WindowsOsInfoResponse(string? windowsOsState)
{
WindowsOsState = windowsOsState;
}
}
}
| 27.928571 | 95 | 0.681586 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/DevTestLab/V20180915/Outputs/WindowsOsInfoResponse.cs | 782 | C# |
using System.Linq;
using MoonSharp.Interpreter;
using UnityEngine;
namespace ULTRAKIT.Lua.API.Proxies
{
public class UKProxyGameObject : UKProxyObjectAbstract<GameObject>
{
public UKProxyGameObject(GameObject target) : base(target)
{
}
#region Properties
public bool activeInHierarchy => target.activeInHierarchy;
public bool activeSelf => target.activeSelf;
public bool isStatic => target.isStatic;
public int layer
{
get => target.layer;
set => target.layer = value;
}
public string tag
{
get => target.tag;
set => target.tag = value;
}
public Transform transform => target.transform;
#endregion
#region Instance Methods
//TODO: AddComponent
public bool CompareTag(string tag) => target.CompareTag(tag);
public void SetActive(bool value) => target.SetActive(value);
// Copied from UKProxyComponent.cs
public Projectile AddProjComponent() => target.AddComponent<Projectile>();
public Explosion AddExplosionComponent() => target.AddComponent<Explosion>();
public FloatingPointErrorPreventer AddFloatingPointErrorPreventer() => target.AddComponent<FloatingPointErrorPreventer>();
public void RemoveOnTime(float _time = 10f, float _randomizer = 0f)
{
RemoveOnTime remover = target.AddComponent<RemoveOnTime>();
remover.time = _time;
remover.randomizer = _randomizer;
}
public Component GetComponent(string typeName) => target.GetComponent(typeName);
public Component GetComponentInParent(string typeName) => target.GetComponentsInParent<Component>()?.Where(t => t.GetType().Name == typeName)?.FirstOrDefault();
public Component GetComponentInChildren(string typeName) => target.GetComponentsInChildren<Component>()?.Where(t => t.GetType().Name == typeName)?.FirstOrDefault();
public Component[] GetComponents(string typeName) => target.GetComponents<Component>()?.Where(t => t.GetType().Name == typeName).ToArray();
public Component[] GetComponentsInChildren(string typeName) => target.GetComponentsInChildren<Component>()?.Where(t => t.GetType().Name == typeName).ToArray();
public Component[] GetComponentsInParent(string typeName) => target.GetComponentsInChildren<Component>()?.Where(t => t.GetType().Name == typeName).ToArray();
public DynValue TryGetComponent(string typeName) {
var component = target.GetComponents<Component>()?.Where(t => t.GetType().Name == typeName)?.FirstOrDefault();
var success = component != null;
if (component == null)
return DynValue.NewTuple(DynValue.Nil, DynValue.NewBoolean(success));
else
return DynValue.NewTuple(UserData.Create(component), DynValue.NewBoolean(success));
}
#endregion
}
}
| 45.318182 | 172 | 0.660314 | [
"MIT"
] | PetersonE1/UltraKit | ULTRAKIT.Lua/API/Proxies/UKProxyGameObject.cs | 2,993 | C# |
namespace QuickGraph.Graphviz.Dot
{
using System;
using System.Collections;
using System.IO;
using System.Collections.Generic;
public class GraphvizGraph
{
private string name = "G";
private GraphvizColor backgroundGraphvizColor = GraphvizColor.White;
private GraphvizClusterMode clusterRank = GraphvizClusterMode.Local;
private string comment = null;
private GraphvizFont font = null;
private GraphvizColor fontGraphvizColor = GraphvizColor.Black;
private bool isCentered = false;
private bool isCompounded = false;
private bool isConcentrated = false;
private bool isLandscape = false;
private bool isNormalized = false;
private bool isReMinCross = false;
private string label = null;
private GraphvizLabelJustification labelJustification = GraphvizLabelJustification.C;
private GraphvizLabelLocation labelLocation = GraphvizLabelLocation.B;
private readonly GraphvizLayerCollection layers = new GraphvizLayerCollection();
private double mcLimit = 1;
private double nodeSeparation = 0.25;
private int nsLimit = -1;
private int nsLimit1 = -1;
private GraphvizOutputMode outputOrder = GraphvizOutputMode.BreadthFirst;
private GraphvizPageDirection pageDirection = GraphvizPageDirection.BL;
private GraphvizSizeF pageSize = new GraphvizSizeF(0, 0);
private double quantum = 0;
private GraphvizRankDirection rankDirection = GraphvizRankDirection.TB;
private double rankSeparation = 0.5;
private GraphvizRatioMode ratio = GraphvizRatioMode.Auto;
private double resolution = 0.96;
private int rotate = 0;
private int samplePoints = 8;
private int searchSize = 30;
private GraphvizSizeF size = new GraphvizSizeF(0, 0);
private string styleSheet = null;
private string url = null;
internal string GenerateDot(Dictionary<string, object> pairs)
{
bool flag = false;
StringWriter writer = new StringWriter();
foreach (var entry in pairs)
{
if (flag)
{
writer.Write(", ");
}
else
{
flag = true;
}
if (entry.Value is string)
{
writer.Write("{0}=\"{1}\"", entry.Key.ToString(), entry.Value.ToString());
continue;
}
if (entry.Value is GraphvizColor)
{
GraphvizColor GraphvizColor = (GraphvizColor) entry.Value;
writer.Write("{0}=\"#{1}{2}{3}{4}\"", new object[] { entry.Key.ToString(), GraphvizColor.R.ToString("x2").ToUpper(), GraphvizColor.G.ToString("x2").ToUpper(), GraphvizColor.B.ToString("x2").ToUpper(), GraphvizColor.A.ToString("x2").ToUpper() });
continue;
}
if ((entry.Value is GraphvizRankDirection) || (entry.Value is GraphvizPageDirection))
{
writer.Write("{0}={1};", entry.Key.ToString(), entry.Value.ToString());
continue;
}
writer.Write(" {0}={1}", entry.Key.ToString(), entry.Value.ToString().ToLower());
}
return writer.ToString();
}
public string ToDot()
{
var pairs = new Dictionary<string, object>(StringComparer.Ordinal);
if (this.Url != null)
{
pairs["URL"] = this.Url;
}
if (!this.BackgroundGraphvizColor.Equals(GraphvizColor.White))
{
pairs["bgGraphvizColor"] = this.BackgroundGraphvizColor;
}
if (this.IsCentered)
{
pairs["center"] = true;
}
if (this.ClusterRank != GraphvizClusterMode.Local)
{
pairs["clusterrank"] = this.ClusterRank.ToString().ToLower();
}
if (this.Comment != null)
{
pairs["comment"] = this.Comment;
}
if (this.IsCompounded)
{
pairs["compound"] = this.IsCompounded;
}
if (this.IsConcentrated)
{
pairs["concentrated"] = this.IsConcentrated;
}
if (this.Font != null)
{
pairs["fontname"] = this.Font.Name;
pairs["fontsize"] = this.Font.SizeInPoints;
}
if (!this.FontGraphvizColor.Equals(GraphvizColor.Black))
{
pairs["fontGraphvizColor"] = this.FontGraphvizColor;
}
if (this.Label != null)
{
pairs["label"] = this.Label;
}
if (this.LabelJustification != GraphvizLabelJustification.C)
{
pairs["labeljust"] = this.LabelJustification.ToString().ToLower();
}
if (this.LabelLocation != GraphvizLabelLocation.B)
{
pairs["labelloc"] = this.LabelLocation.ToString().ToLower();
}
if (this.Layers.Count != 0)
{
pairs["layers"] = this.Layers.ToDot();
}
if (this.McLimit != 1)
{
pairs["mclimit"] = this.McLimit;
}
if (this.NodeSeparation != 0.25)
{
pairs["nodesep"] = this.NodeSeparation;
}
if (this.IsNormalized)
{
pairs["normalize"] = this.IsNormalized;
}
if (this.NsLimit > 0)
{
pairs["nslimit"] = this.NsLimit;
}
if (this.NsLimit1 > 0)
{
pairs["nslimit1"] = this.NsLimit1;
}
if (this.OutputOrder != GraphvizOutputMode.BreadthFirst)
{
pairs["outputorder"] = this.OutputOrder.ToString().ToLower();
}
if (!this.PageSize.IsEmpty)
{
pairs["page"] = string.Format("{0},{1}", this.PageSize.Width, this.PageSize.Height);
}
if (this.PageDirection != GraphvizPageDirection.BL)
{
pairs["pagedir"] = this.PageDirection.ToString().ToLower();
}
if (this.Quantum > 0)
{
pairs["quantum"] = this.Quantum;
}
if (this.RankSeparation != 0.5)
{
pairs["ranksep"] = this.RankSeparation;
}
if (this.Ratio != GraphvizRatioMode.Auto)
{
pairs["ratio"] = this.Ratio.ToString().ToLower();
}
if (this.IsReMinCross)
{
pairs["remincross"] = this.IsReMinCross;
}
if (this.Resolution != 0.96)
{
pairs["resolution"] = this.Resolution;
}
if (this.Rotate != 0)
{
pairs["rotate"] = this.Rotate;
}
else if (this.IsLandscape)
{
pairs["orientation"] = "[1L]*";
}
if (this.SamplePoints != 8)
{
pairs["samplepoints"] = this.SamplePoints;
}
if (this.SearchSize != 30)
{
pairs["searchsize"] = this.SearchSize;
}
if (!this.Size.IsEmpty)
{
pairs["size"] = string.Format("{0},{1}", this.Size.Width, this.Size.Height);
}
if (this.StyleSheet != null)
{
pairs["stylesheet"] = this.StyleSheet;
}
if (this.RankDirection != GraphvizRankDirection.TB)
{
pairs["rankdir"] = this.RankDirection;
}
return this.GenerateDot(pairs);
}
public override string ToString()
{
return this.ToDot();
}
public string Name
{
get { return this.name; }
set { this.name = value; }
}
public GraphvizColor BackgroundGraphvizColor
{
get
{
return this.backgroundGraphvizColor;
}
set
{
this.backgroundGraphvizColor = value;
}
}
public GraphvizClusterMode ClusterRank
{
get
{
return this.clusterRank;
}
set
{
this.clusterRank = value;
}
}
public string Comment
{
get
{
return this.comment;
}
set
{
this.comment = value;
}
}
public GraphvizFont Font
{
get
{
return this.font;
}
set
{
this.font = value;
}
}
public GraphvizColor FontGraphvizColor
{
get
{
return this.fontGraphvizColor;
}
set
{
this.fontGraphvizColor = value;
}
}
public bool IsCentered
{
get
{
return this.isCentered;
}
set
{
this.isCentered = value;
}
}
public bool IsCompounded
{
get
{
return this.isCompounded;
}
set
{
this.isCompounded = value;
}
}
public bool IsConcentrated
{
get
{
return this.isConcentrated;
}
set
{
this.isConcentrated = value;
}
}
public bool IsLandscape
{
get
{
return this.isLandscape;
}
set
{
this.isLandscape = value;
}
}
public bool IsNormalized
{
get
{
return this.isNormalized;
}
set
{
this.isNormalized = value;
}
}
public bool IsReMinCross
{
get
{
return this.isReMinCross;
}
set
{
this.isReMinCross = value;
}
}
public string Label
{
get
{
return this.label;
}
set
{
this.label = value;
}
}
public GraphvizLabelJustification LabelJustification
{
get
{
return this.labelJustification;
}
set
{
this.labelJustification = value;
}
}
public GraphvizLabelLocation LabelLocation
{
get
{
return this.labelLocation;
}
set
{
this.labelLocation = value;
}
}
public GraphvizLayerCollection Layers
{
get
{
return this.layers;
}
}
public double McLimit
{
get
{
return this.mcLimit;
}
set
{
this.mcLimit = value;
}
}
public double NodeSeparation
{
get
{
return this.nodeSeparation;
}
set
{
this.nodeSeparation = value;
}
}
public int NsLimit
{
get
{
return this.nsLimit;
}
set
{
this.nsLimit = value;
}
}
public int NsLimit1
{
get
{
return this.nsLimit1;
}
set
{
this.nsLimit1 = value;
}
}
public GraphvizOutputMode OutputOrder
{
get
{
return this.outputOrder;
}
set
{
this.outputOrder = value;
}
}
public GraphvizPageDirection PageDirection
{
get
{
return this.pageDirection;
}
set
{
this.pageDirection = value;
}
}
public GraphvizSizeF PageSize
{
get
{
return this.pageSize;
}
set
{
this.pageSize = value;
}
}
public double Quantum
{
get
{
return this.quantum;
}
set
{
this.quantum = value;
}
}
public GraphvizRankDirection RankDirection
{
get
{
return this.rankDirection;
}
set
{
this.rankDirection = value;
}
}
public double RankSeparation
{
get
{
return this.rankSeparation;
}
set
{
this.rankSeparation = value;
}
}
public GraphvizRatioMode Ratio
{
get
{
return this.ratio;
}
set
{
this.ratio = value;
}
}
public double Resolution
{
get
{
return this.resolution;
}
set
{
this.resolution = value;
}
}
public int Rotate
{
get
{
return this.rotate;
}
set
{
this.rotate = value;
}
}
public int SamplePoints
{
get
{
return this.samplePoints;
}
set
{
this.samplePoints = value;
}
}
public int SearchSize
{
get
{
return this.searchSize;
}
set
{
this.searchSize = value;
}
}
public GraphvizSizeF Size
{
get
{
return this.size;
}
set
{
this.size = value;
}
}
public string StyleSheet
{
get
{
return this.styleSheet;
}
set
{
this.styleSheet = value;
}
}
public string Url
{
get
{
return this.url;
}
set
{
this.url = value;
}
}
}
}
| 25.258013 | 265 | 0.411015 | [
"MIT"
] | danm-de/quickgraph | 3.0/sources/QuickGraph.Graphviz/Dot/GraphvizGraph.cs | 15,761 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("06. Fold and Sum")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("06. Fold and Sum")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d984d625-c9de-433d-bc6d-b5d766869a31")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.837838 | 84 | 0.743571 | [
"Apache-2.0"
] | Warglaive/TechModuleSeptember2017 | Dictionaries, Lambda and LINQ - Lab/06. Fold and Sum/Properties/AssemblyInfo.cs | 1,403 | C# |
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using RI.Framework.Utilities.ObjectModel;
namespace RI.Framework.Threading.Async
{
/// <summary>
/// Implements a base class to implement custom flowers.
/// </summary>
/// <remarks>
/// <para>
/// Obviously, "flowers" as in "flow"ers, not the nice things you buy your partner on Valentines day...
/// </para>
/// <para>
/// Custom flowers are used to flow certain things around an <c> await </c> by capturing and restoring them.
/// </para>
/// <note type="important">
/// Some virtual methods are called from within locks to <see cref="ISynchronizable.SyncRoot" />.
/// Be careful in inheriting classes when calling outside code from those methods (e.g. through events, callbacks, or other virtual methods) to not produce deadlocks!
/// </note>
/// </remarks>
/// <threadsafety static="true" instance="true" />
public abstract class CustomFlower : CustomAwaiter
{
#region Instance Constructor/Destructor
/// <summary>
/// Creates a new instance of <see cref="CustomFlower" />.
/// </summary>
/// <param name="task"> The <see cref="Task" /> to flow things around when awaited. </param>
/// <exception cref="ArgumentNullException"> <paramref name="task" /> is null. </exception>
protected CustomFlower (Task task)
{
if (task == null)
{
throw new ArgumentNullException(nameof(task));
}
this.TaskAwaiter = task.GetAwaiter();
this.ConfiguredTaskAwaiter = null;
this.CustomAwaiter = null;
this.IsCaptured = false;
}
/// <summary>
/// Creates a new instance of <see cref="CustomFlower" />.
/// </summary>
/// <param name="taskAwaiter"> The <see cref="TaskAwaiter" /> to flow things around when awaited. </param>
protected CustomFlower (TaskAwaiter taskAwaiter)
{
this.TaskAwaiter = taskAwaiter;
this.ConfiguredTaskAwaiter = null;
this.CustomAwaiter = null;
this.IsCaptured = false;
}
/// <summary>
/// Creates a new instance of <see cref="CustomFlower" />.
/// </summary>
/// <param name="configuredTaskAwaitable"> The <see cref="ConfiguredTaskAwaitable" /> to flow things around when awaited. </param>
protected CustomFlower (ConfiguredTaskAwaitable configuredTaskAwaitable)
{
this.TaskAwaiter = null;
this.ConfiguredTaskAwaiter = configuredTaskAwaitable.GetAwaiter();
this.CustomAwaiter = null;
this.IsCaptured = false;
}
/// <summary>
/// Creates a new instance of <see cref="CustomFlower" />.
/// </summary>
/// <param name="customAwaiter"> The <see cref="CustomAwaiter" /> to flow things around when awaited. </param>
/// <exception cref="ArgumentNullException"> <paramref name="customAwaiter" /> is null. </exception>
protected CustomFlower (CustomAwaiter customAwaiter)
{
this.TaskAwaiter = null;
this.ConfiguredTaskAwaiter = null;
this.CustomAwaiter = customAwaiter.GetAwaiter();
this.IsCaptured = false;
}
#endregion
#region Instance Fields
private bool _isCaptured;
#endregion
#region Instance Properties/Indexer
/// <summary>
/// Gets whether the flow was captured and needs restore.
/// </summary>
/// <value>
/// true if the flow was captured and needs restore, false otherwise.
/// </value>
public bool IsCaptured
{
get
{
lock (this.SyncRoot)
{
return this._isCaptured;
}
}
private set
{
lock (this.SyncRoot)
{
this._isCaptured = value;
}
}
}
private ConfiguredTaskAwaitable.ConfiguredTaskAwaiter? ConfiguredTaskAwaiter { get; }
private CustomAwaiter CustomAwaiter { get; }
private TaskAwaiter? TaskAwaiter { get; }
#endregion
#region Abstracts
/// <summary>
/// Called to capture what needs to flow around the <c> await </c>.
/// </summary>
/// <remarks>
/// <note type="important">
/// This method is called inside a lock to <see cref="ISynchronizable.SyncRoot" />.
/// </note>
/// </remarks>
protected abstract void Capture ();
/// <summary>
/// Called to restore what needs to flow around the <c> await </c>.
/// </summary>
/// <remarks>
/// <note type="important">
/// This method is called inside a lock to <see cref="ISynchronizable.SyncRoot" />.
/// </note>
/// </remarks>
protected abstract void Restore ();
#endregion
#region Overrides
/// <inheritdoc />
public override bool IsCompleted => this.TaskAwaiter?.IsCompleted ?? this.ConfiguredTaskAwaiter?.IsCompleted ?? this.CustomAwaiter.IsCompleted;
/// <inheritdoc />
public override void GetResult ()
{
lock (this.SyncRoot)
{
if (this.IsCaptured)
{
this.Restore();
}
}
if (this.TaskAwaiter != null)
{
this.TaskAwaiter.Value.GetResult();
return;
}
if (this.ConfiguredTaskAwaiter != null)
{
this.ConfiguredTaskAwaiter.Value.GetResult();
return;
}
this.CustomAwaiter.GetResult();
}
/// <inheritdoc />
public override void OnCompleted (Action continuation)
{
if (continuation == null)
{
throw new ArgumentNullException(nameof(continuation));
}
lock (this.SyncRoot)
{
this.Capture();
this.IsCaptured = true;
}
if (this.TaskAwaiter != null)
{
this.TaskAwaiter.Value.OnCompleted(continuation);
return;
}
if (this.ConfiguredTaskAwaiter != null)
{
this.ConfiguredTaskAwaiter.Value.OnCompleted(continuation);
return;
}
this.CustomAwaiter.OnCompleted(continuation);
}
/// <inheritdoc />
public override void UnsafeOnCompleted (Action continuation)
{
if (continuation == null)
{
throw new ArgumentNullException(nameof(continuation));
}
lock (this.SyncRoot)
{
this.Capture();
this.IsCaptured = true;
}
if (this.TaskAwaiter != null)
{
this.TaskAwaiter.Value.UnsafeOnCompleted(continuation);
return;
}
if (this.ConfiguredTaskAwaiter != null)
{
this.ConfiguredTaskAwaiter.Value.UnsafeOnCompleted(continuation);
return;
}
this.CustomAwaiter.UnsafeOnCompleted(continuation);
}
#endregion
}
/// <summary>
/// Implements a base class to implement custom flowers.
/// </summary>
/// <typeparam name="T"> The type of the return value of the <c> await </c> that is flowed around. </typeparam>
/// <remarks>
/// <para>
/// Obviously, "flowers" as in "flow"ers, not the nice things you buy your partner on Valentines day...
/// </para>
/// <para>
/// Custom flowers are used to flow certain things around an <c> await </c> by capturing and restoring them.
/// </para>
/// <note type="important">
/// Some virtual methods are called from within locks to <see cref="ISynchronizable.SyncRoot" />.
/// Be careful in inheriting classes when calling outside code from those methods (e.g. through events, callbacks, or other virtual methods) to not produce deadlocks!
/// </note>
/// </remarks>
/// <threadsafety static="true" instance="true" />
public abstract class CustomFlower <T> : CustomAwaiter<T>
{
#region Instance Constructor/Destructor
/// <summary>
/// Creates a new instance of <see cref="CustomFlower" />.
/// </summary>
/// <param name="task"> The <see cref="Task{T}" /> to flow things around when awaited. </param>
/// <exception cref="ArgumentNullException"> <paramref name="task" /> is null. </exception>
protected CustomFlower (Task<T> task)
{
if (task == null)
{
throw new ArgumentNullException(nameof(task));
}
this.TaskAwaiter = task.GetAwaiter();
this.ConfiguredTaskAwaiter = null;
this.CustomAwaiter = null;
this.IsCaptured = false;
}
/// <summary>
/// Creates a new instance of <see cref="CustomFlower" />.
/// </summary>
/// <param name="taskAwaiter"> The <see cref="TaskAwaiter{T}" /> to flow things around when awaited. </param>
protected CustomFlower (TaskAwaiter<T> taskAwaiter)
{
this.TaskAwaiter = taskAwaiter;
this.ConfiguredTaskAwaiter = null;
this.CustomAwaiter = null;
this.IsCaptured = false;
}
/// <summary>
/// Creates a new instance of <see cref="CustomFlower" />.
/// </summary>
/// <param name="configuredTaskAwaitable"> The <see cref="ConfiguredTaskAwaitable{T}" /> to flow things around when awaited. </param>
protected CustomFlower (ConfiguredTaskAwaitable<T> configuredTaskAwaitable)
{
this.TaskAwaiter = null;
this.ConfiguredTaskAwaiter = configuredTaskAwaitable.GetAwaiter();
this.CustomAwaiter = null;
this.IsCaptured = false;
}
/// <summary>
/// Creates a new instance of <see cref="CustomFlower" />.
/// </summary>
/// <param name="customAwaiter"> The <see cref="CustomAwaiter{T}" /> to flow things around when awaited. </param>
protected CustomFlower (CustomAwaiter<T> customAwaiter)
{
this.TaskAwaiter = null;
this.ConfiguredTaskAwaiter = null;
this.CustomAwaiter = customAwaiter.GetAwaiter();
this.IsCaptured = false;
}
#endregion
#region Instance Fields
private bool _isCaptured;
#endregion
#region Instance Properties/Indexer
/// <summary>
/// Gets whether the flow was captured and needs restore.
/// </summary>
/// <value>
/// true if the flow was captured and needs restore, false otherwise.
/// </value>
public bool IsCaptured
{
get
{
lock (this.SyncRoot)
{
return this._isCaptured;
}
}
private set
{
lock (this.SyncRoot)
{
this._isCaptured = value;
}
}
}
private ConfiguredTaskAwaitable<T>.ConfiguredTaskAwaiter? ConfiguredTaskAwaiter { get; }
private CustomAwaiter<T> CustomAwaiter { get; }
private TaskAwaiter<T>? TaskAwaiter { get; }
#endregion
#region Abstracts
/// <summary>
/// Called to capture what needs to flow around the <c> await </c>.
/// </summary>
/// <remarks>
/// <note type="important">
/// This method is called inside a lock to <see cref="ISynchronizable.SyncRoot" />.
/// </note>
/// </remarks>
protected abstract void Capture ();
/// <summary>
/// Called to restore what needs to flow around the <c> await </c>.
/// </summary>
/// <remarks>
/// <note type="important">
/// This method is called inside a lock to <see cref="ISynchronizable.SyncRoot" />.
/// </note>
/// </remarks>
protected abstract void Restore ();
#endregion
#region Overrides
/// <inheritdoc />
public override bool IsCompleted => this.TaskAwaiter?.IsCompleted ?? this.ConfiguredTaskAwaiter?.IsCompleted ?? this.CustomAwaiter.IsCompleted;
/// <inheritdoc />
public override T GetResult ()
{
lock (this.SyncRoot)
{
if (this.IsCaptured)
{
this.Restore();
}
}
if (this.TaskAwaiter != null)
{
return this.TaskAwaiter.Value.GetResult();
}
if (this.ConfiguredTaskAwaiter != null)
{
return this.ConfiguredTaskAwaiter.Value.GetResult();
}
return this.CustomAwaiter.GetResult();
}
/// <inheritdoc />
public override void OnCompleted (Action continuation)
{
if (continuation == null)
{
throw new ArgumentNullException(nameof(continuation));
}
lock (this.SyncRoot)
{
this.Capture();
this.IsCaptured = true;
}
if (this.TaskAwaiter != null)
{
this.TaskAwaiter.Value.OnCompleted(continuation);
return;
}
if (this.ConfiguredTaskAwaiter != null)
{
this.ConfiguredTaskAwaiter.Value.OnCompleted(continuation);
return;
}
this.CustomAwaiter.OnCompleted(continuation);
}
/// <inheritdoc />
public override void UnsafeOnCompleted (Action continuation)
{
if (continuation == null)
{
throw new ArgumentNullException(nameof(continuation));
}
lock (this.SyncRoot)
{
this.Capture();
this.IsCaptured = true;
}
if (this.TaskAwaiter != null)
{
this.TaskAwaiter.Value.UnsafeOnCompleted(continuation);
return;
}
if (this.ConfiguredTaskAwaiter != null)
{
this.ConfiguredTaskAwaiter.Value.UnsafeOnCompleted(continuation);
return;
}
this.CustomAwaiter.UnsafeOnCompleted(continuation);
}
#endregion
}
}
| 29.878906 | 178 | 0.524382 | [
"Apache-2.0"
] | gosystemsgmbh/RI_Framework | RI.Framework.Common/Threading/Async/CustomFlower.cs | 15,300 | C# |
using System.Collections.Generic;
using HotChocolate.Resolvers;
using HotChocolate.Types;
namespace HotChocolate.Benchmark.Tests.Execution
{
public class CharacterType
: InterfaceType
{
protected override void Configure(IInterfaceTypeDescriptor descriptor)
{
descriptor.Name("Character");
descriptor.Field("id").Type<NonNullType<StringType>>();
descriptor.Field("name").Type<StringType>();
descriptor.Field("friends").Type<ListType<CharacterType>>();
descriptor.Field("appearsIn").Type<ListType<EpisodeType>>();
descriptor.Field("height").Type<FloatType>()
.Argument("unit", a => a.Type<EnumType<Unit>>());
}
public static IEnumerable<ICharacter> GetCharacter(
IResolverContext context)
{
ICharacter character = context.Parent<ICharacter>();
CharacterRepository repository = context.Service<CharacterRepository>();
foreach (string friendId in character.Friends)
{
ICharacter friend = repository.GetCharacter(friendId);
if (friend != null)
{
yield return friend;
}
}
}
public static double GetHeight(
IResolverContext context)
{
double height = context.Parent<ICharacter>().Height;
if (context.Argument<Unit?>("unit") == Unit.Foot)
{
return height * 3.28084d;
}
return height;
}
}
}
| 33.541667 | 84 | 0.570807 | [
"MIT"
] | Dolfik1/hotchocolate | benchmarks/Benchmark.Tests/Execution/CharacterType.cs | 1,612 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.RecoveryServices.V20180110.Outputs
{
[OutputType]
public sealed class VMwareCbtProtectedDiskDetailsResponse
{
/// <summary>
/// The disk capacity in bytes.
/// </summary>
public readonly double CapacityInBytes;
/// <summary>
/// The DiskEncryptionSet ARM Id.
/// </summary>
public readonly string DiskEncryptionSetId;
/// <summary>
/// The disk id.
/// </summary>
public readonly string DiskId;
/// <summary>
/// The disk name.
/// </summary>
public readonly string DiskName;
/// <summary>
/// The disk path.
/// </summary>
public readonly string DiskPath;
/// <summary>
/// The disk type.
/// </summary>
public readonly string? DiskType;
/// <summary>
/// A value indicating whether the disk is the OS disk.
/// </summary>
public readonly string IsOSDisk;
/// <summary>
/// The log storage account ARM Id.
/// </summary>
public readonly string LogStorageAccountId;
/// <summary>
/// The key vault secret name of the log storage account.
/// </summary>
public readonly string LogStorageAccountSasSecretName;
/// <summary>
/// The ARM Id of the seed managed disk.
/// </summary>
public readonly string SeedManagedDiskId;
/// <summary>
/// The ARM Id of the target managed disk.
/// </summary>
public readonly string TargetManagedDiskId;
[OutputConstructor]
private VMwareCbtProtectedDiskDetailsResponse(
double capacityInBytes,
string diskEncryptionSetId,
string diskId,
string diskName,
string diskPath,
string? diskType,
string isOSDisk,
string logStorageAccountId,
string logStorageAccountSasSecretName,
string seedManagedDiskId,
string targetManagedDiskId)
{
CapacityInBytes = capacityInBytes;
DiskEncryptionSetId = diskEncryptionSetId;
DiskId = diskId;
DiskName = diskName;
DiskPath = diskPath;
DiskType = diskType;
IsOSDisk = isOSDisk;
LogStorageAccountId = logStorageAccountId;
LogStorageAccountSasSecretName = logStorageAccountSasSecretName;
SeedManagedDiskId = seedManagedDiskId;
TargetManagedDiskId = targetManagedDiskId;
}
}
}
| 29.707071 | 81 | 0.588915 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/RecoveryServices/V20180110/Outputs/VMwareCbtProtectedDiskDetailsResponse.cs | 2,941 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Text;
using System.Runtime.InteropServices;
#pragma warning disable 1591
namespace Microsoft.Diagnostics.Runtime.Interop
{
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("edbed635-372e-4dab-bbfe-ed0d2f63be81")]
public interface IDebugClient2 : IDebugClient
{
/* IDebugClient */
[PreserveSig]
new int AttachKernel(
[In] DEBUG_ATTACH Flags,
[In, MarshalAs(UnmanagedType.LPStr)] string ConnectOptions);
[PreserveSig]
new int GetKernelConnectionOptions(
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer,
[In] Int32 BufferSize,
[Out] out UInt32 OptionsSize);
[PreserveSig]
new int SetKernelConnectionOptions(
[In, MarshalAs(UnmanagedType.LPStr)] string Options);
[PreserveSig]
new int StartProcessServer(
[In] DEBUG_CLASS Flags,
[In, MarshalAs(UnmanagedType.LPStr)] string Options,
[In] IntPtr Reserved);
[PreserveSig]
new int ConnectProcessServer(
[In, MarshalAs(UnmanagedType.LPStr)] string RemoteOptions,
[Out] out UInt64 Server);
[PreserveSig]
new int DisconnectProcessServer(
[In] UInt64 Server);
[PreserveSig]
new int GetRunningProcessSystemIds(
[In] UInt64 Server,
[Out, MarshalAs(UnmanagedType.LPArray)] UInt32[] Ids,
[In] UInt32 Count,
[Out] out UInt32 ActualCount);
[PreserveSig]
new int GetRunningProcessSystemIdByExecutableName(
[In] UInt64 Server,
[In, MarshalAs(UnmanagedType.LPStr)] string ExeName,
[In] DEBUG_GET_PROC Flags,
[Out] out UInt32 Id);
[PreserveSig]
new int GetRunningProcessDescription(
[In] UInt64 Server,
[In] UInt32 SystemId,
[In] DEBUG_PROC_DESC Flags,
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder ExeName,
[In] Int32 ExeNameSize,
[Out] out UInt32 ActualExeNameSize,
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Description,
[In] Int32 DescriptionSize,
[Out] out UInt32 ActualDescriptionSize);
[PreserveSig]
new int AttachProcess(
[In] UInt64 Server,
[In] UInt32 ProcessID,
[In] DEBUG_ATTACH AttachFlags);
[PreserveSig]
new int CreateProcess(
[In] UInt64 Server,
[In, MarshalAs(UnmanagedType.LPStr)] string CommandLine,
[In] DEBUG_CREATE_PROCESS Flags);
[PreserveSig]
new int CreateProcessAndAttach(
[In] UInt64 Server,
[In, MarshalAs(UnmanagedType.LPStr)] string CommandLine,
[In] DEBUG_CREATE_PROCESS Flags,
[In] UInt32 ProcessId,
[In] DEBUG_ATTACH AttachFlags);
[PreserveSig]
new int GetProcessOptions(
[Out] out DEBUG_PROCESS Options);
[PreserveSig]
new int AddProcessOptions(
[In] DEBUG_PROCESS Options);
[PreserveSig]
new int RemoveProcessOptions(
[In] DEBUG_PROCESS Options);
[PreserveSig]
new int SetProcessOptions(
[In] DEBUG_PROCESS Options);
[PreserveSig]
new int OpenDumpFile(
[In, MarshalAs(UnmanagedType.LPStr)] string DumpFile);
[PreserveSig]
new int WriteDumpFile(
[In, MarshalAs(UnmanagedType.LPStr)] string DumpFile,
[In] DEBUG_DUMP Qualifier);
[PreserveSig]
new int ConnectSession(
[In] DEBUG_CONNECT_SESSION Flags,
[In] UInt32 HistoryLimit);
[PreserveSig]
new int StartServer(
[In, MarshalAs(UnmanagedType.LPStr)] string Options);
[PreserveSig]
new int OutputServer(
[In] DEBUG_OUTCTL OutputControl,
[In, MarshalAs(UnmanagedType.LPStr)] string Machine,
[In] DEBUG_SERVERS Flags);
[PreserveSig]
new int TerminateProcesses();
[PreserveSig]
new int DetachProcesses();
[PreserveSig]
new int EndSession(
[In] DEBUG_END Flags);
[PreserveSig]
new int GetExitCode(
[Out] out UInt32 Code);
[PreserveSig]
new int DispatchCallbacks(
[In] UInt32 Timeout);
[PreserveSig]
new int ExitDispatch(
[In, MarshalAs(UnmanagedType.Interface)] IDebugClient Client);
[PreserveSig]
new int CreateClient(
[Out, MarshalAs(UnmanagedType.Interface)] out IDebugClient Client);
[PreserveSig]
new int GetInputCallbacks(
[Out, MarshalAs(UnmanagedType.Interface)] out IDebugInputCallbacks Callbacks);
[PreserveSig]
new int SetInputCallbacks(
[In, MarshalAs(UnmanagedType.Interface)] IDebugInputCallbacks Callbacks);
/* GetOutputCallbacks could a conversion thunk from the debugger engine so we can't specify a specific interface */
[PreserveSig]
new int GetOutputCallbacks(
[Out] out IDebugOutputCallbacks Callbacks);
/* We may have to pass a debugger engine conversion thunk back in so we can't specify a specific interface */
[PreserveSig]
new int SetOutputCallbacks(
[In] IDebugOutputCallbacks Callbacks);
[PreserveSig]
new int GetOutputMask(
[Out] out DEBUG_OUTPUT Mask);
[PreserveSig]
new int SetOutputMask(
[In] DEBUG_OUTPUT Mask);
[PreserveSig]
new int GetOtherOutputMask(
[In, MarshalAs(UnmanagedType.Interface)] IDebugClient Client,
[Out] out DEBUG_OUTPUT Mask);
[PreserveSig]
new int SetOtherOutputMask(
[In, MarshalAs(UnmanagedType.Interface)] IDebugClient Client,
[In] DEBUG_OUTPUT Mask);
[PreserveSig]
new int GetOutputWidth(
[Out] out UInt32 Columns);
[PreserveSig]
new int SetOutputWidth(
[In] UInt32 Columns);
[PreserveSig]
new int GetOutputLinePrefix(
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer,
[In] Int32 BufferSize,
[Out] out UInt32 PrefixSize);
[PreserveSig]
new int SetOutputLinePrefix(
[In, MarshalAs(UnmanagedType.LPStr)] string Prefix);
[PreserveSig]
new int GetIdentity(
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer,
[In] Int32 BufferSize,
[Out] out UInt32 IdentitySize);
[PreserveSig]
new int OutputIdentity(
[In] DEBUG_OUTCTL OutputControl,
[In] UInt32 Flags,
[In, MarshalAs(UnmanagedType.LPStr)] string Format);
/* GetEventCallbacks could a conversion thunk from the debugger engine so we can't specify a specific interface */
[PreserveSig]
new int GetEventCallbacks(
[Out] out IDebugEventCallbacks Callbacks);
/* We may have to pass a debugger engine conversion thunk back in so we can't specify a specific interface */
[PreserveSig]
new int SetEventCallbacks(
[In] IDebugEventCallbacks Callbacks);
[PreserveSig]
new int FlushCallbacks();
/* IDebugClient2 */
[PreserveSig]
int WriteDumpFile2(
[In, MarshalAs(UnmanagedType.LPStr)] string DumpFile,
[In] DEBUG_DUMP Qualifier,
[In] DEBUG_FORMAT FormatFlags,
[In, MarshalAs(UnmanagedType.LPStr)] string Comment);
[PreserveSig]
int AddDumpInformationFile(
[In, MarshalAs(UnmanagedType.LPStr)] string InfoFile,
[In] DEBUG_DUMP_FILE Type);
[PreserveSig]
int EndProcessServer(
[In] UInt64 Server);
[PreserveSig]
int WaitForProcessServerEnd(
[In] UInt32 Timeout);
[PreserveSig]
int IsKernelDebuggerEnabled();
[PreserveSig]
int TerminateCurrentProcess();
[PreserveSig]
int DetachCurrentProcess();
[PreserveSig]
int AbandonCurrentProcess();
}
} | 30.923913 | 123 | 0.604569 | [
"MIT"
] | Bhaskers-Blu-Org2/DbgShell | ClrMemDiag/Debugger/IDebugClient2.cs | 8,537 | C# |
namespace Paseto.Tests.Vectors;
using System.Diagnostics;
using Newtonsoft.Json;
[DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")]
public class PaserkTestItem
{
private string DebuggerDisplay => Name ?? $"{{{typeof(PaserkTestItem)}}}";
public string Name { get; set; }
public string Key { get; set; }
public string Paserk { get; set; }
} | 23.875 | 79 | 0.65445 | [
"MIT"
] | idaviddesmet/paseto-dotnet | tests/Paseto.Tests/Vectors/PaserkTestItem.cs | 384 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Avalonia.Controls;
using Avalonia.Dialogs;
using Avalonia.Layout;
using Avalonia.Markup.Xaml;
#pragma warning disable 4014
namespace ControlCatalog.Pages
{
public class DialogsPage : UserControl
{
public DialogsPage()
{
this.InitializeComponent();
List<FileDialogFilter> GetFilters()
{
if (this.FindControl<CheckBox>("UseFilters").IsChecked != true)
return null;
return new List<FileDialogFilter>
{
new FileDialogFilter
{
Name = "Text files (.txt)", Extensions = new List<string> {"txt"}
},
new FileDialogFilter
{
Name = "All files",
Extensions = new List<string> {"*"}
}
};
}
this.FindControl<Button>("OpenFile").Click += delegate
{
new OpenFileDialog()
{
Title = "Open file",
Filters = GetFilters(),
// Almost guaranteed to exist
InitialFileName = Assembly.GetEntryAssembly()?.GetModules().FirstOrDefault()?.FullyQualifiedName
}.ShowAsync(GetWindow());
};
this.FindControl<Button>("SaveFile").Click += delegate
{
new SaveFileDialog()
{
Title = "Save file",
Filters = GetFilters(),
InitialFileName = "test.txt"
}.ShowAsync(GetWindow());
};
this.FindControl<Button>("SelectFolder").Click += delegate
{
new OpenFolderDialog()
{
Title = "Select folder",
}.ShowAsync(GetWindow());
};
this.FindControl<Button>("OpenBoth").Click += async delegate
{
var res = await new OpenFileDialog()
{
Title = "Select both",
AllowMultiple = true
}.ShowManagedAsync(GetWindow(), new ManagedFileDialogOptions
{
AllowDirectorySelection = true
});
if (res != null)
Console.WriteLine("Selected: \n" + string.Join("\n", res));
};
this.FindControl<Button>("DecoratedWindow").Click += delegate
{
new DecoratedWindow().Show();
};
this.FindControl<Button>("DecoratedWindowDialog").Click += delegate
{
new DecoratedWindow().ShowDialog(GetWindow());
};
this.FindControl<Button>("Dialog").Click += delegate
{
var window = CreateSampleWindow();
window.Height = 200;
window.ShowDialog(GetWindow());
};
this.FindControl<Button>("DialogNoTaskbar").Click += delegate
{
var window = CreateSampleWindow();
window.Height = 200;
window.ShowInTaskbar = false;
window.ShowDialog(GetWindow());
};
this.FindControl<Button>("OwnedWindow").Click += delegate
{
var window = CreateSampleWindow();
window.Show(GetWindow());
};
this.FindControl<Button>("OwnedWindowNoTaskbar").Click += delegate
{
var window = CreateSampleWindow();
window.ShowInTaskbar = false;
window.Show(GetWindow());
};
}
private Window CreateSampleWindow()
{
Button button;
var window = new Window
{
Height = 200,
Width = 200,
Content = new StackPanel
{
Spacing = 4,
Children =
{
new TextBlock { Text = "Hello world!" },
(button = new Button
{
HorizontalAlignment = HorizontalAlignment.Center,
Content = "Click to close"
})
}
},
WindowStartupLocation = WindowStartupLocation.CenterOwner
};
button.Click += (_, __) => window.Close();
return window;
}
Window GetWindow() => (Window)this.VisualRoot;
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
| 32.503311 | 116 | 0.4511 | [
"MIT"
] | 0x90d/Avalonia | samples/ControlCatalog/Pages/DialogsPage.xaml.cs | 4,908 | C# |
using System;
namespace Amw.Identity.NetfxDemo.Areas.HelpPage
{
/// <summary>
/// This represents an invalid sample on the help page. There's a display template named InvalidSample associated with this class.
/// </summary>
public class InvalidSample
{
public InvalidSample(string errorMessage)
{
if (errorMessage == null)
{
throw new ArgumentNullException("errorMessage");
}
ErrorMessage = errorMessage;
}
public string ErrorMessage { get; private set; }
public override bool Equals(object obj)
{
InvalidSample other = obj as InvalidSample;
return other != null && ErrorMessage == other.ErrorMessage;
}
public override int GetHashCode()
{
return ErrorMessage.GetHashCode();
}
public override string ToString()
{
return ErrorMessage;
}
}
} | 26.594595 | 134 | 0.578252 | [
"MIT"
] | amwitx/Amw.Core | Identity/Amw.Identity.NetfxDemo/Areas/HelpPage/SampleGeneration/InvalidSample.cs | 984 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using Xunit;
namespace System.ComponentModel.Composition.Registration.Tests
{
public class PartBuilderInterfaceTests
{
public interface IFirst {}
public interface ISecond {}
public interface IThird {}
public interface IFourth {}
public interface IFifth : IFourth {}
public class Standard : IFirst, ISecond, IThird, IFifth
{
}
public class Dippy : IFirst, ISecond, IThird, IFifth, IDisposable
{
public void Dispose() {}
}
public class BareClass {}
public class Base : IFirst, ISecond {}
public class Derived : Base, IThird, IFifth {}
public class Importer
{
[ImportMany] public IEnumerable<IFirst> First;
[ImportMany] public IEnumerable<ISecond> Second;
[ImportMany] public IEnumerable<IThird> Third;
[ImportMany] public IEnumerable<IFourth> Fourth;
[ImportMany] public IEnumerable<IFifth> Fifth;
[Import(AllowDefault=true)] public Base Base;
[Import(AllowDefault=true)] public Derived Derived;
[Import(AllowDefault=true)] public Dippy Dippy;
[Import(AllowDefault=true)] public Standard Standard;
[Import(AllowDefault=true)] public IDisposable Disposable;
[Import(AllowDefault=true)] public BareClass BareClass;
}
[Fact]
public void StandardExportInterfacesShouldWork()
{
var builder = new RegistrationBuilder();
builder.ForTypesMatching( (t) => true ).ExportInterfaces( (iface) => iface != typeof(System.IDisposable), (iface, bldr) => bldr.AsContractType((Type)iface) );
builder.ForTypesMatching((t) => t.GetInterfaces().Where((iface) => iface != typeof(System.IDisposable)).Count() == 0).Export();
var types = new Type[] { typeof(Standard), typeof(Dippy), typeof(Derived), typeof(BareClass) };
var catalog = new TypeCatalog(types, builder);
CompositionService cs = catalog.CreateCompositionService();
var importer = new Importer();
cs.SatisfyImportsOnce(importer);
Assert.NotNull(importer.First);
Assert.True(importer.First.Count() == 3);
Assert.NotNull(importer.Second);
Assert.True(importer.Second.Count() == 3);
Assert.NotNull(importer.Third);
Assert.True(importer.Third.Count() == 3);
Assert.NotNull(importer.Fourth);
Assert.True(importer.Fourth.Count() == 3);
Assert.NotNull(importer.Fifth);
Assert.True(importer.Fifth.Count() == 3);
Assert.Null(importer.Base);
Assert.Null(importer.Derived);
Assert.Null(importer.Dippy);
Assert.Null(importer.Standard);
Assert.Null(importer.Disposable);
Assert.NotNull(importer.BareClass);
}
[Fact]
public void StandardExportInterfacesDefaultContractShouldWork()
{ //Same test as above only using default export builder
var builder = new RegistrationBuilder();
builder.ForTypesMatching( (t) => true ).ExportInterfaces( (iface) => iface != typeof(System.IDisposable) );
builder.ForTypesMatching((t) => t.GetInterfaces().Where((iface) => iface != typeof(System.IDisposable)).Count() == 0).Export();
var types = new Type[] { typeof(Standard), typeof(Dippy), typeof(Derived), typeof(BareClass) };
var catalog = new TypeCatalog(types, builder);
CompositionService cs = catalog.CreateCompositionService();
var importer = new Importer();
cs.SatisfyImportsOnce(importer);
Assert.NotNull(importer.First);
Assert.True(importer.First.Count() == 3);
Assert.NotNull(importer.Second);
Assert.True(importer.Second.Count() == 3);
Assert.NotNull(importer.Third);
Assert.True(importer.Third.Count() == 3);
Assert.NotNull(importer.Fourth);
Assert.True(importer.Fourth.Count() == 3);
Assert.NotNull(importer.Fifth);
Assert.True(importer.Fifth.Count() == 3);
Assert.Null(importer.Base);
Assert.Null(importer.Derived);
Assert.Null(importer.Dippy);
Assert.Null(importer.Standard);
Assert.Null(importer.Disposable);
Assert.NotNull(importer.BareClass);
}
}
}
| 41.369748 | 170 | 0.606134 | [
"MIT"
] | 2E0PGS/corefx | src/System.ComponentModel.Composition.Registration/tests/System/ComponentModel/Composition/Registration/PartBuilderInterfaceTests.cs | 4,923 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DialogueManager : MonoBehaviour {
public static DialogueManager instance;
[Header("UI Elements")]
public GameObject dialoguePanel;
public Text dialogueText;
public GameObject pressSomethingToContinueText;
private Queue<string> m_sentences;
private Queue<Dialogue> m_dialogues;
private string m_currentSentenceBeingTyped;
private bool m_isTypingSentence;
void Awake() {
if (instance == null) {
instance = this;
// DontDestroyOnLoad(gameObject);
} else {
Destroy(gameObject);
}
m_sentences = new Queue<string>();
m_dialogues = new Queue<Dialogue>();
dialoguePanel.SetActive(false);
pressSomethingToContinueText.SetActive(false);
}
void Update() {
if(Input.GetButtonDown("Submit") || Input.GetKeyDown(KeyCode.Return)) {
DisplayNextSentence();
}
}
public void StartDialogue(Dialogue dialogue) {
dialoguePanel.SetActive(true);
m_sentences.Clear();
foreach(string sentence in dialogue.sentences) {
m_sentences.Enqueue(sentence);
}
DisplayNextSentence();
}
public void StartDialogue(Dialogue[] dialogues) {
m_dialogues.Clear();
foreach(Dialogue dialogue in dialogues) {
m_dialogues.Enqueue(dialogue);
}
StartDialogue(m_dialogues.Dequeue());
}
public void DisplayNextSentence() {
if(m_isTypingSentence) {
StopAllCoroutines();
dialogueText.text = m_currentSentenceBeingTyped;
pressSomethingToContinueText.SetActive(true);
m_isTypingSentence = false;
return;
}
if(m_sentences.Count == 0) {
EndDialog();
return;
}
string sentence = m_sentences.Dequeue();
StopAllCoroutines();
StartCoroutine(TypeSentence(sentence));
}
IEnumerator TypeSentence(string sentence) {
m_isTypingSentence = true;
pressSomethingToContinueText.SetActive(false);
m_currentSentenceBeingTyped = sentence;
dialogueText.text = "";
foreach(char letter in sentence.ToCharArray()) {
dialogueText.text += letter;
yield return null;
}
pressSomethingToContinueText.SetActive(true);
m_isTypingSentence = false;
}
void EndDialog() {
if(m_dialogues.Count > 0) {
StartDialogue(m_dialogues.Dequeue());
} else {
dialoguePanel.SetActive(false);
GameManagement.instance.LoadNextLevel();
}
}
}
| 23.514563 | 74 | 0.708092 | [
"MIT"
] | guilhermepo2/jimjam2 | JimJam2/Assets/Scripts/Dialogue/DialogueManager.cs | 2,424 | C# |
using Engine.Actions;
namespace Engine.Models
{
public class GameItem
{
public enum ItemCategory
{
Miscellaneous,
Weapon,
Consumable
}
public ItemCategory Category { get; }
public int ItemTypeID { get; }
public string Name { get; }
public int Price { get; }
public bool IsUnique { get; }
public IAction Action { get; set; }
public GameItem(ItemCategory category, int itemTypeID, string name, int price,
bool isUnique = false, IAction action = null)
{
Category = category;
ItemTypeID = itemTypeID;
Name = name;
Price = price;
IsUnique = isUnique;
Action = action;
}
public void PerformAction(LivingEntity actor, LivingEntity target)
{
Action?.Execute(actor, target);
}
public GameItem Clone()
{
return new GameItem(Category, ItemTypeID, Name, Price, IsUnique, Action);
}
}
} | 25.97619 | 86 | 0.533456 | [
"MIT"
] | Boyce-Bellair/rphOriginalFiles | Engine/Models/GameItem.cs | 1,093 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Ckafka.V20190819.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeGroupOffsetsRequest : AbstractModel
{
/// <summary>
/// (过滤条件)按照实例 ID 过滤
/// </summary>
[JsonProperty("InstanceId")]
public string InstanceId{ get; set; }
/// <summary>
/// Kafka 消费分组
/// </summary>
[JsonProperty("Group")]
public string Group{ get; set; }
/// <summary>
/// group 订阅的主题名称数组,如果没有该数组,则表示指定的 group 下所有 topic 信息
/// </summary>
[JsonProperty("Topics")]
public string[] Topics{ get; set; }
/// <summary>
/// 模糊匹配 topicName
/// </summary>
[JsonProperty("SearchWord")]
public string SearchWord{ get; set; }
/// <summary>
/// 本次查询的偏移位置,默认为0
/// </summary>
[JsonProperty("Offset")]
public long? Offset{ get; set; }
/// <summary>
/// 本次返回结果的最大个数,默认为50,最大值为50
/// </summary>
[JsonProperty("Limit")]
public long? Limit{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "InstanceId", this.InstanceId);
this.SetParamSimple(map, prefix + "Group", this.Group);
this.SetParamArraySimple(map, prefix + "Topics.", this.Topics);
this.SetParamSimple(map, prefix + "SearchWord", this.SearchWord);
this.SetParamSimple(map, prefix + "Offset", this.Offset);
this.SetParamSimple(map, prefix + "Limit", this.Limit);
}
}
}
| 31.151899 | 81 | 0.598537 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Ckafka/V20190819/Models/DescribeGroupOffsetsRequest.cs | 2,625 | C# |
/******************************************************************************
* Spine Runtimes Software License v2.5
*
* Copyright (c) 2013-2016, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install, execute, and perform the Spine
* Runtimes software and derivative works solely for personal or internal
* use. Without the written permission of Esoteric Software (see Section 2 of
* the Spine Software License Agreement), you may not (a) modify, translate,
* adapt, or develop new applications using the Spine Runtimes or otherwise
* create derivative works or improvements of the Spine Runtimes or (b) remove,
* delete, alter, or obscure any trademarks or any copyright, trademark, patent,
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
* USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
using UnityEngine;
using UnityEditor;
using Spine.Unity.Modules;
namespace Spine.Unity.Editor {
using Editor = UnityEditor.Editor;
public class SlotBlendModesEditor : Editor {
[MenuItem("CONTEXT/SkeletonRenderer/Add Slot Blend Modes Component")]
static void AddSlotBlendModesComponent (MenuCommand command) {
var skeletonRenderer = (SkeletonRenderer)command.context;
skeletonRenderer.gameObject.AddComponent<SlotBlendModes>();
}
}
}
| 48.729167 | 82 | 0.706712 | [
"BSD-3-Clause"
] | kmranrg/SaveKitty | Assets/Spine/Editor/spine-unity/Modules/SlotBlendModes/Editor/SlotBlendModesEditor.cs | 2,341 | C# |
using Kati.Module_Hub;
using System;
using System.Collections.Generic;
using System.Text;
namespace Kati.Data_Modules.GlobalClasses {
/// <summary>
/// Generic parent of all Module Controllers
/// </summary>
public class Controller {
public static Random dice = new Random();
private ModuleLib lib;
private GameData game;
private CharacterData npc;
private Parser parser;
public Controller(string path) {
Lib = new ModuleLib(path);
Game = new GameData();
Npc = new CharacterData();
parser = new Parser(this);
}
public ModuleLib Lib { get => lib; set => lib = value; }
public GameData Game { get => game; set => game = value; }
public CharacterData Npc { get => npc; set => npc = value; }
public Parser Parser { get => parser; set => parser = value; }
//need to update game data
//need to update character data
//need to decide which topic
//need to decide which type of topic
//a list of dialogue topics can be found in Lib.Keys
//overridable method that decides which topic to talk about
}
}
| 28.761905 | 70 | 0.601821 | [
"MIT"
] | ResoTheRed/NLG | Kati/Data_Modules/GlobalClasses/Controller.cs | 1,210 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace CarStore.Data.Migrations
{
public partial class AddedOrderStatus : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "Status",
table: "Orders",
nullable: false,
defaultValue: 0);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Status",
table: "Orders");
}
}
}
| 25.916667 | 71 | 0.564309 | [
"MIT"
] | SimeonGerginov/CarStoreNET | Source/Data/CarStore.Data/Migrations/20190202100342_AddedOrderStatus.cs | 624 | C# |
using System;
using System.Globalization;
using System.Reflection;
using System.Resources;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace PlantHunter.Mobile.Core.MarkupExtensions
{
[ContentProperty( "Text" )]
public class TranslateExtension : IMarkupExtension
{
public string Text { get; set; }
public string StringFormat { get; set; }
public object ProvideValue( IServiceProvider serviceProvider )
{
if ( Text == null )
return null;
var assembly = typeof( TranslateExtension ).GetTypeInfo().Assembly;
var assemblyName = assembly.GetName();
var resourceManager = new ResourceManager( $"{assemblyName.Name}.Resources", assembly );
string result = resourceManager.GetString( Text, CultureInfo.CurrentCulture );
if ( !string.IsNullOrWhiteSpace( StringFormat ) )
{
result = string.Format( StringFormat, result );
}
return result;
}
}
} | 25.628571 | 91 | 0.730212 | [
"MIT"
] | HACC2018/Canoe-tree | PlantHunter.Mobile/PlantHunter.Mobile.Core/MarkupExtensions/TranslateExtension.cs | 899 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
public class driving : MonoBehaviour
{
AudioSource engineSound;
// Start is called before the first frame update
void Start()
{
lastPosition = transform.position;
}
public GameObject speedometer;
public GameObject wheel;
float wheelRotation = 0f;
float lastVelocity = 0f;
public static float mileDistance = 1760f;
float mile_fraction = 0f;
int miles = 12281;
public GameObject o_odometer;
public float carSpeedMult = 900f;
public GameObject lakitu;
public bool stall = false;
public int stallStage = 0;
float yJogTime = 0f;
Vector3 lastPosition;
// Update is called once per frame
void Update()
{
#if UNITY_STANDALONE
if (Input.GetAxis("Escape") != 0)
{
Application.Quit();
}
#endif
if(triggers == 0)
{
if(stallSound != null)
{
Destroy(stallSound);
}
stallTime = 0f;
}
if(stallStage == 1)
{
GetComponent<AudioSource>().enabled = false;
// Spawn lakitu at last good point and move towards player.
int lastStopInMiles = GetComponent<mapper>().magnitude / 6688 * 380;
float currentPositionInMiles = (GetComponent<mapper>().magnitude * GetComponent<mapper>().magnitudeDistance + transform.position.z) / mileDistance;
float lastGoodZ = (currentPositionInMiles - lastStopInMiles) * mileDistance;
lakitu.SetActive(true);
lakitu.transform.localPosition = new Vector3(0, 0.868f, -lastGoodZ + -0.6f);
stallStage += 1;
// Start blinkers
transform.GetChild(18).GetComponent<blinker>().setBlinkerOn();
transform.GetChild(19).GetComponent<blinker>().setBlinkerOn();
}
else if (stallStage == 2)
{
lakitu.transform.localPosition += new Vector3(0, 0, Time.deltaTime * mileDistance * 65f / 3600f);
if(lakitu.transform.localPosition.z >= -0.6f)
{
lakitu.transform.localPosition = new Vector3(0, 0.868f, -0.6f);
stallStage += 1;
}
}
Rigidbody carBody = this.GetComponent<Rigidbody>();
//Progress - originally * 200
float zForce = Input.GetAxis("Vertical") * Time.deltaTime * carSpeedMult;
float cZForce = (Input.GetAxis("XboxRightTrigger") - Input.GetAxis("XboxLeftTrigger")) * Time.deltaTime * carSpeedMult;
zForce = Mathf.Abs(zForce) > Mathf.Abs(cZForce) ? zForce : cZForce;
float pull = -0.15f;
float xForce = zForce != 0 ? Input.GetAxis("Horizontal") * Time.deltaTime * 100f + pull : 0f;
float axisHorizontal = Input.GetAxis("Horizontal");
if (axisHorizontal != 0f)
{
if (axisHorizontal > 0f)
{
if(wheelRotation < 15f)
{
wheelRotation += 1;
wheel.transform.Rotate(new Vector3(0f, 1f, 0f));
}
}
else
{
if(wheelRotation > -15f)
{
wheelRotation -= 1;
wheel.transform.Rotate(new Vector3(0f, -1f, 0f));
}
}
}
else
{
if(wheelRotation > 0f)
{
wheelRotation -= 1;
wheel.transform.Rotate(new Vector3(0f, -1f, 0f));
}
else if(wheelRotation < 0f)
{
wheelRotation += 1;
wheel.transform.Rotate(new Vector3(0f, 1f, 0f));
}
}
if(GetComponent<mapper>().magnitude == 0 && stall)
{
setStall(false);
carBody.velocity = Vector3.zero;
}
if (!stall)
{
carBody.AddRelativeForce(new Vector3(xForce, 0, zForce));
}
else
{
if(stallStage == 3)
{
float xDiff = -2.75f - transform.position.x;
if (GetComponent<mapper>().magnitude <= 0)
{
xDiff = 2.75f - transform.position.x;
}
Vector3 newXForce = Vector3.RotateTowards(new Vector3(0, 0, Time.deltaTime * 100f), new Vector3(xDiff, 0, 0), 100, 100);
Vector3 newZForce = new Vector3(0f, 0f, Time.deltaTime * carSpeedMult);
if (GetComponent<mapper>().magnitude <= 0)
{
carBody.AddRelativeForce(newXForce + newZForce);
}
else
{
carBody.AddRelativeForce(newXForce - newZForce);
}
}
}
if(carBody.velocity.z - lastVelocity < 0.5 && carBody.velocity.z - lastVelocity > -0.5)
{
}
else
{
float speedRatio = Mathf.Round(carBody.velocity.z) / 30f;
speedometer.transform.localRotation = Quaternion.Euler(90f + 110f * speedRatio, 90f, -90f);
lastVelocity = carBody.velocity.z;
}
if(stallStage == 0)
{
mile_fraction += Vector3.Distance(transform.position, lastPosition);
}
if(mile_fraction >= mileDistance)
{
miles += 1;
mile_fraction = 0;
Text odometer_text = o_odometer.GetComponent<Text>();
odometer_text.text = miles + "";
}
if(transform.position.x != lastPosition.x || transform.position.z != lastPosition.z)
{
yJogTime += Time.deltaTime;
transform.position = new Vector3(transform.position.x, 0.25f * Mathf.Sin(yJogTime) + 1.7f, transform.position.z);
if (yJogTime > 2 * Mathf.PI)
{
yJogTime -= 2 * Mathf.PI;
}
}
lastPosition = transform.position;
}
public void setStall(bool stall)
{
this.stall = stall;
if (stall)
{
if(stallStage == 0)
{
stallStage = 1;
}
}
else
{
stallStage = 0;
lakitu.SetActive(false);
transform.GetChild(18).GetComponent<blinker>().setBlinkerOff();
transform.GetChild(19).GetComponent<blinker>().setBlinkerOff();
GetComponent<AudioSource>().enabled = true;
}
}
float stallTime = 0f;
GameObject stallSound;
public AudioClip stallClip;
int triggers = 0;
public void addStallTime(float addTime)
{
if (stallStage == 0)
{
if (stallTime == 0f)
{
stallSound = Instantiate(new GameObject(), transform);
stallSound.AddComponent<setVolume>();
AudioSource toStall = stallSound.AddComponent<AudioSource>();
toStall.clip = stallClip;
toStall.loop = false;
toStall.Play();
}
stallTime += addTime;
if (stallTime > 8.0f)
{
setStall(true);
stallTime = 0f;
Destroy(stallSound);
}
}
}
public void addTrigger(int toAdd)
{
triggers += toAdd;
}
}
| 28.11236 | 159 | 0.514788 | [
"Unlicense"
] | bearsdotzone/DesertGaySolidarity | Assets/Resources/Scripts/driving.cs | 7,508 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Events
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Binary;
/// <summary>
/// Base event implementation.
/// </summary>
public abstract class EventBase : IEvent, IEquatable<EventBase>
{
/** */
private readonly IgniteGuid _id;
/** */
private readonly long _localOrder;
/** */
private readonly IClusterNode _node;
/** */
private readonly string _message;
/** */
private readonly int _type;
/** */
private readonly string _name;
/** */
private readonly DateTime _timestamp;
/// <summary>
/// Initializes a new instance of the <see cref="EventBase"/> class.
/// </summary>
/// <param name="r">The reader to read data from.</param>
protected EventBase(IBinaryRawReader r)
{
var id = IgniteGuid.Read(r);
Debug.Assert(id.HasValue);
_id = id.Value;
_localOrder = r.ReadLong();
_node = ReadNode(r);
_message = r.ReadString();
_type = r.ReadInt();
_name = r.ReadString();
var timestamp = r.ReadTimestamp();
Debug.Assert(timestamp.HasValue);
_timestamp = timestamp.Value;
}
/// <summary>
/// Gets globally unique ID of this event.
/// </summary>
public IgniteGuid Id
{
get { return _id; }
}
/// <summary>
/// Gets locally unique ID that is atomically incremented for each event. Unlike global <see cref="Id" />
/// this local ID can be used for ordering events on this node.
/// <para />
/// Note that for performance considerations Ignite doesn't order events globally.
/// </summary>
public long LocalOrder
{
get { return _localOrder; }
}
/// <summary>
/// Node where event occurred and was recorded.
/// </summary>
public IClusterNode Node
{
get { return _node; }
}
/// <summary>
/// Gets optional message for this event.
/// </summary>
public string Message
{
get { return _message; }
}
/// <summary>
/// Gets type of this event. All system event types are defined in <see cref="EventType" />
/// </summary>
public int Type
{
get { return _type; }
}
/// <summary>
/// Gets name of this event.
/// </summary>
public string Name
{
get { return _name; }
}
/// <summary>
/// Gets event timestamp. Timestamp is local to the node on which this event was produced.
/// Note that more than one event can be generated with the same timestamp.
/// For ordering purposes use <see cref="LocalOrder" /> instead.
/// </summary>
public DateTime Timestamp
{
get { return _timestamp; }
}
/// <summary>
/// Gets shortened version of ToString result.
/// </summary>
public virtual string ToShortString()
{
return ToString();
}
/// <summary>
/// Determines whether the specified object is equal to this instance.
/// </summary>
/// <param name="other">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified object is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(EventBase other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return _id.Equals(other._id);
}
/// <summary>
/// Determines whether the specified object is equal to this instance.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified object is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((EventBase) obj);
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
return _id.GetHashCode();
}
/// <summary>
/// Returns a <see cref="string" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="string" /> that represents this instance.
/// </returns>
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture,
"{0} [Name={1}, Type={2}, Timestamp={3}, Message={4}]", GetType().Name, Name, Type, Timestamp, Message);
}
/// <summary>
/// Reads a node from stream.
/// </summary>
/// <param name="reader">Reader.</param>
/// <returns>Node or null.</returns>
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
protected static IClusterNode ReadNode(IBinaryRawReader reader)
{
return ((BinaryReader)reader).Marshaller.Ignite.GetNode(reader.ReadGuid());
}
}
} | 32.433962 | 121 | 0.562245 | [
"CC0-1.0"
] | andyglick/apache-ignite | modules/platforms/dotnet/Apache.Ignite.Core/Events/EventBase.cs | 6,876 | C# |
using NUnit.Framework;
using System.Collections.Generic;
using System.IO;
#if UNITY_XCODE_API_BUILD
using UnityEditor.iOS.Xcode;
#else
using UnityEditor.iOS.Xcode.Fiftytwo;
#endif
namespace UnityEditor.iOS.Xcode.Tests
{
[TestFixture]
public class XcSchemeUpdating : TextTester
{
public XcSchemeUpdating() : base("XcSchemeTestFiles", "XcSchemeTestOutput", debug:false)
{
}
[Test]
public void ChangingBuildConfigurationWorks()
{
var xcscheme = new XcScheme();
xcscheme.ReadFromString(ReadSourceFile("base1.xcscheme"));
Assert.AreEqual("Debug", xcscheme.GetBuildConfiguration());
xcscheme.SetBuildConfiguration("MyConfiguration");
Assert.AreEqual("MyConfiguration", xcscheme.GetBuildConfiguration());
}
[Test]
public void OutputWorks()
{
TestXmlUpdate("base1.xcscheme", "test1.xcscheme", text =>
{
var xcscheme = new XcScheme();
xcscheme.ReadFromString(text);
xcscheme.SetBuildConfiguration("ReleaseForRunning");
return xcscheme.WriteToString();
});
}
}
}
| 28.511628 | 96 | 0.616639 | [
"MIT"
] | C0DEF52/XcodeAPI | Xcode.Tests/XcSchemeTests.cs | 1,226 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Speech.Recognition;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Friday
{
static class Program
{
static FridayConsole fridayConsole = null;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
fridayConsole = new FridayConsole();
Application.Run(fridayConsole);
}
}
}
| 19.5 | 65 | 0.653846 | [
"Apache-2.0"
] | michaelsalvia/friday | Friday/Program.cs | 548 | C# |
namespace TraktNet.Objects.Get.Shows
{
using Seasons;
using System;
using System.Collections.Generic;
/// <summary>Represents the collection progress of a Trakt show.</summary>
public class TraktShowCollectionProgress : TraktShowProgress, ITraktShowCollectionProgress
{
/// <summary>Gets or sets the UTC datetime, when the last collection occured.</summary>
public DateTime? LastCollectedAt { get; set; }
/// <summary>
/// Gets or sets the collected seasons. See also <seealso cref="ITraktSeasonCollectionProgress" />.
/// <para>Nullable</para>
/// </summary>
public IEnumerable<ITraktSeasonCollectionProgress> Seasons { get; set; }
}
}
| 36.2 | 107 | 0.679558 | [
"MIT"
] | henrikfroehling/Trakt.NET | Source/Lib/Trakt.NET/Objects/Get/Shows/Implementations/TraktShowCollectionProgress.cs | 726 | C# |
using System.Diagnostics;
using System.IO;
using UnityEditor;
// from arcadia
namespace Magic.Unity
{
/// <summary>
/// Facilities to run shell programs
/// </summary>
public static class Shell
{
public static readonly string MonoExecutablePath =
#if UNITY_EDITOR_OSX
Path.Combine(
EditorApplication.applicationPath,
"Contents/MonoBleedingEdge/bin/mono");
#elif UNITY_EDITOR_WIN
Path.Combine(
Path.GetDirectoryName(EditorApplication.applicationPath),
"Data/MonoBleedingEdge/bin/mono.exe");
#elif UNITY_EDITOR_LINUX
Path.Combine(
Path.GetDirectoryName(EditorApplication.applicationPath),
"Data/MonoBleedingEdge/bin/mono");
#endif
public static Process Run(string filename, string arguments = null, string workingDirectory = null)
{
Process process = new Process();
process.StartInfo.FileName = filename;
if (arguments != null) process.StartInfo.Arguments = arguments;
if (workingDirectory != null) process.StartInfo.WorkingDirectory = workingDirectory;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.UseShellExecute = false;
process.EnableRaisingEvents = true;
process.Start();
return process;
}
public static Process MonoRun(string pathToExe, string arguments, string workingDirectory)
{
return Run(MonoExecutablePath, pathToExe + " " + arguments, workingDirectory);
}
public static Process MonoRun(string pathToExe, string arguments)
{
return Run(MonoExecutablePath, pathToExe + " " + arguments);
}
public static Process MonoRun(string pathToExe)
{
return Run(MonoExecutablePath, pathToExe);
}
}
}
| 33.711864 | 107 | 0.632479 | [
"Apache-2.0"
] | nasser/Magic.Unity | Editor/Shell.cs | 1,989 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using UnityEngine;
using UnityEngine.Events;
using DTValidator.Internal;
namespace DTValidator.ValidationErrors {
public class ComponentValidationError : IComponentValidationError {
// PRAGMA MARK - Public Interface
public readonly int ComponentLocalId;
public readonly Type ComponentType;
public readonly MemberInfo MemberInfo;
public readonly object ContextObject;
public readonly string ComponentPath;
public ComponentValidationError(Component component, Type componentType, MemberInfo memberInfo, object contextObject) {
component_ = component;
ComponentLocalId = component.GetLocalId();
ComponentPath = component.gameObject.FullName();
ComponentType = componentType;
MemberInfo = memberInfo;
ContextObject = contextObject;
}
public override string ToString() {
return string.Format("CVE ({0}=>{1}) context: {2}", MemberInfo.DeclaringType.Name, MemberInfo.Name, ContextObject);
}
// PRAGMA MARK - IComponentValidationError Implementation
Component IComponentValidationError.Component {
get { return component_; }
}
// PRAGMA MARK - IValidationError Implementation
int IValidationError.ObjectLocalId {
get { return ComponentLocalId; }
}
Type IValidationError.ObjectType {
get { return ComponentType; }
}
MemberInfo IValidationError.MemberInfo {
get { return MemberInfo; }
}
object IValidationError.ContextObject {
get { return ContextObject; }
}
// PRAGMA MARK - Internal
private readonly Component component_;
}
}
| 25.446154 | 121 | 0.764813 | [
"MIT"
] | DarrenTsung/DTValidator | Validation/Editor/ValidationErrors/ComponentValidationError.cs | 1,654 | C# |
using DataCenter.Data;
using DataCenter.Helpers;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Types;
namespace DataCenter._02_HistoricalPrices
{
internal class HistoricalPrices : DataSource
{
public HistoricalPrices() : base() { }
public HistoricalPrices(bool reload) : base(reload) { }
public override async Task Prepare(DataContainer dataContainer)
{
// Delete old data
if (Reload)
Directory.Delete(Folder, true);
// Create folder
Directory.CreateDirectory(Folder);
// Inernal data
_InternalData internalData = new _InternalData();
// Draw header
base.DrawHeader();
// Download
await Download(dataContainer.Products);
// Parse
Parse(dataContainer.Products, internalData);
// SeDeSerialize
Cache(dataContainer, internalData);
// End info
Console.WriteLine();
}
private async Task Download(List<Product> products)
{
string prefix = "1/3 Downloading...";
Utils.DrawMessage(prefix, Utils.CreateProgressBar(Utils.ProgressBarLength, 0), ConsoleColor.Gray);
// Count when we update progress bar
int drawEvery = Utils.PercentIntervalByLength(products.Count);
// Basic url
string url = "http://real-chart.finance.yahoo.com/table.csv?s=___&d=0&e=0&f=2100&g=d&a=0&b=0&c=1900&ignore=.csv";
// Download
try
{
for (int i = 0; i < products.Count; ++i)
{
// Product
Product p = products[i];
// Prepare url
string productUrl = url.Replace("___", p.Symbol);
// Target file
string targetFile = Path.Combine(Folder, p.Symbol + ".csv");
// Download if needed
if (Reload || !File.Exists(targetFile))
await Downloader.DownloadFileAsync(productUrl, targetFile, null, null);
// Update progress bar
if (i % drawEvery == 0)
Utils.DrawMessage(prefix, Utils.CreateProgressBar(Utils.ProgressBarLength, (double)i / products.Count * 100.0), ConsoleColor.Gray);
}
}
catch (Exception ex)
{
Console.WriteLine();
Utils.DrawMessage("", ex.Message, ConsoleColor.Red);
Console.WriteLine();
System.Environment.Exit(1);
}
Utils.DrawMessage(prefix, Utils.CreateProgressBar(Utils.ProgressBarLength, 100), ConsoleColor.Green);
Console.WriteLine();
}
private void Parse(List<Product> products, _InternalData internalData)
{
string prefix = "2/3 Parsing...";
Utils.DrawMessage(prefix, Utils.CreateProgressBar(Utils.ProgressBarLength, 0), ConsoleColor.Gray);
// Count when we update progress bar
int drawEvery = Utils.PercentIntervalByLength(products.Count);
// Parsing
try
{
if (Reload || !File.Exists(SerializedFile))
{
for (int i = 0; i < products.Count; ++i)
{
// Product
Product p = products[i];
// Load lines
string[] lines = File.ReadAllLines(Path.Combine(Folder, p.Symbol) + ".csv");
// Check first line validity
if (lines[0] != "Date,Open,High,Low,Close,Volume,Adj Close")
throw new Exception("Invalid header for " + p.Symbol + ".csv");
// Process each line
for (int k = 1; k < lines.Length; ++k)
{
// Split line
string[] columns = lines[k].Split(new char[] { ',' });
// Parse date
DateTime date = DateTime.ParseExact(columns[0], "yyyy-MM-dd", CultureInfo.InvariantCulture);
// Parse price - adjusted close
double price = double.Parse(columns[6], CultureInfo.InvariantCulture);
// Set price for date
internalData.Events.Add(new _Event()
{
Symbol = p.Symbol,
Date = date,
Price = price
});
}
// Update progress bar
if (i % drawEvery == 0)
Utils.DrawMessage(prefix, Utils.CreateProgressBar(Utils.ProgressBarLength, (double)i / products.Count * 100.0), ConsoleColor.Gray);
}
}
}
catch (Exception ex)
{
Console.WriteLine();
Utils.DrawMessage("", ex.Message, ConsoleColor.Red);
Console.WriteLine();
System.Environment.Exit(1);
}
Utils.DrawMessage(prefix, Utils.CreateProgressBar(Utils.ProgressBarLength, 100), ConsoleColor.Green);
Console.WriteLine();
}
private void Cache(DataContainer dataContainer, _InternalData internalData)
{
string prefix = "3/3 Caching...";
Utils.DrawMessage(prefix, Utils.CreateProgressBar(Utils.ProgressBarLength, 0), ConsoleColor.Gray);
try
{
// Serialize or deserialize
_Cache cache = null;
if (Reload || !File.Exists(SerializedFile))
{
cache = new _Cache(internalData);
Serializer.Serialize(SerializedFile, cache);
}
else
cache = (_Cache)Serializer.Deserialize(SerializedFile);
Utils.DrawMessage(prefix, Utils.CreateProgressBar(Utils.ProgressBarLength, 50), ConsoleColor.Gray);
int drawEvery = Utils.PercentIntervalByLength(cache.Symbol.Count * 2);
// Save to datacontainer
for (int i = 0; i < cache.Symbol.Count; ++i)
{
// Create event
_Event e = new _Event()
{
Symbol = cache.Symbol[i],
Date = new DateTime(cache.Date[i]),
Price = cache.Price[i]
};
// Add to data container
dataContainer.GetEvent(e.Date).ProductsDatas[e.Symbol].Price = e.Price;
if (i % drawEvery == 0)
Utils.DrawMessage(prefix, Utils.CreateProgressBar(Utils.ProgressBarLength, 50 + (double)i / cache.Symbol.Count * 50), ConsoleColor.Gray);
}
}
catch (Exception ex)
{
Console.WriteLine();
Utils.DrawMessage("", ex.Message, ConsoleColor.Red);
Console.WriteLine();
System.Environment.Exit(1);
}
Utils.DrawMessage(prefix, Utils.CreateProgressBar(Utils.ProgressBarLength, 100), ConsoleColor.Green);
Console.WriteLine();
}
}
}
| 37.649289 | 162 | 0.482251 | [
"MIT"
] | mastercs999/fn-trading | src/DataCenter/02-HistoricalPrices/HistoricalPrices.cs | 7,946 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ViewModelCommandManager.cs" company="Catel development team">
// Copyright (c) 2008 - 2014 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Catel.MVVM
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Input;
using Logging;
using Reflection;
using CommandHandler = System.Action<IViewModel, string, System.Windows.Input.ICommand, object>;
/// <summary>
/// Command manager that manages the execution state of all commands of a view model.
/// </summary>
public class ViewModelCommandManager : IViewModelCommandManager
{
#region Constants
/// <summary>
/// The log.
/// </summary>
private static readonly ILog Log = LogManager.GetCurrentClassLogger();
/// <summary>
/// Dictionary containing all instances of all view model command managers.
/// </summary>
private static readonly Dictionary<int, ViewModelCommandManager> _instances = new Dictionary<int, ViewModelCommandManager>();
#endregion
#region Fields
/// <summary>
/// The lock object.
/// </summary>
private readonly object _lock = new object();
/// <summary>
/// A list of registered command handlers.
/// </summary>
private readonly List<CommandHandler> _commandHandlers = new List<CommandHandler>();
/// <summary>
/// A list of commands that implement the <see cref="ICatelCommand"/> interface.
/// </summary>
/// <remarks>
/// Internal so the <see cref="ViewModelManager"/> can subscribe to the commands. The string is the property name
/// the command is registered with.
/// </remarks>
private readonly Dictionary<ICommand, string> _commands = new Dictionary<ICommand, string>();
/// <summary>
/// The view model.
/// </summary>
private IViewModel _viewModel;
/// <summary>
/// The view model type;
/// </summary>
private readonly Type _viewModelType;
/// <summary>
/// A list of reflection properties for the commands.
/// </summary>
private readonly List<PropertyInfo> _commandProperties = new List<PropertyInfo>();
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ViewModelCommandManager" /> class.
/// </summary>
/// <param name="viewModel">The view model.</param>
/// <exception cref="ArgumentNullException">The <paramref name="viewModel"/> is <c>null</c>.</exception>
private ViewModelCommandManager(IViewModel viewModel)
{
Argument.IsNotNull("viewModel", viewModel);
Log.Debug("Creating a ViewModelCommandManager for view model '{0}' with unique identifier '{1}'", viewModel.GetType().FullName, viewModel.UniqueIdentifier);
_viewModel = viewModel;
_viewModelType = viewModel.GetType();
_viewModel.Initialized += OnViewModelInitialized;
_viewModel.Closed += OnViewModelClosed;
var properties = new List<PropertyInfo>();
properties.AddRange(_viewModelType.GetPropertiesEx());
foreach (var propertyInfo in properties)
{
if (propertyInfo.PropertyType.ImplementsInterfaceEx(typeof(ICommand)))
{
_commandProperties.Add(propertyInfo);
}
}
RegisterCommands(false);
Log.Debug("Created a ViewModelCommandManager for view model '{0}' with unique identifier '{1}'", viewModel.GetType().FullName, viewModel.UniqueIdentifier);
}
#endregion
#region Methods
/// <summary>
/// Registers the commands in a specific <see cref="IViewModel" /> instance. By subscribing
/// to all commands, the <see cref="IViewModel.CommandExecuted" /> can be intercepted.
/// <para />
/// This method will automatically subscribe to the <see cref="IViewModel.Closed"/> event and unsubscribe all commands
/// at that time.
/// </summary>
/// <param name="viewModel">The view model.</param>
/// <exception cref="ArgumentNullException">The <paramref name="viewModel"/> is <c>null</c>.</exception>
public static IViewModelCommandManager Create(IViewModel viewModel)
{
Argument.IsNotNull("viewModel", viewModel);
if (viewModel.IsClosed)
{
Log.Warning("View model '{0}' with unique identifier '{1}' is already closed, cannot manage commands of a closed view model", viewModel.GetType().FullName, viewModel.UniqueIdentifier);
return null;
}
if (!_instances.ContainsKey(viewModel.UniqueIdentifier))
{
_instances[viewModel.UniqueIdentifier] = new ViewModelCommandManager(viewModel);
}
return _instances[viewModel.UniqueIdentifier];
}
/// <summary>
/// Registers the commands in a specific <see cref="IViewModel" /> instance. By subscribing
/// to all commands, the <see cref="IViewModel.CommandExecuted" /> can be intercepted.
/// <para />
/// This method will automatically subscribe to the <see cref="IViewModel.Closed"/> event and unsubscribe all commands
/// at that time.
/// </summary>
/// <param name="force">If <c>true</c>, the already registered commands are cleared and all are registered again.</param>
private void RegisterCommands(bool force)
{
if (_commandProperties.Count == 0)
{
return;
}
lock (_lock)
{
if (_commands.Count > 0)
{
if (!force)
{
return;
}
UnregisterCommands();
}
Log.Debug("Registering commands on view model '{0}' with unique identifier '{1}'", _viewModelType.FullName, _viewModel.UniqueIdentifier);
foreach (var propertyInfo in _commandProperties)
{
try
{
var command = propertyInfo.GetValue(_viewModel, null) as ICommand;
if (command != null)
{
if (!_commands.ContainsKey(command))
{
Log.Debug("Found command '{0}' on view model '{1}'", propertyInfo.Name, _viewModelType.Name);
var commandAsICatelCommand = command as ICatelCommand;
if (commandAsICatelCommand != null)
{
commandAsICatelCommand.Executed += OnViewModelCommandExecuted;
}
_commands.Add(command, propertyInfo.Name);
}
}
}
catch (Exception)
{
Log.Error("Failed to get command from property '{0}'", propertyInfo.Name);
}
}
Log.Debug("Registered commands on view model '{0}' with unique identifier '{1}'", _viewModelType.FullName, _viewModel.UniqueIdentifier);
}
}
/// <summary>
/// Adds a new handler when a command is executed on the specified view model.
/// </summary>
/// <param name="handler">The handler to execute when a command is executed.</param>
/// <exception cref="ArgumentNullException">The <paramref name="handler"/> is <c>null</c>.</exception>
public void AddHandler(CommandHandler handler)
{
Argument.IsNotNull("handler", handler);
_commandHandlers.Add(handler);
}
/// <summary>
/// Invalidates all the commands that implement the <see cref="ICatelCommand"/>.
/// </summary>
/// <param name="force">If <c>true</c>, the commands are re-initialized. The default value is <c>false</c>.</param>
public void InvalidateCommands(bool force = false)
{
// Safe to call, checks whether commands are already registered
RegisterCommands(force);
lock (_lock)
{
foreach (var command in _commands.Keys)
{
var commandAsICatelCommand = command as ICatelCommand;
if (commandAsICatelCommand != null)
{
commandAsICatelCommand.RaiseCanExecuteChanged();
}
}
}
}
/// <summary>
/// Unregisters the commands in the <see cref="IViewModel" /> instance.
/// </summary>
private void UnregisterCommands()
{
Log.Debug("Unregistering commands on view model '{0}' with unique identifier '{1}'", _viewModelType.FullName, _viewModel.UniqueIdentifier);
lock (_lock)
{
foreach (var command in _commands.Keys)
{
var commandAsICatelCommand = command as ICatelCommand;
if (commandAsICatelCommand != null)
{
commandAsICatelCommand.Executed -= OnViewModelCommandExecuted;
}
}
_commands.Clear();
}
Log.Debug("Unregistered commands on view model '{0}' with unique identifier '{1}'", _viewModelType.FullName, _viewModel.UniqueIdentifier);
}
private void OnViewModelCommandExecuted(object sender, CommandExecutedEventArgs e)
{
lock (_lock)
{
foreach (var handler in _commandHandlers)
{
if (handler != null)
{
handler(_viewModel, _commands[e.Command], e.Command, e.CommandParameter);
}
}
}
}
private void OnViewModelInitialized(object sender, EventArgs e)
{
InvalidateCommands(true);
}
private void OnViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
{
RegisterCommands(false);
}
private void OnViewModelClosed(object sender, EventArgs e)
{
_instances.Remove(_viewModel.UniqueIdentifier);
_commandHandlers.Clear();
UnregisterCommands();
_viewModel.Initialized -= OnViewModelInitialized;
_viewModel.PropertyChanged -= OnViewModelPropertyChanged;
_viewModel.Closed -= OnViewModelClosed;
_viewModel = null;
}
#endregion
}
} | 39.231034 | 200 | 0.545311 | [
"MIT"
] | IvanKupriyanov/Catel | src/Catel.MVVM/Catel.MVVM.Shared/MVVM/Commands/ViewModelCommandManager.cs | 11,379 | C# |
// <auto-generated />
// Built from: hl7.fhir.r5.core version: 4.6.0
// Option: "NAMESPACE" = "fhirCsR5"
using fhirCsR5.Models;
namespace fhirCsR5.ValueSets
{
/// <summary>
/// The severity of the audit entry.
/// </summary>
public static class AuditEventSeverityCodes
{
/// <summary>
/// Action must be taken immediately.
/// </summary>
public static readonly Coding Alert = new Coding
{
Code = "alert",
Display = "Alert",
System = "http://hl7.org/fhir/audit-event-severity"
};
/// <summary>
/// Critical conditions.
/// </summary>
public static readonly Coding Critical = new Coding
{
Code = "critical",
Display = "Critical",
System = "http://hl7.org/fhir/audit-event-severity"
};
/// <summary>
/// Debug-level messages.
/// </summary>
public static readonly Coding Debug = new Coding
{
Code = "debug",
Display = "Debug",
System = "http://hl7.org/fhir/audit-event-severity"
};
/// <summary>
/// System is unusable.
/// </summary>
public static readonly Coding Emergency = new Coding
{
Code = "emergency",
Display = "Emergency",
System = "http://hl7.org/fhir/audit-event-severity"
};
/// <summary>
/// Error conditions.
/// </summary>
public static readonly Coding Error = new Coding
{
Code = "error",
Display = "Error",
System = "http://hl7.org/fhir/audit-event-severity"
};
/// <summary>
/// Informational messages.
/// </summary>
public static readonly Coding Informational = new Coding
{
Code = "informational",
Display = "Informational",
System = "http://hl7.org/fhir/audit-event-severity"
};
/// <summary>
/// Normal but significant condition.
/// </summary>
public static readonly Coding Notice = new Coding
{
Code = "notice",
Display = "Notice",
System = "http://hl7.org/fhir/audit-event-severity"
};
/// <summary>
/// Warning conditions.
/// </summary>
public static readonly Coding Warning = new Coding
{
Code = "warning",
Display = "Warning",
System = "http://hl7.org/fhir/audit-event-severity"
};
};
}
| 25.761364 | 60 | 0.57918 | [
"MIT"
] | FirelyTeam/fhir-codegen | src/Microsoft.Health.Fhir.SpecManager/fhir/R5/ValueSets/AuditEventSeverity.cs | 2,267 | C# |
using System.Diagnostics;
using System.Windows.Input;
using Todo.Helpers;
using Todo.Models;
using Todo.Views;
using Xamarin.Forms;
namespace Todo.ViewModels
{
public class RegisterViewModel : BaseViewModel
{
#region Fields
public ICommand RegisterCommand { get; set; }
private string _username;
public string Username
{
get => _username;
set => SetProperty(ref _username, value);
}
private string _email;
public string Email
{
get => _email;
set => SetProperty(ref _email, value);
}
private string _firstName;
public string FirstName
{
get => _firstName;
set => SetProperty(ref _firstName, value);
}
private string _lastName;
public string LastName
{
get => _lastName;
set => SetProperty(ref _lastName, value);
}
private string _password;
public string Password
{
get => _password;
set => SetProperty(ref _password, value);
}
private string _confirmPassword;
public string ConfirmPassword
{
get => _confirmPassword;
set => SetProperty(ref _confirmPassword, value);
}
#endregion
#region Constructor
public RegisterViewModel() => RegisterCommand = new Command(OnRegisterClicked);
#endregion
#region Methods
private async void OnRegisterClicked(object obj)
{
IsBusy = true;
try
{
var register = new Register
{
Username = Username,
Email = Email,
FirstName = FirstName,
LastName = LastName,
Password = Password,
ConfirmPassword = ConfirmPassword
};
if (await UserService.Register(register))
{
await Shell.Current.GoToAsync($"//{nameof(ItemsPage)}");
}
}
catch (System.Exception ex)
{
Debug.WriteLine(ex);
throw;
}
finally
{
IsBusy = false;
}
}
#endregion
}
}
| 23.221154 | 87 | 0.49234 | [
"MIT"
] | niteshrestha/todo-mobile | Todo/Todo/ViewModels/RegisterViewModel.cs | 2,417 | C# |
using System;
using UnityEngine;
using Verse;
namespace EdB.PrepareCarefully {
abstract public class TabViewBase : ITabView {
public TabRecord TabRecord {
get;
set;
}
public abstract string Name {
get;
}
public Rect TabViewRect = new Rect(float.MinValue, float.MinValue, float.MinValue, float.MinValue);
public TabViewBase() {
}
public virtual void Draw(State state, Rect rect) {
if (rect != TabViewRect) {
Resize(rect);
}
}
protected virtual void Resize(Rect rect) {
TabViewRect = rect;
}
}
}
| 26.076923 | 107 | 0.548673 | [
"MIT"
] | Alias44/EdBPrepareCarefully | Source/EdBPrepareCarefully/EdBPrepareCarefully/TabViewBase.cs | 678 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Host.Scale;
using Microsoft.Azure.WebJobs.Logging;
using Microsoft.Azure.WebJobs.Script.Diagnostics;
using Microsoft.Azure.WebJobs.Script.Eventing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Microsoft.Azure.WebJobs.Script.Workers
{
internal abstract class WorkerProcess : IWorkerProcess, IDisposable
{
private readonly IProcessRegistry _processRegistry;
private readonly ILogger _workerProcessLogger;
private readonly IWorkerConsoleLogSource _consoleLogSource;
private readonly IScriptEventManager _eventManager;
private readonly IMetricsLogger _metricsLogger;
private readonly int processExitTimeoutInMilliseconds = 1000;
private readonly IServiceProvider _serviceProvider;
private readonly IDisposable _eventSubscription;
private bool _useStdErrorStreamForErrorsOnly;
private Queue<string> _processStdErrDataQueue = new Queue<string>(3);
private IHostProcessMonitor _processMonitor;
private object _syncLock = new object();
internal WorkerProcess(IScriptEventManager eventManager, IProcessRegistry processRegistry, ILogger workerProcessLogger, IWorkerConsoleLogSource consoleLogSource, IMetricsLogger metricsLogger, IServiceProvider serviceProvider, bool useStdErrStreamForErrorsOnly = false)
{
_processRegistry = processRegistry;
_workerProcessLogger = workerProcessLogger;
_consoleLogSource = consoleLogSource;
_eventManager = eventManager;
_metricsLogger = metricsLogger;
_useStdErrorStreamForErrorsOnly = useStdErrStreamForErrorsOnly;
_serviceProvider = serviceProvider;
// We subscribe to host start events so we can handle the restart that occurs
// on host specialization.
_eventSubscription = _eventManager.OfType<HostStartEvent>().Subscribe(OnHostStart);
}
protected bool Disposing { get; private set; }
public int Id => Process.Id;
internal Queue<string> ProcessStdErrDataQueue => _processStdErrDataQueue;
// for testing
internal Process Process { get; set; }
internal abstract Process CreateWorkerProcess();
public Task StartProcessAsync()
{
using (_metricsLogger.LatencyEvent(MetricEventNames.ProcessStart))
{
Process = CreateWorkerProcess();
try
{
Process.ErrorDataReceived += (sender, e) => OnErrorDataReceived(sender, e);
Process.OutputDataReceived += (sender, e) => OnOutputDataReceived(sender, e);
Process.Exited += (sender, e) => OnProcessExited(sender, e);
Process.EnableRaisingEvents = true;
_workerProcessLogger?.LogDebug($"Starting worker process with FileName:{Process.StartInfo.FileName} WorkingDirectory:{Process.StartInfo.WorkingDirectory} Arguments:{Process.StartInfo.Arguments}");
Process.Start();
_workerProcessLogger?.LogDebug($"{Process.StartInfo.FileName} process with Id={Process.Id} started");
Process.BeginErrorReadLine();
Process.BeginOutputReadLine();
// Register process only after it starts
_processRegistry?.Register(Process);
RegisterWithProcessMonitor();
return Task.CompletedTask;
}
catch (Exception ex)
{
_workerProcessLogger.LogError(ex, $"Failed to start Worker Channel. Process fileName: {Process.StartInfo.FileName}");
return Task.FromException(ex);
}
}
}
private void OnErrorDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
ParseErrorMessageAndLog(e.Data);
}
}
internal void ParseErrorMessageAndLog(string msg)
{
if (msg.IndexOf("warn", StringComparison.OrdinalIgnoreCase) > -1)
{
BuildAndLogConsoleLog(msg, LogLevel.Warning);
}
else
{
if (_useStdErrorStreamForErrorsOnly)
{
LogError(msg);
}
else
{
// TODO: redesign how we log errors so it's not based on the string contents (GH issue #8273)
if ((msg.IndexOf("error", StringComparison.OrdinalIgnoreCase) > -1) ||
(msg.IndexOf("fail", StringComparison.OrdinalIgnoreCase) > -1) ||
(msg.IndexOf("severe", StringComparison.OrdinalIgnoreCase) > -1) ||
(msg.IndexOf("unhandled exception", StringComparison.OrdinalIgnoreCase) > -1))
{
LogError(msg);
}
else
{
BuildAndLogConsoleLog(msg, LogLevel.Information);
}
}
}
}
private void LogError(string msg)
{
BuildAndLogConsoleLog(msg, LogLevel.Error);
_processStdErrDataQueue = WorkerProcessUtilities.AddStdErrMessage(_processStdErrDataQueue, Sanitizer.Sanitize(msg));
}
private void OnProcessExited(object sender, EventArgs e)
{
if (Disposing)
{
// No action needed
return;
}
string exceptionMessage = string.Join(",", _processStdErrDataQueue.Where(s => !string.IsNullOrEmpty(s)));
try
{
if (Process.ExitCode == WorkerConstants.SuccessExitCode)
{
Process.WaitForExit();
Process.Close();
}
else if (Process.ExitCode == WorkerConstants.IntentionalRestartExitCode)
{
HandleWorkerProcessRestart();
}
else
{
var processExitEx = new WorkerProcessExitException($"{Process.StartInfo.FileName} exited with code {Process.ExitCode} (0x{Process.ExitCode.ToString("X")})", new Exception(exceptionMessage));
processExitEx.ExitCode = Process.ExitCode;
processExitEx.Pid = Process.Id;
HandleWorkerProcessExitError(processExitEx);
}
}
catch (Exception exc)
{
_workerProcessLogger?.LogDebug(exc, "Exception on worker process exit.");
// ignore process is already disposed
}
finally
{
UnregisterFromProcessMonitor();
}
}
private void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
BuildAndLogConsoleLog(e.Data, LogLevel.Information);
}
}
internal void BuildAndLogConsoleLog(string msg, LogLevel level)
{
ConsoleLog consoleLog = new ConsoleLog()
{
Message = msg,
Level = level
};
if (WorkerProcessUtilities.IsConsoleLog(msg))
{
_workerProcessLogger?.Log(level, WorkerProcessUtilities.RemoveLogPrefix(msg));
}
else
{
_consoleLogSource?.Log(consoleLog);
}
}
internal abstract void HandleWorkerProcessExitError(WorkerProcessExitException langExc);
internal abstract void HandleWorkerProcessRestart();
public void Dispose()
{
Disposing = true;
// best effort process disposal
try
{
_eventSubscription?.Dispose();
if (Process != null)
{
if (!Process.HasExited)
{
Process.Kill();
if (!Process.WaitForExit(processExitTimeoutInMilliseconds))
{
_workerProcessLogger.LogWarning($"Worker process has not exited despite waiting for {processExitTimeoutInMilliseconds} ms");
}
}
Process.Dispose();
}
}
catch (Exception exc)
{
_workerProcessLogger?.LogDebug(exc, "Exception on worker disposal.");
//ignore
}
}
internal void OnHostStart(HostStartEvent evt)
{
if (!Disposing)
{
RegisterWithProcessMonitor();
}
}
/// <summary>
/// Ensures that our process is registered with <see cref="IHostProcessMonitor"/>.
/// </summary>
/// <remarks>
/// The goal is to ensure that all worker processes are registered with the monitor for the active host.
/// There are a few different cases to consider:
/// - Starting up in normal mode, we register on when the process is started.
/// - When a placeholder mode host is specialized, a new host will be started but the previously initialized
/// worker process will remain running. We need to re-register with the new host.
/// - When the worker process dies and a new instance of this class is created.
/// </remarks>
internal void RegisterWithProcessMonitor()
{
var processMonitor = _serviceProvider.GetScriptHostServiceOrNull<IHostProcessMonitor>();
lock (_syncLock)
{
if (processMonitor != null && processMonitor != _processMonitor && Process != null)
{
processMonitor.RegisterChildProcess(Process);
_processMonitor = processMonitor;
}
}
}
internal void UnregisterFromProcessMonitor()
{
lock (_syncLock)
{
if (_processMonitor != null && Process != null)
{
// if we've registered our process with the monitor, unregister
_processMonitor.UnregisterChildProcess(Process);
_processMonitor = null;
}
}
}
}
}
| 38.996441 | 276 | 0.567531 | [
"MIT"
] | Azure/azure-webjobs-sdk-script | src/WebJobs.Script/Workers/ProcessManagement/WorkerProcess.cs | 10,960 | C# |
using System.Linq;
namespace Microsoft.Recognizers.Text
{
public sealed class Culture
{
public const string English = "en-us";
public const string Chinese = "zh-cn";
public const string Spanish = "es-es";
public const string Portuguese = "pt-br";
public const string French = "fr-fr";
public const string German = "de-de";
public const string Japanese = "ja-jp";
public string CultureName;
public string CultureCode;
public static readonly Culture[] SupportedCultures = {
new Culture("English", English),
new Culture("Chinese", Chinese),
new Culture("Spanish", Spanish),
new Culture("Portuguese", Portuguese),
new Culture("French", French),
new Culture("German", German),
new Culture("Japanese", Japanese)
};
private Culture(string cultureName, string cultureCode)
{
this.CultureName = cultureName;
this.CultureCode = cultureCode;
}
public static string[] GetSupportedCultureCodes()
{
return SupportedCultures.Select(c => c.CultureCode).ToArray();
}
}
}
| 30.675 | 74 | 0.589242 | [
"MIT"
] | stevengum97/Recognizers-Text | .NET/Microsoft.Recognizers.Text/Culture.cs | 1,227 | C# |
namespace ClassLib080
{
public class Class076
{
public static string Property => "ClassLib080";
}
}
| 15 | 55 | 0.633333 | [
"MIT"
] | 333fred/performance | src/scenarios/weblarge2.0/src/ClassLib080/Class076.cs | 120 | C# |
#region
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
#endregion
namespace GenericRepository
{
public sealed class RepositoryQuery<TEntity> : IRepositoryQuery<TEntity> where TEntity : EntityBase
{
private readonly List<Expression<Func<TEntity, object>>> _includeProperties;
private readonly Repository<TEntity> _repository;
private Expression<Func<TEntity, bool>> _filter;
private Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> _orderByQuerable;
private int? _page;
private int? _pageSize;
private bool? _trackingOff;
public RepositoryQuery(Repository<TEntity> repository)
{
_repository = repository;
_includeProperties = new List<Expression<Func<TEntity, object>>>();
}
public RepositoryQuery<TEntity> Filter(Expression<Func<TEntity, bool>> filter)
{
_filter = filter;
return this;
}
public RepositoryQuery<TEntity> OrderBy(Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy)
{
_orderByQuerable = orderBy;
return this;
}
public RepositoryQuery<TEntity> Include(Expression<Func<TEntity, object>> expression)
{
_includeProperties.Add(expression);
return this;
}
public RepositoryQuery<TEntity> TrackingOff()
{
_trackingOff = true;
return this;
}
public IEnumerable<TEntity> GetPage(int page, int pageSize, out int totalCount)
{
_page = page;
_pageSize = pageSize;
totalCount = _repository.Get(_filter).Count();
return _repository.Get(_filter, _orderByQuerable, _includeProperties, _page, _pageSize);
}
public IQueryable<TEntity> Get()
{
return _repository.Get(_filter, _orderByQuerable, _includeProperties, _page, _pageSize, _trackingOff);
}
public async Task<IEnumerable<TEntity>> GetAsync()
{
return await _repository.GetAsync(_filter, _orderByQuerable, _includeProperties, _page, _pageSize);
}
public IQueryable<TEntity> SqlQuery(string query, params object[] parameters)
{
return _repository.SqlQuery(query, parameters).AsQueryable();
}
}
} | 31.753247 | 114 | 0.640082 | [
"MIT"
] | bravecollective/doctrine-contracts | GenericRepository/RepositoryQuery.cs | 2,447 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Arbor.TemplateRenderer.Tool
{
public record InputArgs(string ModelFile, string TemplateFile);
}
| 20.727273 | 67 | 0.802632 | [
"MIT"
] | niklaslundberg/Arbor.TemplateRenderer | src/Arbor.TemplateRenderer.Tool/InputArgs.cs | 230 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Exam")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Exam")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("734ea07a-5256-46ee-9126-bb604ad238cb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.189189 | 84 | 0.744913 | [
"MIT"
] | radoslavvv/Programming-Fundamentals-Extended-May-2017 | Exam/01. Trainers/Properties/AssemblyInfo.cs | 1,379 | C# |
using UnityEngine;
using System.Collections;
using System;
public class Projectile : Pawn {
public override string Name {
get {
return "Projectile";
}
}
public override string DefaultModel {
get {
return "Projectile";
}
}
private Rigidbody m_RBody { get; set; }
private CharacterController m_Controller { get; set; }
private Vector3 m_Velocity { get; set; }
private float m_LifeTime { get; set; }
private float m_TimeSinceAlive;
public override void OnStart() {
m_RBody = GetComponent<Rigidbody>();
m_Controller = GetComponent<CharacterController>();
GetComponentInChildren<BoxCollider>().isTrigger = true;
m_RBody.useGravity = false;
m_RBody.isKinematic = false;
m_Controller.enabled = false;
}
public override void OnUpdate() {
if (m_TimeSinceAlive > m_LifeTime) Destroy(gameObject);
else {
m_TimeSinceAlive += Time.deltaTime;
//transform.position += m_Velocity * Time.deltaTime;
}
}
public void FixedUpdate() {
if (m_TimeSinceAlive < m_LifeTime) m_RBody.velocity = m_Velocity;
}
public void SetTrajectory(Vector3 velocity, float lifeTime) {
m_Velocity = velocity;
m_LifeTime = lifeTime;
}
public void OnTriggerEnter(Collider other) {
if (other.GetComponent<Pawn>()) {
other.SendMessage("Damage", new DamageInfo(DamageType.PHYSICAL, DamageElement.NONE, 10f, this, false), SendMessageOptions.DontRequireReceiver);
Destroy(gameObject);
}
}
}
| 23.8 | 146 | 0.727591 | [
"Apache-2.0"
] | dresswithpockets/Project-Cygnus | Assets/Scripts/Game/Pawns/Projectile.cs | 1,430 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.