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 System; using System.Diagnostics; namespace WhatNow.Essentials { public class BlockStopwatch : IDisposable { readonly Stopwatch stopwatch; readonly Action<TimeSpan> closeAction; public TimeSpan ElapsedTime => stopwatch.Elapsed; public BlockStopwatch() { stopwatch = Stopwatch.StartNew(); } public BlockStopwatch(Action<TimeSpan> closeAction) : this() { this.closeAction = closeAction; } public void Invoke() => closeAction?.Invoke(ElapsedTime); public void Dispose() { stopwatch.Stop(); Invoke(); } } }
20.969697
68
0.572254
[ "Apache-2.0" ]
rbenes86/WhatNow
WhatNow/WhatNow.Essentials/BlockStopwatch.cs
694
C#
using System.Diagnostics; namespace Monorail.Debug { public static class Insist { [Conditional("DEBUG")] [DebuggerHidden] public static void Fail() { Log.Core.Error("Assertion failed."); Debugger.Break(); } [Conditional("DEBUG")] [DebuggerHidden] public static void Fail(string message, params object[] args) { Log.Core.Error(message, args); Debugger.Break(); } [Conditional("DEBUG")] [DebuggerHidden] public static void Assert(bool condition) { if (!condition) Fail(); } [Conditional("DEBUG")] [DebuggerHidden] public static void Assert(bool condition, string message, params object[] args) { if (!condition) Fail(message, args); } [Conditional("DEBUG")] [DebuggerHidden] public static void AssertFalse(bool condition) { Assert(!condition); } [Conditional("DEBUG")] [DebuggerHidden] public static void AssertFalse(bool condition, string message, params object[] args) { Assert(!condition, message, args); } /// <summary> /// asserts that obj is null /// </summary> /// <param name="obj">Object.</param> /// <param name="message">Message.</param> /// <param name="args">Arguments.</param> [Conditional("DEBUG")] [DebuggerHidden] public static void AssertNull(object obj) { Assert(obj == null); } /// <summary> /// asserts that obj is null /// </summary> /// <param name="obj">Object.</param> /// <param name="message">Message.</param> /// <param name="args">Arguments.</param> [Conditional("DEBUG")] [DebuggerHidden] public static void AssertNull(object obj, string message, params object[] args) { Assert(obj == null, message, args); } /// <summary> /// asserts that obj is not null /// </summary> /// <param name="obj">Object.</param> /// <param name="message">Message.</param> /// <param name="args">Arguments.</param> [Conditional("DEBUG")] [DebuggerHidden] public static void AssertNotNull(object obj) { Assert(obj != null); } /// <summary> /// asserts that obj is not null /// </summary> /// <param name="obj">Object.</param> /// <param name="message">Message.</param> /// <param name="args">Arguments.</param> [Conditional("DEBUG")] [DebuggerHidden] public static void AssertNotNull(object obj, string message, params object[] args) { Assert(obj != null, message, args); } /// <summary> /// asserts that first is equal to second /// </summary> /// <param name="first">First.</param> /// <param name="second">Second.</param> /// <param name="message">Message.</param> /// <param name="args">Arguments.</param> [Conditional("DEBUG")] [DebuggerHidden] public static void AssertEq(object first, object second) { Assert(first.Equals(second)); } /// <summary> /// asserts that first is not equal to second /// </summary> /// <param name="first">First.</param> /// <param name="second">Second.</param> /// <param name="message">Message.</param> /// <param name="args">Arguments.</param> [Conditional("DEBUG")] [DebuggerHidden] public static void AssertNotEq(object first, object second) { Assert(!first.Equals(second)); } /// <summary> /// asserts that first is equal to second /// </summary> /// <param name="first">First.</param> /// <param name="second">Second.</param> /// <param name="message">Message.</param> /// <param name="args">Arguments.</param> [Conditional("DEBUG")] [DebuggerHidden] public static void AssertEq(object first, object second, string message, params object[] args) { Assert(first.Equals(second), message, args); } /// <summary> /// asserts that first is not equal to second /// </summary> /// <param name="first">First.</param> /// <param name="second">Second.</param> /// <param name="message">Message.</param> /// <param name="args">Arguments.</param> [Conditional("DEBUG")] [DebuggerHidden] public static void AssertNotEq(object first, object second, string message, params object[] args) { Assert(!first.Equals(second), message, args); } } }
23.491429
99
0.638774
[ "MIT" ]
MissaelAnda/Monorail
Monorail/Debug/Insist.cs
4,113
C#
// <auto-generated /> using System; using Abp.VueTemplate.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Abp.VueTemplate.Migrations { [DbContext(typeof(IdentityServerMigrationsDbContext))] [Migration("20200428132118_Initial")] partial class Initial { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.3") .HasAnnotation("Relational:MaxIdentifierLength", 64); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResource", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("char(36)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime(6)"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("char(36)"); b.Property<Guid?>("DeleterId") .HasColumnName("DeleterId") .HasColumnType("char(36)"); b.Property<DateTime?>("DeletionTime") .HasColumnName("DeletionTime") .HasColumnType("datetime(6)"); b.Property<string>("Description") .HasColumnType("varchar(1000) CHARACTER SET utf8mb4") .HasMaxLength(1000); b.Property<string>("DisplayName") .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.Property<bool>("Enabled") .HasColumnType("tinyint(1)"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnName("IsDeleted") .HasColumnType("tinyint(1)") .HasDefaultValue(false); b.Property<DateTime?>("LastModificationTime") .HasColumnName("LastModificationTime") .HasColumnType("datetime(6)"); b.Property<Guid?>("LastModifierId") .HasColumnName("LastModifierId") .HasColumnType("char(36)"); b.Property<string>("Name") .IsRequired() .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.Property<string>("Properties") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.HasKey("Id"); b.ToTable("IdentityServerApiResources"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceClaim", b => { b.Property<Guid>("ApiResourceId") .HasColumnType("char(36)"); b.Property<string>("Type") .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.HasKey("ApiResourceId", "Type"); b.ToTable("IdentityServerApiClaims"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiScope", b => { b.Property<Guid>("ApiResourceId") .HasColumnType("char(36)"); b.Property<string>("Name") .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.Property<string>("Description") .HasColumnType("varchar(1000) CHARACTER SET utf8mb4") .HasMaxLength(1000); b.Property<string>("DisplayName") .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.Property<bool>("Emphasize") .HasColumnType("tinyint(1)"); b.Property<bool>("Required") .HasColumnType("tinyint(1)"); b.Property<bool>("ShowInDiscoveryDocument") .HasColumnType("tinyint(1)"); b.HasKey("ApiResourceId", "Name"); b.ToTable("IdentityServerApiScopes"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiScopeClaim", b => { b.Property<Guid>("ApiResourceId") .HasColumnType("char(36)"); b.Property<string>("Name") .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.Property<string>("Type") .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.HasKey("ApiResourceId", "Name", "Type"); b.ToTable("IdentityServerApiScopeClaims"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiSecret", b => { b.Property<Guid>("ApiResourceId") .HasColumnType("char(36)"); b.Property<string>("Type") .HasColumnType("varchar(250) CHARACTER SET utf8mb4") .HasMaxLength(250); b.Property<string>("Value") .HasColumnType("varchar(300) CHARACTER SET utf8mb4") .HasMaxLength(300); b.Property<string>("Description") .HasColumnType("varchar(2000) CHARACTER SET utf8mb4") .HasMaxLength(2000); b.Property<DateTime?>("Expiration") .HasColumnType("datetime(6)"); b.HasKey("ApiResourceId", "Type", "Value"); b.ToTable("IdentityServerApiSecrets"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.Client", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("char(36)"); b.Property<int>("AbsoluteRefreshTokenLifetime") .HasColumnType("int"); b.Property<int>("AccessTokenLifetime") .HasColumnType("int"); b.Property<int>("AccessTokenType") .HasColumnType("int"); b.Property<bool>("AllowAccessTokensViaBrowser") .HasColumnType("tinyint(1)"); b.Property<bool>("AllowOfflineAccess") .HasColumnType("tinyint(1)"); b.Property<bool>("AllowPlainTextPkce") .HasColumnType("tinyint(1)"); b.Property<bool>("AllowRememberConsent") .HasColumnType("tinyint(1)"); b.Property<bool>("AlwaysIncludeUserClaimsInIdToken") .HasColumnType("tinyint(1)"); b.Property<bool>("AlwaysSendClientClaims") .HasColumnType("tinyint(1)"); b.Property<int>("AuthorizationCodeLifetime") .HasColumnType("int"); b.Property<bool>("BackChannelLogoutSessionRequired") .HasColumnType("tinyint(1)"); b.Property<string>("BackChannelLogoutUri") .HasColumnType("varchar(2000) CHARACTER SET utf8mb4") .HasMaxLength(2000); b.Property<string>("ClientClaimsPrefix") .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.Property<string>("ClientId") .IsRequired() .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.Property<string>("ClientName") .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.Property<string>("ClientUri") .HasColumnType("varchar(2000) CHARACTER SET utf8mb4") .HasMaxLength(2000); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<int?>("ConsentLifetime") .HasColumnType("int"); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime(6)"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("char(36)"); b.Property<Guid?>("DeleterId") .HasColumnName("DeleterId") .HasColumnType("char(36)"); b.Property<DateTime?>("DeletionTime") .HasColumnName("DeletionTime") .HasColumnType("datetime(6)"); b.Property<string>("Description") .HasColumnType("varchar(1000) CHARACTER SET utf8mb4") .HasMaxLength(1000); b.Property<int>("DeviceCodeLifetime") .HasColumnType("int"); b.Property<bool>("EnableLocalLogin") .HasColumnType("tinyint(1)"); b.Property<bool>("Enabled") .HasColumnType("tinyint(1)"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<bool>("FrontChannelLogoutSessionRequired") .HasColumnType("tinyint(1)"); b.Property<string>("FrontChannelLogoutUri") .HasColumnType("varchar(2000) CHARACTER SET utf8mb4") .HasMaxLength(2000); b.Property<int>("IdentityTokenLifetime") .HasColumnType("int"); b.Property<bool>("IncludeJwtId") .HasColumnType("tinyint(1)"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnName("IsDeleted") .HasColumnType("tinyint(1)") .HasDefaultValue(false); b.Property<DateTime?>("LastModificationTime") .HasColumnName("LastModificationTime") .HasColumnType("datetime(6)"); b.Property<Guid?>("LastModifierId") .HasColumnName("LastModifierId") .HasColumnType("char(36)"); b.Property<string>("LogoUri") .HasColumnType("varchar(2000) CHARACTER SET utf8mb4") .HasMaxLength(2000); b.Property<string>("PairWiseSubjectSalt") .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.Property<string>("ProtocolType") .IsRequired() .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.Property<int>("RefreshTokenExpiration") .HasColumnType("int"); b.Property<int>("RefreshTokenUsage") .HasColumnType("int"); b.Property<bool>("RequireClientSecret") .HasColumnType("tinyint(1)"); b.Property<bool>("RequireConsent") .HasColumnType("tinyint(1)"); b.Property<bool>("RequirePkce") .HasColumnType("tinyint(1)"); b.Property<int>("SlidingRefreshTokenLifetime") .HasColumnType("int"); b.Property<bool>("UpdateAccessTokenClaimsOnRefresh") .HasColumnType("tinyint(1)"); b.Property<string>("UserCodeType") .HasColumnType("varchar(100) CHARACTER SET utf8mb4") .HasMaxLength(100); b.Property<int?>("UserSsoLifetime") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("ClientId"); b.ToTable("IdentityServerClients"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientClaim", b => { b.Property<Guid>("ClientId") .HasColumnType("char(36)"); b.Property<string>("Type") .HasColumnType("varchar(250) CHARACTER SET utf8mb4") .HasMaxLength(250); b.Property<string>("Value") .HasColumnType("varchar(250) CHARACTER SET utf8mb4") .HasMaxLength(250); b.HasKey("ClientId", "Type", "Value"); b.ToTable("IdentityServerClientClaims"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientCorsOrigin", b => { b.Property<Guid>("ClientId") .HasColumnType("char(36)"); b.Property<string>("Origin") .HasColumnType("varchar(150) CHARACTER SET utf8mb4") .HasMaxLength(150); b.HasKey("ClientId", "Origin"); b.ToTable("IdentityServerClientCorsOrigins"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientGrantType", b => { b.Property<Guid>("ClientId") .HasColumnType("char(36)"); b.Property<string>("GrantType") .HasColumnType("varchar(250) CHARACTER SET utf8mb4") .HasMaxLength(250); b.HasKey("ClientId", "GrantType"); b.ToTable("IdentityServerClientGrantTypes"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientIdPRestriction", b => { b.Property<Guid>("ClientId") .HasColumnType("char(36)"); b.Property<string>("Provider") .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.HasKey("ClientId", "Provider"); b.ToTable("IdentityServerClientIdPRestrictions"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientPostLogoutRedirectUri", b => { b.Property<Guid>("ClientId") .HasColumnType("char(36)"); b.Property<string>("PostLogoutRedirectUri") .HasColumnType("varchar(300) CHARACTER SET utf8mb4") .HasMaxLength(300); b.HasKey("ClientId", "PostLogoutRedirectUri"); b.ToTable("IdentityServerClientPostLogoutRedirectUris"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientProperty", b => { b.Property<Guid>("ClientId") .HasColumnType("char(36)"); b.Property<string>("Key") .HasColumnType("varchar(250) CHARACTER SET utf8mb4") .HasMaxLength(250); b.Property<string>("Value") .IsRequired() .HasColumnType("varchar(2000) CHARACTER SET utf8mb4") .HasMaxLength(2000); b.HasKey("ClientId", "Key"); b.ToTable("IdentityServerClientProperties"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientRedirectUri", b => { b.Property<Guid>("ClientId") .HasColumnType("char(36)"); b.Property<string>("RedirectUri") .HasColumnType("varchar(300) CHARACTER SET utf8mb4") .HasMaxLength(300); b.HasKey("ClientId", "RedirectUri"); b.ToTable("IdentityServerClientRedirectUris"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientScope", b => { b.Property<Guid>("ClientId") .HasColumnType("char(36)"); b.Property<string>("Scope") .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.HasKey("ClientId", "Scope"); b.ToTable("IdentityServerClientScopes"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientSecret", b => { b.Property<Guid>("ClientId") .HasColumnType("char(36)"); b.Property<string>("Type") .HasColumnType("varchar(250) CHARACTER SET utf8mb4") .HasMaxLength(250); b.Property<string>("Value") .HasColumnType("varchar(300) CHARACTER SET utf8mb4") .HasMaxLength(300); b.Property<string>("Description") .HasColumnType("varchar(2000) CHARACTER SET utf8mb4") .HasMaxLength(2000); b.Property<DateTime?>("Expiration") .HasColumnType("datetime(6)"); b.HasKey("ClientId", "Type", "Value"); b.ToTable("IdentityServerClientSecrets"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Devices.DeviceFlowCodes", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("char(36)"); b.Property<string>("ClientId") .IsRequired() .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime(6)"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("char(36)"); b.Property<string>("Data") .IsRequired() .HasColumnType("longtext CHARACTER SET utf8mb4") .HasMaxLength(50000); b.Property<string>("DeviceCode") .IsRequired() .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.Property<DateTime?>("Expiration") .IsRequired() .HasColumnType("datetime(6)"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("SubjectId") .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.Property<string>("UserCode") .IsRequired() .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.HasKey("Id"); b.HasIndex("DeviceCode") .IsUnique(); b.HasIndex("Expiration"); b.HasIndex("UserCode") .IsUnique(); b.ToTable("IdentityServerDeviceFlowCodes"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Grants.PersistedGrant", b => { b.Property<string>("Key") .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.Property<string>("ClientId") .IsRequired() .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime(6)"); b.Property<string>("Data") .IsRequired() .HasColumnType("longtext CHARACTER SET utf8mb4") .HasMaxLength(10000); b.Property<DateTime?>("Expiration") .HasColumnType("datetime(6)"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<string>("SubjectId") .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.Property<string>("Type") .IsRequired() .HasColumnType("varchar(50) CHARACTER SET utf8mb4") .HasMaxLength(50); b.HasKey("Key"); b.HasIndex("Expiration"); b.HasIndex("SubjectId", "ClientId", "Type"); b.ToTable("IdentityServerPersistedGrants"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityClaim", b => { b.Property<Guid>("IdentityResourceId") .HasColumnType("char(36)"); b.Property<string>("Type") .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.HasKey("IdentityResourceId", "Type"); b.ToTable("IdentityServerIdentityClaims"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityResource", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("char(36)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("ConcurrencyStamp") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<DateTime>("CreationTime") .HasColumnName("CreationTime") .HasColumnType("datetime(6)"); b.Property<Guid?>("CreatorId") .HasColumnName("CreatorId") .HasColumnType("char(36)"); b.Property<Guid?>("DeleterId") .HasColumnName("DeleterId") .HasColumnType("char(36)"); b.Property<DateTime?>("DeletionTime") .HasColumnName("DeletionTime") .HasColumnType("datetime(6)"); b.Property<string>("Description") .HasColumnType("varchar(1000) CHARACTER SET utf8mb4") .HasMaxLength(1000); b.Property<string>("DisplayName") .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.Property<bool>("Emphasize") .HasColumnType("tinyint(1)"); b.Property<bool>("Enabled") .HasColumnType("tinyint(1)"); b.Property<string>("ExtraProperties") .HasColumnName("ExtraProperties") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnName("IsDeleted") .HasColumnType("tinyint(1)") .HasDefaultValue(false); b.Property<DateTime?>("LastModificationTime") .HasColumnName("LastModificationTime") .HasColumnType("datetime(6)"); b.Property<Guid?>("LastModifierId") .HasColumnName("LastModifierId") .HasColumnType("char(36)"); b.Property<string>("Name") .IsRequired() .HasColumnType("varchar(200) CHARACTER SET utf8mb4") .HasMaxLength(200); b.Property<string>("Properties") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<bool>("Required") .HasColumnType("tinyint(1)"); b.Property<bool>("ShowInDiscoveryDocument") .HasColumnType("tinyint(1)"); b.HasKey("Id"); b.ToTable("IdentityServerIdentityResources"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceClaim", b => { b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiResource", null) .WithMany("UserClaims") .HasForeignKey("ApiResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiScope", b => { b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiResource", null) .WithMany("Scopes") .HasForeignKey("ApiResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiScopeClaim", b => { b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiScope", null) .WithMany("UserClaims") .HasForeignKey("ApiResourceId", "Name") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiSecret", b => { b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiResource", null) .WithMany("Secrets") .HasForeignKey("ApiResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientClaim", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("Claims") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientCorsOrigin", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("AllowedCorsOrigins") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientGrantType", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("AllowedGrantTypes") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientIdPRestriction", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("IdentityProviderRestrictions") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientPostLogoutRedirectUri", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("PostLogoutRedirectUris") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientProperty", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("Properties") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientRedirectUri", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("RedirectUris") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientScope", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("AllowedScopes") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientSecret", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("ClientSecrets") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityClaim", b => { b.HasOne("Volo.Abp.IdentityServer.IdentityResources.IdentityResource", null) .WithMany("UserClaims") .HasForeignKey("IdentityResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
40.225537
99
0.466018
[ "MIT" ]
zhk0603/abp-vue
src/aspnet-core/src/Abp.VueTemplate.IdentityServer/Migrations/20200428132118_Initial.Designer.cs
33,711
C#
using DesignPatterns.GangOfFourPatterns.FactoryMethod.Ingredients; namespace DesignPatterns.GangOfFourPatterns.FactoryMethod.Burgers { public class DoubleCheeseburgerFactory : BurgerFactory { protected class DoubleCheeseburger : Burger { public override string DisplayName => "Double cheeseburger"; public DoubleCheeseburger() { Bun = new RegularBun(); Cheese = new PasteurizedCheese(); Cutlets = new Cutlet[] { new BeefCutlet(), new BeefCutlet() }; Sauces = new Sauce[] { new Ketchup() }; Vegetables = new Vegetables[] { new PickleSlices(), new Onions() }; Seasonings = new Seasoning[] { new GrillSeasoning() }; } } protected override Burger CreateBurger() => new DoubleCheeseburger(); } }
36.708333
83
0.603859
[ "MIT" ]
catman0745/DesignPatterns
src/DesignPatterns.GangOfFourPatterns/FactoryMethod/Burgers/DoubleCheeseburgerFactory.cs
881
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using Kore.Web; using Kore.Web.Infrastructure; using Kore.Web.Mvc; using Kore.Web.Security.Membership.Permissions; namespace KoreCMS.Areas.Admin.Controllers { [Authorize] [RouteArea(KoreWebConstants.Areas.Admin)] public class HomeController : KoreController { private readonly Lazy<IEnumerable<IDurandalRouteProvider>> durandalRouteProviders; private readonly Lazy<IEnumerable<IRequireJSConfigProvider>> requireJSConfigProviders; public HomeController( Lazy<IEnumerable<IDurandalRouteProvider>> durandalRouteProviders, Lazy<IEnumerable<IRequireJSConfigProvider>> requireJSConfigProviders) { this.durandalRouteProviders = durandalRouteProviders; this.requireJSConfigProviders = requireJSConfigProviders; } [Route("")] public ActionResult Host() { return View(); } [Route("dashboard")] public ActionResult Dashboard() { if (!CheckPermission(StandardPermissions.DashboardAccess)) { return new HttpUnauthorizedResult(); } ViewBag.Title = T(LocalizableStrings.Dashboard.Title); return View(); } [Route("shell")] public ActionResult Shell() { return View(); } [Route("get-spa-routes")] public JsonResult GetSpaRoutes() { var routes = durandalRouteProviders.Value.SelectMany(x => x.Routes); return Json(routes, JsonRequestBehavior.AllowGet); } [Route("get-requirejs-config")] public JsonResult GetRequireJsConfig() { var config = new RequireJsConfig { Paths = new Dictionary<string, string>(), Shim = new Dictionary<string, string[]>() }; // Routes First var routes = durandalRouteProviders.Value.SelectMany(x => x.Routes); foreach (var route in routes) { config.Paths.Add(route.ModuleId, route.JsPath); } // Then Others foreach (var provider in requireJSConfigProviders.Value) { foreach (var pair in provider.Paths) { if (!config.Paths.ContainsKey(pair.Key)) { config.Paths.Add(pair.Key, pair.Value); } } foreach (var pair in provider.Shim) { if (!config.Shim.ContainsKey(pair.Key)) { config.Shim.Add(pair.Key, pair.Value); } } } return Json(config, JsonRequestBehavior.AllowGet); } } public struct RequireJsConfig { public Dictionary<string, string> Paths { get; set; } public Dictionary<string, string[]> Shim { get; set; } } }
30.666667
95
0.537888
[ "MIT" ]
artinite21/KoreCMS
KoreCMS/Areas/Admin/Controllers/HomeController.cs
3,222
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; using System.Data.Entity; using System.ComponentModel.DataAnnotations.Schema; namespace MvcThesis { [Table("webpages_Roles")] public class Role { public Role() { Members = new List<MvcThesisMembership>(); PermissionsInRoles = new List<PermissionsInRoles>(); } [Key] [Display(Name = "ID")] public int RoleId { get; set; } [Required(ErrorMessage="请输入名称")] [Display(Name = "名称")] [StringLength(256)] public string RoleName { get; set; } public ICollection<MvcThesisMembership> Members { get; set; } [ForeignKey("RoleId")] public ICollection<PermissionsInRoles> PermissionsInRoles { set; get; } } }
25.166667
79
0.640177
[ "Apache-2.0" ]
KingsoChina/MvcThesis
MvcThesis/Models/Membership/Models/Role.cs
922
C#
// Decompiled with JetBrains decompiler // Type: WebView2.ICoreWebView2HttpHeadersCollectionIterator // Assembly: WebView2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null // MVID: 680EA815-80DF-438D-AA0D-D4F0EB9B8A6C // Assembly location: O:\webview2\V9538\WebView2.dll using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Diga.WebView2.Interop { [Guid("4212F3A7-0FBC-4C9C-8118-17ED6370C1B3")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ICoreWebView2HttpHeadersCollectionIterator { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetCurrentHeader([MarshalAs(UnmanagedType.LPWStr)] out string name, [MarshalAs(UnmanagedType.LPWStr)] out string value); [DispId(1610678273)] int HasCurrentHeader { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] get; } [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void MoveNext(out int hasNext); } }
39.814815
129
0.796279
[ "MIT" ]
ITAgnesmeyer/Diga.WebView2
Archive/V9538/Diga.WebView2.Interop.V9538/ICoreWebView2HttpHeadersCollectionIterator.cs
1,077
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("TypeAwesome.ExampleFrontend")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TypeAwesome.ExampleFrontend")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("4f057d66-869b-479f-aad6-5145fb3e8a63")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.388889
84
0.755427
[ "MIT" ]
2718e/TypeAwesome
TypeAwesome.ExampleFrontend/Properties/AssemblyInfo.cs
1,385
C#
using Clarity.App.Worlds.Assets; using Clarity.Common.Infra.Files; using Clarity.Engine.Objects.WorldTree; namespace Clarity.App.Worlds.SaveLoad { public interface IFileLoadInfo { IFileSystem FileSystem { get; } string FilePath { get; } bool PreferReadOnly { get; } IAsset OnFoundAsset(AssetLoadInfo assetLoadInfo); void OnLoadedWorld(IWorld world); void OnLoadedReadOnlyWorld(IWorld world); void OnLoadedNoWorld(); } }
28.764706
57
0.693252
[ "MIT" ]
Zulkir/ClarityWorlds
Source/Clarity.App.Worlds/SaveLoad/IFileLoadInfo.cs
491
C#
using System.Collections.Generic; using System.Linq; using Xunit.Abstractions; using Xunit.Internal; using Xunit.v3; namespace Xunit.Runner.v2 { /// <summary> /// Provides a class which wraps <see cref="_IAssemblyInfo"/> instances to implement <see cref="IAssemblyInfo"/>. /// </summary> public class Xunit2AssemblyInfo : LongLivedMarshalByRefObject, IAssemblyInfo { /// <summary> /// Initializes a new instance of the <see cref="Xunit2AssemblyInfo"/> class. /// </summary> /// <param name="v3AssemblyInfo">The v3 assembly info to wrap.</param> public Xunit2AssemblyInfo(_IAssemblyInfo v3AssemblyInfo) { V3AssemblyInfo = Guard.ArgumentNotNull(nameof(v3AssemblyInfo), v3AssemblyInfo); } /// <inheritdoc/> public string? AssemblyPath => V3AssemblyInfo.AssemblyPath; /// <inheritdoc/> public string Name => V3AssemblyInfo.Name; /// <summary> /// Gets the underlying xUnit.net v3 <see cref="_IAssemblyInfo"/> that this class is wrapping. /// </summary> public _IAssemblyInfo V3AssemblyInfo { get; } /// <inheritdoc/> public IEnumerable<IAttributeInfo> GetCustomAttributes(string assemblyQualifiedAttributeTypeName) => V3AssemblyInfo.GetCustomAttributes(assemblyQualifiedAttributeTypeName).Select(a => new Xunit2AttributeInfo(a)).ToList(); /// <inheritdoc/> public ITypeInfo? GetType(string typeName) { var v3TypeInfo = V3AssemblyInfo.GetType(typeName); return v3TypeInfo == null ? null : new Xunit2TypeInfo(v3TypeInfo); } /// <inheritdoc/> public IEnumerable<ITypeInfo> GetTypes(bool includePrivateTypes) => V3AssemblyInfo.GetTypes(includePrivateTypes).Select(t => new Xunit2TypeInfo(t)).ToList(); } }
33.46
123
0.738793
[ "Apache-2.0" ]
BruceForstall/xunit
src/xunit.v3.runner.utility/Frameworks/v2/Reflection/Xunit2AssemblyInfo.cs
1,675
C#
using UnityEngine; using UnityEngine.UI; public class SensitivityController : MonoBehaviour { [SerializeField] private Slider sensitivity; //Set value based on player prefs and saves it when value changes private void Awake() => sensitivity.value = PlayerPrefs.GetFloat(PlayerPrefsKeys.TapSensitivity, 8); public void ChangeSensitivity(float value) => PlayerPrefs.SetFloat(PlayerPrefsKeys.TapSensitivity, value); }
36.166667
110
0.78341
[ "MIT" ]
SpeedyE1780/Brick-Breaker
Assets/Scripts/Utilities/SensitivityController.cs
436
C#
/* _BEGIN_TEMPLATE_ { "id": "ULD_135a", "name": [ "结识古树", "Befriend the Ancient" ], "text": [ "召唤一棵6/6并具有<b>嘲讽</b>的\n古树。", "Summon a 6/6 Ancient with <b>Taunt</b>." ], "cardClass": "DRUID", "type": "SPELL", "cost": 0, "rarity": null, "set": "ULDUM", "collectible": null, "dbfId": 53578 } _END_TEMPLATE_ */ namespace HREngine.Bots { class Sim_ULD_135a : SimTemplate //* 结识古树 Befriend the Ancient { //Summon a 6/6 Ancient with <b>Taunt</b>. //召唤一棵6/6并具有<b>嘲讽</b>的古树。 } }
18.517241
66
0.556797
[ "MIT" ]
chi-rei-den/Silverfish
cards/ULDUM/ULD/Sim_ULD_135a.cs
605
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CollisionAndDestruye : MonoBehaviour { //public GameObject Banana; public GameObject explosion; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.tag == "Banana") { Debug.Log("why wont you work ;_;"); Instantiate(explosion, transform.position, transform.rotation); //Destroy(Banana); Destroy(GameObject.FindWithTag("Banana")); } if (other.gameObject.tag == "Patata") { Debug.Log("why wont you work ;_;"); Instantiate(explosion, transform.position, transform.rotation); //Destroy(Banana); GameObject.FindWithTag("Patata"); } } }
20.307692
66
0.700758
[ "MIT" ]
cheitovilla/ScriptsEssentials
Scripts IF/Assets/Scripts/CollisionAndDestruye.cs
794
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the mediaconvert-2017-08-29.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.MediaConvert.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.MediaConvert.Model.Internal.MarshallTransformations { /// <summary> /// VideoPreprocessor Marshaller /// </summary> public class VideoPreprocessorMarshaller : IRequestMarshaller<VideoPreprocessor, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(VideoPreprocessor requestObject, JsonMarshallerContext context) { if(requestObject.IsSetColorCorrector()) { context.Writer.WritePropertyName("colorCorrector"); context.Writer.WriteObjectStart(); var marshaller = ColorCorrectorMarshaller.Instance; marshaller.Marshall(requestObject.ColorCorrector, context); context.Writer.WriteObjectEnd(); } if(requestObject.IsSetDeinterlacer()) { context.Writer.WritePropertyName("deinterlacer"); context.Writer.WriteObjectStart(); var marshaller = DeinterlacerMarshaller.Instance; marshaller.Marshall(requestObject.Deinterlacer, context); context.Writer.WriteObjectEnd(); } if(requestObject.IsSetDolbyVision()) { context.Writer.WritePropertyName("dolbyVision"); context.Writer.WriteObjectStart(); var marshaller = DolbyVisionMarshaller.Instance; marshaller.Marshall(requestObject.DolbyVision, context); context.Writer.WriteObjectEnd(); } if(requestObject.IsSetImageInserter()) { context.Writer.WritePropertyName("imageInserter"); context.Writer.WriteObjectStart(); var marshaller = ImageInserterMarshaller.Instance; marshaller.Marshall(requestObject.ImageInserter, context); context.Writer.WriteObjectEnd(); } if(requestObject.IsSetNoiseReducer()) { context.Writer.WritePropertyName("noiseReducer"); context.Writer.WriteObjectStart(); var marshaller = NoiseReducerMarshaller.Instance; marshaller.Marshall(requestObject.NoiseReducer, context); context.Writer.WriteObjectEnd(); } if(requestObject.IsSetTimecodeBurnin()) { context.Writer.WritePropertyName("timecodeBurnin"); context.Writer.WriteObjectStart(); var marshaller = TimecodeBurninMarshaller.Instance; marshaller.Marshall(requestObject.TimecodeBurnin, context); context.Writer.WriteObjectEnd(); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static VideoPreprocessorMarshaller Instance = new VideoPreprocessorMarshaller(); } }
34.5
110
0.635543
[ "Apache-2.0" ]
Melvinerall/aws-sdk-net
sdk/src/Services/MediaConvert/Generated/Model/Internal/MarshallTransformations/VideoPreprocessorMarshaller.cs
4,209
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PerceptronLibrary { public class NumberFeatureExtractor : FeatureExtractor { private string _name = null; private bool _useAmount = true; private bool _useAmountR0 = true; private bool _useAmountR10 = true; private bool _useAmountR100 = true; private bool _useDocAmount = true; private bool _useDocAmountR0 = true; private bool _useDocAmountR10 = true; private bool _useDocAmountR100 = true; private bool _useProportion = true; public override string Name { get { return _name; } set { _name = value; } } public NumberFeatureExtractor() { _name = "n"; } public NumberFeatureExtractor(string name) { _name = name; } public NumberFeatureExtractor(string name,bool useAmount, bool useAmountR0, bool useAmountR10, bool useAmountR100, bool useProportion, bool useDocAmount, bool useDocAmountR0, bool useDocAmountR10, bool useDocAmountR100) { _useAmount = useAmount; _useAmountR0 = useAmountR0; _useAmountR10 = useAmountR10; _useAmountR100 = useAmountR100; _useDocAmount = useDocAmount; _useDocAmountR0 = useDocAmountR0; _useDocAmountR10 = useDocAmountR10; _useDocAmountR100 = useDocAmountR100; _useProportion = useProportion; _name = name; } public override List<string> GetValuesFromEntry(EntryElement entry) { HashSet<string> res = new HashSet<string>(); StringBuilder current = new StringBuilder(50); if (_useAmount) { current.Append(Name); current.Append("_a_"); current.Append(entry.rowAmount.ToString()); res.Add(current.ToString()); } if (_useAmountR0) { current = new StringBuilder(50); current.Append(Name); current.Append("_a_r_"); current.Append(Math.Round(entry.rowAmount, 0).ToString()); res.Add(current.ToString()); } if (_useAmountR10) { current = new StringBuilder(50); current.Append(Name); current.Append("_a_r10_"); current.Append(Math.Round(entry.rowAmount / 10, 0).ToString()); res.Add(current.ToString()); } if (_useAmountR100) { current = new StringBuilder(50); current.Append(Name); current.Append("_a_r100_"); current.Append(Math.Round(entry.rowAmount / 100, 0).ToString()); res.Add(current.ToString()); } if (_useProportion) { current = new StringBuilder(50); current.Append(Name); current.Append("_p_"); current.Append(entry.proportion.ToString()); res.Add(current.ToString()); } if (_useDocAmount) { current.Append(Name); current.Append("_da_"); current.Append(entry.docAmount.ToString()); res.Add(current.ToString()); } if (_useDocAmountR0) { current = new StringBuilder(50); current.Append(Name); current.Append("_da_r_"); current.Append(Math.Round(entry.docAmount, 0).ToString()); res.Add(current.ToString()); } if (_useDocAmountR10) { current = new StringBuilder(50); current.Append(Name); current.Append("_da_r10_"); current.Append(Math.Round(entry.docAmount / 10, 0).ToString()); res.Add(current.ToString()); } if (_useDocAmountR100) { current = new StringBuilder(50); current.Append(Name); current.Append("_da_r100_"); current.Append(Math.Round(entry.docAmount / 100, 0).ToString()); res.Add(current.ToString()); } return res.ToList(); } } }
35.601504
228
0.502429
[ "MIT" ]
tilde-nlp/averaged-perceptron-classifier
PerceptronClassificationForAccounting/NumberFeatureExtractor.cs
4,737
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.ServiceFabric.V20210701Preview.Outputs { /// <summary> /// Identities for the virtual machine scale set under the node type. /// </summary> [OutputType] public sealed class VmManagedIdentityResponse { /// <summary> /// The list of user identities associated with the virtual machine scale set under the node type. Each entry will be an ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. /// </summary> public readonly ImmutableArray<string> UserAssignedIdentities; [OutputConstructor] private VmManagedIdentityResponse(ImmutableArray<string> userAssignedIdentities) { UserAssignedIdentities = userAssignedIdentities; } } }
38.064516
302
0.724576
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/ServiceFabric/V20210701Preview/Outputs/VmManagedIdentityResponse.cs
1,180
C#
//----------------------------------------------------------------------------- // Copyright : (c) Chris Moore, 2020 // License : MIT //----------------------------------------------------------------------------- namespace Z0.Vec { using System; using System.Runtime.CompilerServices; using static Root; using static core; public struct vector<N,T> : IVector<T> where T : unmanaged where N : unmanaged, ITypeNat { public static ByteSize SZ => size<T>()*Typed.nat32u<N>(); readonly Index<T> Data; [MethodImpl(Inline)] internal vector(T[] src) { Data = src; } public Span<T> Cells { [MethodImpl(Inline)] get => Data.Edit; } [MethodImpl(Inline)] public ref T Cell(uint index) => ref Data[index]; public ref T this[uint index] { [MethodImpl(Inline)] get => ref Cell(index); } public string Format() => api.format(this); public override string ToString() => Format(); BitWidth IBlittable.StorageWidth => Data.Length*width<T>(); BitWidth IBlittable.ContentWidth => Data.Length* Typed.nat32u<N>(); uint IVector.N => Typed.nat32u<N>(); public static vector<N,T> Empty => default; } partial struct api { [MethodImpl(Inline)] public static vector<N,T> v<N,T>(N n, T[] src) where N : unmanaged, ITypeNat where T : unmanaged { if(Typed.nat32i<N>() != src.Length) return vector<N,T>.Empty; else return new vector<N,T>(src); } public static string format<N,T>(in vector<N,T> src) where T : unmanaged where N : unmanaged, ITypeNat { var cells = src.Cells; var count = cells.Length; var buffer = TextTools.buffer(); var last = cells.Length - 1; for(var i=0; i<count; i++) { ref readonly var cell = ref skip(cells,i); var fmt = string.Format("{0}", cell).Trim(); if(nonempty(fmt)) { buffer.Append(fmt); if(i != last) buffer.Append(Chars.Comma); } else break; } return buffer.Emit(); } } }
25.81
79
0.437427
[ "BSD-3-Clause" ]
0xCM/z0
src/core/src/vectors/vN.cs
2,581
C#
// Copyright (c) zhenlei520 All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Newtonsoft.Json; namespace EInfrastructure.Core.AliYun.Tbk.Respose.Success { /// <summary> /// 淘宝客淘口令 /// </summary> public class TaobaoTbkTpwdCreateResponseDto { /// <summary> /// /// </summary> [JsonProperty(PropertyName = "data")] public DataDto Data { get; set; } /// <summary> /// data数据 /// </summary> public class DataDto { /// <summary> /// 淘口令 /// </summary> [JsonProperty(PropertyName = "model")] public string Model { get; set; } } } }
24.935484
95
0.538163
[ "MIT" ]
DavideYang125/System.Extension.Core
src/Marketing/AliMaMa/src/EInfrastructure.Core.AliYun.Tbk/Respose/Success/TaobaoTbkTpwdCreateResponseDto.cs
795
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using Bicep.Core.Diagnostics; using Bicep.Core.Extensions; namespace Bicep.Core.Parsing { public class ExpectedTokenException : Exception { public ExpectedTokenException(Token unexpectedToken, DiagnosticBuilder.ErrorBuilderDelegate errorFunc) : base() { // To avoid the squiggly spanning multiple lines, return a 0-length span at the end of the line for a newline token. var errorSpan = unexpectedToken.Type == TokenType.NewLine ? unexpectedToken.ToZeroLengthSpan() : unexpectedToken.Span; Error = errorFunc(DiagnosticBuilder.ForPosition(errorSpan)); } public ErrorDiagnostic Error { get; } public override string Message => Error.Message; } }
32.185185
128
0.675489
[ "MIT" ]
Agazoth/bicep
src/Bicep.Core/Parsing/ExpectedTokenException.cs
869
C#
namespace brewjournal.Domain.Enums { public enum TemperatureUnit { DegreesCelsius, DegreesFarenheit } }
14.777778
35
0.646617
[ "MIT" ]
matt-goldman/brewjournal
src/Domain/Enums/TemperatureUnit.cs
135
C#
using System; class Program { static void Main(string[] args) { // input // 0.05, 0.10, 0.20, 0.50, and 1.00 double n1 = double.Parse(Console.ReadLine()); n1 *= 0.05; double n2 = double.Parse(Console.ReadLine()); n2 *= 0.10; double n3 = double.Parse(Console.ReadLine()); n3 *= 0.20; double n4 = double.Parse(Console.ReadLine()); n4 *= 0.50; double n5 = double.Parse(Console.ReadLine()); n5 *= 1.00; double A = double.Parse(Console.ReadLine()); double P = double.Parse(Console.ReadLine()); double sum = n1+n2+n3+n4+n5; // logic double substract = A - P; if (A < P) { Console.WriteLine("More {0:F2}", (P - A)); } else if ((A - P) <= sum) { Console.WriteLine("Yes {0:F2}", (sum - (A - P))); } else { Console.WriteLine("No {0:F2}", ((A - P) - sum)); } } }
26.736842
61
0.461614
[ "MIT" ]
kossov/Telerik-Academy
C#/C#1/ExamPrep/23June2013/01.VendingMachine/Program.cs
1,018
C#
using System.Web; using System.Web.Mvc; using HuiNet.Admin.Utils; namespace HuiNet.Admin { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleAjaxErrorAttribute()); } } }
19.666667
80
0.671186
[ "Apache-2.0" ]
ericktse/HuiNet.Admin
HuiNet.Admin/App_Start/FilterConfig.cs
297
C#
using System.Collections; using System.Collections.Generic; using Tools.BehaviourTree; using UnityEngine; public abstract class UnitTask : Task { protected AIController AIController { get; private set; } protected Unit Unit { get; private set; } protected UnitBlackboard UnitBlackboard { get; private set; } public override void Init() { AIController = (AIController)BehaviourTree.Executor; Unit = AIController.Unit; UnitBlackboard = (UnitBlackboard)BehaviourTree.Blackboard; } public override void Begin() { } }
27.142857
66
0.715789
[ "MIT" ]
AlexandrKlimkin/MilitaryStrategy-2.0
Assets/Scripts/Gameplay/AI/My/BehaviourTree/Tasks/UnitTask.cs
572
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore; #nullable disable namespace ModBot.Models { [Table("anonbans")] public partial class AnonBan { [Key] [Column("user")] public string User { get; set; } [Key] [Column("server")] public string Server { get; set; } public ulong ExpiresAt { get; set; } } }
22.130435
51
0.654224
[ "MIT" ]
scratchyone/ModBotSharp
DBModels/AnonBan.cs
511
C#
// ***************************************************************************** // // © Component Factory Pty Ltd, 2006 - 2016. All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, PO Box 1504, // Glen Waverley, Vic 3150, Australia and are supplied subject to licence terms. // // Version 5.451.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Drawing; using System.Windows.Forms; using ComponentFactory.Krypton.Navigator; using ComponentFactory.Krypton.Toolkit; using ComponentFactory.Krypton.Workspace; namespace WorkspacePersistence { public partial class Form1 : Form { private int _count = 1; private byte[] _byteArray; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Create three cells that each contain two pages KryptonWorkspaceCell cell1 = new KryptonWorkspaceCell(); KryptonWorkspaceCell cell2 = new KryptonWorkspaceCell(); KryptonWorkspaceCell cell3 = new KryptonWorkspaceCell(); cell1.Pages.AddRange(new KryptonPage[] { CreatePage(), CreatePage() }); cell2.Pages.AddRange(new KryptonPage[] { CreatePage(), CreatePage() }); cell3.Pages.AddRange(new KryptonPage[] { CreatePage(), CreatePage() }); // Create a vertical sequence that contains two of the pages KryptonWorkspaceSequence sequence = new KryptonWorkspaceSequence(Orientation.Vertical); sequence.Children.AddRange(new KryptonWorkspaceCell[] { cell2, cell3 }); // Remove starting contents and add a cell with a sequence kryptonWorkspace.Root.Children.Clear(); kryptonWorkspace.Root.Children.Add(cell1); kryptonWorkspace.Root.Children.Add(sequence); } private void bSaveToArray_Click(object sender, EventArgs e) { _byteArray = kryptonWorkspace.SaveLayoutToArray(); bLoadFromArray.Enabled = true; } private void bLoadFromArray_Click(object sender, EventArgs e) { kryptonWorkspace.LoadLayoutFromArray(_byteArray); } private void bSaveToFile_Click(object sender, EventArgs e) { if (saveFileDialog.ShowDialog() == DialogResult.OK) kryptonWorkspace.SaveLayoutToFile(saveFileDialog.FileName); } private void bLoadFromFile_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) { try { kryptonWorkspace.LoadLayoutFromFile(openFileDialog.FileName); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error Loading from File"); } } } private void kryptonWorkspace_PageSaving(object sender, PageSavingEventArgs e) { // Get access to the text box inside the page KryptonRichTextBox rtb = (KryptonRichTextBox)e.Page.Controls[0]; // Save the text in the textbox into the per-page storage e.XmlWriter.WriteCData(rtb.Text); } private void kryptonWorkspace_PageLoading(object sender, PageLoadingEventArgs e) { KryptonRichTextBox rtb; // If a new page then it does not have any children... if (e.Page.Controls.Count == 0) { // Add a rich text box as the child of the page rtb = new KryptonRichTextBox(); rtb.Dock = DockStyle.Fill; rtb.StateCommon.Border.Draw = InheritBool.False; e.Page.Controls.Add(rtb); e.Page.Padding = new Padding(5); } else rtb = (KryptonRichTextBox)e.Page.Controls[0]; // Move past the current xml element to the child CData e.XmlReader.Read(); // Read in the stored text and use it in the rich text box rtb.Text = e.XmlReader.ReadContentAsString(); } private void kryptonWorkspace_RecreateLoadingPage(object sender, RecreateLoadingPageEventArgs e) { e.Page = new KryptonPage(); } private void kryptonWorkspace_PagesUnmatched(object sender, PagesUnmatchedEventArgs e) { foreach (KryptonPage page in e.Unmatched) Console.WriteLine("Unmatched Page {0}", page.Text); } private void buttonAddPage_Click(object sender, EventArgs e) { // Add page to the currently active cell if (kryptonWorkspace.ActiveCell != null) { kryptonWorkspace.ActiveCell.Pages.Add(CreatePage()); kryptonWorkspace.ActiveCell.SelectedIndex = kryptonWorkspace.ActiveCell.Pages.Count - 1; } } private void buttonClearPages_Click(object sender, EventArgs e) { kryptonWorkspace.Root.Children.Clear(); } private void buttonClose_Click(object sender, EventArgs e) { Close(); } private KryptonPage CreatePage() { // Give each page a unique number string pageNumber = (_count++).ToString(); // Create a new page and give it a name and image KryptonPage page = new KryptonPage(); page.Text = "P" + pageNumber; page.TextTitle = "P" + pageNumber + " Title"; page.TextDescription = "P" + pageNumber + " Description"; page.ImageSmall = imageList.Images[_count % imageList.Images.Count]; page.MinimumSize = new Size(200, 250); // Create a rich text box with some sample text inside KryptonRichTextBox rtb = new KryptonRichTextBox(); rtb.Text = "This page (" + page.Text + ") contains a rich text box control as example content.\n\nTry saving the layout and then dragging the page headers in order to rearrange the workspace layout. Once altered you can use the load button to get back to the original state."; rtb.Dock = DockStyle.Fill; rtb.StateCommon.Border.Draw = InheritBool.False; // Add rich text box as the contents of the page page.Padding = new Padding(5); page.Controls.Add(rtb); return page; } } }
38.572254
288
0.591338
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-NET-5.451
Source/Demos/Non-NuGet/Krypton Workspace Examples/Workspace Persistence/Form1.cs
6,676
C#
namespace WinFormNorrisAPI { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.CboCategory = new System.Windows.Forms.ComboBox(); this.BtnQueryAPI = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // CboCategory // this.CboCategory.FormattingEnabled = true; this.CboCategory.Location = new System.Drawing.Point(6, 21); this.CboCategory.Name = "CboCategory"; this.CboCategory.Size = new System.Drawing.Size(121, 21); this.CboCategory.TabIndex = 0; this.CboCategory.SelectedIndexChanged += new System.EventHandler(this.CboCategory_SelectedIndexChanged); // // BtnQueryAPI // this.BtnQueryAPI.Location = new System.Drawing.Point(133, 19); this.BtnQueryAPI.Name = "BtnQueryAPI"; this.BtnQueryAPI.Size = new System.Drawing.Size(85, 23); this.BtnQueryAPI.TabIndex = 1; this.BtnQueryAPI.Text = "Search"; this.BtnQueryAPI.UseVisualStyleBackColor = true; this.BtnQueryAPI.Click += new System.EventHandler(this.BtnQueryAPI_Click); // // groupBox1 // this.groupBox1.Controls.Add(this.CboCategory); this.groupBox1.Controls.Add(this.BtnQueryAPI); this.groupBox1.Location = new System.Drawing.Point(12, 12); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(221, 56); this.groupBox1.TabIndex = 2; this.groupBox1.TabStop = false; this.groupBox1.Text = "Controls"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(245, 80); this.Controls.Add(this.groupBox1); this.Name = "Form1"; this.Text = "Chuck Norris"; this.groupBox1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ComboBox CboCategory; private System.Windows.Forms.Button BtnQueryAPI; private System.Windows.Forms.GroupBox groupBox1; } }
37.943182
116
0.575921
[ "MIT" ]
TannerDisney/ChuckNorris-DotNetAPI
WinFormNorrisAPI/Form1.Designer.cs
3,341
C#
using System; using System.Collections.Generic; using JetBrains.Annotations; using essentialMix.Comparers; namespace essentialMix.Collections; [Serializable] public class NumericRangeList<T> : List<NumericRange<T>>, IComparable<NumericRangeList<T>>, IComparable, IEquatable<NumericRangeList<T>> where T : struct, IComparable, IComparable<T>, IEquatable<T>, IConvertible, IFormattable { public NumericRangeList() { } public NumericRangeList([NotNull] List<NumericRange<T>> list) : base(list) { } public NumericRangeList([NotNull] IEnumerable<NumericRange<T>> collection) : base(collection) { } public virtual TResult Simplify<TResult>(NumericRangeComparer<T> comparer = null, TResult defaultValue = default(TResult)) where TResult : List<NumericRange<T>>, new() { return NumericRangeCollectionComparer<T>.Default.Simplify(this, comparer, defaultValue); } public virtual int CompareTo(NumericRangeList<T> other) { return NumericRangeCollectionComparer<T>.Default.Compare(this, other); } public virtual int CompareTo(object obj) { return ReferenceComparer.Default.Compare(this, obj); } public virtual bool Equals(NumericRangeList<T> other) { return NumericRangeCollectionComparer<T>.Default.Equals(this, other); } }
33.702703
136
0.778669
[ "MIT" ]
asm2025/essentialMix
Standard/essentialMix/Collections/NumericRangeList.cs
1,249
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; namespace Microsoft.Diagnostics.Runtime.CorDebug { // Technically 0x40 is the only flag that could be set in combination with others, but we might // want to test for the presence of this value so we'll mark the enum as 'Flags'. // But in almost all cases we just use one of the individual values. // Reflection (Enum.ToString) appears to do a good job of picking the simplest combination to // represent a value as a set of flags, but the Visual Studio debugger does not - it just does // a linear search from the start looking for matches. To make debugging these values easier, // their order is reversed so that VS always produces the simplest representation. [Flags] public enum CorElementType { ELEMENT_TYPE_PINNED = 0x45, ELEMENT_TYPE_SENTINEL = 0x41, ELEMENT_TYPE_MODIFIER = 0x40, ELEMENT_TYPE_MAX = 0x22, ELEMENT_TYPE_INTERNAL = 0x21, ELEMENT_TYPE_CMOD_OPT = 0x20, ELEMENT_TYPE_CMOD_REQD = 0x1f, ELEMENT_TYPE_MVAR = 0x1e, ELEMENT_TYPE_SZARRAY = 0x1d, ELEMENT_TYPE_OBJECT = 0x1c, ELEMENT_TYPE_FNPTR = 0x1b, ELEMENT_TYPE_U = 0x19, ELEMENT_TYPE_I = 0x18, ELEMENT_TYPE_TYPEDBYREF = 0x16, ELEMENT_TYPE_GENERICINST = 0x15, ELEMENT_TYPE_ARRAY = 0x14, ELEMENT_TYPE_VAR = 0x13, ELEMENT_TYPE_CLASS = 0x12, ELEMENT_TYPE_VALUETYPE = 0x11, ELEMENT_TYPE_BYREF = 0x10, ELEMENT_TYPE_PTR = 0xf, ELEMENT_TYPE_STRING = 0xe, ELEMENT_TYPE_R8 = 0xd, ELEMENT_TYPE_R4 = 0xc, ELEMENT_TYPE_U8 = 0xb, ELEMENT_TYPE_I8 = 0xa, ELEMENT_TYPE_U4 = 0x9, ELEMENT_TYPE_I4 = 0x8, ELEMENT_TYPE_U2 = 0x7, ELEMENT_TYPE_I2 = 0x6, ELEMENT_TYPE_U1 = 0x5, ELEMENT_TYPE_I1 = 0x4, ELEMENT_TYPE_CHAR = 0x3, ELEMENT_TYPE_BOOLEAN = 0x2, ELEMENT_TYPE_VOID = 0x1, ELEMENT_TYPE_END = 0x0 } }
35.031746
99
0.669234
[ "MIT" ]
TylerAP/clrmd
src/Microsoft.Diagnostics.Runtime/src/ICorDebug/CorDebugWrappers/CorElementType.cs
2,207
C#
using System.Collections.Generic; using System.Linq; namespace Lucene.Net.Search { /* * 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. */ using BooleanWeight = Lucene.Net.Search.BooleanQuery.BooleanWeight; /// <summary> /// See the description in <see cref="BooleanScorer"/> comparing /// <see cref="BooleanScorer"/> &amp; <see cref="BooleanScorer2"/>. /// <para/> /// An alternative to <see cref="BooleanScorer"/> that also allows a minimum number /// of optional scorers that should match. /// <para/>Implements SkipTo(), and has no limitations on the numbers of added scorers. /// <para/>Uses <see cref="ConjunctionScorer"/>, <see cref="DisjunctionScorer"/>, <see cref="ReqOptSumScorer"/> and <see cref="ReqExclScorer"/>. /// </summary> internal class BooleanScorer2 : Scorer { private readonly IList<Scorer> requiredScorers; private readonly IList<Scorer> optionalScorers; private readonly IList<Scorer> prohibitedScorers; private class Coordinator { private readonly BooleanScorer2 outerInstance; internal readonly float[] coordFactors; internal Coordinator(BooleanScorer2 outerInstance, int maxCoord, bool disableCoord) { this.outerInstance = outerInstance; coordFactors = new float[outerInstance.optionalScorers.Count + outerInstance.requiredScorers.Count + 1]; for (int i = 0; i < coordFactors.Length; i++) { coordFactors[i] = disableCoord ? 1.0f : ((BooleanWeight)outerInstance.m_weight).Coord(i, maxCoord); } } internal int nrMatchers; // to be increased by score() of match counting scorers. } private readonly Coordinator coordinator; /// <summary> /// The scorer to which all scoring will be delegated, /// except for computing and using the coordination factor. /// </summary> private readonly Scorer countingSumScorer; /// <summary> /// The number of optionalScorers that need to match (if there are any) </summary> private readonly int minNrShouldMatch; private int doc = -1; /// <summary> /// Creates a <see cref="Scorer"/> with the given similarity and lists of required, /// prohibited and optional scorers. In no required scorers are added, at least /// one of the optional scorers will have to match during the search. /// </summary> /// <param name="weight"> /// The <see cref="BooleanWeight"/> to be used. </param> /// <param name="disableCoord"> /// If this parameter is <c>true</c>, coordination level matching /// (<see cref="Similarities.Similarity.Coord(int, int)"/>) is not used. </param> /// <param name="minNrShouldMatch"> /// The minimum number of optional added scorers that should match /// during the search. In case no required scorers are added, at least /// one of the optional scorers will have to match during the search. </param> /// <param name="required"> /// The list of required scorers. </param> /// <param name="prohibited"> /// The list of prohibited scorers. </param> /// <param name="optional"> /// The list of optional scorers. </param> /// <param name="maxCoord"> /// The max coord. </param> public BooleanScorer2(BooleanWeight weight, bool disableCoord, int minNrShouldMatch, IList<Scorer> required, IList<Scorer> prohibited, IList<Scorer> optional, int maxCoord) : base(weight) { if (minNrShouldMatch < 0) { throw new System.ArgumentException("Minimum number of optional scorers should not be negative"); } this.minNrShouldMatch = minNrShouldMatch; optionalScorers = optional; requiredScorers = required; prohibitedScorers = prohibited; coordinator = new Coordinator(this, maxCoord, disableCoord); countingSumScorer = MakeCountingSumScorer(disableCoord); } /// <summary> /// Count a scorer as a single match. </summary> private class SingleMatchScorer : Scorer { private readonly BooleanScorer2 outerInstance; internal Scorer scorer; internal int lastScoredDoc = -1; // Save the score of lastScoredDoc, so that we don't compute it more than // once in score(). internal float lastDocScore = float.NaN; internal SingleMatchScorer(BooleanScorer2 outerInstance, Scorer scorer) : base(scorer.m_weight) { this.outerInstance = outerInstance; this.scorer = scorer; } public override float GetScore() { int doc = DocID; if (doc >= lastScoredDoc) { if (doc > lastScoredDoc) { lastDocScore = scorer.GetScore(); lastScoredDoc = doc; } outerInstance.coordinator.nrMatchers++; } return lastDocScore; } public override int Freq { get { return 1; } } public override int DocID { get { return scorer.DocID; } } public override int NextDoc() { return scorer.NextDoc(); } public override int Advance(int target) { return scorer.Advance(target); } public override long GetCost() { return scorer.GetCost(); } } private Scorer CountingDisjunctionSumScorer(IList<Scorer> scorers, int minNrShouldMatch) { // each scorer from the list counted as a single matcher if (minNrShouldMatch > 1) { return new MinShouldMatchSumScorerAnonymousInnerClassHelper(this, m_weight, scorers, minNrShouldMatch); } else { // we pass null for coord[] since we coordinate ourselves and override score() return new DisjunctionSumScorerAnonymousInnerClassHelper(this, m_weight, scorers.ToArray(), null); } } private class MinShouldMatchSumScorerAnonymousInnerClassHelper : MinShouldMatchSumScorer { private readonly BooleanScorer2 outerInstance; public MinShouldMatchSumScorerAnonymousInnerClassHelper(BooleanScorer2 outerInstance, Lucene.Net.Search.Weight weight, IList<Scorer> scorers, int minNrShouldMatch) : base(weight, scorers, minNrShouldMatch) { this.outerInstance = outerInstance; } public override float GetScore() { outerInstance.coordinator.nrMatchers += base.m_nrMatchers; return base.GetScore(); } } private class DisjunctionSumScorerAnonymousInnerClassHelper : DisjunctionSumScorer { private readonly BooleanScorer2 outerInstance; public DisjunctionSumScorerAnonymousInnerClassHelper(BooleanScorer2 outerInstance, Weight weight, Scorer[] subScorers, float[] coord) : base(weight, subScorers, coord) { this.outerInstance = outerInstance; } public override float GetScore() { outerInstance.coordinator.nrMatchers += base.m_nrMatchers; return (float)base.m_score; } } private Scorer CountingConjunctionSumScorer(bool disableCoord, IList<Scorer> requiredScorers) { // each scorer from the list counted as a single matcher int requiredNrMatchers = requiredScorers.Count; return new ConjunctionScorerAnonymousInnerClassHelper(this, m_weight, requiredScorers.ToArray(), requiredNrMatchers); } private class ConjunctionScorerAnonymousInnerClassHelper : ConjunctionScorer { private readonly BooleanScorer2 outerInstance; private int requiredNrMatchers; public ConjunctionScorerAnonymousInnerClassHelper(BooleanScorer2 outerInstance, Weight weight, Scorer[] scorers, int requiredNrMatchers) : base(weight, scorers) { this.outerInstance = outerInstance; this.requiredNrMatchers = requiredNrMatchers; lastScoredDoc = -1; lastDocScore = float.NaN; } private int lastScoredDoc; // Save the score of lastScoredDoc, so that we don't compute it more than // once in score(). private float lastDocScore; public override float GetScore() { int doc = outerInstance.DocID; if (doc >= lastScoredDoc) { if (doc > lastScoredDoc) { lastDocScore = base.GetScore(); lastScoredDoc = doc; } outerInstance.coordinator.nrMatchers += requiredNrMatchers; } // All scorers match, so defaultSimilarity super.score() always has 1 as // the coordination factor. // Therefore the sum of the scores of the requiredScorers // is used as score. return lastDocScore; } } private Scorer DualConjunctionSumScorer(bool disableCoord, Scorer req1, Scorer req2) // non counting. { return new ConjunctionScorer(m_weight, new Scorer[] { req1, req2 }); // All scorers match, so defaultSimilarity always has 1 as // the coordination factor. // Therefore the sum of the scores of two scorers // is used as score. } /// <summary> /// Returns the scorer to be used for match counting and score summing. /// Uses requiredScorers, optionalScorers and prohibitedScorers. /// </summary> private Scorer MakeCountingSumScorer(bool disableCoord) // each scorer counted as a single matcher { return (requiredScorers.Count == 0) ? MakeCountingSumScorerNoReq(disableCoord) : MakeCountingSumScorerSomeReq(disableCoord); } private Scorer MakeCountingSumScorerNoReq(bool disableCoord) // No required scorers { // minNrShouldMatch optional scorers are required, but at least 1 int nrOptRequired = (minNrShouldMatch < 1) ? 1 : minNrShouldMatch; Scorer requiredCountingSumScorer; if (optionalScorers.Count > nrOptRequired) { requiredCountingSumScorer = CountingDisjunctionSumScorer(optionalScorers, nrOptRequired); } else if (optionalScorers.Count == 1) { requiredCountingSumScorer = new SingleMatchScorer(this, optionalScorers[0]); } else { requiredCountingSumScorer = CountingConjunctionSumScorer(disableCoord, optionalScorers); } return AddProhibitedScorers(requiredCountingSumScorer); } private Scorer MakeCountingSumScorerSomeReq(bool disableCoord) // At least one required scorer. { if (optionalScorers.Count == minNrShouldMatch) // all optional scorers also required. { List<Scorer> allReq = new List<Scorer>(requiredScorers); allReq.AddRange(optionalScorers); return AddProhibitedScorers(CountingConjunctionSumScorer(disableCoord, allReq)); } // optionalScorers.size() > minNrShouldMatch, and at least one required scorer else { Scorer requiredCountingSumScorer = requiredScorers.Count == 1 ? new SingleMatchScorer(this, requiredScorers[0]) : CountingConjunctionSumScorer(disableCoord, requiredScorers); if (minNrShouldMatch > 0) // use a required disjunction scorer over the optional scorers { return AddProhibitedScorers(DualConjunctionSumScorer(disableCoord, requiredCountingSumScorer, CountingDisjunctionSumScorer(optionalScorers, minNrShouldMatch))); // non counting } // minNrShouldMatch == 0 else { return new ReqOptSumScorer(AddProhibitedScorers(requiredCountingSumScorer), optionalScorers.Count == 1 ? new SingleMatchScorer(this, optionalScorers[0]) // require 1 in combined, optional scorer. : CountingDisjunctionSumScorer(optionalScorers, 1)); } } } /// <summary> /// Returns the scorer to be used for match counting and score summing. /// Uses the given required scorer and the prohibitedScorers. </summary> /// <param name="requiredCountingSumScorer"> A required scorer already built. </param> private Scorer AddProhibitedScorers(Scorer requiredCountingSumScorer) { return (prohibitedScorers.Count == 0) ? requiredCountingSumScorer : new ReqExclScorer(requiredCountingSumScorer, ((prohibitedScorers.Count == 1) ? prohibitedScorers[0] : new MinShouldMatchSumScorer(m_weight, prohibitedScorers))); // no prohibited } public override int DocID { get { return doc; } } public override int NextDoc() { return doc = countingSumScorer.NextDoc(); } public override float GetScore() { coordinator.nrMatchers = 0; float sum = countingSumScorer.GetScore(); return sum * coordinator.coordFactors[coordinator.nrMatchers]; } public override int Freq { get { return countingSumScorer.Freq; } } public override int Advance(int target) { return doc = countingSumScorer.Advance(target); } public override long GetCost() { return countingSumScorer.GetCost(); } public override ICollection<ChildScorer> GetChildren() { List<ChildScorer> children = new List<ChildScorer>(); foreach (Scorer s in optionalScorers) { children.Add(new ChildScorer(s, "SHOULD")); } foreach (Scorer s in prohibitedScorers) { children.Add(new ChildScorer(s, "MUST_NOT")); } foreach (Scorer s in requiredScorers) { children.Add(new ChildScorer(s, "MUST")); } return children; } } }
41.094388
258
0.589236
[ "Apache-2.0" ]
DiogenesPolanco/lucenenet
src/Lucene.Net/Search/BooleanScorer2.cs
16,109
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class PlayerHealth : MonoBehaviour { [Range(0.0f, 1.0f)] [Tooltip("How long the player can stay alive after being hit")] public float InvincibilitySeconds; private Rigidbody2D rb; private Color regularColor = new Color(0.66f, 0.66f, 0.66f, 1f); private bool invincible; public string resetSceneName; void Start() { rb = GetComponent<Rigidbody2D>(); invincible = false; } void Update() { if (gameObject.transform.position.y < -9) { Die(); } } void OnCollisionStay2D(Collision2D other) { if (other.gameObject.tag == "Enemy") { Rigidbody2D enemyRB = other.gameObject.GetComponent<Rigidbody2D>(); if (invincible == true) { return; } else { if (rb.position.y > enemyRB.position.y + 0.3f) { return; } if (PlayerBehaviour.playerState == 0) { Die(); } if (PlayerBehaviour.playerState == 2) { invincible = true; PlayerBehaviour.playerState = 0; GetComponent<SpriteRenderer>().color = regularColor; Invoke("StayAlive", InvincibilitySeconds); } else if (PlayerBehaviour.playerState == 1) { invincible = true; PlayerBehaviour.playerState = 0; GetComponent<SpriteRenderer>().color = regularColor; Invoke("StayAlive", InvincibilitySeconds); } } } } void StayAlive() { invincible = false; } void Die() { SceneManager.LoadScene(resetSceneName); } }
25.65
79
0.494152
[ "MIT" ]
MohamedAmin1996/Project_Mario-Clone
Assets/Scripts/PlayerHealth.cs
2,054
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using System.Text.Json; using Azure.Core; namespace Azure.Security.KeyVault.Storage.Models { public partial class DeletedStorageBundle { internal static DeletedStorageBundle DeserializeDeletedStorageBundle(JsonElement element) { Optional<string> recoveryId = default; Optional<DateTimeOffset> scheduledPurgeDate = default; Optional<DateTimeOffset> deletedDate = default; Optional<string> id = default; Optional<string> resourceId = default; Optional<string> activeKeyName = default; Optional<bool> autoRegenerateKey = default; Optional<string> regenerationPeriod = default; Optional<StorageAccountAttributes> attributes = default; Optional<IReadOnlyDictionary<string, string>> tags = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("recoveryId")) { recoveryId = property.Value.GetString(); continue; } if (property.NameEquals("scheduledPurgeDate")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } scheduledPurgeDate = property.Value.GetDateTimeOffset("U"); continue; } if (property.NameEquals("deletedDate")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } deletedDate = property.Value.GetDateTimeOffset("U"); continue; } if (property.NameEquals("id")) { id = property.Value.GetString(); continue; } if (property.NameEquals("resourceId")) { resourceId = property.Value.GetString(); continue; } if (property.NameEquals("activeKeyName")) { activeKeyName = property.Value.GetString(); continue; } if (property.NameEquals("autoRegenerateKey")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } autoRegenerateKey = property.Value.GetBoolean(); continue; } if (property.NameEquals("regenerationPeriod")) { regenerationPeriod = property.Value.GetString(); continue; } if (property.NameEquals("attributes")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } attributes = StorageAccountAttributes.DeserializeStorageAccountAttributes(property.Value); continue; } if (property.NameEquals("tags")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } Dictionary<string, string> dictionary = new Dictionary<string, string>(); foreach (var property0 in property.Value.EnumerateObject()) { dictionary.Add(property0.Name, property0.Value.GetString()); } tags = dictionary; continue; } } return new DeletedStorageBundle(id.Value, resourceId.Value, activeKeyName.Value, Optional.ToNullable(autoRegenerateKey), regenerationPeriod.Value, attributes.Value, Optional.ToDictionary(tags), recoveryId.Value, Optional.ToNullable(scheduledPurgeDate), Optional.ToNullable(deletedDate)); } } }
40.732759
299
0.503492
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/keyvault/samples/sharelink/Generated/Models/DeletedStorageBundle.Serialization.cs
4,725
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; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization.Formatters.Tests; using Xunit; using TestAttributes; [module: Foo] [module: Complicated(1, Stuff = 2)] namespace TestAttributes { public class FooAttribute : Attribute { } public class ComplicatedAttribute : Attribute { public int Stuff { get; set; } public int Foo { get; } public ComplicatedAttribute(int foo) { Foo = foo; } } } namespace System.Reflection.Tests { public class ModuleTests { public static Module Module => typeof(ModuleTests).Module; public static Module TestModule => typeof(TestModule.Dummy).Module; [Fact] public void TestAssembly() { Assert.Equal(Assembly.GetExecutingAssembly(), Module.Assembly); } [Fact] public void ModuleHandle() { Assert.Equal(typeof(PointerTests).Module.ModuleHandle, Module.ModuleHandle); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Module CustomAttributes not supported on UapAot.")] public void CustomAttributes() { List<CustomAttributeData> customAttributes = Module.CustomAttributes.ToList(); Assert.True(customAttributes.Count >= 2); CustomAttributeData fooAttribute = customAttributes.Single(a => a.AttributeType == typeof(FooAttribute)); Assert.Equal(typeof(FooAttribute).GetConstructors().First(), fooAttribute.Constructor); Assert.Equal(0, fooAttribute.ConstructorArguments.Count); Assert.Equal(0, fooAttribute.NamedArguments.Count); CustomAttributeData complicatedAttribute = customAttributes.Single(a => a.AttributeType == typeof(ComplicatedAttribute)); Assert.Equal(typeof(ComplicatedAttribute).GetConstructors().First(), complicatedAttribute.Constructor); Assert.Equal(1, complicatedAttribute.ConstructorArguments.Count); Assert.Equal(typeof(int), complicatedAttribute.ConstructorArguments[0].ArgumentType); Assert.Equal(1, (int)complicatedAttribute.ConstructorArguments[0].Value); Assert.Equal(1, complicatedAttribute.NamedArguments.Count); Assert.Equal(false, complicatedAttribute.NamedArguments[0].IsField); Assert.Equal("Stuff", complicatedAttribute.NamedArguments[0].MemberName); #if !MONO // Mono issue #11572 Assert.Equal(typeof(ComplicatedAttribute).GetProperty("Stuff"), complicatedAttribute.NamedArguments[0].MemberInfo); #endif Assert.Equal(typeof(int), complicatedAttribute.NamedArguments[0].TypedValue.ArgumentType); Assert.Equal(2, complicatedAttribute.NamedArguments[0].TypedValue.Value); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Module.FullyQualifiedName does not indicate file location on UwpAot")] public void FullyQualifiedName() { Assert.Equal(Assembly.GetExecutingAssembly().Location, Module.FullyQualifiedName); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Module.Name does not indicate file location on UwpAot")] public void Name() { #if MONO Assert.EndsWith("corlib_xunit-test.dll", Module.Name); #else Assert.Equal("system.runtime.tests.dll", Module.Name, ignoreCase: true); #endif } [Fact] public void Equality() { Assert.True(Assembly.GetExecutingAssembly().GetModules().First() == Module); Assert.True(Module.Equals(Assembly.GetExecutingAssembly().GetModules().First())); } [Fact] public void TestGetHashCode() { Assert.Equal(Assembly.GetExecutingAssembly().GetModules().First().GetHashCode(), Module.GetHashCode()); } [Theory] [InlineData(typeof(ModuleTests))] [InlineData(typeof(PointerTests))] public void TestGetType(Type type) { Assert.Equal(type, Module.GetType(type.FullName, true, true)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Module.ToString() does not indicate file location on UwpAot")] public void TestToString() { #if MONO Assert.EndsWith("corlib_xunit-test.dll", Module.ToString()); #else Assert.Equal("System.Runtime.Tests.dll", Module.ToString()); #endif } [Fact] public void IsDefined_NullType() { ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("attributeType", () => { Module.IsDefined(null, false); }); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Module.GetField apis not supported on UapAot.")] public void GetField_NullName() { ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("name", () => { Module.GetField(null); }); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); ex = AssertExtensions.Throws<ArgumentNullException>("name", () => { Module.GetField(null, 0); }); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } [Fact(Skip="Mono issue")] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Module.GetField apis not supported on UapAot.")] public void GetField() { FieldInfo testInt = TestModule.GetField("TestInt", BindingFlags.Public | BindingFlags.Static); Assert.Equal(1, (int)testInt.GetValue(null)); testInt.SetValue(null, 100); Assert.Equal(100, (int)testInt.GetValue(null)); FieldInfo testLong = TestModule.GetField("TestLong", BindingFlags.NonPublic | BindingFlags.Static); Assert.Equal(2L, (long)testLong.GetValue(null)); testLong.SetValue(null, 200); Assert.Equal(200L, (long)testLong.GetValue(null)); } [Fact(Skip="Mono issue")] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Module.GetField apis not supported on UapAot.")] public void GetFields() { List<FieldInfo> fields = TestModule.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static).OrderBy(f => f.Name).ToList(); Assert.Equal(2, fields.Count); Assert.Equal(TestModule.GetField("TestInt"), fields[0]); Assert.Equal(TestModule.GetField("TestLong", BindingFlags.NonPublic | BindingFlags.Static), fields[1]); } public static IEnumerable<object[]> Types => Module.GetTypes().Select(t => new object[] { t }); [Theory] [MemberData(nameof(Types))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Module.Resolve apis not supported on UapAot.")] public void ResolveType(Type t) { Assert.Equal(t, Module.ResolveType(t.MetadataToken)); } public static IEnumerable<object[]> BadResolveTypes => new[] { new object[] { 1234 }, new object[] { typeof(ModuleTests).GetMethod("ResolveType").MetadataToken }, }; [Theory] [MemberData(nameof(BadResolveTypes))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Module.Resolve apis not supported on UapAot.")] public void ResolveTypeFail(int token) { Assert.ThrowsAny<ArgumentException>(() => { Module.ResolveType(token); }); } public static IEnumerable<object[]> Methods => Module.GetMethods().Select(m => new object[] { m }); [Theory] [MemberData(nameof(Methods))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Module.Resolve apis not supported on UapAot.")] public void ResolveMethod(MethodInfo t) { Assert.Equal(t, Module.ResolveMethod(t.MetadataToken)); } public static IEnumerable<object[]> BadResolveMethods => new[] { new object[] { 1234 }, new object[] { typeof(ModuleTests).MetadataToken }, new object[] { typeof(ModuleTests).MetadataToken + 1000 }, }; [Theory] [MemberData(nameof(BadResolveMethods))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Module.Resolve apis not supported on UapAot.")] public void ResolveMethodFail(int token) { Assert.ThrowsAny<ArgumentException>(() => { Module.ResolveMethod(token); }); } public static IEnumerable<object[]> Fields => Module.GetFields().Select(f => new object[] { f }); [Theory] [MemberData(nameof(Fields))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Module.Resolve apis not supported on UapAot.")] public void ResolveField(FieldInfo t) { Assert.Equal(t, Module.ResolveField(t.MetadataToken)); } public static IEnumerable<object[]> BadResolveFields => new[] { new object[] { 1234 }, new object[] { typeof(ModuleTests).MetadataToken }, new object[] { typeof(ModuleTests).MetadataToken + 1000 }, }; [Theory] [MemberData(nameof(BadResolveFields))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Module.Resolve apis not supported on UapAot.")] public void ResolveFieldFail(int token) { Assert.ThrowsAny<ArgumentException>(() => { Module.ResolveField(token); }); } public static IEnumerable<object[]> BadResolveStrings => new[] { new object[] { 1234 }, new object[] { typeof(ModuleTests).MetadataToken }, new object[] { typeof(ModuleTests).MetadataToken + 1000 }, }; [Theory] [MemberData(nameof(BadResolveStrings))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Module.Resolve apis not supported on UapAot.")] public void ResolveStringFail(int token) { Assert.ThrowsAny<ArgumentException>(() => { Module.ResolveString(token); }); } [Theory] [MemberData(nameof(Types))] [MemberData(nameof(Methods))] [MemberData(nameof(Fields))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Module.Resolve apis not supported on UapAot.")] public void ResolveMember(MemberInfo member) { Assert.Equal(member, Module.ResolveMember(member.MetadataToken)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Module.Resolve apis not supported on UapAot.")] public void ResolveMethodOfGenericClass() { Type t = typeof(Foo<>); Module mod = t.Module; MethodInfo method = t.GetMethod("Bar"); MethodBase actual = mod.ResolveMethod(method.MetadataToken); Assert.Equal(method, actual); } [Fact(Skip="Mono issue")] public void GetTypes() { List<Type> types = TestModule.GetTypes().ToList(); Assert.Equal(1, types.Count); Assert.Equal("System.Reflection.TestModule.Dummy, System.Reflection.TestModule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", types[0].AssemblyQualifiedName); } } public class Foo<T> { public void Bar(T t) { } } }
37.038922
192
0.609732
[ "MIT" ]
lambdageek/mono-corefx
src/System.Runtime/tests/System/Reflection/ModuleTests.cs
12,371
C#
using System; namespace HPSocket { /// <summary> /// client 基础接口 /// </summary> public interface IClient : ISocket { #region 基础属性 /// <summary> /// 远程服务器地址 /// </summary> string Address { get; set; } /// <summary> /// 远程服务器端口 /// </summary> ushort Port { get; set; } /// <summary> /// 本地绑定到哪个ip /// </summary> string BindAddress { get; set; } /// <summary> /// 本地绑定到哪个端口 /// </summary> ushort BindPort { get; set; } /// <summary> /// 是否异步连接,默认为真 /// </summary> bool Async { get; set; } /// <summary> /// 附加数据 /// <para>赋值:client.ExtraData = myObj;</para> /// <para>取值:var data = ExtraData as MyData;</para> /// </summary> object ExtraData { get; set; } #endregion #region 客户端事件 /// <summary> /// 准备连接了事件 /// </summary> event ClientPrepareConnectEventHandler OnPrepareConnect; /// <summary> /// 连接事件 /// </summary> event ClientConnectEventHandler OnConnect; /// <summary> /// 数据发送事件 /// </summary> event ClientSendEventHandler OnSend; /// <summary> /// 数据到达事件 /// </summary> event ClientReceiveEventHandler OnReceive; /// <summary> /// 连接关闭事件 /// </summary> event ClientCloseEventHandler OnClose; /// <summary> /// 握手事件 /// </summary> event ClientHandShakeEventHandler OnHandShake; #endregion #region 客户端属性 /// <summary> /// 读取或设置内存块缓存池大小(通常设置为 -> PUSH 模型:5 - 10;PULL 模型:10 - 20 ) /// </summary> uint FreeBufferPoolSize { get; set; } /// <summary> /// 读取或设置内存块缓存池回收阀值(通常设置为内存块缓存池大小的 3 倍) /// </summary> uint FreeBufferPoolHold { get; set; } /// <summary> /// 检查通信组件是否已启动 /// </summary> bool HasStarted { get; } /// <summary> /// 是否已连接 /// </summary> bool IsConnected { get; } /// <summary> /// 状态 /// </summary> ServiceState State { get; } /// <summary> /// 获取该组件对象的连接Id /// </summary> IntPtr ConnectionId { get; } /// <summary> /// 是否为安全连接(SSL/HTTPS) /// </summary> bool IsSecure { get; } /// <summary> /// 获取或设置暂停接收状态,设置状态时,不允许设置为ReceiveState.Unknown, /// </summary> ReceiveState PauseReceive { get; set; } /// <summary> /// 获取或设置地址重用选项 /// </summary> ReuseAddressPolicy ReuseAddressPolicy { get; set; } /// <summary> /// 获取错误码 /// </summary> SocketError ErrorCode { get; } /// <summary> /// 获取错误信息 /// </summary> string ErrorMessage { get; } #endregion #region 客户端方法 /// <summary> /// 启动通讯组件并连接到服务器 /// </summary> /// <returns></returns> bool Connect(); /// <summary> /// 启动通讯组件并连接到服务器 /// </summary> /// <param name="address">远程服务器地址</param> /// <param name="port">远程服务器端口</param> /// <returns></returns> bool Connect(string address, ushort port); /// <summary> /// 停止服务 /// </summary> /// <returns></returns> bool Stop(); /// <summary> /// 发送数据 /// </summary> /// <param name="bytes"></param> /// <param name="length"></param> /// <returns></returns> bool Send(byte[] bytes, int length); /// <summary> /// 发送数据 /// </summary> /// <param name="bytes"></param> /// <param name="offset">针对bytes的偏移</param> /// <param name="length">发多大</param> /// <returns></returns> bool Send(byte[] bytes, int offset, int length); /// <summary> /// 发送多组数据 /// 向指定连接发送多组数据 /// TCP - 顺序发送所有数据包 /// </summary> /// <param name="buffers">发送缓冲区数组</param> /// <param name="count">发送缓冲区数目</param> /// <returns>true.成功,false.失败,可通过 SYSGetLastError() 获取 Windows 错误代码</returns> bool SendPackets(Wsabuf[] buffers, int count); /// <summary> /// 获取连接中未发出数据的长度 /// </summary> /// <param name="length"></param> /// <returns></returns> bool GetPendingDataLength(out int length); /// <summary> /// 获取监听socket的地址信息 /// </summary> /// <param name="host"></param> /// <param name="port"></param> /// <returns></returns> bool GetListenAddress(out string host, out ushort port); /// <summary> /// 获取连接的远程主机信息 /// </summary> /// <param name="host"></param> /// <param name="port"></param> /// <returns></returns> bool GetRemoteHost(out string host, out ushort port); #endregion } }
24.004695
85
0.470761
[ "Apache-2.0" ]
Gao996/HPSocket.Net
src/HPSocket.Net/IClient.cs
5,909
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. namespace mshtml { using System.Runtime.InteropServices; [ComImport, Guid("3050F57F-98B5-11CF-BB82-00AA00BDCE0B"),] public interface HTCPropertyBehavior : DispHTCPropertyBehavior { } }
24.857143
84
0.735632
[ "MIT" ]
BobinYang/OpenLiveWriter
src/managed/OpenLiveWriter.Interop.Mshtml/mshtml/HTCPropertyBehavior.cs
348
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.AzureNextGen.RecoveryServices.V20201201.Inputs { /// <summary> /// Container for SQL workloads under SQL Availability Group. /// </summary> public sealed class AzureSQLAGWorkloadContainerProtectionContainerArgs : Pulumi.ResourceArgs { /// <summary> /// Type of backup management for the container. /// </summary> [Input("backupManagementType")] public InputUnion<string, Pulumi.AzureNextGen.RecoveryServices.V20201201.BackupManagementType>? BackupManagementType { get; set; } /// <summary> /// Type of the container. The value of this property for: 1. Compute Azure VM is Microsoft.Compute/virtualMachines 2. /// Classic Compute Azure VM is Microsoft.ClassicCompute/virtualMachines 3. Windows machines (like MAB, DPM etc) is /// Windows 4. Azure SQL instance is AzureSqlContainer. 5. Storage containers is StorageContainer. 6. Azure workload /// Backup is VMAppContainer /// Expected value is 'AzureWorkloadContainer'. /// </summary> [Input("containerType", required: true)] public Input<string> ContainerType { get; set; } = null!; /// <summary> /// Additional details of a workload container. /// </summary> [Input("extendedInfo")] public Input<Inputs.AzureWorkloadContainerExtendedInfoArgs>? ExtendedInfo { get; set; } /// <summary> /// Friendly name of the container. /// </summary> [Input("friendlyName")] public Input<string>? FriendlyName { get; set; } /// <summary> /// Status of health of the container. /// </summary> [Input("healthStatus")] public Input<string>? HealthStatus { get; set; } /// <summary> /// Time stamp when this container was updated. /// </summary> [Input("lastUpdatedTime")] public Input<string>? LastUpdatedTime { get; set; } /// <summary> /// Re-Do Operation /// </summary> [Input("operationType")] public InputUnion<string, Pulumi.AzureNextGen.RecoveryServices.V20201201.OperationType>? OperationType { get; set; } /// <summary> /// Status of registration of the container with the Recovery Services Vault. /// </summary> [Input("registrationStatus")] public Input<string>? RegistrationStatus { get; set; } /// <summary> /// ARM ID of the virtual machine represented by this Azure Workload Container /// </summary> [Input("sourceResourceId")] public Input<string>? SourceResourceId { get; set; } /// <summary> /// Workload type for which registration was sent. /// </summary> [Input("workloadType")] public InputUnion<string, Pulumi.AzureNextGen.RecoveryServices.V20201201.WorkloadType>? WorkloadType { get; set; } public AzureSQLAGWorkloadContainerProtectionContainerArgs() { } } }
38.229885
138
0.635298
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/RecoveryServices/V20201201/Inputs/AzureSQLAGWorkloadContainerProtectionContainerArgs.cs
3,326
C#
namespace FD.SampleData.Models.Production { public partial class ProductInventory { public int ProductID { get; set; } public short LocationID { get; set; } public string Shelf { get; set; } public byte Bin { get; set; } public short Quantity { get; set; } public System.Guid rowguid { get; set; } public System.DateTime ModifiedDate { get; set; } public virtual Location Location { get; set; } public virtual Product Product { get; set; } } }
31.176471
57
0.611321
[ "MIT" ]
araujofrancisco/FD.DataProvider
FD.SampleData/Models/Production/ProductInventory.cs
532
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------ using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models; using Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Models.KnownStrings; using Microsoft.OpenApi.Models; namespace Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.OperationFilters { /// <summary> /// Parses the value of group tag in xml documentation and apply that as tag in operation. /// </summary> public class GroupToTagFilter : IOperationFilter { /// <summary> /// Fetches the value of "group" tag from xml documentation and populates operation's tag. /// </summary> /// <param name="operation">The operation to be updated.</param> /// <param name="element">The xml element representing an operation in the annotation xml.</param> /// <param name="settings">The operation filter settings.</param> /// <remarks> /// Care should be taken to not overwrite the existing value in Operation if already present. /// This guarantees the predictable behavior that the first tag in the XML will be respected. /// It also guarantees that common annotations in the config file do not overwrite the /// annotations in the main documentation. /// </remarks> /// <returns>The list of generation errors, if any produced when processing the filter.</returns> public IList<GenerationError> Apply( OpenApiOperation operation, XElement element, OperationFilterSettings settings) { var generationErrors = new List<GenerationError>(); try { var groupElement = element.Descendants().FirstOrDefault(i => i.Name == KnownXmlStrings.Group); var groupValue = groupElement?.Value.Trim(); if (string.IsNullOrWhiteSpace(groupValue)) { return generationErrors; } if (!operation.Tags.Select(t => t.Name).Contains(groupValue)) { operation.Tags.Add( new OpenApiTag { Name = groupValue } ); } } catch (Exception ex) { generationErrors.Add( new GenerationError { Message = ex.Message, ExceptionType = ex.GetType().Name }); } return generationErrors; } } }
39.786667
110
0.558646
[ "MIT" ]
AndrewDessin/OpenAPI.NET.CSharpAnnotations
src/Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration/OperationFilters/GroupToTagFilter.cs
2,984
C#
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. // // Microsoft Bot Framework: http://botframework.com // // Bot Builder SDK Github: // https://github.com/Microsoft/BotBuilder // // Copyright (c) Microsoft Corporation // All rights reserved. // // MIT License: // 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.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.Bot.Builder.Dialogs; namespace Microsoft.Bot.Builder.FormFlow.Advanced { internal class FieldStep<T> : IStep<T> where T : class { public FieldStep(string name, IForm<T> form) { _name = name; _field = form.Fields.Field(name); } public string Name { get { return _name; } } public StepType Type { get { return StepType.Field; } } public TemplateBaseAttribute Annotation { get { return _field.Prompt?.Annotation; } } public IField<T> Field { get { return _field; } } public void SaveResources() { _field.SaveResources(); } public void Localize() { _field.Localize(); } public bool Active(T state) { return _field.Active(state); } public async Task<bool> DefineAsync(T state) { return await _field.DefineAsync(state); } public FormPrompt Start(IDialogContext context, T state, FormState form) { form.SetPhase(StepPhase.Responding); form.StepState = new FieldStepState(FieldStepStates.SentPrompt); return _field.Prompt.Prompt(state, _field, _field.Prompt.Recognizer.PromptArgs()); } public IEnumerable<TermMatch> Match(IDialogContext context, T state, FormState form, string input) { IEnumerable<TermMatch> matches = null; Debug.Assert(form.Phase() == StepPhase.Responding); var stepState = (FieldStepState)form.StepState; if (stepState.State == FieldStepStates.SentPrompt) { matches = _field.Prompt.Recognizer.Matches(input, _field.GetValue(state)); } else if (stepState.State == FieldStepStates.SentClarify) { var fieldState = (FieldStepState)form.StepState; var iprompt = _field.Prompt; var choiceRecognizer = ClarifyRecognizer(fieldState, iprompt.Recognizer); matches = MatchAnalyzer.Coalesce(MatchAnalyzer.HighestConfidence(choiceRecognizer.Matches(input)), input).ToArray(); if (matches.Count() > 1) { matches = new TermMatch[0]; } } #if DEBUG if (FormDialog.DebugRecognizers) { MatchAnalyzer.PrintMatches(matches, 2); } #endif return matches; } public async Task<StepResult> ProcessAsync(IDialogContext context, T state, FormState form, string input, IEnumerable<TermMatch> matches) { ValidateResult feedback = new ValidateResult(); feedback.IsValid = true; feedback.Feedback = null; feedback.FeedbackCard = null; feedback.Choices = null; FormPrompt prompt = null; FormPrompt feedbackPrompt = null; var iprompt = _field.Prompt; var fieldState = (FieldStepState)form.StepState; object response = null; if (fieldState.State == FieldStepStates.SentPrompt) { // Response to prompt var firstMatch = matches.FirstOrDefault(); if (matches.Count() == 1) { response = firstMatch.Value; if (_field.AllowsMultiple && response != null && (response.GetType() == typeof(string) || !response.GetType().IsIEnumerable())) { response = new List<object>() { response }; } feedback = await SetValueAsync(state, response, form); if (!feedback.IsValid && feedback.Choices != null) { var choices = new Ambiguous(input.Substring(firstMatch.Start, firstMatch.Length), feedback.Choices); fieldState.State = FieldStepStates.SentClarify; fieldState.Settled = new List<object>(); fieldState.Clarifications = new List<Ambiguous>() { choices }; response = SetValue(state, null); prompt = ClarifyPrompt((FieldStepState)form.StepState, iprompt.Recognizer, state); } } else if (matches.Count() > 1) { // Check multiple matches for ambiguity var groups = MatchAnalyzer.GroupedMatches(matches); // 1) Could be multiple match groups like for ingredients. // 2) Could be overlapping matches like "onion". // 3) Could be multiple matches where only one is expected. if (!_field.AllowsMultiple) { // Create a single group of all possibilities if only want one value var mergedGroup = groups.SelectMany((group) => group).ToList(); groups = new List<List<TermMatch>>() { mergedGroup }; } var ambiguous = new List<Ambiguous>(); var settled = new List<object>(); foreach (var choices in groups) { if (choices.Count > 1) { var unclearResponses = string.Join(" ", (from choice in choices select input.Substring(choice.Start, choice.Length)).Distinct()); var values = from match in choices select match.Value; ambiguous.Add(new Ambiguous(unclearResponses, values)); } else { var matchValue = choices.First().Value; if (matchValue != null && matchValue.GetType() != typeof(string) && matchValue.GetType().IsIEnumerable()) { foreach (var value in (System.Collections.IEnumerable)matchValue) { settled.Add(value); } } else { settled.Add(choices.First().Value); } } } if (settled.Count > 1) { // Remove no preference if present settled.Remove(null); } if (ambiguous.Count > 0) { // Need 1 or more clarifications fieldState.State = FieldStepStates.SentClarify; fieldState.Settled = settled; fieldState.Clarifications = ambiguous; response = SetValue(state, null); prompt = ClarifyPrompt((FieldStepState)form.StepState, iprompt.Recognizer, state); } else { if (_field.AllowsMultiple) { response = settled; feedback = await SetValueAsync(state, response, form); } else { Debug.Assert(settled.Count == 1); response = settled.First(); feedback = await SetValueAsync(state, response, form); } } } var unmatched = MatchAnalyzer.Unmatched(input, matches); var unmatchedWords = string.Join(" ", unmatched); var nonNoise = Language.NonNoiseWords(Language.WordBreak(unmatchedWords)).ToArray(); fieldState.Unmatched = null; if (_field.Prompt.Annotation.Feedback == FeedbackOptions.Always) { fieldState.Unmatched = string.Join(" ", nonNoise); } else if (_field.Prompt.Annotation.Feedback == FeedbackOptions.Auto && nonNoise.Any() && unmatched.Any()) { fieldState.Unmatched = string.Join(" ", nonNoise); } } else if (fieldState.State == FieldStepStates.SentClarify) { if (matches.Count() == 1) { // Clarified ambiguity var clarify = NeedsClarification(fieldState); fieldState.Settled.Add(matches.First().Value); fieldState.Clarifications.Remove(clarify); if (prompt == null) { // No clarification left, so set the field if (_field.AllowsMultiple) { response = fieldState.Settled; feedback = await SetValueAsync(state, response, form); } else { Debug.Assert(fieldState.Settled.Count == 1); response = fieldState.Settled.First(); feedback = await SetValueAsync(state, response, form); } form.SetPhase(StepPhase.Completed); } } } if (form.Phase() == StepPhase.Completed) { form.StepState = null; if (fieldState.Unmatched != null) { if (feedback.FeedbackCard != null) { feedbackPrompt = feedback.FeedbackCard; } else if (feedback.Feedback != null) { feedbackPrompt = new FormPrompt { Prompt = feedback.Feedback }; } else { if (fieldState.Unmatched != "") { feedbackPrompt = new Prompter<T>(_field.Template(TemplateUsage.Feedback), _field.Form, null).Prompt(state, _field, fieldState.Unmatched); } else { feedbackPrompt = new Prompter<T>(_field.Template(TemplateUsage.Feedback), _field.Form, null).Prompt(state, _field); } } } } var next = _field.Next(response, state); return new StepResult(feedback.IsValid, next, feedbackPrompt ?? (feedback.FeedbackCard ?? new FormPrompt { Prompt = feedback.Feedback }), prompt); } public bool InClarify(FormState form) { var state = (FieldStepState)form.StepState; return state.State == FieldStepStates.SentClarify; } public FormPrompt NotUnderstood(IDialogContext context, T state, FormState form, string input) { FormPrompt feedback = null; var iprompt = _field.Prompt; var fieldState = (FieldStepState)form.StepState; if (fieldState.State == FieldStepStates.SentPrompt) { feedback = Template(TemplateUsage.NotUnderstood).Prompt(state, _field, input); } else if (fieldState.State == FieldStepStates.SentClarify) { feedback = Template(TemplateUsage.NotUnderstood).Prompt(state, _field, input); } return feedback; } public bool Back(IDialogContext context, T state, FormState form) { bool backedUp = false; var fieldState = (FieldStepState)form.StepState; if (fieldState.State == FieldStepStates.SentClarify) { var desc = _field.Form.Fields.Field(_name); if (desc.AllowsMultiple) { desc.SetValue(state, fieldState.Settled); } else if (fieldState.Settled.Any()) { desc.SetValue(state, fieldState.Settled.First()); } form.SetPhase(StepPhase.Ready); backedUp = true; } return backedUp; } public FormPrompt Help(T state, FormState form, string commandHelp) { var fieldState = (FieldStepState)form.StepState; IPrompt<T> template; if (fieldState.State == FieldStepStates.SentClarify) { template = Template(TemplateUsage.HelpClarify, ClarifyRecognizer(fieldState, _field.Prompt.Recognizer)); } else { template = Template(TemplateUsage.Help, _field.Prompt.Recognizer); } var help = template.Prompt(state, _field, "* " + template.Recognizer.Help(state, _field.GetValue(state)), commandHelp); return new FormPrompt { Prompt = "* " + help.Prompt, Buttons = help.Buttons }; } public IEnumerable<string> Dependencies { get { return Array.Empty<string>(); } } private IPrompt<T> Template(TemplateUsage usage, IRecognize<T> recognizer = null) { var template = _field.Template(usage); return new Prompter<T>(template, _field.Form, recognizer == null ? _field.Prompt.Recognizer : recognizer); } private object SetValue(T state, object value) { var desc = _field.Form.Fields.Field(_name); if (value == null) { desc.SetUnknown(state); } else { desc.SetValue(state, value); } return value; } private async Task<ValidateResult> SetValueAsync(T state, object value, FormState form) { var desc = _field.Form.Fields.Field(_name); var feedback = await desc.ValidateAsync(state, value); if (feedback.IsValid) { SetValue(state, feedback.Value); form.SetPhase(StepPhase.Completed); } else if (feedback.Feedback == null) { feedback.Feedback = ""; } return feedback; } private Ambiguous NeedsClarification(FieldStepState stepState) { Ambiguous clarify = null; foreach (var clarification in stepState.Clarifications) { if (clarification.Values.Length > 1) { clarify = clarification; break; } } return clarify; } private class FieldClarify : Field<T> { public FieldClarify(IField<T> root) : base(root.Name, FieldRole.Value) { Form = root.Form; var template = root.Template(TemplateUsage.Clarify); SetPrompt(new PromptAttribute(template)); ReplaceTemplate(template); ReplaceTemplate(root.Template(template.AllowNumbers ? TemplateUsage.EnumOneNumberHelp : TemplateUsage.EnumManyNumberHelp)); } public override bool IsUnknown(T state) { return true; } } private IField<T> ClarifyField(Ambiguous clarify, IRecognize<T> recognizer) { var field = new FieldClarify(_field); foreach (var value in clarify.Values) { var choice = value as Choice; if (choice != null) { field.AddDescription(choice.Value, choice.Description.Description, choice.Description.Image, choice.Description.Message); field.AddTerms(choice.Value, choice.Terms.Alternatives); } else { var desc = recognizer.ValueDescription(value); field.AddDescription(value, desc.Description, desc.Image); field.AddTerms(value, recognizer.ValidInputs(value).ToArray()); } } return field; } private IRecognize<T> ClarifyRecognizer(FieldStepState stepState, IRecognize<T> recognizer) { var clarify = NeedsClarification(stepState); return (clarify != null ? new RecognizeEnumeration<T>(ClarifyField(clarify, recognizer)) : null); } private FormPrompt ClarifyPrompt(FieldStepState stepState, IRecognize<T> recognizer, T state) { var clarify = NeedsClarification(stepState); FormPrompt prompt = null; if (clarify != null) { var field = ClarifyField(clarify, recognizer); var prompter = new Prompter<T>(field.Template(TemplateUsage.Clarify), field.Form, new RecognizeEnumeration<T>(field)); prompt = prompter.Prompt(state, field, clarify.Response); } return prompt; } internal enum FieldStepStates { Unknown, SentPrompt, SentClarify }; [Serializable] internal class Ambiguous { public readonly string Response; public object[] Values; public Ambiguous(string response, IEnumerable<object> values) { Response = response; Values = values.ToArray<object>(); } } [Serializable] internal class FieldStepState { internal FieldStepStates State; internal string Unmatched; internal List<object> Settled; internal List<Ambiguous> Clarifications; public FieldStepState(FieldStepStates state) { State = state; } } private readonly string _name; private readonly IField<T> _field; } internal class ConfirmStep<T> : IStep<T> where T : class { public ConfirmStep(IField<T> field) { _field = field; } public bool Back(IDialogContext context, T state, FormState form) { return false; } public IField<T> Field { get { return _field; } } public void SaveResources() { _field.SaveResources(); } public void Localize() { _field.Localize(); } public bool Active(T state) { return _field.Active(state); } public IEnumerable<TermMatch> Match(IDialogContext context, T state, FormState form, string input) { return _field.Prompt.Recognizer.Matches(input); } public string Name { get { return _field.Name; } } public TemplateBaseAttribute Annotation { get { return _field.Prompt?.Annotation; } } public FormPrompt NotUnderstood(IDialogContext context, T state, FormState form, string input) { var template = _field.Template(TemplateUsage.NotUnderstood); var prompter = new Prompter<T>(template, _field.Form, null); return prompter.Prompt(state, _field, input); } public async Task<StepResult> ProcessAsync(IDialogContext context, T state, FormState form, string input, IEnumerable<TermMatch> matches) { var value = matches.First().Value; form.StepState = null; form.SetPhase((bool)value ? StepPhase.Completed : StepPhase.Ready); var next = _field.Next(value, state); return new StepResult(true, next, feedback: null, prompt: null); } public async Task<bool> DefineAsync(T state) { return await _field.DefineAsync(state); } public FormPrompt Start(IDialogContext context, T state, FormState form) { form.SetPhase(StepPhase.Responding); return _field.Prompt.Prompt(state, _field); } public FormPrompt Help(T state, FormState form, string commandHelp) { var template = _field.Template(TemplateUsage.HelpConfirm); var prompt = new Prompter<T>(template, _field.Form, _field.Prompt.Recognizer); var help = prompt.Prompt(state, _field, "* " + prompt.Recognizer.Help(state, null), commandHelp); return new FormPrompt { Prompt = "* " + help.Prompt, Buttons = help.Buttons }; } public bool InClarify(FormState form) { return false; } public StepType Type { get { return StepType.Confirm; } } public IEnumerable<string> Dependencies { get { return _field.Dependencies; } } private readonly IField<T> _field; } internal class NavigationField<T> : Field<T> where T : class { public NavigationField(string name, string startField, IForm<T> form, T state, FormState formState, Fields<T> fields) : base(name, FieldRole.Value) { Form = form; var field = form.Fields.Field(startField); SetFieldDescription(_form.Configuration.Navigation); SetOptional(); foreach (var value in formState.Next.Names) { var svalue = (string)value; var sfield = form.Fields.Field(svalue); var fieldPrompt = sfield.Template(TemplateUsage.NavigationFormat); var prompter = new Prompter<T>(fieldPrompt, form, sfield.Prompt.Recognizer); AddDescription(value, prompter.Prompt(state, sfield).Prompt, null, svalue); AddTerms(value, form.Fields.Field(svalue).FieldTerms.ToArray()); } var template = field.Template(TemplateUsage.Navigation); SetPrompt(new PromptAttribute(template)); SetRecognizer(new RecognizeEnumeration<T>(this)); _prompt = new Prompter<T>(template, form, _recognizer, fields); } public override bool IsUnknown(T state) { return true; } } internal class NavigationStep<T> : IStep<T> where T : class { private const string _name = "__navigate__"; public NavigationStep(string startField, IForm<T> form, T state, FormState formState) { var fields = new Fields<T>(); _field = new NavigationField<T>(_name, startField, form, state, formState, fields); fields.Add(_field); _fields = fields; } public bool Back(IDialogContext context, T state, FormState form) { form.Next = null; return false; } public IField<T> Field { get { return _field; } } public bool Active(T state) { return true; } public IEnumerable<TermMatch> Match(IDialogContext context, T state, FormState form, string input) { return _field.Prompt.Recognizer.Matches(input); } public string Name { get { return "Navigation"; } } public TemplateBaseAttribute Annotation { get { return _field.Prompt.Annotation; } } public bool InClarify(FormState form) { return false; } public FormPrompt NotUnderstood(IDialogContext context, T state, FormState form, string input) { var template = _field.Template(TemplateUsage.NotUnderstood); return new Prompter<T>(template, _field.Form, _field.Prompt.Recognizer, _fields).Prompt(state, _field, input); } public async Task<StepResult> ProcessAsync(IDialogContext context, T state, FormState form, string input, IEnumerable<TermMatch> matches) { NextStep next; form.Next = null; var val = matches.First().Value; if (val == null) { next = new NextStep(); } else { next = new NextStep(new string[] { (string)val }); } return new StepResult(true, next, feedback: null, prompt: null); } public Task<bool> DefineAsync(T state) { throw new NotImplementedException(); } public FormPrompt Start(IDialogContext context, T state, FormState form) { return _field.Prompt.Prompt(state, _field); } public StepType Type { get { return StepType.Navigation; } } public FormPrompt Help(T state, FormState form, string commandHelp) { var recognizer = _field.Prompt.Recognizer; var prompt = new Prompter<T>(_field.Template(TemplateUsage.HelpNavigation), _field.Form, recognizer, _fields); var help = prompt.Prompt(state, _field, "* " + recognizer.Help(state, null), commandHelp); return new FormPrompt { Prompt = "* " + help.Prompt, Buttons = help.Buttons }; } public void SaveResources() { } public void Localize() { } public IEnumerable<string> Dependencies { get { return Array.Empty<string>(); } } private readonly IField<T> _field; private readonly IFields<T> _fields; } internal class MessageStep<T> : IStep<T> where T : class { public MessageStep(MessageDelegate<T> generateMessage, ActiveDelegate<T> condition, IEnumerable<string> dependencies, IForm<T> form) { _name = "message" + form.Steps.Count.ToString(); _form = form; _message = generateMessage; _condition = (condition == null ? (state) => true : condition); _dependencies = dependencies ?? form.Dependencies(form.Steps.Count); } public MessageStep(PromptAttribute prompt, ActiveDelegate<T> condition, IEnumerable<string> dependencies, IForm<T> form) { _name = "message" + form.Steps.Count.ToString(); _form = form; _promptDefinition = prompt; _condition = (condition == null ? (state) => true : condition); _dependencies = dependencies ?? form.Dependencies(form.Steps.Count); } public bool Active(T state) { return _condition(state); } public bool Back(IDialogContext context, T state, FormState form) { return false; } public FormPrompt Help(T state, FormState form, string commandHelp) { return null; } public IEnumerable<string> Dependencies { get { return _dependencies; } } public IField<T> Field { get { throw new NotImplementedException(); } } public IEnumerable<TermMatch> Match(IDialogContext context, T state, FormState form, string input) { throw new NotImplementedException(); } public string Name { get { return _name; } } public TemplateBaseAttribute Annotation { get { return _promptDefinition; } } public bool InClarify(FormState form) { return false; } public FormPrompt NotUnderstood(IDialogContext context, T state, FormState form, string input) { throw new NotImplementedException(); } public Task<StepResult> ProcessAsync(IDialogContext context, T state, FormState form, string input, IEnumerable<TermMatch> matches) { throw new NotImplementedException(); } public async Task<bool> DefineAsync(T state) { if (_message != null) { _promptDefinition = await _message(state); } return true; } public FormPrompt Start(IDialogContext context, T state, FormState form) { form.SetPhase(StepPhase.Completed); var prompt = new Prompter<T>(_promptDefinition, _form, null); return prompt.Prompt(state, null); } public void SaveResources() { if (_message == null) { _form.Resources.Add(_name, _promptDefinition.Patterns); } } public void Localize() { if (_message == null) { string[] patterns; _form.Resources.LookupValues(_name, out patterns); if (patterns != null) _promptDefinition.Patterns = patterns; } } public StepType Type { get { return StepType.Message; } } private readonly string _name; private readonly IForm<T> _form; private PromptAttribute _promptDefinition; private readonly MessageDelegate<T> _message; private readonly ActiveDelegate<T> _condition; private readonly IEnumerable<string> _dependencies; } }
35.610932
166
0.502092
[ "MIT" ]
BhagiSivaganesh/ChatBots
CSharp/Library/FormFlow/Steps.cs
33,227
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace MedManager { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } }
23.076923
61
0.661667
[ "MIT" ]
GT-rc/MedManager
MedManager/Program.cs
602
C#
/* * Copyright 2014 Splunk, Inc. * * 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. */ //// TODO: //// [O] Contracts //// [O] Documentation namespace Splunk.Client { using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.IO; using System.Linq; using System.Threading.Tasks; /// <summary> /// Provides an object representation of a Splunk server message entity. /// </summary> /// <seealso cref="T:Splunk.Client.Entity{Splunk.Client.Resource}"/> /// <seealso cref="T:Splunk.Client.IServerMessage"/> public class ServerMessage : Entity<Resource>, IServerMessage { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ServerMessage"/> class. /// </summary> /// <param name="service"> /// An object representing a root Splunk service endpoint. /// </param> /// <param name="name"> /// An object identifying a Splunk resource within /// <paramref name= "service"/>.<see cref="Namespace"/>. /// </param> /// /// ### <exception cref="ArgumentNullException"> /// <paramref name="service"/> or <paramref name="name"/> are <c>null</c>. /// </exception> protected internal ServerMessage(Service service, string name) : this(service.Context, service.Namespace, name) { Contract.Requires<ArgumentNullException>(service != null); } /// <summary> /// Initializes a new instance of the <see cref="ServerMessage"/> class. /// </summary> /// <param name="context"> /// An object representing a Splunk server session. /// </param> /// <param name="feed"> /// A Splunk response atom feed. /// </param> /// /// ### <exception cref="ArgumentNullException"> /// <paramref name="context"/> or <paramref name="feed"/> are <c>null</c>. /// </exception> /// ### <exception cref="InvalidDataException"> /// <paramref name="feed"/> is in an invalid format. /// </exception> protected internal ServerMessage(Context context, AtomFeed feed) { this.Initialize(context, feed); } /// <summary> /// Initializes a new instance of the <see cref="ServerMessage"/> class. /// </summary> /// <param name="context"> /// An object representing a Splunk server session. /// </param> /// <param name="ns"> /// An object identifying a Splunk services namespace. /// </param> /// <param name="name"> /// The name of the <see cref="ServerMessage"/>. /// </param> /// /// ### <exception cref="ArgumentException"> /// <paramref name="name"/> is <c>null</c> or empty. /// </exception> /// ### <exception cref="ArgumentNullException"> /// <paramref name="context"/> or <paramref name="ns"/> are <c>null</c>. /// </exception> /// ### <exception cref="ArgumentOutOfRangeException"> /// <paramref name="ns"/> is not specific. /// </exception> protected internal ServerMessage(Context context, Namespace ns, string name) : base(context, ns, ServerMessageCollection.ClassResourceName, name) { } /// <summary> /// Infrastructure. Initializes a new instance of the /// <see cref= "ServerMessage"/> class. /// </summary> /// <remarks> /// This API supports the Splunk client infrastructure and is not intended to /// be used directly from your code. /// </remarks> public ServerMessage() { } #endregion #region Properties /// <inheritdoc/> public Eai Eai { get { return this.Content.GetValue("Eai", Eai.Converter.Instance); } } /// <inheritdoc/> public ServerMessageSeverity Severity { get { return this.Content.GetValue("Severity", EnumConverter<ServerMessageSeverity>.Instance); } } /// <inheritdoc/> public string Text { get { return this.Content.GetValue("Message", StringConverter.Instance); } } /// <inheritdoc/> public DateTime TimeCreated { get { return this.Content.GetValue("TimeCreatedEpochSecs", UnixDateTimeConverter.Instance); } } #endregion #region Methods /// <summary> /// Unsupported. This method is not supported by the /// <see cref= "ServerMessage"/> class because it is not supported by the /// <a href= "http://goo.gl/S13BE0">Splunk messages/{name} endpoint</a>. /// </summary> /// <param name="arguments"> /// A variable-length parameters list containing arguments. /// </param> /// <returns> /// <c>true</c> if the current snapshot was also updated. /// </returns> public override async Task<bool> UpdateAsync(params Argument[] arguments) { return await this.UpdateAsync(arguments.AsEnumerable()).ConfigureAwait(false); } /// <summary> /// Unsupported. This method is not supported by the /// <see cref= "ServerMessage"/> class because it is not supported by the /// <a href= "http://goo.gl/S13BE0">Splunk messages/{name} endpoint</a>. /// </summary> /// <exception cref="NotSupportedException"> /// Thrown when the requested operation is not supported. /// </exception> /// <param name="arguments"> /// The arguments. /// </param> /// <returns> /// <c>true</c> if the current snapshot was also updated. /// </returns> public override Task<bool> UpdateAsync(IEnumerable<Argument> arguments) { throw new NotSupportedException("The Splunk messages/{name} endpoint does not provide an update method.") { HelpLink = "http://docs.splunk.com/Documentation/Splunk/latest/RESTAPI/RESTsystem#messages.2F.7Bname.7D" }; } #endregion } }
35.752632
120
0.577653
[ "Apache-2.0" ]
codereflection/splunk-sdk-csharp-pcl
src/Splunk.Client/Splunk/Client/ServerMessage.cs
6,795
C#
using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using SharpShell.Pidl; using SharpShell.SharpNamespaceExtension; namespace GitHubNamespaceExtension { public class GitHubBranch : IShellNamespaceItem { public GitHubBranch() { } public string Name { get; set; } public ShellId GetShellId() { return ShellId.FromString(Name); } public string GetDisplayName(DisplayNameContext displayNameContext) { return Name; } public AttributeFlags GetAttributes() { return AttributeFlags.IsReadOnly; } public Icon GetIcon() { return null; } } }
20.425
76
0.559364
[ "MIT" ]
0x4a616e/sharpshell
SharpShell/Samples/NamespaceExtension/GitHubNamespaceExtension/GitHubBranch.cs
819
C#
using System.ComponentModel.DataAnnotations; namespace Shared.ViewModels { public class OrderItemVM { [Required(ErrorMessage = "Attribute Id is required")] public int AttributeId { get; set; } public int ProductId { get; set; } public int? Quantity { get; set; } [Required(ErrorMessage = "Price is is required")] public double? Price { get; set; } public string Name { get; set; } public string Image { get; set; } public string Size { get; set; } } }
31.529412
61
0.61194
[ "Unlicense" ]
vtoan/fashion-ecom-ns
src/Shared/ViewModels/OrderItemVM.cs
536
C#
using System; using System.Reflection; using FubuCore.Formatting; using FubuCore.Reflection; using NUnit.Framework; namespace FubuCore.Testing.Formatting { [TestFixture] public class StringifierTester { #region Setup/Teardown [SetUp] public void SetUp() { stringifier = new Stringifier(); locator = new InMemoryServiceLocator(); } #endregion private IStringifier stringifier; private InMemoryServiceLocator locator; public interface Something { string Description { get; } } public class RedSomething : Something { public string Description { get { return "Red"; } } } public class BlueSomething : Something { public string Description { get { return "Blue"; } } } public class FakeSite { public Address Shipping { get; set; } public Address Billing { get; set; } public string[] Names { get; set; } } private void configure(Action<DisplayConversionRegistry> configure) { var registry = new DisplayConversionRegistry(); configure(registry); registry.Configure(stringifier); } [Test] public void get_date_value_out_of_the_box() { var date = DateTime.Today; stringifier.GetString(date).ShouldEqual(date.ToString()); } [Test] public void get_int_array_out_of_the_box() { var array = new[]{1, 2, 4, 8}; stringifier.GetString(array).ShouldEqual("1, 2, 4, 8"); } [Test] public void get_int_values_out_of_the_box() { stringifier.GetString(123).ShouldEqual(123); } [Test] public void get_string_array_out_of_the_box() { var array = new[]{"a", "b", "c"}; stringifier.GetString(array).ShouldEqual("a, b, c"); } [Test] public void get_string_values_out_of_the_box() { stringifier.GetString(null).ShouldBeEmpty(); stringifier.GetString("a").ShouldEqual("a"); } [Test] public void register_a_property_override_for_a_string_conversion() { configure(x => { //specific override formatting for Address objects named Shipping x.IfPropertyMatches<Address>(prop => prop.Name == "Shipping").ConvertBy( a => "{1}-{0}".ToFormat(a.Address1, a.City)); //default formatting for Address objects x.IfIsType<Address>().ConvertBy(a => "{0}, {1}".ToFormat(a.Address1, a.City)); }); var address = new Address{ Address1 = "2050 Ozark", City = "Joplin" }; const string expectedDefaultFormatting = "2050 Ozark, Joplin"; const string expectedOverrideFormatting = "Joplin-2050 Ozark"; var billingRequest = new GetStringRequest(ReflectionHelper.GetAccessor<FakeSite>(s => s.Billing), address, locator); var shippingRequest = new GetStringRequest(ReflectionHelper.GetAccessor<FakeSite>(s => s.Shipping), address, locator); stringifier.GetString(billingRequest).ShouldEqual(expectedDefaultFormatting); stringifier.GetString(shippingRequest).ShouldEqual(expectedOverrideFormatting); } [Test] public void register_a_property_override_for_a_string_conversion_passing_property_info() { PropertyInfo passedProperty = null; configure(x => { //specific override formatting for Address objects named Shipping x.IfPropertyMatches<Address>(prop => prop.Name == "Shipping") .ConvertBy((req, value) => { passedProperty = req.Property; return "{1}-{0}".ToFormat(value.Address1, value.City); }); //default formatting for Address objects x.IfIsType<Address>().ConvertBy(a => "{0}, {1}".ToFormat(a.Address1, a.City)); }); var address = new Address(); var shippingRequest = new GetStringRequest(ReflectionHelper.GetAccessor<FakeSite>(s => s.Shipping), address, locator); stringifier.GetString(shippingRequest); passedProperty.Name.ShouldEqual("Shipping"); } [Test] public void register_a_property_override_for_a_string_conversion_passing_raw_value() { object passedRawValue = null; configure(x => { //specific override formatting for Address objects named Shipping x.IfPropertyMatches<Address>(prop => prop.Name == "Shipping").ConvertBy((req, value) => { passedRawValue = req.RawValue; return "{1}-{0}".ToFormat(value.Address1, value.City); }); //default formatting for Address objects x.IfIsType<Address>().ConvertBy(a => "{0}, {1}".ToFormat(a.Address1, a.City)); }); var address = new Address(); var shippingRequest = new GetStringRequest(ReflectionHelper.GetAccessor<FakeSite>(s => s.Shipping), address, locator); stringifier.GetString(shippingRequest); passedRawValue.ShouldBeTheSameAs(address); } [Test] public void register_a_string_conversion_for_a_class() { configure(x => x.IfIsType<Address>().ConvertBy(a => "{0}, {1}".ToFormat(a.Address1, a.City))); var address = new Address{ Address1 = "2050 Ozark", City = "Joplin" }; stringifier.GetString(address).ShouldEqual("2050 Ozark, Joplin"); } [Test] public void register_a_string_conversion_for_a_series_of_types() { configure(x => x.IfCanBeCastToType<Something>().ConvertBy(s => s.Description)); stringifier.GetString(new RedSomething()).ShouldEqual("Red"); stringifier.GetString(new BlueSomething()).ShouldEqual("Blue"); } [Test] public void register_a_string_conversion_function_by_a_struct_type() { configure(x => x.IfIsType<DateTime>().ConvertBy(d => d.ToShortDateString())); var date = DateTime.Today; stringifier.GetString(date).ShouldEqual(date.ToShortDateString()); } [Test] public void should_return_empty_when_no_converter_is_defined_for_type() { stringifier.GetString(null).ShouldEqual(""); } [Test] public void should_return_empty_when_value_is_null() { configure(x => x.IfIsType<DateTime>().ConvertBy(d => d.ToShortDateString())); stringifier.GetString(null).ShouldEqual(""); } [Test] public void string_conversion_functions_work_for_nullable_types() { configure(x => x.IfIsType<DateTime>().ConvertBy(d => d.ToShortDateString())); var date = DateTime.Today; stringifier.GetString(date).ShouldEqual(date.ToShortDateString()); } [Test] public void string_conversion_functions_work_for_nullable_types_that_are_null() { configure(x => x.IfIsType<DateTime>().ConvertBy(d => d.ToShortDateString())); stringifier.GetString(DateTime.Parse("17-JAN-2007")).ShouldEqual( DateTime.Parse("17-JAN-2007").ToShortDateString()); } [Test] public void stringifier_can_use_a_service_to_get_at_a_display() { locator.Add<IWidgetDisplayer>(new WidgetDisplayer()); configure( x => { x.IfCanBeCastToType<Widget>().ConvertBy((r, w) => r.Get<IWidgetDisplayer>().ToDisplay(w)); }); var widget = new Widget{ Color = "Red" }; var request = new GetStringRequest(null, widget, locator); stringifier.GetString(request).ShouldEqual("A Red widget"); } } public class Widget { public string Color { get; set; } } public interface IWidgetDisplayer { string ToDisplay(Widget widget); } public class WidgetDisplayer : IWidgetDisplayer { public string ToDisplay(Widget widget) { return "A {0} widget".ToFormat(widget.Color); } } public class Address { public Address() { StateOrProvince = string.Empty; Country = string.Empty; AddressType = string.Empty; } public int Order { get; set; } public bool IsActive { get; set; } public string AddressType { get; set; } public string Address1 { get; set; } public string Address2 { get; set; } public string City { get; set; } public string StateOrProvince { get; set; } public string Country { get; set; } public string PostalCode { get; set; } //[Required] //public TimeZoneInfo TimeZone { get; set; } public DateTime DateEntered { get; set; } public Guid Guid { get; set; } } }
31.721003
121
0.536219
[ "Apache-2.0" ]
DovetailSoftware/fubucore
src/FubuCore.Testing/Formatting/StringifierTester.cs
10,119
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using Blockcore.AsyncWork; using Blockcore.Configuration; using Blockcore.Connection; using Blockcore.P2P.Peer; using Blockcore.Utilities; using Blockcore.Utilities.Extensions; using Microsoft.Extensions.Logging; using NBitcoin; namespace Blockcore.P2P { /// <summary> /// Contract for <see cref="PeerDiscovery"/>. /// </summary> public interface IPeerDiscovery : IDisposable { /// <summary> /// Starts the peer discovery process. /// </summary> void DiscoverPeers(IConnectionManager connectionManager); } /// <summary>Async loop that discovers new peers to connect to.</summary> public sealed class PeerDiscovery : IPeerDiscovery { /// <summary>The async loop for performing discovery on actual peers. We need to wait upon it before we can shut down this connector.</summary> private IAsyncLoop discoverFromPeersLoop; /// <summary>The async loop for discovering from DNS seeds & seed nodes. We need to wait upon it before we can shut down this connector.</summary> private IAsyncLoop discoverFromDnsSeedsLoop; /// <summary>Factory for creating background async loop tasks.</summary> private readonly IAsyncProvider asyncProvider; /// <summary>The parameters cloned from the connection manager.</summary> private NetworkPeerConnectionParameters currentParameters; /// <summary>Instance logger.</summary> private readonly ILogger logger; /// <summary>Logger factory to create loggers.</summary> private readonly ILoggerFactory loggerFactory; /// <summary>Global application life cycle control - triggers when application shuts down.</summary> private readonly INodeLifetime nodeLifetime; /// <summary>User defined node settings.</summary> private readonly NodeSettings nodeSettings; /// <summary>Peer address manager instance, see <see cref="IPeerAddressManager"/>.</summary> private readonly IPeerAddressManager peerAddressManager; /// <summary>The network the node is running on.</summary> private readonly Network network; /// <summary>Factory for creating P2P network peers.</summary> private readonly INetworkPeerFactory networkPeerFactory; private const int TargetAmountOfPeersToDiscover = 2000; public PeerDiscovery( IAsyncProvider asyncProvider, ILoggerFactory loggerFactory, Network network, INetworkPeerFactory networkPeerFactory, INodeLifetime nodeLifetime, NodeSettings nodeSettings, IPeerAddressManager peerAddressManager) { this.asyncProvider = asyncProvider; this.loggerFactory = loggerFactory; this.logger = this.loggerFactory.CreateLogger(this.GetType().FullName); this.peerAddressManager = peerAddressManager; this.network = network; this.networkPeerFactory = networkPeerFactory; this.nodeLifetime = nodeLifetime; this.nodeSettings = nodeSettings; } /// <inheritdoc/> public void DiscoverPeers(IConnectionManager connectionManager) { // If peers are specified in the -connect arg then discovery does not happen. if (connectionManager.ConnectionSettings.Connect.Any()) return; if (!connectionManager.Parameters.PeerAddressManagerBehaviour().Mode.HasFlag(PeerAddressManagerBehaviourMode.Discover)) return; this.currentParameters = connectionManager.Parameters.Clone(); // TODO we shouldn't add all the behaviors, only those that we need. this.discoverFromDnsSeedsLoop = this.asyncProvider.CreateAndRunAsyncLoop(nameof(this.DiscoverFromDnsSeedsAsync), async token => { if (this.peerAddressManager.Peers.Count < TargetAmountOfPeersToDiscover) await this.DiscoverFromDnsSeedsAsync(); }, this.nodeLifetime.ApplicationStopping, TimeSpan.FromHours(1)); this.discoverFromPeersLoop = this.asyncProvider.CreateAndRunAsyncLoop(nameof(this.DiscoverPeersAsync), async token => { if (this.peerAddressManager.Peers.Count < TargetAmountOfPeersToDiscover) await this.DiscoverPeersAsync(); }, this.nodeLifetime.ApplicationStopping, TimeSpans.TenSeconds); } /// <summary> /// See <see cref="DiscoverPeers"/>. This loop deals with discovery from DNS seeds and seed nodes as opposed to peers. /// </summary> private async Task DiscoverFromDnsSeedsAsync() { var peersToDiscover = new List<IPEndPoint>(); // First see if we need to do DNS discovery at all. We may have peers from a previous cycle that still need to be tried. if (this.peerAddressManager.Peers.Select(a => !a.Attempted).Any()) { this.logger.LogTrace("(-)[SKIP_DISCOVERY_UNATTEMPTED_PEERS_REMAINING]"); return; } // At this point there are either no peers that we know of, or all the ones we do know of have been attempted & failed. this.AddDNSSeedNodes(peersToDiscover); this.AddSeedNodes(peersToDiscover); if (peersToDiscover.Count == 0) { this.logger.LogTrace("(-)[NO_DNS_SEED_ADDRESSES]"); return; } // Randomise the order prior to attempting connections. peersToDiscover = peersToDiscover.OrderBy(a => RandomUtils.GetInt32()).ToList(); await this.ConnectToDiscoveryCandidatesAsync(peersToDiscover).ConfigureAwait(false); } /// <summary> /// See <see cref="DiscoverPeers"/>. This loop deals with discovery from peers as opposed to DNS seeds and seed nodes. /// </summary> private async Task DiscoverPeersAsync() { var peersToDiscover = new List<IPEndPoint>(); // The peer selector returns a quantity of peers for discovery already in random order. List<PeerAddress> foundPeers = this.peerAddressManager.PeerSelector.SelectPeersForDiscovery(1000).ToList(); peersToDiscover.AddRange(foundPeers.Select(p => p.Endpoint)); if (peersToDiscover.Count == 0) { this.logger.LogTrace("(-)[NO_ADDRESSES]"); return; } await this.ConnectToDiscoveryCandidatesAsync(peersToDiscover).ConfigureAwait(false); } private async Task ConnectToDiscoveryCandidatesAsync(List<IPEndPoint> peersToDiscover) { await peersToDiscover.ForEachAsync(5, this.nodeLifetime.ApplicationStopping, async (endPoint, cancellation) => { using (CancellationTokenSource connectTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellation)) { this.logger.LogDebug("Attempting to discover from : '{0}'", endPoint); connectTokenSource.CancelAfter(TimeSpan.FromSeconds(5)); INetworkPeer networkPeer = null; // Try to connect to a peer with only the address-sharing behaviour, to learn about their peers and disconnect within 5 seconds. try { NetworkPeerConnectionParameters clonedParameters = this.currentParameters.Clone(); clonedParameters.ConnectCancellation = connectTokenSource.Token; PeerAddressManagerBehaviour addressManagerBehaviour = clonedParameters.TemplateBehaviors.OfType<PeerAddressManagerBehaviour>().FirstOrDefault(); clonedParameters.TemplateBehaviors.Clear(); clonedParameters.TemplateBehaviors.Add(addressManagerBehaviour); networkPeer = await this.networkPeerFactory.CreateConnectedNetworkPeerAsync(endPoint, clonedParameters).ConfigureAwait(false); await networkPeer.VersionHandshakeAsync(connectTokenSource.Token).ConfigureAwait(false); this.peerAddressManager.PeerDiscoveredFrom(endPoint, DateTimeProvider.Default.GetUtcNow()); connectTokenSource.Token.WaitHandle.WaitOne(TimeSpan.FromSeconds(5)); } catch { } finally { networkPeer?.Disconnect("Discovery job done"); networkPeer?.Dispose(); } this.logger.LogDebug("Discovery from '{0}' finished", endPoint); } }).ConfigureAwait(false); } /// <summary> /// Add peers to the address manager from the network's DNS seed nodes. /// </summary> private void AddDNSSeedNodes(List<IPEndPoint> endPoints) { foreach (DNSSeedData seed in this.network.DNSSeeds) { try { // We want to try to ensure we get a fresh set of results from the seeder each time we query it. IPAddress[] ipAddresses = seed.GetAddressNodes(true); endPoints.AddRange(ipAddresses.Select(ip => new IPEndPoint(ip, this.network.DefaultPort))); } catch (Exception) { this.logger.LogWarning("Error getting seed node addresses from {0}.", seed.Host); } } } /// <summary> /// Add peers to the address manager from the network's seed nodes. /// </summary> private void AddSeedNodes(List<IPEndPoint> endPoints) { endPoints.AddRange(this.network.SeedNodes.Select(ipAddress => ipAddress.Endpoint)); } /// <inheritdoc /> public void Dispose() { this.discoverFromPeersLoop?.Dispose(); this.discoverFromDnsSeedsLoop?.Dispose(); } } }
42.663934
168
0.626225
[ "MIT" ]
dangershony/blockcore
src/Blockcore/P2P/PeerDiscoveryLoop.cs
10,412
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace PHStudios.Models { using System; using System.Collections.Generic; public partial class VideoResource { public int Video_ID { get; set; } public int Resource_ID { get; set; } public System.DateTime Created { get; set; } public virtual Resource Resource { get; set; } public virtual Video Video { get; set; } } }
33.6
86
0.509524
[ "MIT" ]
nbiefeld/Site-MVC
Version 1/PHStudios/Models/VideoResource.cs
840
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> /// OutboundMessagingMessagingCampaignProgressEventCampaignProgress /// </summary> [DataContract] public partial class OutboundMessagingMessagingCampaignProgressEventCampaignProgress : IEquatable<OutboundMessagingMessagingCampaignProgressEventCampaignProgress> { /// <summary> /// Initializes a new instance of the <see cref="OutboundMessagingMessagingCampaignProgressEventCampaignProgress" /> class. /// </summary> /// <param name="Campaign">Campaign.</param> /// <param name="NumberOfContactsCalled">The number of contacts that have been called so far.</param> /// <param name="NumberOfContactsMessaged">The number of contacts that have been messaged so far.</param> /// <param name="TotalNumberOfContacts">The total number of contacts in the contact list.</param> /// <param name="Percentage">numberOfContactsContacted/totalNumberOfContacts*100.</param> public OutboundMessagingMessagingCampaignProgressEventCampaignProgress(OutboundMessagingMessagingCampaignProgressEventUriReference Campaign = null, double? NumberOfContactsCalled = null, double? NumberOfContactsMessaged = null, double? TotalNumberOfContacts = null, int? Percentage = null) { this.Campaign = Campaign; this.NumberOfContactsCalled = NumberOfContactsCalled; this.NumberOfContactsMessaged = NumberOfContactsMessaged; this.TotalNumberOfContacts = TotalNumberOfContacts; this.Percentage = Percentage; } /// <summary> /// Gets or Sets Campaign /// </summary> [DataMember(Name="campaign", EmitDefaultValue=false)] public OutboundMessagingMessagingCampaignProgressEventUriReference Campaign { get; set; } /// <summary> /// The number of contacts that have been called so far /// </summary> /// <value>The number of contacts that have been called so far</value> [DataMember(Name="numberOfContactsCalled", EmitDefaultValue=false)] public double? NumberOfContactsCalled { get; set; } /// <summary> /// The number of contacts that have been messaged so far /// </summary> /// <value>The number of contacts that have been messaged so far</value> [DataMember(Name="numberOfContactsMessaged", EmitDefaultValue=false)] public double? NumberOfContactsMessaged { get; set; } /// <summary> /// The total number of contacts in the contact list /// </summary> /// <value>The total number of contacts in the contact list</value> [DataMember(Name="totalNumberOfContacts", EmitDefaultValue=false)] public double? TotalNumberOfContacts { get; set; } /// <summary> /// numberOfContactsContacted/totalNumberOfContacts*100 /// </summary> /// <value>numberOfContactsContacted/totalNumberOfContacts*100</value> [DataMember(Name="percentage", EmitDefaultValue=false)] public int? Percentage { 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 OutboundMessagingMessagingCampaignProgressEventCampaignProgress {\n"); sb.Append(" Campaign: ").Append(Campaign).Append("\n"); sb.Append(" NumberOfContactsCalled: ").Append(NumberOfContactsCalled).Append("\n"); sb.Append(" NumberOfContactsMessaged: ").Append(NumberOfContactsMessaged).Append("\n"); sb.Append(" TotalNumberOfContacts: ").Append(TotalNumberOfContacts).Append("\n"); sb.Append(" Percentage: ").Append(Percentage).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 OutboundMessagingMessagingCampaignProgressEventCampaignProgress); } /// <summary> /// Returns true if OutboundMessagingMessagingCampaignProgressEventCampaignProgress instances are equal /// </summary> /// <param name="other">Instance of OutboundMessagingMessagingCampaignProgressEventCampaignProgress to be compared</param> /// <returns>Boolean</returns> public bool Equals(OutboundMessagingMessagingCampaignProgressEventCampaignProgress other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return true && ( this.Campaign == other.Campaign || this.Campaign != null && this.Campaign.Equals(other.Campaign) ) && ( this.NumberOfContactsCalled == other.NumberOfContactsCalled || this.NumberOfContactsCalled != null && this.NumberOfContactsCalled.Equals(other.NumberOfContactsCalled) ) && ( this.NumberOfContactsMessaged == other.NumberOfContactsMessaged || this.NumberOfContactsMessaged != null && this.NumberOfContactsMessaged.Equals(other.NumberOfContactsMessaged) ) && ( this.TotalNumberOfContacts == other.TotalNumberOfContacts || this.TotalNumberOfContacts != null && this.TotalNumberOfContacts.Equals(other.TotalNumberOfContacts) ) && ( this.Percentage == other.Percentage || this.Percentage != null && this.Percentage.Equals(other.Percentage) ); } /// <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.Campaign != null) hash = hash * 59 + this.Campaign.GetHashCode(); if (this.NumberOfContactsCalled != null) hash = hash * 59 + this.NumberOfContactsCalled.GetHashCode(); if (this.NumberOfContactsMessaged != null) hash = hash * 59 + this.NumberOfContactsMessaged.GetHashCode(); if (this.TotalNumberOfContacts != null) hash = hash * 59 + this.TotalNumberOfContacts.GetHashCode(); if (this.Percentage != null) hash = hash * 59 + this.Percentage.GetHashCode(); return hash; } } } }
38.119469
297
0.575624
[ "MIT" ]
MyPureCloud/platform-client-sdk-dotnet
build/src/PureCloudPlatform.Client.V2/Model/OutboundMessagingMessagingCampaignProgressEventCampaignProgress.cs
8,615
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 System.Collections.Generic; using System.Linq; using System.Management.Automation; using Microsoft.VisualStudio.Threading; using NuGet.PackageManagement.UI; using NuGet.ProjectManagement; using NuGet.Versioning; namespace NuGet.PackageManagement.PowerShellCmdlets { /// <summary> /// FindPackage is similar to GetPackage -ListAvailable, but have the following difference: /// Without -StartWith present, it find packages by keyword anywhere in the package Id, description or summary. /// With -StartWith present, it only returns packages with Ids starting with the specified string. /// </summary> [Cmdlet(VerbsCommon.Find, "Package")] [OutputType(typeof(PowerShellPackage))] public class FindPackageCommand : NuGetPowerShellBaseCommand { // NOTE: Number of packages returned by api.nuget.org is static and is 20 // Display the same number of results with other endpoints, such as nuget.org/api/v2, as well private const int MaxReturnedPackages = 20; [Parameter(ValueFromPipelineByPropertyName = true, Position = 0)] public string Id { get; set; } [Parameter] [ValidateNotNullOrEmpty] public string Version { get; set; } [Parameter] [ValidateNotNullOrEmpty] public virtual string Source { get; set; } [Parameter] [Alias("Prerelease")] public SwitchParameter IncludePrerelease { get; set; } [Parameter] public SwitchParameter AllVersions { get; set; } /// <summary> /// Determines if an exact Id match would be performed with the search results. By default, FindPackage /// returns all packages that contain Filter value in package ID, description or summary. /// </summary> [Parameter] public SwitchParameter ExactMatch { get; set; } /// <summary> /// Find packages by AutoComplete endpoint, starting with Id. /// Also used for tab expansion. /// </summary> [Parameter] public SwitchParameter StartWith { get; set; } [Parameter] [ValidateRange(0, Int32.MaxValue)] public virtual int First { get; set; } [Parameter] [ValidateRange(0, Int32.MaxValue)] public int Skip { get; set; } protected void Preprocess() { // Since this is also used for intellisense, we need to limit the number of packages that we return. Otherwise, // typing InstallPackage TAB would download the entire feed. if (First == 0) { First = MaxReturnedPackages; } if (Id == null) { Id = string.Empty; } if (Version == null) { Version = string.Empty; } UpdateActiveSourceRepository(Source); } protected override void ProcessRecordCore() { Preprocess(); if (StartWith.IsPresent) { FindPackageStartWithId(excludeVersionInfo: false); } else { FindPackagesByPSSearchService(); } } private void FindPackagesByPSSearchService() { var errors = new List<string>(); var remotePackages = GetPackagesFromRemoteSource(Id, IncludePrerelease.IsPresent, errors.Add); if (ExactMatch.IsPresent) { remotePackages = remotePackages.Where(p => string.Equals(p.Identity.Id, Id, StringComparison.OrdinalIgnoreCase)); } remotePackages = remotePackages.Skip(Skip).Take(First); VersionType versionType; if (AllVersions.IsPresent) { versionType = VersionType.All; } else { versionType = VersionType.Latest; } var view = PowerShellRemotePackage.GetPowerShellPackageView(remotePackages, versionType); foreach (var package in view) { // Just start the task and don't wait for it to complete package.AsyncLazyVersions.GetValueAsync(); } if (view.Any()) { WriteObject(view, enumerateCollection: true); } foreach (var error in errors) { LogCore(MessageLevel.Error, error); } } protected void FindPackageStartWithId(bool excludeVersionInfo) { var packageIds = NuGetUIThreadHelper.JoinableTaskFactory.Run( () => GetPackageIdsFromRemoteSourceAsync(Id, IncludePrerelease.IsPresent)); Token.ThrowIfCancellationRequested(); packageIds = packageIds?.Skip(Skip).Take(First) ?? Enumerable.Empty<string>(); if (excludeVersionInfo) { var packages = packageIds.Select(id => new PowerShellPackage { Id = id }); WriteObject(packages, enumerateCollection: true); return; } if (!ExactMatch.IsPresent) { var packages = new List<PowerShellPackage>(); foreach (var id in packageIds) { var package = GetPowerShellPackageFromRemoteSource(id); // Just start the task and don't wait for it to complete package.AsyncLazyVersions.GetValueAsync(); packages.Add(package); } WriteObject(packages, enumerateCollection: true); } else { if (packageIds.Any()) { var packageId = packageIds.Where(p => string.Equals(p, Id, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); if (!string.IsNullOrEmpty(packageId)) { var package = GetPowerShellPackageFromRemoteSource(packageId); // Just start the task and don't wait for it to complete package.AsyncLazyVersions.GetValueAsync(); WriteObject(package); } } } } /// <summary> /// Get IPowerShellPackage from the remote package source /// </summary> private PowerShellPackage GetPowerShellPackageFromRemoteSource(string id) { var asyncLazyVersions = new AsyncLazy<IEnumerable<NuGetVersion>>( () => GetPackageVersionsFromRemoteSourceAsync(id, Version, IncludePrerelease.IsPresent), NuGetUIThreadHelper.JoinableTaskFactory); var package = new PowerShellPackage(); package.Id = id; package.AsyncLazyVersions = asyncLazyVersions; if (AllVersions.IsPresent) { package.AllVersions = true; } else { package.AllVersions = false; } return package; } } }
34.364486
133
0.568942
[ "Apache-2.0" ]
MarkOsborneMS/NuGet.Client
src/NuGet.Clients/PackageManagement.PowerShellCmdlets/Cmdlets/FindPackageCommand.cs
7,356
C#
/* * Copyright Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the monitoring-2010-08-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.CloudWatch.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.CloudWatch.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for PutInsightRule operation /// </summary> public class PutInsightRuleResponseUnmarshaller : XmlResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { PutInsightRuleResponse response = new PutInsightRuleResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.IsStartElement) { if(context.TestExpression("PutInsightRuleResult", 2)) { UnmarshallResult(context, response); continue; } if (context.TestExpression("ResponseMetadata", 2)) { response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context); } } } return response; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId="response")] private static void UnmarshallResult(XmlUnmarshallerContext context, PutInsightRuleResponse response) { int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { } } return; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new XmlUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterValue")) { return InvalidParameterValueExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("LimitExceededException")) { return LimitExceededExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("MissingParameter")) { return MissingRequiredParameterExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonCloudWatchException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static PutInsightRuleResponseUnmarshaller _instance = new PutInsightRuleResponseUnmarshaller(); internal static PutInsightRuleResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static PutInsightRuleResponseUnmarshaller Instance { get { return _instance; } } } }
38.965278
166
0.595081
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/CloudWatch/Generated/Model/Internal/MarshallTransformations/PutInsightRuleResponseUnmarshaller.cs
5,611
C#
using System; using System.Collections.Generic; using System.Text; namespace Tensorflow.Keras.Regularizers { class L1L2 { } }
12.727273
39
0.714286
[ "Apache-2.0" ]
mahedee/TensorFlow.NET
src/TensorFlowNET.Keras/Regularizers/L1L2.cs
142
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace MovieDeckApi { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
24.821429
70
0.644604
[ "MIT" ]
Iceto04/SoftUni
ASP.NET Core/05. Web API/MovieDeckApi/MovieDeckApi/Program.cs
695
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Collections.Generic; using System.Diagnostics; namespace Microsoft.Languages.Core.Text { /// <summary> /// A collection of text ranges that are not next to another. /// Ranges must not overlap. Can be sorted by range start positions. /// Can be searched in order to locate range that contains given /// position or range that starts at a given position. /// The search is a binary search. Collection derives from /// <seealso cref="TextRangeCollection"/> /// </summary> /// <typeparam name="T">A class or an interface that derives from <seealso cref="ITextRange"/></typeparam> [DebuggerDisplay("Count={Count}")] public class DisjointTextRangeCollection<T> : TextRangeCollection<T> where T : ITextRange { #region Construction public DisjointTextRangeCollection() { } public DisjointTextRangeCollection(IEnumerable<T> ranges) : base(ranges) { } #endregion #region ITextRange public override bool Contains(int position) { if (this.Count == 0) return false; foreach (ITextRange range in this) { if (range.Contains(position)) return true; } return false; } #endregion public bool Contains(int position, bool inclusiveEnd) { if (this.Count == 0) return false; foreach (ITextRange range in this) { if (range.Contains(position) || (inclusiveEnd && range.End == position)) return true; } return false; } } }
33.163636
110
0.607456
[ "MIT" ]
AlexanderSher/RTVS-Old
src/Languages/Core/Impl/Text/DisjointTextRangeCollection.cs
1,826
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; using System.Globalization; using System.IO; using System.Runtime; namespace System.ServiceModel.Security { /// <summary> /// This is the in-memory nonce-cache used for turnkey replay detection. /// The nonce cache is based on a hashtable implementation for fast lookups. /// The hashcode is computed based on the nonce byte array. /// The nonce cache periodically purges stale nonce entries. /// </summary> internal sealed class InMemoryNonceCache : NonceCache { private NonceCacheImpl _cacheImpl; public InMemoryNonceCache(TimeSpan cachingTime, int maxCachedNonces) { CacheSize = maxCachedNonces; CachingTimeSpan = cachingTime; _cacheImpl = new NonceCacheImpl(cachingTime, maxCachedNonces); } public override bool CheckNonce(byte[] nonce) { return _cacheImpl.CheckNonce(nonce); } public override bool TryAddNonce(byte[] nonce) { return _cacheImpl.TryAddNonce(nonce); } public override string ToString() { StringWriter writer = new StringWriter(CultureInfo.InvariantCulture); writer.WriteLine("NonceCache:"); writer.WriteLine(" Caching Timespan: {0}", CachingTimeSpan); writer.WriteLine(" Capacity: {0}", CacheSize); return writer.ToString(); } internal sealed class NonceCacheImpl : TimeBoundedCache { private static NonceKeyComparer s_comparer = new NonceKeyComparer(); private static object s_dummyItem = new Object(); // if there are less than lowWaterMark entries, no purging is done private static int s_lowWaterMark = 50; // We created a key for the nonce using the first 4 bytes, and hence the minimum length of nonce // that can be added to the cache. private static int s_minimumNonceLength = 4; private TimeSpan _cachingTimeSpan; public NonceCacheImpl(TimeSpan cachingTimeSpan, int maxCachedNonces) : base(s_lowWaterMark, maxCachedNonces, s_comparer, PurgingMode.AccessBasedPurge, TimeSpan.FromTicks(cachingTimeSpan.Ticks >> 2), false) { _cachingTimeSpan = cachingTimeSpan; } public bool TryAddNonce(byte[] nonce) { if (nonce == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(nonce)); } if (nonce.Length < s_minimumNonceLength) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.NonceLengthTooShort); } DateTime expirationTime = TimeoutHelper.Add(DateTime.UtcNow, _cachingTimeSpan); return base.TryAddItem(nonce, s_dummyItem, expirationTime, false); } public bool CheckNonce(byte[] nonce) { if (nonce == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(nonce)); } if (nonce.Length < s_minimumNonceLength) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.NonceLengthTooShort); } if (base.GetItem(nonce) != null) { return true; } else { return false; } } /// <summary> /// This class provides the hash-code value for the key (nonce) of the nonce cache. /// The hash code is obtained from the nonce byte array by making an int of /// the first 4 bytes /// </summary> internal sealed class NonceKeyComparer : IEqualityComparer, Collections.Generic.IEqualityComparer<byte[]> { public int GetHashCode(object o) { return GetHashCode((byte[])o); } public int GetHashCode(byte[] o) { byte[] nonce = (byte[])o; return (((int)nonce[0]) | (((int)nonce[1]) << 8) | (((int)nonce[2]) << 16) | (((int)nonce[3]) << 24)); } public int Compare(object x, object y) { return Compare((byte[])x, (byte[])y); } public int Compare(byte[] x, byte[] y) { if (Object.ReferenceEquals(x, y)) { return 0; } if (x == null) { return -1; } else if (y == null) { return 1; } byte[] nonce1 = (byte[])x; int length1 = nonce1.Length; byte[] nonce2 = (byte[])y; int length2 = nonce2.Length; if (length1 == length2) { for (int i = 0; i < length1; ++i) { int diff = ((int)nonce1[i] - (int)nonce2[i]); if (diff != 0) { return diff; } } return 0; } else if (length1 > length2) { return 1; } else { return -1; } } public new bool Equals(object x, object y) { return (Compare(x, y) == 0); } public bool Equals(byte[] x, byte[] y) { return (Compare(x, y) == 0); } } } } }
34.908108
152
0.480644
[ "MIT" ]
Bencargs/wcf
src/System.Private.ServiceModel/src/System/ServiceModel/Security/InMemoryNonceCache.cs
6,458
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EntityType.cs.tt namespace Microsoft.Graph2.CallRecords { using System; using System.Collections.Generic; using System.IO; using System.Text.Json.Serialization; /// <summary> /// The type Photo. /// </summary> public partial class Photo : Microsoft.Graph.Entity { /// <summary> /// Gets or sets failure info. /// </summary> [JsonPropertyName("failureInfo")] public FailureInfo FailureInfo { get; set; } /// <summary> /// Gets or sets option. /// </summary> [JsonPropertyName("option")] public Option Option { get; set; } } }
29.131579
153
0.526649
[ "MIT" ]
Dakoni4400/MSGraph-SDK-Code-Generator
test/Typewriter.Test/TestDataCSharp/com/microsoft/graph2/callrecords/model/Photo.cs
1,107
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace ZAD_10 { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
25.481481
70
0.642442
[ "MIT" ]
S17918/PJATK
APBD/Zad_10_11/ZAD_10/ZAD_10/ZAD_10/Program.cs
688
C#
// ************************************************************************************* // SCICHART® Copyright SciChart Ltd. 2011-2020. All rights reserved. // // Web: http://www.scichart.com // Support: support@scichart.com // Sales: sales@scichart.com // // ChartLegendsExampleView.xaml.cs is part of the SCICHART® Examples. Permission is hereby granted // to modify, create derivative works, distribute and publish any part of this source // code whether for commercial, private or personal use. // // The SCICHART® examples are distributed in the hope that they will be useful, but // without any warranty. It is provided "AS IS" without warranty of any kind, either // expressed or implied. // ************************************************************************************* using System; using System.Windows; using System.Windows.Controls; using SciChart.Charting.ChartModifiers; using SciChart.Charting.Model.DataSeries; using SciChart.Examples.ExternalDependencies.Data; namespace SciChart.Examples.Examples.CreateMultiseriesChart { public partial class MultipleLinesView : UserControl { public MultipleLinesView() { InitializeComponent(); cboGetLegendFor.ItemsSource = Enum.GetNames(typeof (SourceMode)); cboGetLegendFor.SelectedIndex = 1; cboLegendPlacement.ItemsSource = Enum.GetNames(typeof (LegendPlacement)); cboLegendPlacement.SelectedItem = Enum.GetName(typeof (LegendPlacement), LegendPlacement.Inside); cboLegendOrientation.ItemsSource = Enum.GetNames(typeof (Orientation)); cboLegendOrientation.SelectedItem = Enum.GetName(typeof (Orientation), Orientation.Vertical); cboHorizontalAlignment.ItemsSource = Enum.GetNames(typeof (HorizontalAlignment)); cboHorizontalAlignment.SelectedItem = Enum.GetName(typeof(HorizontalAlignment), System.Windows.HorizontalAlignment.Left); cboVerticalAlignment.ItemsSource = Enum.GetNames(typeof(VerticalAlignment)); cboVerticalAlignment.SelectedItem = Enum.GetName(typeof(VerticalAlignment), System.Windows.VerticalAlignment.Top); } private void MultipleLinesView_OnLoaded(object sender, RoutedEventArgs e) { // Add some data series of type X=double, Y=double var dataSeries0 = new XyDataSeries<double, double> {SeriesName = "Curve A"}; var dataSeries1 = new XyDataSeries<double, double> {SeriesName = "Curve B"}; var dataSeries2 = new XyDataSeries<double, double> {SeriesName = "Curve C"}; var dataSeries3 = new XyDataSeries<double, double> { SeriesName = "Curve D" }; var data1 = DataManager.Instance.GetStraightLine(1000, 1.0, 10); var data2 = DataManager.Instance.GetStraightLine(2000, 1.0, 10); var data3 = DataManager.Instance.GetStraightLine(3000, 1.0, 10); var data4 = DataManager.Instance.GetStraightLine(4000, 1.0, 10); // Append data to series. dataSeries0.Append(data1.XData, data1.YData); dataSeries1.Append(data2.XData, data2.YData); dataSeries2.Append(data3.XData, data3.YData); dataSeries3.Append(data4.XData, data4.YData); sciChart.RenderableSeries[0].DataSeries = dataSeries0; sciChart.RenderableSeries[1].DataSeries = dataSeries1; sciChart.RenderableSeries[2].DataSeries = dataSeries2; sciChart.RenderableSeries[3].DataSeries = dataSeries3; // Zoom to extents of the data sciChart.ZoomExtents(); } private void OnLegendModeChanged(object sender, SelectionChangedEventArgs e) { if (legendModifier != null) { legendModifier.GetLegendDataFor = (SourceMode)Enum.Parse(typeof(SourceMode), (string)e.AddedItems[0], true); } } private void OnLegendPlacementChanged(object sender, SelectionChangedEventArgs e) { if (legendModifier != null) { legendModifier.LegendPlacement = (LegendPlacement)Enum.Parse(typeof(LegendPlacement), (string)e.AddedItems[0], true); } } private void OnLegendOrientationChanged(object sender, SelectionChangedEventArgs e) { if (legendModifier != null) { legendModifier.Orientation = (Orientation)Enum.Parse(typeof(Orientation), (string)e.AddedItems[0], true); } } private void OnLegendHorizontalAlignmentChanged(object sender, SelectionChangedEventArgs e) { if (legendModifier != null) { legendModifier.HorizontalAlignment = (HorizontalAlignment)Enum.Parse(typeof(HorizontalAlignment), (string)e.AddedItems[0], true); } } private void OnLegendVerticalAlignmentChanged(object sender, SelectionChangedEventArgs e) { if (legendModifier != null) { legendModifier.VerticalAlignment = (VerticalAlignment)Enum.Parse(typeof(VerticalAlignment), (string)e.AddedItems[0], true); } } } }
44.939655
145
0.644542
[ "MIT" ]
gwlund/SciChart.Wpf.Examples.v6
Examples/SciChart.Examples/Examples/CreateMultiseriesChart/ChartLegendsExampleView.xaml.cs
5,218
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Net.Http; using System.Net.Http.Headers; namespace PointOfInterestSkill.Services { /// <summary> /// Point of Interest skill helper class. /// </summary> public class ServiceHelper { private static HttpClient httpClient = new HttpClient(); /// <summary> /// Generate httpClient. /// </summary> /// <param name="accessToken">API access token.</param> /// <returns>Generated httpClient.</returns> public static HttpClient GetHttpClient() { if (!httpClient.DefaultRequestHeaders.Contains("Accept")) { httpClient.DefaultRequestHeaders.Add("Accept", "application/json"); } return httpClient; } } }
27.09375
83
0.605536
[ "MIT" ]
Yi-Coder/botframework-solutions
skills/csharp/pointofinterestskill/Services/ServiceHelper.cs
869
C#
/* * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with this file, You can obtain one at * http://mozilla.org/MPL/2.0/. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using FSO.Vitaboy; using FSO.Content.Framework; using System.Text.RegularExpressions; using FSO.Content.Codecs; namespace FSO.Content { /// <summary> /// Provides access to animation (*.anim) data in FAR3 archives. /// </summary> public class AvatarAnimationProvider : FAR3Provider<Animation> { public Dictionary<string, Far3ProviderEntry<Animation>> AnimationsByName { get { return EntriesByName; //expose so we can list all animations, for now. //todo: cleanup } } public AvatarAnimationProvider(Content contentManager) : base(contentManager, new AnimationCodec(), new Regex(".*/animations/.*\\.dat")) { } } }
28
93
0.640977
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
francot514/FreeSims
SimsVille/ContentManager/AvatarAnimationProvider.cs
1,066
C#
class TKLjF0GW5RGFJc4sH63GQSsgx8_nsssRvm6gWzT { public bool I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr = false; public string GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = null; int K9KadQaurGm = 0; string bg327eVJDKiTt40DKCso6m = null; private bool mYH1VIWj6vllki0nUbxdaTnhL40f5 = false; public float E4kE9be0yRH2DA5abk9kV7BauCmNjOE = 0.0f; private double qDhY4uH2YDKI2xru3SRLZqVh3a = 0.0; public double W_hPdJDugNsCiHq = 0.0; private int bKzwvBsDbqe70Es7txGzrbd2zWt_l = 0; public float JKaPiVcUnqzykldk1b = 0.0f; private double cSK9R_wK85Cd4bCy8VBxH1Zcw5hVCJqgfNuqa = 0.0; private double Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi = 0.0; public bool Lfu2KF4MsWk3H4 = false; float FAEFxJLoH3VdtwoZRv4vEmMJva7Zt2yye8iiVgS = 0.0f; double kKmlcjd2p6ylBTQAYpP = 0.0; int nDseIQ_zqPMfRCs = 0; private bool wJFnjzSaOMsiZyzNHSIua4YhqQln = false; int P11CoOr_aaRo = 0; private bool S9cWjfPHgxiHxCspAlhQCv9XVZB = false; float C0EfV40NqIbNVsTIUlRNgnuNNrCbGfi_q = 0.0f; int hCJtcAOtqe56KAkQfAFbA6mPwoATXN = 0; float BKA1K12H5lhBzajQcUA2pVLHT9_p7Gl = 0.0f; public string Omd6xWNsSMXBnj27p1BTRV = null; public float m85UNThrIL7aDr1rgZalNB = 0.0f; public string cXPnOXH1sypIib3P0HO6b2VWDc = null; public int u2GzJZLsk1cDhtSwWWV7hard5Bm3rG9 = 0; private double KYFvSOwZIQjSmgw9Vf0xHvartzgN = 0.0; public int H63W8NLA3F0L19T = 0; private int lB1CHJanPGXmpLWFV9TQ2pXBRaaVidV = 0; private float qRUEd28YBQ = 0.0f; public int SnxzbWQNmH1rgIdC6MIqBdQZFGOwlmHNn8BPDB { get; set; } public int CdCcEWh8apJw5V1PtuKUSTQqMS8u3TCWHYcb { get; set; } public int GaVnCNcPZi9gBkJ7HfgXXW52u_ { get; set; } public int qyITr9EMhcO0o77qx8kGvT_zR { get; set; } public int drto98_5g6biP { get; set; } public int AWeJhJGJm5Uyq0LBQe1myBQk9SxQEaI7 { get; set; } public int PqV0MgM4933EU7ZeMNNof { get; set; } public int b976I7twpXTIjs { get; set; } public int cy4Xtz3Bg3ZMx8nEKZFXYX50G8GBM1C4VZJ { get; set; } public int NpScRoNnTENf5GK30tjU6txQ2erY696 { get; set; } public int YokKRmVP6CLHANTTxsGMBjW38p { get; set; } public float DF0OIh0O7UW_PrdEM { get { return m85UNThrIL7aDr1rgZalNB; } set { m85UNThrIL7aDr1rgZalNB = value; } } public bool cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs { get { return Lfu2KF4MsWk3H4; } set { Lfu2KF4MsWk3H4 = value; } } public int cZdHPP_Dkn_69KklSxwaOJCzLUsGL { get; set; } public int aN9AovwT1ldGcKvWVjGg8xBFBvdbSreF3lI6Wgo6 { get { return K9KadQaurGm; } set { K9KadQaurGm = value; } } public float YSuXwyVWYnt0M_g89rljZ4Me9 { get { return qRUEd28YBQ; } set { qRUEd28YBQ = value; } } public int Y8QGmU1yyeZLaCxkAKP8fBHl2yHEt6YRGMefanJ { get; set; } public int IPlh91wjDg_jrk { get; set; } public int xkhw_OXQHvjxYe2IgL { get; set; } public int H_vcPMzNmR { get; set; } public int KWe1knMNkr7 { get; set; } public double E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3 { get { return cSK9R_wK85Cd4bCy8VBxH1Zcw5hVCJqgfNuqa; } set { cSK9R_wK85Cd4bCy8VBxH1Zcw5hVCJqgfNuqa = value; } } public int AFoZoUs6sJehwI1g0HfR { get; set; } public int XnCalPp9SjWcJZRW41Nb60F5eATCX { get; set; } public int mneOUpeEI41vVP5SBTgxxrwIsqMslGM_F5B_fw { get; set; } public int RUQANPnRn3V_kV { get; set; } public float m1CunzrKaSUTgwuFe5aRvtxeqBZ1sgZkqo { get { return BKA1K12H5lhBzajQcUA2pVLHT9_p7Gl; } set { BKA1K12H5lhBzajQcUA2pVLHT9_p7Gl = value; } } public int Hx38iCaBiywtWA1TlUAJE6OeOiYjNaf71da { get; set; } public int PpMhcDbHtSQTd765YVfceuaNQg5lkKE { get; set; } public int ogkUz8j5TWT6EL { get; set; } public void KhcvUxdxhesRNPq55BL2t0qalX1noAWujn() { BKA1K12H5lhBzajQcUA2pVLHT9_p7Gl = C0EfV40NqIbNVsTIUlRNgnuNNrCbGfi_q; JKaPiVcUnqzykldk1b = C0EfV40NqIbNVsTIUlRNgnuNNrCbGfi_q; Omd6xWNsSMXBnj27p1BTRV = GaB905q4fsO_wO7zAE0jkYPm3O9LLBz; GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = GaB905q4fsO_wO7zAE0jkYPm3O9LLBz; DF0OIh0O7UW_PrdEM = BKA1K12H5lhBzajQcUA2pVLHT9_p7Gl - JKaPiVcUnqzykldk1b; if(I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr && S9cWjfPHgxiHxCspAlhQCv9XVZB) { Lfu2KF4MsWk3H4 = !Lfu2KF4MsWk3H4; } bg327eVJDKiTt40DKCso6m = Omd6xWNsSMXBnj27p1BTRV + cXPnOXH1sypIib3P0HO6b2VWDc; GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = Omd6xWNsSMXBnj27p1BTRV + GaB905q4fsO_wO7zAE0jkYPm3O9LLBz; if(mYH1VIWj6vllki0nUbxdaTnhL40f5 && I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr) { Lfu2KF4MsWk3H4 = !Lfu2KF4MsWk3H4; } bg327eVJDKiTt40DKCso6m = bg327eVJDKiTt40DKCso6m + cXPnOXH1sypIib3P0HO6b2VWDc; mneOUpeEI41vVP5SBTgxxrwIsqMslGM_F5B_fw = aN9AovwT1ldGcKvWVjGg8xBFBvdbSreF3lI6Wgo6 - H_vcPMzNmR; m1CunzrKaSUTgwuFe5aRvtxeqBZ1sgZkqo = C0EfV40NqIbNVsTIUlRNgnuNNrCbGfi_q * E4kE9be0yRH2DA5abk9kV7BauCmNjOE; } public void d1mJ2nui1AP_k() { cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs = Lfu2KF4MsWk3H4 || cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs; bg327eVJDKiTt40DKCso6m = string.Format(cXPnOXH1sypIib3P0HO6b2VWDc,GaB905q4fsO_wO7zAE0jkYPm3O9LLBz); cSK9R_wK85Cd4bCy8VBxH1Zcw5hVCJqgfNuqa = kKmlcjd2p6ylBTQAYpP - qDhY4uH2YDKI2xru3SRLZqVh3a; if(Lfu2KF4MsWk3H4 && mYH1VIWj6vllki0nUbxdaTnhL40f5) { cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs = !cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs; } BKA1K12H5lhBzajQcUA2pVLHT9_p7Gl = YSuXwyVWYnt0M_g89rljZ4Me9 + E4kE9be0yRH2DA5abk9kV7BauCmNjOE; ogkUz8j5TWT6EL = AWeJhJGJm5Uyq0LBQe1myBQk9SxQEaI7; GaVnCNcPZi9gBkJ7HfgXXW52u_ = AWeJhJGJm5Uyq0LBQe1myBQk9SxQEaI7; kKmlcjd2p6ylBTQAYpP = cSK9R_wK85Cd4bCy8VBxH1Zcw5hVCJqgfNuqa - E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3; CdCcEWh8apJw5V1PtuKUSTQqMS8u3TCWHYcb = KWe1knMNkr7 + IPlh91wjDg_jrk; Omd6xWNsSMXBnj27p1BTRV = string.Format(bg327eVJDKiTt40DKCso6m,Omd6xWNsSMXBnj27p1BTRV); BKA1K12H5lhBzajQcUA2pVLHT9_p7Gl = JKaPiVcUnqzykldk1b * YSuXwyVWYnt0M_g89rljZ4Me9; } public void KtUJN1hCXb19() { cSK9R_wK85Cd4bCy8VBxH1Zcw5hVCJqgfNuqa = Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi; KYFvSOwZIQjSmgw9Vf0xHvartzgN = Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi; qDhY4uH2YDKI2xru3SRLZqVh3a = 2235.0; W_hPdJDugNsCiHq = 9740.0; KYFvSOwZIQjSmgw9Vf0xHvartzgN = 557.0; AFoZoUs6sJehwI1g0HfR = 51003; K9KadQaurGm = 20918; NpScRoNnTENf5GK30tjU6txQ2erY696 = 61675; GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = Omd6xWNsSMXBnj27p1BTRV; bg327eVJDKiTt40DKCso6m = Omd6xWNsSMXBnj27p1BTRV; qRUEd28YBQ = FAEFxJLoH3VdtwoZRv4vEmMJva7Zt2yye8iiVgS / JKaPiVcUnqzykldk1b; u2GzJZLsk1cDhtSwWWV7hard5Bm3rG9 = u2GzJZLsk1cDhtSwWWV7hard5Bm3rG9 + Y8QGmU1yyeZLaCxkAKP8fBHl2yHEt6YRGMefanJ; E4kE9be0yRH2DA5abk9kV7BauCmNjOE = FAEFxJLoH3VdtwoZRv4vEmMJva7Zt2yye8iiVgS - BKA1K12H5lhBzajQcUA2pVLHT9_p7Gl; qyITr9EMhcO0o77qx8kGvT_zR = drto98_5g6biP - cy4Xtz3Bg3ZMx8nEKZFXYX50G8GBM1C4VZJ; qRUEd28YBQ = DF0OIh0O7UW_PrdEM * DF0OIh0O7UW_PrdEM; if(wJFnjzSaOMsiZyzNHSIua4YhqQln) { cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs = !S9cWjfPHgxiHxCspAlhQCv9XVZB; } } public void OM9bJwhMbNLrbHzmn1fASq() { bg327eVJDKiTt40DKCso6m = Omd6xWNsSMXBnj27p1BTRV + bg327eVJDKiTt40DKCso6m; E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3 = 7587.0; Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi = 7842.0; W_hPdJDugNsCiHq = 6358.0; u2GzJZLsk1cDhtSwWWV7hard5Bm3rG9 = 31935; XnCalPp9SjWcJZRW41Nb60F5eATCX = 60925; GaVnCNcPZi9gBkJ7HfgXXW52u_ = 23668; nDseIQ_zqPMfRCs = cZdHPP_Dkn_69KklSxwaOJCzLUsGL * AFoZoUs6sJehwI1g0HfR; m1CunzrKaSUTgwuFe5aRvtxeqBZ1sgZkqo = 9543.0f; qRUEd28YBQ = 358.0f; JKaPiVcUnqzykldk1b = 7438.0f; E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3 = 7409.0; kKmlcjd2p6ylBTQAYpP = 4200.0; W_hPdJDugNsCiHq = 3785.0; aN9AovwT1ldGcKvWVjGg8xBFBvdbSreF3lI6Wgo6 = CdCcEWh8apJw5V1PtuKUSTQqMS8u3TCWHYcb; NpScRoNnTENf5GK30tjU6txQ2erY696 = CdCcEWh8apJw5V1PtuKUSTQqMS8u3TCWHYcb; qRUEd28YBQ = 9617.0f; E4kE9be0yRH2DA5abk9kV7BauCmNjOE = 982.0f; m85UNThrIL7aDr1rgZalNB = 3162.0f; GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = string.Format(bg327eVJDKiTt40DKCso6m,Omd6xWNsSMXBnj27p1BTRV); if(wJFnjzSaOMsiZyzNHSIua4YhqQln) { S9cWjfPHgxiHxCspAlhQCv9XVZB = !S9cWjfPHgxiHxCspAlhQCv9XVZB; } } public void Cw22eVw_ycUmLVPtV() { W_hPdJDugNsCiHq = qDhY4uH2YDKI2xru3SRLZqVh3a - kKmlcjd2p6ylBTQAYpP; S9cWjfPHgxiHxCspAlhQCv9XVZB = I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr && S9cWjfPHgxiHxCspAlhQCv9XVZB; cXPnOXH1sypIib3P0HO6b2VWDc = string.Format(Omd6xWNsSMXBnj27p1BTRV,Omd6xWNsSMXBnj27p1BTRV); kKmlcjd2p6ylBTQAYpP = 2265.0; KYFvSOwZIQjSmgw9Vf0xHvartzgN = 181.0; kKmlcjd2p6ylBTQAYpP = 4435.0; cXPnOXH1sypIib3P0HO6b2VWDc = bg327eVJDKiTt40DKCso6m + Omd6xWNsSMXBnj27p1BTRV; bg327eVJDKiTt40DKCso6m = string.Format(bg327eVJDKiTt40DKCso6m,Omd6xWNsSMXBnj27p1BTRV); cXPnOXH1sypIib3P0HO6b2VWDc = string.Format(cXPnOXH1sypIib3P0HO6b2VWDc,Omd6xWNsSMXBnj27p1BTRV); if(cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs && I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr) { S9cWjfPHgxiHxCspAlhQCv9XVZB = !S9cWjfPHgxiHxCspAlhQCv9XVZB; } W_hPdJDugNsCiHq = 9812.0; KYFvSOwZIQjSmgw9Vf0xHvartzgN = 7166.0; W_hPdJDugNsCiHq = 2873.0; Omd6xWNsSMXBnj27p1BTRV = cXPnOXH1sypIib3P0HO6b2VWDc; bg327eVJDKiTt40DKCso6m = cXPnOXH1sypIib3P0HO6b2VWDc; } public void JYqCxAT74FcZ8xQ() { GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = GaB905q4fsO_wO7zAE0jkYPm3O9LLBz; GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = GaB905q4fsO_wO7zAE0jkYPm3O9LLBz; bg327eVJDKiTt40DKCso6m = bg327eVJDKiTt40DKCso6m + GaB905q4fsO_wO7zAE0jkYPm3O9LLBz; E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3 = W_hPdJDugNsCiHq; E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3 = W_hPdJDugNsCiHq; for(int i=0;i<Hx38iCaBiywtWA1TlUAJE6OeOiYjNaf71da;++i) { Y8QGmU1yyeZLaCxkAKP8fBHl2yHEt6YRGMefanJ+=1; nDseIQ_zqPMfRCs+=Y8QGmU1yyeZLaCxkAKP8fBHl2yHEt6YRGMefanJ; } PqV0MgM4933EU7ZeMNNof = 49944; NpScRoNnTENf5GK30tjU6txQ2erY696 = 81573; IPlh91wjDg_jrk = 14677; cZdHPP_Dkn_69KklSxwaOJCzLUsGL = drto98_5g6biP / XnCalPp9SjWcJZRW41Nb60F5eATCX; qDhY4uH2YDKI2xru3SRLZqVh3a = KYFvSOwZIQjSmgw9Vf0xHvartzgN + Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi; Omd6xWNsSMXBnj27p1BTRV = cXPnOXH1sypIib3P0HO6b2VWDc + bg327eVJDKiTt40DKCso6m; qRUEd28YBQ = 6794.0f; m85UNThrIL7aDr1rgZalNB = 653.0f; m1CunzrKaSUTgwuFe5aRvtxeqBZ1sgZkqo = 2397.0f; lB1CHJanPGXmpLWFV9TQ2pXBRaaVidV = KWe1knMNkr7 / IPlh91wjDg_jrk; } public void DnzVNX2UTOOofEBN95eTb() { nDseIQ_zqPMfRCs = NpScRoNnTENf5GK30tjU6txQ2erY696 + NpScRoNnTENf5GK30tjU6txQ2erY696; JKaPiVcUnqzykldk1b = 4769.0f; YSuXwyVWYnt0M_g89rljZ4Me9 = 8179.0f; qRUEd28YBQ = 6818.0f; bg327eVJDKiTt40DKCso6m = GaB905q4fsO_wO7zAE0jkYPm3O9LLBz + cXPnOXH1sypIib3P0HO6b2VWDc; if(mYH1VIWj6vllki0nUbxdaTnhL40f5 || I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr) { I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr = !I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr; } DF0OIh0O7UW_PrdEM = FAEFxJLoH3VdtwoZRv4vEmMJva7Zt2yye8iiVgS; C0EfV40NqIbNVsTIUlRNgnuNNrCbGfi_q = FAEFxJLoH3VdtwoZRv4vEmMJva7Zt2yye8iiVgS; cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs = Lfu2KF4MsWk3H4 && mYH1VIWj6vllki0nUbxdaTnhL40f5; cXPnOXH1sypIib3P0HO6b2VWDc = GaB905q4fsO_wO7zAE0jkYPm3O9LLBz; Omd6xWNsSMXBnj27p1BTRV = GaB905q4fsO_wO7zAE0jkYPm3O9LLBz; if(mYH1VIWj6vllki0nUbxdaTnhL40f5 && Lfu2KF4MsWk3H4) { cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs = !cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs; } wJFnjzSaOMsiZyzNHSIua4YhqQln = S9cWjfPHgxiHxCspAlhQCv9XVZB || mYH1VIWj6vllki0nUbxdaTnhL40f5; KYFvSOwZIQjSmgw9Vf0xHvartzgN = cSK9R_wK85Cd4bCy8VBxH1Zcw5hVCJqgfNuqa - KYFvSOwZIQjSmgw9Vf0xHvartzgN; } public void ED1HdF2h2uKJBaNICRnS7L7ikJ_lzYc() { DF0OIh0O7UW_PrdEM = YSuXwyVWYnt0M_g89rljZ4Me9; YSuXwyVWYnt0M_g89rljZ4Me9 = YSuXwyVWYnt0M_g89rljZ4Me9; bg327eVJDKiTt40DKCso6m = GaB905q4fsO_wO7zAE0jkYPm3O9LLBz; Omd6xWNsSMXBnj27p1BTRV = GaB905q4fsO_wO7zAE0jkYPm3O9LLBz; if(S9cWjfPHgxiHxCspAlhQCv9XVZB) { cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs = !Lfu2KF4MsWk3H4; } FAEFxJLoH3VdtwoZRv4vEmMJva7Zt2yye8iiVgS = qRUEd28YBQ - qRUEd28YBQ; aN9AovwT1ldGcKvWVjGg8xBFBvdbSreF3lI6Wgo6 = 78320; aN9AovwT1ldGcKvWVjGg8xBFBvdbSreF3lI6Wgo6 = 40294; hCJtcAOtqe56KAkQfAFbA6mPwoATXN = 88617; bg327eVJDKiTt40DKCso6m = string.Format(bg327eVJDKiTt40DKCso6m,Omd6xWNsSMXBnj27p1BTRV); for(int i=0;i<GaVnCNcPZi9gBkJ7HfgXXW52u_;++i) { AWeJhJGJm5Uyq0LBQe1myBQk9SxQEaI7+=1; qyITr9EMhcO0o77qx8kGvT_zR+=AWeJhJGJm5Uyq0LBQe1myBQk9SxQEaI7; } AWeJhJGJm5Uyq0LBQe1myBQk9SxQEaI7 = nDseIQ_zqPMfRCs + H_vcPMzNmR; for(int i=0;i<IPlh91wjDg_jrk;++i) { GaVnCNcPZi9gBkJ7HfgXXW52u_+=1; SnxzbWQNmH1rgIdC6MIqBdQZFGOwlmHNn8BPDB+=GaVnCNcPZi9gBkJ7HfgXXW52u_; } m1CunzrKaSUTgwuFe5aRvtxeqBZ1sgZkqo = E4kE9be0yRH2DA5abk9kV7BauCmNjOE * m1CunzrKaSUTgwuFe5aRvtxeqBZ1sgZkqo; } public void ErNloMI5IjhjBVoVwVG8JObajsfHwTa2() { cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs = Lfu2KF4MsWk3H4 || Lfu2KF4MsWk3H4; KYFvSOwZIQjSmgw9Vf0xHvartzgN = E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3 + kKmlcjd2p6ylBTQAYpP; XnCalPp9SjWcJZRW41Nb60F5eATCX = u2GzJZLsk1cDhtSwWWV7hard5Bm3rG9 * GaVnCNcPZi9gBkJ7HfgXXW52u_; Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi = W_hPdJDugNsCiHq + kKmlcjd2p6ylBTQAYpP; kKmlcjd2p6ylBTQAYpP = Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi - cSK9R_wK85Cd4bCy8VBxH1Zcw5hVCJqgfNuqa; Omd6xWNsSMXBnj27p1BTRV = bg327eVJDKiTt40DKCso6m; bg327eVJDKiTt40DKCso6m = bg327eVJDKiTt40DKCso6m; if(cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs || Lfu2KF4MsWk3H4) { Lfu2KF4MsWk3H4 = !Lfu2KF4MsWk3H4; } KWe1knMNkr7 = 96802; K9KadQaurGm = 51369; CdCcEWh8apJw5V1PtuKUSTQqMS8u3TCWHYcb = 998; YSuXwyVWYnt0M_g89rljZ4Me9 = JKaPiVcUnqzykldk1b - m1CunzrKaSUTgwuFe5aRvtxeqBZ1sgZkqo; CdCcEWh8apJw5V1PtuKUSTQqMS8u3TCWHYcb = bKzwvBsDbqe70Es7txGzrbd2zWt_l * hCJtcAOtqe56KAkQfAFbA6mPwoATXN; } public void WnWZdRkvogjEE() { GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = bg327eVJDKiTt40DKCso6m; GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = bg327eVJDKiTt40DKCso6m; GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = Omd6xWNsSMXBnj27p1BTRV; bg327eVJDKiTt40DKCso6m = Omd6xWNsSMXBnj27p1BTRV; C0EfV40NqIbNVsTIUlRNgnuNNrCbGfi_q = qRUEd28YBQ - DF0OIh0O7UW_PrdEM; kKmlcjd2p6ylBTQAYpP = E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3 * E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3; cXPnOXH1sypIib3P0HO6b2VWDc = string.Format(Omd6xWNsSMXBnj27p1BTRV,cXPnOXH1sypIib3P0HO6b2VWDc); Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi = qDhY4uH2YDKI2xru3SRLZqVh3a * W_hPdJDugNsCiHq; kKmlcjd2p6ylBTQAYpP = W_hPdJDugNsCiHq - kKmlcjd2p6ylBTQAYpP; cXPnOXH1sypIib3P0HO6b2VWDc = Omd6xWNsSMXBnj27p1BTRV; Omd6xWNsSMXBnj27p1BTRV = Omd6xWNsSMXBnj27p1BTRV; RUQANPnRn3V_kV = KWe1knMNkr7 - PqV0MgM4933EU7ZeMNNof; for(int i=0;i<SnxzbWQNmH1rgIdC6MIqBdQZFGOwlmHNn8BPDB;++i) { hCJtcAOtqe56KAkQfAFbA6mPwoATXN+=1; PpMhcDbHtSQTd765YVfceuaNQg5lkKE+=hCJtcAOtqe56KAkQfAFbA6mPwoATXN; } } public void Oi_EJZUrOMkttOO8_56sHNV5eFMseOC() { E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3 = 2627.0; qDhY4uH2YDKI2xru3SRLZqVh3a = 8587.0; qDhY4uH2YDKI2xru3SRLZqVh3a = 9097.0; Omd6xWNsSMXBnj27p1BTRV = string.Format(Omd6xWNsSMXBnj27p1BTRV,Omd6xWNsSMXBnj27p1BTRV); S9cWjfPHgxiHxCspAlhQCv9XVZB = wJFnjzSaOMsiZyzNHSIua4YhqQln && I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr; for(int i=0;i<cy4Xtz3Bg3ZMx8nEKZFXYX50G8GBM1C4VZJ;++i) { CdCcEWh8apJw5V1PtuKUSTQqMS8u3TCWHYcb+=1; AWeJhJGJm5Uyq0LBQe1myBQk9SxQEaI7+=CdCcEWh8apJw5V1PtuKUSTQqMS8u3TCWHYcb; } XnCalPp9SjWcJZRW41Nb60F5eATCX = 14384; AFoZoUs6sJehwI1g0HfR = 31425; PqV0MgM4933EU7ZeMNNof = 37843; for(int i=0;i<drto98_5g6biP;++i) { cZdHPP_Dkn_69KklSxwaOJCzLUsGL+=1; AWeJhJGJm5Uyq0LBQe1myBQk9SxQEaI7+=cZdHPP_Dkn_69KklSxwaOJCzLUsGL; } Y8QGmU1yyeZLaCxkAKP8fBHl2yHEt6YRGMefanJ = b976I7twpXTIjs / drto98_5g6biP; cSK9R_wK85Cd4bCy8VBxH1Zcw5hVCJqgfNuqa = KYFvSOwZIQjSmgw9Vf0xHvartzgN + E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3; kKmlcjd2p6ylBTQAYpP = KYFvSOwZIQjSmgw9Vf0xHvartzgN * cSK9R_wK85Cd4bCy8VBxH1Zcw5hVCJqgfNuqa; Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi = W_hPdJDugNsCiHq; E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3 = W_hPdJDugNsCiHq; } public void lxKKc8KjR2MthAdL_jlbOFqQZFe0CJmTEfZiBFY() { PqV0MgM4933EU7ZeMNNof = 56032; XnCalPp9SjWcJZRW41Nb60F5eATCX = 35729; ogkUz8j5TWT6EL = 46245; cSK9R_wK85Cd4bCy8VBxH1Zcw5hVCJqgfNuqa = 8516.0; cSK9R_wK85Cd4bCy8VBxH1Zcw5hVCJqgfNuqa = 8443.0; Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi = 3929.0; YokKRmVP6CLHANTTxsGMBjW38p = bKzwvBsDbqe70Es7txGzrbd2zWt_l / drto98_5g6biP; kKmlcjd2p6ylBTQAYpP = qDhY4uH2YDKI2xru3SRLZqVh3a + W_hPdJDugNsCiHq; aN9AovwT1ldGcKvWVjGg8xBFBvdbSreF3lI6Wgo6 = bKzwvBsDbqe70Es7txGzrbd2zWt_l + mneOUpeEI41vVP5SBTgxxrwIsqMslGM_F5B_fw; qRUEd28YBQ = JKaPiVcUnqzykldk1b - FAEFxJLoH3VdtwoZRv4vEmMJva7Zt2yye8iiVgS; JKaPiVcUnqzykldk1b = m1CunzrKaSUTgwuFe5aRvtxeqBZ1sgZkqo + JKaPiVcUnqzykldk1b; E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3 = E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3 * cSK9R_wK85Cd4bCy8VBxH1Zcw5hVCJqgfNuqa; YSuXwyVWYnt0M_g89rljZ4Me9 = YSuXwyVWYnt0M_g89rljZ4Me9 * qRUEd28YBQ; m1CunzrKaSUTgwuFe5aRvtxeqBZ1sgZkqo = qRUEd28YBQ / E4kE9be0yRH2DA5abk9kV7BauCmNjOE; } public void jyIC84LHf6T_Z4k2O_JZ40A() { m85UNThrIL7aDr1rgZalNB = JKaPiVcUnqzykldk1b / JKaPiVcUnqzykldk1b; K9KadQaurGm = PqV0MgM4933EU7ZeMNNof + PpMhcDbHtSQTd765YVfceuaNQg5lkKE; GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = string.Format(cXPnOXH1sypIib3P0HO6b2VWDc,cXPnOXH1sypIib3P0HO6b2VWDc); if(wJFnjzSaOMsiZyzNHSIua4YhqQln && I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr) { I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr = !I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr; } cXPnOXH1sypIib3P0HO6b2VWDc = Omd6xWNsSMXBnj27p1BTRV; cXPnOXH1sypIib3P0HO6b2VWDc = Omd6xWNsSMXBnj27p1BTRV; kKmlcjd2p6ylBTQAYpP = W_hPdJDugNsCiHq; E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3 = W_hPdJDugNsCiHq; YokKRmVP6CLHANTTxsGMBjW38p = XnCalPp9SjWcJZRW41Nb60F5eATCX / PpMhcDbHtSQTd765YVfceuaNQg5lkKE; YSuXwyVWYnt0M_g89rljZ4Me9 = m85UNThrIL7aDr1rgZalNB - m85UNThrIL7aDr1rgZalNB; mYH1VIWj6vllki0nUbxdaTnhL40f5 = S9cWjfPHgxiHxCspAlhQCv9XVZB || cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs; S9cWjfPHgxiHxCspAlhQCv9XVZB = S9cWjfPHgxiHxCspAlhQCv9XVZB || I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr; } public void Gx2iifNRVcd_hwfkG7vaP1u9W2Zoo5() { m85UNThrIL7aDr1rgZalNB = 528.0f; JKaPiVcUnqzykldk1b = 9209.0f; DF0OIh0O7UW_PrdEM = 7696.0f; if(Lfu2KF4MsWk3H4 && mYH1VIWj6vllki0nUbxdaTnhL40f5) { S9cWjfPHgxiHxCspAlhQCv9XVZB = !S9cWjfPHgxiHxCspAlhQCv9XVZB; } u2GzJZLsk1cDhtSwWWV7hard5Bm3rG9 = PqV0MgM4933EU7ZeMNNof + H_vcPMzNmR; GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = string.Format(bg327eVJDKiTt40DKCso6m,bg327eVJDKiTt40DKCso6m); JKaPiVcUnqzykldk1b = m1CunzrKaSUTgwuFe5aRvtxeqBZ1sgZkqo + FAEFxJLoH3VdtwoZRv4vEmMJva7Zt2yye8iiVgS; hCJtcAOtqe56KAkQfAFbA6mPwoATXN = AWeJhJGJm5Uyq0LBQe1myBQk9SxQEaI7 / b976I7twpXTIjs; if(S9cWjfPHgxiHxCspAlhQCv9XVZB) { wJFnjzSaOMsiZyzNHSIua4YhqQln = !mYH1VIWj6vllki0nUbxdaTnhL40f5; } Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi = 9708.0; W_hPdJDugNsCiHq = 8401.0; KYFvSOwZIQjSmgw9Vf0xHvartzgN = 2616.0; wJFnjzSaOMsiZyzNHSIua4YhqQln = S9cWjfPHgxiHxCspAlhQCv9XVZB || wJFnjzSaOMsiZyzNHSIua4YhqQln; S9cWjfPHgxiHxCspAlhQCv9XVZB = cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs || mYH1VIWj6vllki0nUbxdaTnhL40f5; } public void QAZoTnxQqWzpB8eS8IaiU6foELkAw0WXA46() { C0EfV40NqIbNVsTIUlRNgnuNNrCbGfi_q = 3558.0f; DF0OIh0O7UW_PrdEM = 4764.0f; E4kE9be0yRH2DA5abk9kV7BauCmNjOE = 6220.0f; E4kE9be0yRH2DA5abk9kV7BauCmNjOE = YSuXwyVWYnt0M_g89rljZ4Me9 + qRUEd28YBQ; AWeJhJGJm5Uyq0LBQe1myBQk9SxQEaI7 = aN9AovwT1ldGcKvWVjGg8xBFBvdbSreF3lI6Wgo6 / AWeJhJGJm5Uyq0LBQe1myBQk9SxQEaI7; E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3 = 9996.0; E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3 = 5761.0; kKmlcjd2p6ylBTQAYpP = 3447.0; if(I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr || I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr) { I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr = !I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr; } aN9AovwT1ldGcKvWVjGg8xBFBvdbSreF3lI6Wgo6 = lB1CHJanPGXmpLWFV9TQ2pXBRaaVidV; hCJtcAOtqe56KAkQfAFbA6mPwoATXN = lB1CHJanPGXmpLWFV9TQ2pXBRaaVidV; wJFnjzSaOMsiZyzNHSIua4YhqQln = Lfu2KF4MsWk3H4 || cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs; cZdHPP_Dkn_69KklSxwaOJCzLUsGL = XnCalPp9SjWcJZRW41Nb60F5eATCX - CdCcEWh8apJw5V1PtuKUSTQqMS8u3TCWHYcb; DF0OIh0O7UW_PrdEM = FAEFxJLoH3VdtwoZRv4vEmMJva7Zt2yye8iiVgS; E4kE9be0yRH2DA5abk9kV7BauCmNjOE = FAEFxJLoH3VdtwoZRv4vEmMJva7Zt2yye8iiVgS; if(cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs || wJFnjzSaOMsiZyzNHSIua4YhqQln) { wJFnjzSaOMsiZyzNHSIua4YhqQln = !wJFnjzSaOMsiZyzNHSIua4YhqQln; } } public void mdplkxYOaQ() { GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = cXPnOXH1sypIib3P0HO6b2VWDc; bg327eVJDKiTt40DKCso6m = cXPnOXH1sypIib3P0HO6b2VWDc; qDhY4uH2YDKI2xru3SRLZqVh3a = 846.0; KYFvSOwZIQjSmgw9Vf0xHvartzgN = 6620.0; cSK9R_wK85Cd4bCy8VBxH1Zcw5hVCJqgfNuqa = 9039.0; KWe1knMNkr7 = AWeJhJGJm5Uyq0LBQe1myBQk9SxQEaI7; bKzwvBsDbqe70Es7txGzrbd2zWt_l = AWeJhJGJm5Uyq0LBQe1myBQk9SxQEaI7; P11CoOr_aaRo = aN9AovwT1ldGcKvWVjGg8xBFBvdbSreF3lI6Wgo6 + aN9AovwT1ldGcKvWVjGg8xBFBvdbSreF3lI6Wgo6; Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi = qDhY4uH2YDKI2xru3SRLZqVh3a + W_hPdJDugNsCiHq; GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = string.Format(bg327eVJDKiTt40DKCso6m,bg327eVJDKiTt40DKCso6m); cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs = S9cWjfPHgxiHxCspAlhQCv9XVZB || cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs; wJFnjzSaOMsiZyzNHSIua4YhqQln = wJFnjzSaOMsiZyzNHSIua4YhqQln || cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs; C0EfV40NqIbNVsTIUlRNgnuNNrCbGfi_q = m85UNThrIL7aDr1rgZalNB * YSuXwyVWYnt0M_g89rljZ4Me9; E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3 = qDhY4uH2YDKI2xru3SRLZqVh3a + W_hPdJDugNsCiHq; } public void JCOoe3HlguWfHbUw3V3IV1HKP_ibgcivXW() { FAEFxJLoH3VdtwoZRv4vEmMJva7Zt2yye8iiVgS = 9749.0f; BKA1K12H5lhBzajQcUA2pVLHT9_p7Gl = 7734.0f; E4kE9be0yRH2DA5abk9kV7BauCmNjOE = 3079.0f; GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = Omd6xWNsSMXBnj27p1BTRV; GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = Omd6xWNsSMXBnj27p1BTRV; if(wJFnjzSaOMsiZyzNHSIua4YhqQln && I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr) { S9cWjfPHgxiHxCspAlhQCv9XVZB = !S9cWjfPHgxiHxCspAlhQCv9XVZB; } qDhY4uH2YDKI2xru3SRLZqVh3a = kKmlcjd2p6ylBTQAYpP / E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3; kKmlcjd2p6ylBTQAYpP = 7208.0; E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3 = 2653.0; kKmlcjd2p6ylBTQAYpP = 7506.0; nDseIQ_zqPMfRCs = drto98_5g6biP * bKzwvBsDbqe70Es7txGzrbd2zWt_l; DF0OIh0O7UW_PrdEM = JKaPiVcUnqzykldk1b + m1CunzrKaSUTgwuFe5aRvtxeqBZ1sgZkqo; Lfu2KF4MsWk3H4 = I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr || wJFnjzSaOMsiZyzNHSIua4YhqQln; YSuXwyVWYnt0M_g89rljZ4Me9 = C0EfV40NqIbNVsTIUlRNgnuNNrCbGfi_q; E4kE9be0yRH2DA5abk9kV7BauCmNjOE = C0EfV40NqIbNVsTIUlRNgnuNNrCbGfi_q; C0EfV40NqIbNVsTIUlRNgnuNNrCbGfi_q = 2939.0f; JKaPiVcUnqzykldk1b = 9045.0f; YSuXwyVWYnt0M_g89rljZ4Me9 = 8186.0f; } public void BoEsEvDU472DulEYHspG3_3gFNt5ZzVOi0wDK() { u2GzJZLsk1cDhtSwWWV7hard5Bm3rG9 = AFoZoUs6sJehwI1g0HfR * H_vcPMzNmR; W_hPdJDugNsCiHq = 4157.0; Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi = 6671.0; qDhY4uH2YDKI2xru3SRLZqVh3a = 3495.0; bKzwvBsDbqe70Es7txGzrbd2zWt_l = NpScRoNnTENf5GK30tjU6txQ2erY696 * mneOUpeEI41vVP5SBTgxxrwIsqMslGM_F5B_fw; wJFnjzSaOMsiZyzNHSIua4YhqQln = Lfu2KF4MsWk3H4 || Lfu2KF4MsWk3H4; KWe1knMNkr7 = 82889; nDseIQ_zqPMfRCs = 50506; P11CoOr_aaRo = 24766; ogkUz8j5TWT6EL = GaVnCNcPZi9gBkJ7HfgXXW52u_ * bKzwvBsDbqe70Es7txGzrbd2zWt_l; W_hPdJDugNsCiHq = cSK9R_wK85Cd4bCy8VBxH1Zcw5hVCJqgfNuqa; KYFvSOwZIQjSmgw9Vf0xHvartzgN = cSK9R_wK85Cd4bCy8VBxH1Zcw5hVCJqgfNuqa; if(wJFnjzSaOMsiZyzNHSIua4YhqQln) { cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs = !wJFnjzSaOMsiZyzNHSIua4YhqQln; } cy4Xtz3Bg3ZMx8nEKZFXYX50G8GBM1C4VZJ = K9KadQaurGm + PpMhcDbHtSQTd765YVfceuaNQg5lkKE; Omd6xWNsSMXBnj27p1BTRV = bg327eVJDKiTt40DKCso6m; Omd6xWNsSMXBnj27p1BTRV = bg327eVJDKiTt40DKCso6m; } public void nI636P2d_sN4SKcyuYb7RE7rlUatKSXfM4() { S9cWjfPHgxiHxCspAlhQCv9XVZB = wJFnjzSaOMsiZyzNHSIua4YhqQln && mYH1VIWj6vllki0nUbxdaTnhL40f5; cXPnOXH1sypIib3P0HO6b2VWDc = bg327eVJDKiTt40DKCso6m + Omd6xWNsSMXBnj27p1BTRV; E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3 = 8302.0; KYFvSOwZIQjSmgw9Vf0xHvartzgN = 8522.0; Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi = 6923.0; mYH1VIWj6vllki0nUbxdaTnhL40f5 = wJFnjzSaOMsiZyzNHSIua4YhqQln || mYH1VIWj6vllki0nUbxdaTnhL40f5; C0EfV40NqIbNVsTIUlRNgnuNNrCbGfi_q = 3006.0f; DF0OIh0O7UW_PrdEM = 2422.0f; JKaPiVcUnqzykldk1b = 3722.0f; bg327eVJDKiTt40DKCso6m = Omd6xWNsSMXBnj27p1BTRV; cXPnOXH1sypIib3P0HO6b2VWDc = Omd6xWNsSMXBnj27p1BTRV; cXPnOXH1sypIib3P0HO6b2VWDc = Omd6xWNsSMXBnj27p1BTRV; GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = Omd6xWNsSMXBnj27p1BTRV; if(I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr) { I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr = !Lfu2KF4MsWk3H4; } bg327eVJDKiTt40DKCso6m = cXPnOXH1sypIib3P0HO6b2VWDc + cXPnOXH1sypIib3P0HO6b2VWDc; BKA1K12H5lhBzajQcUA2pVLHT9_p7Gl = DF0OIh0O7UW_PrdEM * E4kE9be0yRH2DA5abk9kV7BauCmNjOE; } public void rcEfxmZvL7() { qDhY4uH2YDKI2xru3SRLZqVh3a = Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi - E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3; if(wJFnjzSaOMsiZyzNHSIua4YhqQln || S9cWjfPHgxiHxCspAlhQCv9XVZB) { S9cWjfPHgxiHxCspAlhQCv9XVZB = !S9cWjfPHgxiHxCspAlhQCv9XVZB; } wJFnjzSaOMsiZyzNHSIua4YhqQln = mYH1VIWj6vllki0nUbxdaTnhL40f5 || Lfu2KF4MsWk3H4; C0EfV40NqIbNVsTIUlRNgnuNNrCbGfi_q = FAEFxJLoH3VdtwoZRv4vEmMJva7Zt2yye8iiVgS + C0EfV40NqIbNVsTIUlRNgnuNNrCbGfi_q; mYH1VIWj6vllki0nUbxdaTnhL40f5 = cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs || wJFnjzSaOMsiZyzNHSIua4YhqQln; S9cWjfPHgxiHxCspAlhQCv9XVZB = cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs || I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr; if(Lfu2KF4MsWk3H4 && Lfu2KF4MsWk3H4) { wJFnjzSaOMsiZyzNHSIua4YhqQln = !wJFnjzSaOMsiZyzNHSIua4YhqQln; } I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr = mYH1VIWj6vllki0nUbxdaTnhL40f5 || S9cWjfPHgxiHxCspAlhQCv9XVZB; m1CunzrKaSUTgwuFe5aRvtxeqBZ1sgZkqo = m1CunzrKaSUTgwuFe5aRvtxeqBZ1sgZkqo - FAEFxJLoH3VdtwoZRv4vEmMJva7Zt2yye8iiVgS; PpMhcDbHtSQTd765YVfceuaNQg5lkKE = K9KadQaurGm; K9KadQaurGm = K9KadQaurGm; } public void jkfTDDoy0e() { if(I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr || S9cWjfPHgxiHxCspAlhQCv9XVZB) { S9cWjfPHgxiHxCspAlhQCv9XVZB = !S9cWjfPHgxiHxCspAlhQCv9XVZB; } for(int i=0;i<P11CoOr_aaRo;++i) { P11CoOr_aaRo+=1; H63W8NLA3F0L19T+=P11CoOr_aaRo; } BKA1K12H5lhBzajQcUA2pVLHT9_p7Gl = m1CunzrKaSUTgwuFe5aRvtxeqBZ1sgZkqo / BKA1K12H5lhBzajQcUA2pVLHT9_p7Gl; if(wJFnjzSaOMsiZyzNHSIua4YhqQln && S9cWjfPHgxiHxCspAlhQCv9XVZB) { wJFnjzSaOMsiZyzNHSIua4YhqQln = !wJFnjzSaOMsiZyzNHSIua4YhqQln; } bg327eVJDKiTt40DKCso6m = cXPnOXH1sypIib3P0HO6b2VWDc + cXPnOXH1sypIib3P0HO6b2VWDc; bg327eVJDKiTt40DKCso6m = bg327eVJDKiTt40DKCso6m; Omd6xWNsSMXBnj27p1BTRV = bg327eVJDKiTt40DKCso6m; Omd6xWNsSMXBnj27p1BTRV = bg327eVJDKiTt40DKCso6m; cXPnOXH1sypIib3P0HO6b2VWDc = bg327eVJDKiTt40DKCso6m; BKA1K12H5lhBzajQcUA2pVLHT9_p7Gl = qRUEd28YBQ; m85UNThrIL7aDr1rgZalNB = qRUEd28YBQ; Lfu2KF4MsWk3H4 = Lfu2KF4MsWk3H4 && S9cWjfPHgxiHxCspAlhQCv9XVZB; H63W8NLA3F0L19T = 77734; mneOUpeEI41vVP5SBTgxxrwIsqMslGM_F5B_fw = 19514; hCJtcAOtqe56KAkQfAFbA6mPwoATXN = 25105; } public void KO2tFI2omssa() { m1CunzrKaSUTgwuFe5aRvtxeqBZ1sgZkqo = YSuXwyVWYnt0M_g89rljZ4Me9 + JKaPiVcUnqzykldk1b; Lfu2KF4MsWk3H4 = wJFnjzSaOMsiZyzNHSIua4YhqQln && I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr; Lfu2KF4MsWk3H4 = I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr && I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr; mYH1VIWj6vllki0nUbxdaTnhL40f5 = S9cWjfPHgxiHxCspAlhQCv9XVZB || Lfu2KF4MsWk3H4; YSuXwyVWYnt0M_g89rljZ4Me9 = DF0OIh0O7UW_PrdEM; FAEFxJLoH3VdtwoZRv4vEmMJva7Zt2yye8iiVgS = DF0OIh0O7UW_PrdEM; kKmlcjd2p6ylBTQAYpP = E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3 - W_hPdJDugNsCiHq; W_hPdJDugNsCiHq = KYFvSOwZIQjSmgw9Vf0xHvartzgN * kKmlcjd2p6ylBTQAYpP; bg327eVJDKiTt40DKCso6m = string.Format(GaB905q4fsO_wO7zAE0jkYPm3O9LLBz,GaB905q4fsO_wO7zAE0jkYPm3O9LLBz); mYH1VIWj6vllki0nUbxdaTnhL40f5 = Lfu2KF4MsWk3H4 && wJFnjzSaOMsiZyzNHSIua4YhqQln; drto98_5g6biP = aN9AovwT1ldGcKvWVjGg8xBFBvdbSreF3lI6Wgo6 / AFoZoUs6sJehwI1g0HfR; } public void VYSaCWlWH4ciKI6mh2xeraAlGZtp5() { for(int i=0;i<mneOUpeEI41vVP5SBTgxxrwIsqMslGM_F5B_fw;++i) { Hx38iCaBiywtWA1TlUAJE6OeOiYjNaf71da+=1; H63W8NLA3F0L19T+=Hx38iCaBiywtWA1TlUAJE6OeOiYjNaf71da; } bg327eVJDKiTt40DKCso6m = bg327eVJDKiTt40DKCso6m + bg327eVJDKiTt40DKCso6m; cZdHPP_Dkn_69KklSxwaOJCzLUsGL = AFoZoUs6sJehwI1g0HfR - qyITr9EMhcO0o77qx8kGvT_zR; Omd6xWNsSMXBnj27p1BTRV = Omd6xWNsSMXBnj27p1BTRV; GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = Omd6xWNsSMXBnj27p1BTRV; YSuXwyVWYnt0M_g89rljZ4Me9 = DF0OIh0O7UW_PrdEM / m85UNThrIL7aDr1rgZalNB; cSK9R_wK85Cd4bCy8VBxH1Zcw5hVCJqgfNuqa = Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi - W_hPdJDugNsCiHq; Omd6xWNsSMXBnj27p1BTRV = string.Format(cXPnOXH1sypIib3P0HO6b2VWDc,bg327eVJDKiTt40DKCso6m); qRUEd28YBQ = 447.0f; DF0OIh0O7UW_PrdEM = 7579.0f; m85UNThrIL7aDr1rgZalNB = 1705.0f; cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs = Lfu2KF4MsWk3H4 && Lfu2KF4MsWk3H4; kKmlcjd2p6ylBTQAYpP = W_hPdJDugNsCiHq; kKmlcjd2p6ylBTQAYpP = W_hPdJDugNsCiHq; } public void EF82TUegONnuvoikTEP3igQcxvdq4em() { bg327eVJDKiTt40DKCso6m = string.Format(GaB905q4fsO_wO7zAE0jkYPm3O9LLBz,GaB905q4fsO_wO7zAE0jkYPm3O9LLBz); GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = cXPnOXH1sypIib3P0HO6b2VWDc + GaB905q4fsO_wO7zAE0jkYPm3O9LLBz; qDhY4uH2YDKI2xru3SRLZqVh3a = 9431.0; kKmlcjd2p6ylBTQAYpP = 7490.0; W_hPdJDugNsCiHq = 9498.0; if(mYH1VIWj6vllki0nUbxdaTnhL40f5) { cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs = !S9cWjfPHgxiHxCspAlhQCv9XVZB; } SnxzbWQNmH1rgIdC6MIqBdQZFGOwlmHNn8BPDB = Y8QGmU1yyeZLaCxkAKP8fBHl2yHEt6YRGMefanJ * H63W8NLA3F0L19T; GaVnCNcPZi9gBkJ7HfgXXW52u_ = 78415; mneOUpeEI41vVP5SBTgxxrwIsqMslGM_F5B_fw = 17588; K9KadQaurGm = 45189; bg327eVJDKiTt40DKCso6m = GaB905q4fsO_wO7zAE0jkYPm3O9LLBz; bg327eVJDKiTt40DKCso6m = GaB905q4fsO_wO7zAE0jkYPm3O9LLBz; Omd6xWNsSMXBnj27p1BTRV = GaB905q4fsO_wO7zAE0jkYPm3O9LLBz + GaB905q4fsO_wO7zAE0jkYPm3O9LLBz; if(S9cWjfPHgxiHxCspAlhQCv9XVZB) { Lfu2KF4MsWk3H4 = !wJFnjzSaOMsiZyzNHSIua4YhqQln; } if(wJFnjzSaOMsiZyzNHSIua4YhqQln || Lfu2KF4MsWk3H4) { Lfu2KF4MsWk3H4 = !Lfu2KF4MsWk3H4; } } public void AbT1VwfG3i5Qp() { if(Lfu2KF4MsWk3H4) { cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs = !cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs; } qDhY4uH2YDKI2xru3SRLZqVh3a = Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi / cSK9R_wK85Cd4bCy8VBxH1Zcw5hVCJqgfNuqa; Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi = kKmlcjd2p6ylBTQAYpP - E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3; Omd6xWNsSMXBnj27p1BTRV = string.Format(Omd6xWNsSMXBnj27p1BTRV,Omd6xWNsSMXBnj27p1BTRV); qDhY4uH2YDKI2xru3SRLZqVh3a = kKmlcjd2p6ylBTQAYpP + KYFvSOwZIQjSmgw9Vf0xHvartzgN; C0EfV40NqIbNVsTIUlRNgnuNNrCbGfi_q = E4kE9be0yRH2DA5abk9kV7BauCmNjOE - m1CunzrKaSUTgwuFe5aRvtxeqBZ1sgZkqo; qRUEd28YBQ = 6043.0f; E4kE9be0yRH2DA5abk9kV7BauCmNjOE = 6861.0f; FAEFxJLoH3VdtwoZRv4vEmMJva7Zt2yye8iiVgS = 8200.0f; if(Lfu2KF4MsWk3H4 || Lfu2KF4MsWk3H4) { Lfu2KF4MsWk3H4 = !Lfu2KF4MsWk3H4; } if(cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs || I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr) { I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr = !I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr; } cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs = S9cWjfPHgxiHxCspAlhQCv9XVZB || mYH1VIWj6vllki0nUbxdaTnhL40f5; } public void QoFzeDl9WqvTHWi2O_U() { kKmlcjd2p6ylBTQAYpP = W_hPdJDugNsCiHq; W_hPdJDugNsCiHq = W_hPdJDugNsCiHq; for(int i=0;i<drto98_5g6biP;++i) { Hx38iCaBiywtWA1TlUAJE6OeOiYjNaf71da+=1; xkhw_OXQHvjxYe2IgL+=Hx38iCaBiywtWA1TlUAJE6OeOiYjNaf71da; } W_hPdJDugNsCiHq = E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3; Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi = E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3; I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr = S9cWjfPHgxiHxCspAlhQCv9XVZB || mYH1VIWj6vllki0nUbxdaTnhL40f5; qRUEd28YBQ = C0EfV40NqIbNVsTIUlRNgnuNNrCbGfi_q - FAEFxJLoH3VdtwoZRv4vEmMJva7Zt2yye8iiVgS; if(cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs && I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr) { mYH1VIWj6vllki0nUbxdaTnhL40f5 = !mYH1VIWj6vllki0nUbxdaTnhL40f5; } wJFnjzSaOMsiZyzNHSIua4YhqQln = S9cWjfPHgxiHxCspAlhQCv9XVZB || mYH1VIWj6vllki0nUbxdaTnhL40f5; JKaPiVcUnqzykldk1b = qRUEd28YBQ - JKaPiVcUnqzykldk1b; PqV0MgM4933EU7ZeMNNof = K9KadQaurGm * H_vcPMzNmR; GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = string.Format(Omd6xWNsSMXBnj27p1BTRV,cXPnOXH1sypIib3P0HO6b2VWDc); } public void b2RuLg8ubqlYqXcbGAlc6ATPh0hQG() { mneOUpeEI41vVP5SBTgxxrwIsqMslGM_F5B_fw = mneOUpeEI41vVP5SBTgxxrwIsqMslGM_F5B_fw - H63W8NLA3F0L19T; for(int i=0;i<K9KadQaurGm;++i) { Y8QGmU1yyeZLaCxkAKP8fBHl2yHEt6YRGMefanJ+=1; K9KadQaurGm+=Y8QGmU1yyeZLaCxkAKP8fBHl2yHEt6YRGMefanJ; } S9cWjfPHgxiHxCspAlhQCv9XVZB = mYH1VIWj6vllki0nUbxdaTnhL40f5 || wJFnjzSaOMsiZyzNHSIua4YhqQln; KYFvSOwZIQjSmgw9Vf0xHvartzgN = 4882.0; qDhY4uH2YDKI2xru3SRLZqVh3a = 4421.0; W_hPdJDugNsCiHq = 3591.0; kKmlcjd2p6ylBTQAYpP = 2450.0; kKmlcjd2p6ylBTQAYpP = 8002.0; KYFvSOwZIQjSmgw9Vf0xHvartzgN = 1061.0; mYH1VIWj6vllki0nUbxdaTnhL40f5 = Lfu2KF4MsWk3H4 && I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr; bg327eVJDKiTt40DKCso6m = GaB905q4fsO_wO7zAE0jkYPm3O9LLBz; cXPnOXH1sypIib3P0HO6b2VWDc = GaB905q4fsO_wO7zAE0jkYPm3O9LLBz; kKmlcjd2p6ylBTQAYpP = 264.0; kKmlcjd2p6ylBTQAYpP = 2632.0; kKmlcjd2p6ylBTQAYpP = 1869.0; KYFvSOwZIQjSmgw9Vf0xHvartzgN = Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi; qDhY4uH2YDKI2xru3SRLZqVh3a = Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi; if(Lfu2KF4MsWk3H4 && cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs) { S9cWjfPHgxiHxCspAlhQCv9XVZB = !S9cWjfPHgxiHxCspAlhQCv9XVZB; } } public void FXFqpOYYGsh7() { mneOUpeEI41vVP5SBTgxxrwIsqMslGM_F5B_fw = xkhw_OXQHvjxYe2IgL - PpMhcDbHtSQTd765YVfceuaNQg5lkKE; KYFvSOwZIQjSmgw9Vf0xHvartzgN = 8891.0; kKmlcjd2p6ylBTQAYpP = 4692.0; E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3 = 8024.0; KYFvSOwZIQjSmgw9Vf0xHvartzgN = Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi + W_hPdJDugNsCiHq; JKaPiVcUnqzykldk1b = 2587.0f; DF0OIh0O7UW_PrdEM = 7251.0f; m85UNThrIL7aDr1rgZalNB = 2332.0f; JKaPiVcUnqzykldk1b = C0EfV40NqIbNVsTIUlRNgnuNNrCbGfi_q - BKA1K12H5lhBzajQcUA2pVLHT9_p7Gl; hCJtcAOtqe56KAkQfAFbA6mPwoATXN = 83661; b976I7twpXTIjs = 65130; bKzwvBsDbqe70Es7txGzrbd2zWt_l = 63586; cSK9R_wK85Cd4bCy8VBxH1Zcw5hVCJqgfNuqa = kKmlcjd2p6ylBTQAYpP * KYFvSOwZIQjSmgw9Vf0xHvartzgN; Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi = kKmlcjd2p6ylBTQAYpP - qDhY4uH2YDKI2xru3SRLZqVh3a; E4kE9be0yRH2DA5abk9kV7BauCmNjOE = C0EfV40NqIbNVsTIUlRNgnuNNrCbGfi_q * qRUEd28YBQ; SnxzbWQNmH1rgIdC6MIqBdQZFGOwlmHNn8BPDB = Y8QGmU1yyeZLaCxkAKP8fBHl2yHEt6YRGMefanJ - KWe1knMNkr7; } public void wA41xHVOtxpSk44ZKq() { kKmlcjd2p6ylBTQAYpP = Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi; KYFvSOwZIQjSmgw9Vf0xHvartzgN = Aynv7LbBkZaU8BmSvswfDOXsZ_iSBqjx8CSemBi; mYH1VIWj6vllki0nUbxdaTnhL40f5 = Lfu2KF4MsWk3H4 || I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr; if(cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs || cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs) { cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs = !cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs; } cSK9R_wK85Cd4bCy8VBxH1Zcw5hVCJqgfNuqa = qDhY4uH2YDKI2xru3SRLZqVh3a * kKmlcjd2p6ylBTQAYpP; YSuXwyVWYnt0M_g89rljZ4Me9 = DF0OIh0O7UW_PrdEM / C0EfV40NqIbNVsTIUlRNgnuNNrCbGfi_q; cXPnOXH1sypIib3P0HO6b2VWDc = GaB905q4fsO_wO7zAE0jkYPm3O9LLBz; bg327eVJDKiTt40DKCso6m = GaB905q4fsO_wO7zAE0jkYPm3O9LLBz; GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = Omd6xWNsSMXBnj27p1BTRV; bg327eVJDKiTt40DKCso6m = Omd6xWNsSMXBnj27p1BTRV; GaVnCNcPZi9gBkJ7HfgXXW52u_ = Hx38iCaBiywtWA1TlUAJE6OeOiYjNaf71da - cy4Xtz3Bg3ZMx8nEKZFXYX50G8GBM1C4VZJ; Omd6xWNsSMXBnj27p1BTRV = GaB905q4fsO_wO7zAE0jkYPm3O9LLBz + cXPnOXH1sypIib3P0HO6b2VWDc; SnxzbWQNmH1rgIdC6MIqBdQZFGOwlmHNn8BPDB = Hx38iCaBiywtWA1TlUAJE6OeOiYjNaf71da * mneOUpeEI41vVP5SBTgxxrwIsqMslGM_F5B_fw; } public void EsUj60Gh5GOEDyn4cllsVAk1oVvvNwJpPhzS() { if(I8uzJ0EdVrxRFgKW1XN8qHYxObOES2ZrwIerr && wJFnjzSaOMsiZyzNHSIua4YhqQln) { cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs = !cS9QO3Qsb1N1hdLT7BhQ78d0b1u_K4Fmzs; } E4kE9be0yRH2DA5abk9kV7BauCmNjOE = DF0OIh0O7UW_PrdEM - C0EfV40NqIbNVsTIUlRNgnuNNrCbGfi_q; Omd6xWNsSMXBnj27p1BTRV = bg327eVJDKiTt40DKCso6m; GaB905q4fsO_wO7zAE0jkYPm3O9LLBz = bg327eVJDKiTt40DKCso6m; cXPnOXH1sypIib3P0HO6b2VWDc = Omd6xWNsSMXBnj27p1BTRV; bg327eVJDKiTt40DKCso6m = Omd6xWNsSMXBnj27p1BTRV; SnxzbWQNmH1rgIdC6MIqBdQZFGOwlmHNn8BPDB = RUQANPnRn3V_kV - RUQANPnRn3V_kV; KYFvSOwZIQjSmgw9Vf0xHvartzgN = KYFvSOwZIQjSmgw9Vf0xHvartzgN * KYFvSOwZIQjSmgw9Vf0xHvartzgN; mneOUpeEI41vVP5SBTgxxrwIsqMslGM_F5B_fw = PpMhcDbHtSQTd765YVfceuaNQg5lkKE - bKzwvBsDbqe70Es7txGzrbd2zWt_l; BKA1K12H5lhBzajQcUA2pVLHT9_p7Gl = DF0OIh0O7UW_PrdEM; BKA1K12H5lhBzajQcUA2pVLHT9_p7Gl = DF0OIh0O7UW_PrdEM; u2GzJZLsk1cDhtSwWWV7hard5Bm3rG9 = xkhw_OXQHvjxYe2IgL * CdCcEWh8apJw5V1PtuKUSTQqMS8u3TCWHYcb; qDhY4uH2YDKI2xru3SRLZqVh3a = W_hPdJDugNsCiHq / E3MrOxjWr67fW_67aXqcIY9uFJvtiMjoy3; } }
48.390476
126
0.747171
[ "MIT" ]
1174290471/HotUpdateSolution
Assets/Scripts/Core/TKLjF0GW5RGFJc4sH63GQSsgx8_nsssRvm6gWzT.cs
40,648
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; using BrawlLib.OpenGL; using BrawlLib.SSBB.ResourceNodes; namespace BrawlCostumeManager { public partial class ModelManager : UserControl { /// <summary> /// The string between "Fit" and the number. /// </summary> private string _charString; /// <summary> /// In case the file needs to be reloaded. /// </summary> private string _path; /// <summary> /// Should be disposed when you switch to a new file. /// </summary> ResourceNode _root; public ResourceNode WorkingRoot { get { return _root; } } public Size? ModelPreviewSize { get { return Dock == DockStyle.Fill ? (Size?)null : modelPanel1.Size; } set { if (value == null) { modelPanel1.Dock = DockStyle.Fill; } else { modelPanel1.Dock = DockStyle.None; modelPanel1.Size = value.Value; } } } public bool ZoomOut; public bool UseExceptions; private string _delayedPath; public ModelManager() { InitializeComponent(); UseExceptions = true; modelPanel1.DragEnter += modelPanel1_DragEnter; modelPanel1.DragDrop += modelPanel1_DragDrop; } void modelPanel1_DragEnter(object sender, DragEventArgs e) { if (_path != null && e.Data.GetDataPresent(DataFormats.FileDrop)) { string[] s = (string[])e.Data.GetData(DataFormats.FileDrop); if (s.Length == 1) { // Can only drag and drop one file string filename = s[0].ToLower(); if (filename.EndsWith(".pac") || filename.EndsWith(".pcs")) { e.Effect = DragDropEffects.Copy; } } } } void modelPanel1_DragDrop(object sender, DragEventArgs e) { if (e.Effect == DragDropEffects.Copy) { string newpath = ((string[])e.Data.GetData(DataFormats.FileDrop))[0]; this.BeginInvoke(new Action(() => { using (ResourceNode newroot = NodeFactory.FromFile(null, newpath)) { if (newroot is ARCNode) { string basePath = _path; if (Path.HasExtension(basePath)) { basePath = basePath.Substring(0, basePath.LastIndexOf('.')); } FileInfo pac = new FileInfo(basePath + ".pac"); FileInfo pcs = new FileInfo(basePath + ".pcs"); bool cont = true; if (pac.Exists || pcs.Exists) { cont = (DialogResult.OK == MessageBox.Show( "Replace " + pac.Name + "/" + pcs.Name + "?", "Overwrite?", MessageBoxButtons.OKCancel)); } if (!cont) return; if (_root != null) { _root.Dispose(); _root = null; } pac.Directory.Create(); (newroot as ARCNode).ExportPAC(pac.FullName); (newroot as ARCNode).ExportPCS(pcs.FullName); if (ParentForm is CostumeManager) { (ParentForm as CostumeManager).updateCostumeSelectionPane(); } LoadFile(_path); } else { MessageBox.Show("Invalid format: root node is not an ARC archive.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } })); } } public void LoadFileDelayed(string delayedPath) { this._delayedPath = delayedPath; if (!String.IsNullOrWhiteSpace(_delayedPath)) { var tmp_timer = new System.Timers.Timer(1000); tmp_timer.AutoReset = false; tmp_timer.Elapsed += new System.Timers.ElapsedEventHandler(initializeModelPanel); tmp_timer.Enabled = true; } } private void initializeModelPanel(object o, System.Timers.ElapsedEventArgs target) { LoadFile(_delayedPath); } public void RefreshModel() { LoadFile(_path); } public void LoadFile(string path) { if (_root != null) { _root.Dispose(); _root = null; } if (path == null) { return; } _path = path; _charString = getCharString(path); comboBox1.Items.Clear(); modelPanel1.ClearAll(); modelPanel1.Invalidate(); this.Text = new FileInfo(path).Name; try { //if (!File.Exists(path)) path = Settings.Default.FallbackBrawlRoot + '\\' + path.Substring(path.IndexOf("fighter")); _root = NodeFactory.FromFile(null, path); List<MDL0Node> models = findAllMDL0s(_root); if (models.Count > 0) { comboBox1.Items.AddRange(models.ToArray()); comboBox1.SelectedIndex = 0; } } catch (IOException) { } } private static string getCharString(string path) { string working = path.ToLower(); working = working.Substring(working.LastIndexOf("fit")+3); int length = 0; foreach (char c in working) { if (c >= '0' && c <= '9') { break; } else { length++; } } working = working.Substring(0, length); return working; } public void LoadModel(MDL0Node model) { model.Populate(); model.ResetToBindState(); modelPanel1.ClearAll(); modelPanel1.AddTarget((IRenderedObject)model); if (UseExceptions && PolygonsToDisable.ContainsKey(_charString)) { foreach (string polygonNum in PolygonsToDisable[_charString]) { MDL0ObjectNode poly = model.PolygonGroup.FindChild(polygonNum, false) as MDL0ObjectNode; if (poly != null) poly.IsRendering = false; } } Box box = model.GetBox(); Vector3 min = box.Min, max = box.Max; if (ZoomOut) { min._x += 20; max._x -= 20; } modelPanel1.SetCamWithBox(min, max); } private List<MDL0Node> findAllMDL0s(ResourceNode root) { List<MDL0Node> list = new List<MDL0Node>(); if (root is MDL0Node) { list.Add((MDL0Node)root); } else { foreach (ResourceNode node in root.Children) { list.AddRange(findAllMDL0s(node)); } } return list; } private MDL0Node findFirstMDL0(ResourceNode root) { if (root is MDL0Node) { return (MDL0Node)root; } foreach (ResourceNode node in root.Children) { MDL0Node result = findFirstMDL0(node); if (result != null) { return result; } } return null; } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { object item = comboBox1.SelectedItem; if (item is MDL0Node) { LoadModel(item as MDL0Node); } } public static Dictionary<string, string[]> PolygonsToDisable = new Dictionary<string, string[]> { { "mario", new string[] { "polygon4", "polygon5", "polygon6", "polygon7", "polygon12", "polygon13", "eyehurt", "facehurt", "hair_full", "FaceOuch", "EyeOuch" } }, // open eyelids { "samus", new string[] { "Sphere", "Ball", "BallSpider", "BallLED", "BallCore", "BallHazard", "BallHazardLED", "SphereGold", "polygon15", "ball", "balllight", "polygon19", "polygon20" } }, // remove morph ball { "yoshi", new string[] {"polygon8", "polygon10" } }, // remove Final Smash eyes { "kirby", new string[] { "polygon2", "polygon0", "polygon1", "polygon6", "polygon7" } }, // remove Final Smash eyes { "fox", new string[] { "polygon9", "polygon10", "polygon11", "polygon12", "polygon13", "polygon14", "polygon15", "polygon16", "polygon20", "polygon21", "polygon22", "eyeLyellow", "eyeRyellow", "HeadBlink", "HeadOuch", "HeadHalfBlink", "eyes_half_blink", "eyes_half_blink2", "fur_blink", "face_blink", "fur_ouch", "face_ouch" } }, // open eyelids { "luigi", new string[] { "polygon5", "polygon8", "polygon9", "polygon10", "polygon11", "polygon12", "polygon17", "EyeYellowL", "EyeYellowR", "Damage_Eye", "Eyebrow_Damage", "Damage_Face", "FaceHurt", "MaskHurt", "Hair_NoHat", "MaskFS", "Hair_Full", "Damage_Eyes", "Damage_Eyebrows", "Damage_Face" } }, // open eyelids { "ness", new string[] { "polygon1", "polygon2", "polygon5", "polygon6", "polygon1_BurnHead", "polygon2BurnHead" } }, // remove wild "intro" hair and FS eyes { "koopa", new string[] { "polygon22", "polygon21", "polygon20", "polygon19" } }, // remove shell { "zelda", new string[] { "polygon19", "polygon21", "polygon25", "face_halfblink", "face_blink", "Blink", "Blink_Half", "Ouch", "face_ouch_" } }, // open eyelids { "marth", new string[] { "FaceBlinkHalf", "FaceBlink", "FaceOuch", "MouthTalk", "polygon8","polygon9", "polygon10", "polygon11", "polygon13", "polygon14" } }, // open eyelids { "metaknight", new string[] { "kage" } }, // remove shadow { "pit", new string[] { "polygon14","polygon15", "polygon16", "polygon17", "polygon19", "polygon20", "polygon22", "polygon23", "polygon28", "polygon29", "polygon31", "polygon32", "Blink", "Mouth_Open", "Hurt", "Yellow_Eyes", "Half_Blink", "Angry" } }, // open eyelids { "szerosuit", new string[] { "polygon3", "polygon4", "polygon5", "polygon6", "polygon8", "polygon9", "polygon14", "polygon15", "polygon17", "polygon18", "Face HalfBlink", "Eyelashes HalfBlink", "Face Blink", "Eyelashes Blink", "Face Ouch", "Eyelashes Ouch", "Mouth Talk" } }, // open eyelids { "pikmin", new string[] {"polygon5", "helm", "helmet", "eyes_hurt", "Eyebuggy" } }, // "close" eyelids (normal facial expression for Olimar) { "mewtwo", new string[] { "polygon6", "polygon7", "polygon10", "polygon11", "polygon12", "polygon13", "EyelidsBlinkHalf", "EyelidsBlink" } }, // open eyelids { "dedede", new string[] { "polygon12", "polygon13","polygon18", "polygon19", "newbloat","SwellBelt","puff1S", "puff2S", "puff3S" } }, // remove inflated Dedede { "lucario", new string[] { "polygon32", "polygon33", "polygon35", "polygon36" } }, // remove close eyelids { "ike", new string[] { "polygon7", "polygon8", "polygon9", "polygon10", "polygon11", "polygon15", "polygon18", "polygon19", "polygon20", "polygon24", "polygon36", "polygon37", "polygon38", "polygon42", "polygon45", "polygon46", "polygon47", "polygon51", "FaceHalfBlinkAlpha", "FaceBlinkAlpha", "FaceTalkAlpha", "FaceOuchAlpha", "FaceHalfBlink", "FaceBlink", "FaceTalk", "FaceOuch", "Face BlinkHalf", "Neck BlinkHalf", "Face Blink", "Neck Blink", "Face Ouch", "Neck Ouch", "Face Talk", "Neck Talk" } }, // open eyelids { "roy", new string[] { "Roy_polygon7RY", "Roy_polygon8LY", "Half_Blink", "Mouth_Open", "hurt", "Blink", "FaceHalf", "FaceBlink", "FaceOuch", "FaceTalk", "EyeRYellow", "EyeLYellow", "TalkM_Eyes", "BlinkM_Eyes", "OuchM_Eyes", "BlinkHalf_Eyes", "OuchM_Mouth", "TalkM_Mouth", "TalkM_Alpha", "BlinkHalfM_Alpha", "OuchM_Alpha", "BlinkM_Alpha" } }, // open eyelids { "knuckles", new string[] { "Angry_Mouth", "Anrgy_Brows", "Angry_Brows", "Surprise_Mouth", "Surprise_Brows", "Fun_Mouth", "Fun_Brows", "Sad_Mouth", "Sad_Brows", "Grin_Mouth", "No_Mouth", "LidsClosed", "LidsHalf", "Sphere" } }, // remove expressions and sphere { "wolf", new string[] { "EyeYellow", "AngryWolfLeftEar", "AngryWolfFace", "AngryEyepatchBand", "BlinkWolfLeftEar3", "BlinkWolfFace", "BlinkEyepatchBand", "HalfWolfFace", "HalfWolfLeftEar4", "HalfEyepatchBand7", "polygon8", "polygon9", "polygon10", "polygon11", "polygon28", "polygon29", "polygon30", "polygon31", "polygon32", "polygon33", "polygon50", "polygon51", "polygon52", "polygon53", "polygon76", "polygon77", "polygon94", "polygon95", "polygon96", "polygon97", "polygon98", "polygon99" } }, // open eyelids { "snake", new string[] { "face_halfblink", "eyelash_halfblink1", "eyelash_halfblink2", "face_blink", "eyelash_blink1", "eyelash_blink2", "face_ouch", "eyelash_ouch1", "eyelash_ouch2", "face_talk", "eyelash_talk1", "eyelash_talk2", "face_angry", "eyelash_angry1", "eyelash_angry2", "polygon0", "polygon1", "polygon2", "polygon3", "polygon4", "polygon5", "polygon6", "polygon7", "polygon8", "polygon9", "polygon10", "polygon14", "polygon15", "polygon16", "polygon17", "polygon18", "polygon19", "eyelash_angry", "eyelash_halfblink", "eyelash_blink", "eyelash_ouch", "face_ouch", "face_blink", "face_angry", "face_talk", "face_blink_half" } }, // open eyelids { "sonic", new string[] {"polygon14", "polygon15", "polygon16", "polygon18", "polygon20", "polygon21", "polygon22", "polygon24", "polygon26", "polygon27", "polygon28", "polygon29", "polygon30", "Sphere02", "Sphere04" } }, // open eyelids, remove sphere, etc. }; public Bitmap GrabScreenshot(bool withTransparency) { modelPanel1.Refresh(); return modelPanel1.GetScreenshot(modelPanel1.ClientRectangle, withTransparency); } } }
45.662921
668
0.653871
[ "MIT" ]
jeffnwarner/BrawlManagers
CostumeManager/ModelManager.cs
12,194
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.269 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace GnomoriaEnhanced.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("GnomoriaEnhanced.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
43.640625
182
0.614393
[ "Apache-2.0" ]
bvierra/GnomoriaEnhanced
Gnomoria Enhanced/Properties/Resources.Designer.cs
2,795
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Stl.DependencyInjection; using Stl.IO; using Stl.Fusion.Bridge; using Stl.Fusion.Bridge.Messages; using Stl.Fusion.Client; using Stl.Fusion.EntityFramework; #if NETCOREAPP using Stl.Fusion.EntityFramework.Npgsql; #endif using Stl.Fusion.Extensions; using Stl.Fusion.Tests.Model; using Stl.Fusion.Tests.Services; using Stl.Fusion.Tests.UIModels; using Stl.Fusion.Internal; using Stl.Fusion.Server; using Stl.Testing; using Stl.Testing.Output; using Stl.Time; using Stl.Time.Testing; using Xunit; using Xunit.Abstractions; using Xunit.DependencyInjection.Logging; namespace Stl.Fusion.Tests { public enum FusionTestDbType { Sqlite = 0, InMemory = 1, PostgreSql = 2, } public class FusionTestOptions { public FusionTestDbType DbType { get; set; } = FusionTestDbType.Sqlite; public bool UseInMemoryKeyValueStore { get; set; } public bool UseInMemoryAuthService { get; set; } public bool UseTestClock { get; set; } public bool UseLogging { get; set; } = true; } public class FusionTestBase : TestBase, IAsyncLifetime { public FusionTestOptions Options { get; } public bool IsLoggingEnabled { get; set; } = true; public PathString SqliteDbPath { get; protected set; } public string PostgreSqlConnectionString { get; protected set; } = "Server=localhost;Database=stl_fusion_tests;Port=5432;User Id=postgres;Password=Fusion.0.to.1"; public FusionTestWebHost WebHost { get; } public IServiceProvider Services { get; } public IServiceProvider WebServices { get; } public IServiceProvider ClientServices { get; } public ILogger Log { get; } public FusionTestBase(ITestOutputHelper @out, FusionTestOptions? options = null) : base(@out) { Options = options ?? new FusionTestOptions(); // ReSharper disable once VirtualMemberCallInConstructor Services = CreateServices(); WebHost = Services.GetRequiredService<FusionTestWebHost>(); WebServices = WebHost.Services; ClientServices = CreateServices(true); if (Options.UseLogging) Log = (ILogger) Services.GetRequiredService(typeof(ILogger<>).MakeGenericType(GetType())); else Log = NullLogger.Instance; } public override async Task InitializeAsync() { for (var i = 0; i < 10 && File.Exists(SqliteDbPath); i++) { try { File.Delete(SqliteDbPath); break; } catch { await Delay(0.3); } } await using var dbContext = CreateDbContext(); if (Options.DbType != FusionTestDbType.Sqlite) await dbContext.Database.EnsureDeletedAsync(); await dbContext.Database.EnsureCreatedAsync(); await Services.HostedServices().Start(); } public override async Task DisposeAsync() { if (ClientServices is IDisposable dcs) dcs.Dispose(); try { await Services.HostedServices().Stop(); } finally { if (Services is IDisposable ds) ds.Dispose(); } } protected IServiceProvider CreateServices(bool isClient = false) { var services = (IServiceCollection) new ServiceCollection(); ConfigureServices(services, isClient); return services.BuildServiceProvider(); } protected virtual void ConfigureServices(IServiceCollection services, bool isClient = false) { if (Options.UseTestClock) services.AddSingleton<IMomentClock, TestClock>(); services.AddSingleton(Out); // Logging if (Options.UseLogging) services.AddLogging(logging => { var debugCategories = new List<string> { "Stl.Fusion", "Stl.CommandR", "Stl.Tests.Fusion", // DbLoggerCategory.Database.Transaction.Name, // DbLoggerCategory.Database.Connection.Name, // DbLoggerCategory.Database.Command.Name, // DbLoggerCategory.Query.Name, // DbLoggerCategory.Update.Name, }; bool LogFilter(string category, LogLevel level) => IsLoggingEnabled && debugCategories.Any(category.StartsWith) && level >= LogLevel.Debug; logging.ClearProviders(); logging.SetMinimumLevel(LogLevel.Debug); logging.AddFilter(LogFilter); logging.AddDebug(); // XUnit logging requires weird setup b/c otherwise it filters out // everything below LogLevel.Information logging.AddProvider(new XunitTestOutputLoggerProvider( new TestOutputHelperAccessor(Out), LogFilter)); }); // Core Fusion services var fusion = services.AddFusion(); fusion.AddFusionTime(); // Auto-discovered services var testType = GetType(); services.UseRegisterAttributeScanner() .WithTypeFilter(testType.Namespace!) .RegisterFrom(testType.Assembly); if (!isClient) { // Configuring Services and ServerServices services.UseRegisterAttributeScanner(ServiceScope.Services) .WithTypeFilter(testType.Namespace!) .RegisterFrom(testType.Assembly); // DbContext & related services var appTempDir = PathEx.GetApplicationTempDirectory("", true); SqliteDbPath = appTempDir & PathEx.GetHashedName($"{testType.Name}_{testType.Namespace}.db"); services.AddPooledDbContextFactory<TestDbContext>(builder => { switch (Options.DbType) { case FusionTestDbType.Sqlite: builder.UseSqlite($"Data Source={SqliteDbPath}"); break; case FusionTestDbType.InMemory: builder.UseInMemoryDatabase(SqliteDbPath) .ConfigureWarnings(w => { w.Ignore(InMemoryEventId.TransactionIgnoredWarning); }); break; case FusionTestDbType.PostgreSql: #if NETCOREAPP builder.UseNpgsql(PostgreSqlConnectionString); break; #else throw new NotSupportedException("PostgreSql is supported only for .net core."); #endif default: throw new ArgumentOutOfRangeException(); } builder.EnableSensitiveDataLogging(); }, 256); services.AddDbContextServices<TestDbContext>(b => { b.AddDbOperations((_, o) => { o.UnconditionalWakeUpPeriod = TimeSpan.FromSeconds(5); // Enable this if you debug multi-host invalidation // o.MaxCommitDuration = TimeSpan.FromMinutes(5); }); if (Options.DbType == FusionTestDbType.PostgreSql) #if NETCOREAPP b.AddNpgsqlDbOperationLogChangeTracking(); #else throw new NotSupportedException("PostgreSql is supported only for .net core."); #endif else b.AddFileBasedDbOperationLogChangeTracking(); if (!Options.UseInMemoryAuthService) b.AddDbAuthentication(); if (!Options.UseInMemoryKeyValueStore) b.AddKeyValueStore(); b.AddDbEntityResolver<long, User>(); }); if (Options.UseInMemoryKeyValueStore) fusion.AddInMemoryKeyValueStore(); if (Options.UseInMemoryAuthService) fusion.AddAuthentication().AddServerSideAuthService(); // WebHost var webHost = (FusionTestWebHost?) WebHost; if (webHost == null) { var webHostOptions = new FusionTestWebHostOptions(); #if NETFRAMEWORK var controllerTypes = testType.Assembly.GetControllerTypes(testType.Namespace).ToArray(); webHostOptions.ControllerTypes = controllerTypes; #endif webHost = new FusionTestWebHost(services, webHostOptions); } services.AddSingleton(c => webHost); } else { // Configuring ClientServices services.UseRegisterAttributeScanner(ServiceScope.ClientServices) .WithTypeFilter(testType.Namespace!) .RegisterFrom(testType.Assembly); // Fusion client var fusionClient = fusion.AddRestEaseClient( (c, options) => { options.BaseUri = WebHost.ServerUri; options.IsMessageLoggingEnabled = true; }).ConfigureHttpClientFactory( (c, name, options) => { var baseUri = WebHost.ServerUri; var apiUri = new Uri($"{baseUri}api/"); var isFusionService = !(name ?? "").Contains("Tests"); var clientBaseUri = isFusionService ? baseUri : apiUri; options.HttpClientActions.Add(c => c.BaseAddress = clientBaseUri); }); fusion.AddAuthentication(fusionAuth => fusionAuth.AddRestEaseClient()); // Custom computed state services.AddSingleton(c => c.StateFactory().NewComputed<ServerTimeModel2>( async (_, cancellationToken) => { var client = c.GetRequiredService<IClientTimeService>(); var time = await client.GetTime(cancellationToken).ConfigureAwait(false); return new ServerTimeModel2(time); })); } } protected TestDbContext CreateDbContext() => Services.GetRequiredService<IDbContextFactory<TestDbContext>>().CreateDbContext(); protected Task<Channel<BridgeMessage>> ConnectToPublisher(CancellationToken cancellationToken = default) { var publisher = WebServices.GetRequiredService<IPublisher>(); var channelProvider = ClientServices.GetRequiredService<IChannelProvider>(); return channelProvider.CreateChannel(publisher.Id, cancellationToken); } protected virtual TestChannelPair<BridgeMessage> CreateChannelPair( string name, bool dump = true) => new(name, dump ? Out : null); protected virtual Task Delay(double seconds) => Timeouts.Clock.Delay(TimeSpan.FromSeconds(seconds)); protected void GCCollect() { for (var i = 0; i < 3; i++) { GC.Collect(); Thread.Sleep(10); } } } }
41.325342
112
0.564598
[ "MIT" ]
wdichler/Stl.Fusion
tests/Stl.Fusion.Tests/FusionTestBase.cs
12,067
C#
// MonoGame - Copyright (C) The MonoGame Team // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. using System; using System.IO; using System.Collections.Generic; using System.Diagnostics; using Eto.Forms; using Eto.Drawing; using System.Reflection; namespace MonoGame.Tools.Pipeline { #if IDE partial class MainWindow : DynamicLayout, IView { public string Title { get; set; } public Icon Icon { get; set; } public MenuBar Menu { get; set; } public ToolBar ToolBar { get; set; } #else partial class MainWindow : Form, IView { #endif #pragma warning disable 649 public EventHandler<EventArgs> RecentChanged; public EventHandler<EventArgs> TitleChanged; #pragma warning restore 649 public const string TitleBase = "MGCB Editor"; public static MainWindow Instance; private List<Pad> _pads; private Clipboard _clipboard; private ContextMenu _contextMenu; private FileFilter _mgcbFileFilter, _allFileFilter, _xnaFileFilter; public MainWindow() { _pads = new List<Pad>(); _clipboard = new Clipboard(); InitializeComponent(); Instance = this; // Fill in Pad menu foreach (var pad in _pads) { if (pad.Commands.Count > 0) { var menu = new ButtonMenuItem(); menu.Text = pad.Title; foreach (var com in pad.Commands) menu.Items.Add(com.CreateMenuItem()); menuView.Items.Add(menu); } } _contextMenu = new ContextMenu(); projectControl.SetContextMenu(_contextMenu); _mgcbFileFilter = new FileFilter("MonoGame Content Build Project (*.mgcb)", new[] { ".mgcb" }); _allFileFilter = new FileFilter("All Files (*.*)", new[] { ".*" }); _xnaFileFilter = new FileFilter("XNA Content Projects (*.contentproj)", new[] { ".contentproj" }); } #if !IDE protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { e.Cancel = !PipelineController.Instance.Exit(); base.OnClosing(e); } #endif #region IView implements public void Attach(IController controller) { PipelineController.Instance.OnProjectLoaded += () => projectControl.ExpandBase(); cmdDebugMode.Checked = PipelineSettings.Default.DebugMode; foreach (var control in _pads) control.LoadSettings(); Style = "MainWindow"; } public void Invoke(Action action) { Application.Instance.Invoke(action); } public AskResult AskSaveOrCancel() { var result = MessageBox.Show(this, "Do you want to save the project first?", "Save Project", MessageBoxButtons.YesNoCancel, MessageBoxType.Question); if (result == DialogResult.Yes) return AskResult.Yes; if (result == DialogResult.No) return AskResult.No; return AskResult.Cancel; } public bool AskSaveName(ref string filePath, string title) { var dialog = new SaveFileDialog(); dialog.Title = title; dialog.Filters.Add(_mgcbFileFilter); dialog.Filters.Add(_allFileFilter); dialog.CurrentFilter = _mgcbFileFilter; if (dialog.Show(this) == DialogResult.Ok) { filePath = dialog.FileName; if (dialog.CurrentFilter == _mgcbFileFilter && !filePath.EndsWith(".mgcb")) filePath += ".mgcb"; return true; } return false; } public bool AskOpenProject(out string projectFilePath) { var dialog = new OpenFileDialog(); dialog.Filters.Add(_mgcbFileFilter); dialog.Filters.Add(_allFileFilter); dialog.CurrentFilter = _mgcbFileFilter; if (dialog.Show(this) == DialogResult.Ok) { projectFilePath = dialog.FileName; return true; } projectFilePath = ""; return false; } public bool AskImportProject(out string projectFilePath) { var dialog = new OpenFileDialog(); dialog.Filters.Add(_xnaFileFilter); dialog.Filters.Add(_allFileFilter); dialog.CurrentFilter = _xnaFileFilter; if (dialog.Show(this) == DialogResult.Ok) { projectFilePath = dialog.FileName; return true; } projectFilePath = ""; return false; } public void ShowError(string title, string message) { MessageBox.Show(this, message, title, MessageBoxButtons.OK, MessageBoxType.Error); } public void ShowMessage(string message) { MessageBox.Show(this, message, "Info", MessageBoxButtons.OK, MessageBoxType.Information); } public void BeginTreeUpdate() { } public void SetTreeRoot(IProjectItem item) { projectControl.SetRoot(item); } public void AddTreeItem(IProjectItem item) { projectControl.AddItem(item); } public void RemoveTreeItem(IProjectItem item) { projectControl.RemoveItem(item); } public void UpdateTreeItem(IProjectItem item) { projectControl.UpdateItem(item); } public void EndTreeUpdate() { } public void UpdateProperties() { propertyGridControl.SetObjects(PipelineController.Instance.SelectedItems); } public void OutputAppend(string text) { #if !IDE Application.Instance.AsyncInvoke(() => buildOutput.WriteLine(text)); #endif } public void OutputClear() { #if !IDE Application.Instance.Invoke(() => buildOutput.ClearOutput()); #endif } public bool ShowDeleteDialog(List<IProjectItem> items) { var dialog = new DeleteDialog(PipelineController.Instance, items); return dialog.Show(this); } public bool ShowEditDialog(string title, string text, string oldname, bool file, out string newname) { var dialog = new EditDialog(title, text, oldname, file); var result = dialog.Show(this); newname = dialog.Text; return result; } public bool ChooseContentFile(string initialDirectory, out List<string> files) { var dialog = new OpenFileDialog(); dialog.Directory = new Uri(initialDirectory); dialog.MultiSelect = true; dialog.Filters.Add(_allFileFilter); dialog.CurrentFilter = _allFileFilter; var result = dialog.Show(this) == DialogResult.Ok; files = new List<string>(); files.AddRange(dialog.Filenames); return result; } public bool ChooseContentFolder(string initialDirectory, out string folder) { var dialog = new SelectFolderDialog(); dialog.Directory = initialDirectory; var result = dialog.Show(this) == DialogResult.Ok; if (result) folder = dialog.Directory; else folder = string.Empty; return result; } public bool ChooseItemTemplate(string folder, out ContentItemTemplate template, out string name) { var dialog = new NewItemDialog(PipelineController.Instance.Templates.GetEnumerator(), folder); var result = dialog.Show(this); if (result) { template = dialog.Selected; name = dialog.Name + Path.GetExtension(template.TemplateFile); } else { template = null; name = ""; } return result; } public bool CopyOrLinkFile(string file, bool exists, out IncludeType action, out bool applyforall) { var dialog = new AddItemDialog(file, exists, FileType.File); var result = dialog.Show(this); action = dialog.Responce; applyforall = dialog.ApplyForAll; return result; } public bool CopyOrLinkFolder(string folder, bool exists, out IncludeType action, out bool applyforall) { var afd = new AddItemDialog(folder, exists, FileType.Folder); applyforall = false; if (afd.Show(this)) { action = afd.Responce; return true; } action = IncludeType.Link; return false; } public void UpdateCommands(MenuInfo info) { #if IDE info.RebuildItem = false; info.OpenItemWith = false; #endif // Title if (TitleChanged != null) TitleChanged(this, EventArgs.Empty); else { var title = TitleBase; if (PipelineController.Instance.ProjectOpen) { title += " - " + Path.GetFileName(PipelineController.Instance.ProjectItem.OriginalPath); if (PipelineController.Instance.ProjectDirty) title += "*"; } Title = title; } // Menu cmdNew.Enabled = info.New; cmdOpen.Enabled = info.Open; cmdImport.Enabled = info.Import; cmdSave.Enabled = info.Save; cmdSaveAs.Enabled = info.SaveAs; cmdClose.Enabled = info.Close; cmdExit.Enabled = info.Exit; cmdUndo.Enabled = info.Undo; cmdRedo.Enabled = info.Redo; cmdAdd.Enabled = info.Add; cmdNewItem.Enabled = info.Add; cmdNewFolder.Enabled = info.Add; cmdExistingItem.Enabled = info.Add; cmdExistingFolder.Enabled = info.Add; cmdExclude.Enabled = info.Exclude; cmdRename.Enabled = info.Rename; cmdDelete.Enabled = info.Delete; cmdBuild.Enabled = info.Build; cmdRebuild.Enabled = info.Rebuild; cmdClean.Enabled = info.Clean; cmdCancelBuild.Enabled = info.Cancel; cmdOpenItem.Enabled = info.OpenItem; cmdOpenItemWith.Enabled = info.OpenItemWith; cmdOpenItemLocation.Enabled = info.OpenItemLocation; cmdOpenOutputItemLocation.Enabled = info.OpenOutputItemLocation; cmdCopyAssetName.Enabled = info.CopyAssetPath; cmdRebuildItem.Enabled = info.RebuildItem; // Visibility of menu items can't be changed so // we need to recreate the context menu each time. // Context Menu var sep = false; _contextMenu.Items.Clear(); AddContextMenu(cmOpenItem, ref sep); AddContextMenu(cmOpenItemWith, ref sep); AddContextMenu(cmAdd, ref sep); AddContextMenu(cmRebuildItem, ref sep); AddSeparator(ref sep); AddContextMenu(cmOpenItemLocation, ref sep); AddContextMenu(cmOpenOutputItemLocation, ref sep); AddContextMenu(cmCopyAssetPath, ref sep); AddSeparator(ref sep); AddContextMenu(cmExclude, ref sep); AddSeparator(ref sep); AddContextMenu(cmRename, ref sep); //AddContextMenu(cmDelete, ref sep); if (_contextMenu.Items.Count > 0) { var lastItem = _contextMenu.Items[_contextMenu.Items.Count - 1]; if (lastItem is SeparatorMenuItem) _contextMenu.Items.Remove(lastItem); } } private void AddContextMenu(MenuItem item, ref bool separator) { item.Shortcut = Keys.None; if (item.Enabled) _contextMenu.Items.Add(item); separator |= item.Enabled; } private void AddSeparator(ref bool separator) { if (separator) { if (!(_contextMenu.Items[_contextMenu.Items.Count - 1] is SeparatorMenuItem)) _contextMenu.Items.Add(new SeparatorMenuItem()); separator = false; } } public void UpdateRecentList(List<string> recentList) { if (RecentChanged != null) { RecentChanged(recentList, EventArgs.Empty); return; } menuRecent.Items.Clear(); foreach (var recent in recentList) { var item = new ButtonMenuItem(); item.Text = recent; item.Click += (sender, e) => PipelineController.Instance.OpenProject(recent); menuRecent.Items.Insert(0, item); } if (menuRecent.Items.Count > 0) { menuRecent.Items.Add(new SeparatorMenuItem()); var clearItem = new ButtonMenuItem(); clearItem.Text = "Clear"; clearItem.Click += (sender, e) => PipelineController.Instance.ClearRecentList(); menuRecent.Items.Add(clearItem); } } public void SetClipboard(string text) { _clipboard.Clear(); _clipboard.Text = text; } #endregion #region Commands private void CmdNew_Executed(object sender, EventArgs e) { PipelineController.Instance.NewProject(); } private void CmdOpen_Executed(object sender, EventArgs e) { PipelineController.Instance.OpenProject(); } private void CmdClose_Executed(object sender, EventArgs e) { PipelineController.Instance.CloseProject(); } private void CmdImport_Executed(object sender, EventArgs e) { PipelineController.Instance.ImportProject(); } private void CmdSave_Executed(object sender, EventArgs e) { PipelineController.Instance.SaveProject(false); } private void CmdSaveAs_Executed(object sender, EventArgs e) { PipelineController.Instance.SaveProject(true); } private void CmdExit_Executed(object sender, EventArgs e) { Application.Instance.Quit(); } private void CmdUndo_Executed(object sender, EventArgs e) { PipelineController.Instance.Undo(); } private void CmdRedo_Executed(object sender, EventArgs e) { PipelineController.Instance.Redo(); } private void CmdExclude_Executed(object sender, EventArgs e) { PipelineController.Instance.Exclude(false); } private void CmdRename_Executed(object sender, EventArgs e) { PipelineController.Instance.Rename(); } private void CmdDelete_Executed(object sender, EventArgs e) { PipelineController.Instance.Exclude(true); } private void CmdNewItem_Executed(object sender, EventArgs e) { PipelineController.Instance.NewItem(); } private void CmdNewFolder_Executed(object sender, EventArgs e) { PipelineController.Instance.NewFolder(); } private void CmdExistingItem_Executed(object sender, EventArgs e) { PipelineController.Instance.Include(); } private void CmdExistingFolder_Executed(object sender, EventArgs e) { PipelineController.Instance.IncludeFolder(); } private void CmdBuild_Executed(object sender, EventArgs e) { PipelineController.Instance.Build(false); } private void CmdRebuild_Executed(object sender, EventArgs e) { PipelineController.Instance.Build(true); } private void CmdClean_Executed(object sender, EventArgs e) { PipelineController.Instance.Clean(); } private void CmdCancelBuild_Executed(object sender, EventArgs e) { PipelineController.Instance.CancelBuild(); } private void CmdDebugMode_Executed(object sender, EventArgs e) { PipelineSettings.Default.DebugMode = cmdDebugMode.Checked; } private void CmdHelp_Executed(object sender, EventArgs e) { Process.Start(new ProcessStartInfo() { FileName = "https://docs.monogame.net/articles/tools/mgcb_editor.html", UseShellExecute = true, Verb = "open" }); } private void CmdAbout_Executed(object sender, EventArgs e) { var adialog = new AboutDialog(); adialog.Logo = Bitmap.FromResource("Icons.monogame.png"); adialog.WebsiteLabel = "MonoGame Website"; adialog.Website = new Uri("http://www.monogame.net/"); using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("LICENSE.txt")) using (var reader = new StreamReader(stream)) adialog.License = reader.ReadToEnd(); adialog.Show(this); } public void CmdOpenItem_Executed(object sender, EventArgs e) { if (PipelineController.Instance.SelectedItem is ContentItem) { var filePath = PipelineController.Instance.GetFullPath(PipelineController.Instance.SelectedItem.OriginalPath); #if IDE MonoDevelop.Ide.IdeApp.Workbench.OpenDocument(filePath, MonoDevelop.Ide.Gui.OpenDocumentOptions.Default); #else Process.Start(new ProcessStartInfo() { FileName = filePath, UseShellExecute = true, Verb = "open" }); #endif } } private void CmdOpenItemWith_Executed(object sender, EventArgs e) { if (PipelineController.Instance.SelectedItem != null) { try { var filepath = PipelineController.Instance.GetFullPath(PipelineController.Instance.SelectedItem.OriginalPath); var dialog = new OpenWithDialog(filepath); dialog.Show(this); } catch { ShowError("Error", "An error occured while trying to launch an open with dialog."); } } } private void CmdOpenItemLocation_Executed(object sender, EventArgs e) { if (PipelineController.Instance.SelectedItem != null) { var filePath = PipelineController.Instance.GetFullPath(PipelineController.Instance.SelectedItem.Location); Process.Start(new ProcessStartInfo() { FileName = filePath, UseShellExecute = true, Verb = "open" }); } } private void CmdOpenOutputItemLocation_Executed(object sender, EventArgs e) { if (PipelineController.Instance.SelectedItem != null) { var dir = Path.Combine( PipelineController.Instance.ProjectItem.Location, PipelineController.Instance.ProjectOutputDir, PipelineController.Instance.SelectedItem.Location ); dir = dir.Replace("$(Platform)", PipelineController.Instance.ProjectItem.Platform.ToString()); dir = dir.Replace("$(Configuration)", PipelineController.Instance.ProjectItem.Config); dir = dir.Replace("$(Config)", PipelineController.Instance.ProjectItem.Config); dir = dir.Replace("$(Profile)", PipelineController.Instance.ProjectItem.Profile.ToString()); if (Directory.Exists(dir)) Process.Start(new ProcessStartInfo() { FileName = dir, UseShellExecute = true, Verb = "open" }); else ShowError("Directory Not Found", "The project output directory was not found, did you forget to build the project?"); } } private void CmdCopyAssetPath_Executed(object sender, EventArgs e) { PipelineController.Instance.CopyAssetPath(); } private void CmdRebuildItem_Executed(object sender, EventArgs e) { PipelineController.Instance.RebuildItems(); } #endregion } }
31.657658
164
0.568678
[ "MIT" ]
BlueElectivire/MonoGame
Tools/MonoGame.Content.Builder.Editor/MainWindow.cs
21,086
C#
#if !NOSOCKET using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBitcoin.Protocol.Behaviors { public class NodeBehaviorsCollection : ThreadSafeCollection<INodeBehavior> { Node _Node; public NodeBehaviorsCollection(Node node) { _Node = node; } bool CanAttach { get { return _Node != null && !DelayAttach && _Node.State != NodeState.Offline && _Node.State != NodeState.Failed && _Node.State != NodeState.Disconnecting; } } protected override void OnAdding(INodeBehavior obj) { if(CanAttach) obj.Attach(_Node); } protected override void OnRemoved(INodeBehavior obj) { if(obj.AttachedNode != null) obj.Detach(); } bool _DelayAttach; internal bool DelayAttach { get { return _DelayAttach; } set { _DelayAttach = value; if(CanAttach) foreach(var b in this) b.Attach(_Node); } } } } #endif
19
155
0.647556
[ "MIT" ]
AkioNak/NElements
NBitcoin/Protocol/Behaviors/NodeBehaviorsCollection.cs
1,066
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace TwilightSparkle.Forum.Repository.Migrations { public partial class Threads : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Sections", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Name = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Sections", x => x.Id); }); migrationBuilder.CreateTable( name: "Threads", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Title = table.Column<string>(nullable: true), Content = table.Column<string>(nullable: true), AuthorId = table.Column<int>(nullable: false), SectionId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Threads", x => x.Id); table.ForeignKey( name: "FK_Threads_Users_AuthorId", column: x => x.AuthorId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Threads_Sections_SectionId", column: x => x.SectionId, principalTable: "Sections", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Threads_AuthorId", table: "Threads", column: "AuthorId"); migrationBuilder.CreateIndex( name: "IX_Threads_SectionId", table: "Threads", column: "SectionId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Threads"); migrationBuilder.DropTable( name: "Sections"); } } }
36.633803
71
0.467897
[ "Apache-2.0" ]
pavvlik777/TwilightSparkleForum
src/TwilightSparkle.Forum.Repository/Migrations/20200601005735_Threads.cs
2,603
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("L_ExtractEmails")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("L_ExtractEmails")] [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("ec3cd8d0-3926-44a2-88b7-a10eb0a88b79")] // 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.918919
84
0.746258
[ "MIT" ]
mayapeneva/Programming-Fundamentals
10.RegularExpressions/L_ExtractEmails/Properties/AssemblyInfo.cs
1,406
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("02. Bricks")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("02. Bricks")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("5690860e-5ae2-478e-8acc-5aee3befddf1")] // 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.648649
84
0.741565
[ "MIT" ]
Hmmrpss/Exam-Preps
00.Programming_Basics_Exam_jan_2016/02. Bricks/Properties/AssemblyInfo.cs
1,396
C#
using Chireiden.Silverfish; using HearthDb; /* _BEGIN_TEMPLATE_ { "id": "KAR_710", "name": [ "奥能铁匠", "Arcanosmith" ], "text": [ "<b>战吼:</b>召唤一个0/5并具有<b>嘲讽</b>的随从。", "<b>Battlecry:</b> Summon a 0/5 minion with <b>Taunt</b>." ], "cardClass": "NEUTRAL", "type": "MINION", "cost": 4, "rarity": "COMMON", "set": "KARA", "collectible": true, "dbfId": 39491 } _END_TEMPLATE_ */ namespace HREngine.Bots { class Sim_KAR_710 : SimTemplate //* Arcanosmith { //Battlecry: Summon a 0/5 minion with Taunt. SimCard kid = CardIds.NonCollectible.Neutral.Arcanosmith_AnimatedShield; //Animated Shield public override void getBattlecryEffect(Playfield p, Minion own, Minion target, int choice) { p.callKid(this.kid, own.zonepos, own.own); } } }
21.921053
99
0.609844
[ "MIT" ]
chi-rei-den/Silverfish
cards/KARA/KAR/Sim_KAR_710.cs
873
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201 { using Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell; /// <summary>Azure capacity definition.</summary> [System.ComponentModel.TypeConverter(typeof(AzureCapacityTypeConverter))] public partial class AzureCapacity { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.AzureCapacity" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal AzureCapacity(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("ScaleType")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IAzureCapacityInternal)this).ScaleType = (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.AzureScaleType) content.GetValueForProperty("ScaleType",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IAzureCapacityInternal)this).ScaleType, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.AzureScaleType.CreateFrom); } if (content.Contains("Minimum")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IAzureCapacityInternal)this).Minimum = (int) content.GetValueForProperty("Minimum",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IAzureCapacityInternal)this).Minimum, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); } if (content.Contains("Maximum")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IAzureCapacityInternal)this).Maximum = (int) content.GetValueForProperty("Maximum",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IAzureCapacityInternal)this).Maximum, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); } if (content.Contains("Default")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IAzureCapacityInternal)this).Default = (int) content.GetValueForProperty("Default",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IAzureCapacityInternal)this).Default, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); } AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.AzureCapacity" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal AzureCapacity(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("ScaleType")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IAzureCapacityInternal)this).ScaleType = (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.AzureScaleType) content.GetValueForProperty("ScaleType",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IAzureCapacityInternal)this).ScaleType, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.AzureScaleType.CreateFrom); } if (content.Contains("Minimum")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IAzureCapacityInternal)this).Minimum = (int) content.GetValueForProperty("Minimum",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IAzureCapacityInternal)this).Minimum, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); } if (content.Contains("Maximum")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IAzureCapacityInternal)this).Maximum = (int) content.GetValueForProperty("Maximum",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IAzureCapacityInternal)this).Maximum, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); } if (content.Contains("Default")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IAzureCapacityInternal)this).Default = (int) content.GetValueForProperty("Default",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IAzureCapacityInternal)this).Default, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); } AfterDeserializePSObject(content); } /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.AzureCapacity" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IAzureCapacity" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IAzureCapacity DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new AzureCapacity(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.AzureCapacity" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IAzureCapacity" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IAzureCapacity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new AzureCapacity(content); } /// <summary> /// Creates a new instance of <see cref="AzureCapacity" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IAzureCapacity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// Azure capacity definition. [System.ComponentModel.TypeConverter(typeof(AzureCapacityTypeConverter))] public partial interface IAzureCapacity { } }
66.084337
404
0.680675
[ "MIT" ]
AlanFlorance/azure-powershell
src/Kusto/generated/api/Models/Api20220201/AzureCapacity.PowerShell.cs
10,805
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace SimpleSoft.Database { /// <summary> /// Represents an entity query /// </summary> /// <typeparam name="TEntity">The entity type</typeparam> public class EFCoreQueryable<TEntity> : IQueryable<TEntity> where TEntity : class, IEntity { private readonly IQueryable<TEntity> _query; /// <summary> /// Creates a new instance /// </summary> /// <param name="container"></param> public EFCoreQueryable( EFCoreContextContainer container ) { if (container == null) throw new ArgumentNullException(nameof(container)); _query = container.Query<TEntity>(); } /// <inheritdoc /> public IEnumerator<TEntity> GetEnumerator() => _query.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// <inheritdoc /> public Type ElementType => _query.ElementType; /// <inheritdoc /> public Expression Expression => _query.Expression; /// <inheritdoc /> public IQueryProvider Provider => _query.Provider; } }
28.088889
86
0.61788
[ "MIT" ]
estouaway/Database
src/SimpleSoft.Database.EFCore/EFCoreQueryable.cs
1,266
C#
namespace ArtGallery.Orders.Models { using System; using System.Collections.Generic; using System.Text; public class OrderOtuputModel { } }
15.090909
37
0.680723
[ "MIT" ]
vanya-ant/ArtGallery2.0
Server/ArtGallery.Orders/Models/OrderOtuputModel.cs
168
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { public static GameManager Instance { get; private set; } public GameObject m_objMainPlayer; void Awake() { if (Instance != null) { Destroy(gameObject); } Instance = this; } void Start() { } void Update() { } }
16.32
60
0.607843
[ "MIT" ]
jsham0414/QuarterviewShootingGame
Assets/GameManager.cs
410
C#
using Microsoft.Maui.Controls.Xaml; namespace Microsoft.Maui.Controls.Compatibility.ControlGallery.GalleryPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class IndicatorsSample : ContentPage { public IndicatorsSample() { InitializeComponent(); BindingContext = new GalleryPages.CollectionViewGalleries.CarouselViewGalleries.CarouselItemsGalleryViewModel(false, false); } } }
29.785714
127
0.817746
[ "MIT" ]
10088/maui
src/Compatibility/ControlGallery/src/Core/GalleryPages/IndicatorViewGalleries/IndicatorsSample.xaml.cs
419
C#
/* * Copyright 2012-2021 The Pkcs11Interop Project * * 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. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <jimrich@jimrich.sk> */ using System; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.HighLevelAPI; using Net.Pkcs11Interop.HighLevelAPI.MechanismParams; using Net.Pkcs11Interop.LowLevelAPI40.MechanismParams; using NativeULong = System.UInt32; // Note: Code in this file is generated automatically. namespace Net.Pkcs11Interop.HighLevelAPI40.MechanismParams { /// <summary> /// Parameters for the CKM_KIP_DERIVE, CKM_KIP_WRAP and CKM_KIP_MAC mechanisms /// </summary> public class CkKipParams : ICkKipParams { /// <summary> /// Flag indicating whether instance has been disposed /// </summary> private bool _disposed = false; /// <summary> /// Low level mechanism parameters /// </summary> private CK_KIP_PARAMS _lowLevelStruct = new CK_KIP_PARAMS(); /// <summary> /// Initializes a new instance of the CkKipParams class. /// </summary> /// <param name='mechanism'>Underlying cryptographic mechanism (CKM)</param> /// <param name='key'>Handle to a key that will contribute to the entropy of the derived key (CKM_KIP_DERIVE) or will be used in the MAC operation (CKM_KIP_MAC)</param> /// <param name='seed'>Input seed</param> public CkKipParams(NativeULong? mechanism, IObjectHandle key, byte[] seed) { _lowLevelStruct.Mechanism = IntPtr.Zero; _lowLevelStruct.Key = 0; _lowLevelStruct.Seed = IntPtr.Zero; _lowLevelStruct.SeedLen = 0; if (mechanism != null) { byte[] bytes = ConvertUtils.UInt32ToBytes(mechanism.Value); _lowLevelStruct.Mechanism = UnmanagedMemory.Allocate(bytes.Length); UnmanagedMemory.Write(_lowLevelStruct.Mechanism, bytes); } if (key == null) throw new ArgumentNullException("key"); _lowLevelStruct.Key = ConvertUtils.UInt32FromUInt64(key.ObjectId); if (seed != null) { _lowLevelStruct.Seed = UnmanagedMemory.Allocate(seed.Length); UnmanagedMemory.Write(_lowLevelStruct.Seed, seed); _lowLevelStruct.SeedLen = ConvertUtils.UInt32FromInt32(seed.Length); } } #region IMechanismParams /// <summary> /// Returns managed object that can be marshaled to an unmanaged block of memory /// </summary> /// <returns>A managed object holding the data to be marshaled. This object must be an instance of a formatted class.</returns> public object ToMarshalableStructure() { if (this._disposed) throw new ObjectDisposedException(this.GetType().FullName); return _lowLevelStruct; } #endregion #region IDisposable /// <summary> /// Disposes object /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Disposes object /// </summary> /// <param name="disposing">Flag indicating whether managed resources should be disposed</param> protected virtual void Dispose(bool disposing) { if (!this._disposed) { if (disposing) { // Dispose managed objects } // Dispose unmanaged objects UnmanagedMemory.Free(ref _lowLevelStruct.Mechanism); UnmanagedMemory.Free(ref _lowLevelStruct.Seed); _lowLevelStruct.SeedLen = 0; _disposed = true; } } /// <summary> /// Class destructor that disposes object if caller forgot to do so /// </summary> ~CkKipParams() { Dispose(false); } #endregion } }
33.787234
176
0.593829
[ "Apache-2.0" ]
Pkcs11Interop/Pkcs11Interop
src/Pkcs11Interop/HighLevelAPI40/MechanismParams/CkKipParams.cs
4,764
C#
using PrimeInputActions; using ProTrans; using UniInject; using UniRx; using UnityEngine; using UnityEngine.UIElements; // Disable warning about fields that are never assigned, their values are injected. #pragma warning disable CS0649 public class OptionsOverviewSceneControl : MonoBehaviour, INeedInjection, ITranslator { [Inject(UxmlName = R.UxmlNames.sceneTitle)] private Label sceneTitle; [Inject(UxmlName = R.UxmlNames.backButton)] private Button backButton; [Inject(UxmlName = R.UxmlNames.gameOptionsButton)] private Button gameOptionsButton; [Inject(UxmlName = R.UxmlNames.songsOptionsButton)] private Button songsOptionsButton; [Inject(UxmlName = R.UxmlNames.graphicsOptionsButton)] private Button graphicsOptionsButton; [Inject(UxmlName = R.UxmlNames.soundOptionsButton)] private Button soundOptionsButton; [Inject(UxmlName = R.UxmlNames.recordingOptionsButton)] private Button recordingOptionsButton; [Inject(UxmlName = R.UxmlNames.profileOptionsButton)] private Button profileOptionsButton; [Inject(UxmlName = R.UxmlNames.designOptionsButton)] private Button designOptionsButton; [Inject(UxmlName = R.UxmlNames.internetOptionsButton)] private Button internetOptionsButton; [Inject(UxmlName = R.UxmlNames.appOptionsButton)] private Button appOptionsButton; [Inject(UxmlName = R.UxmlNames.developerOptionsButton)] private Button developerOptionsButton; [Inject(UxmlName = R.UxmlNames.languageChooser)] private ItemPicker languageChooser; [Inject] private SceneNavigator sceneNavigator; [Inject] private TranslationManager translationManager; [Inject] private Settings settings; [Inject] private UIDocument uiDoc; private void Start() { gameOptionsButton.Focus(); gameOptionsButton.RegisterCallbackButtonTriggered(() => sceneNavigator.LoadScene(EScene.OptionsGameScene)); backButton.RegisterCallbackButtonTriggered(() => sceneNavigator.LoadScene(EScene.MainScene)); songsOptionsButton.RegisterCallbackButtonTriggered(() => sceneNavigator.LoadScene(EScene.SongLibraryOptionsScene)); graphicsOptionsButton.RegisterCallbackButtonTriggered(() => sceneNavigator.LoadScene(EScene.OptionsGraphicsScene)); soundOptionsButton.RegisterCallbackButtonTriggered(() => sceneNavigator.LoadScene(EScene.OptionsSoundScene)); recordingOptionsButton.RegisterCallbackButtonTriggered(() => sceneNavigator.LoadScene(EScene.RecordingOptionsScene)); profileOptionsButton.RegisterCallbackButtonTriggered(() => sceneNavigator.LoadScene(EScene.PlayerProfileSetupScene)); designOptionsButton.RegisterCallbackButtonTriggered(() => sceneNavigator.LoadScene(EScene.ThemeOptionsScene)); internetOptionsButton.RegisterCallbackButtonTriggered(() => sceneNavigator.LoadScene(EScene.NetworkOptionsScene)); appOptionsButton.RegisterCallbackButtonTriggered(() => sceneNavigator.LoadScene(EScene.CompanionAppOptionsScene)); developerOptionsButton.RegisterCallbackButtonTriggered(() => sceneNavigator.LoadScene(EScene.DevelopmentOptionsScene)); InitLanguageChooser(); InputManager.GetInputAction(R.InputActions.usplay_back).PerformedAsObservable(5) .Subscribe(_ => sceneNavigator.LoadScene(EScene.MainScene)); } private void InitLanguageChooser() { new LabeledItemPickerControl<SystemLanguage>( languageChooser, translationManager.GetTranslatedLanguages()) .Bind(() => translationManager.currentLanguage, newValue => SetLanguage(newValue)); } public void UpdateTranslation() { if (!Application.isPlaying && backButton == null) { SceneInjectionManager.Instance.DoInjection(); } sceneTitle.text = TranslationManager.GetTranslation(R.Messages.options); backButton.Q<Label>().text = TranslationManager.GetTranslation(R.Messages.back); gameOptionsButton.Q<Label>().text = TranslationManager.GetTranslation(R.Messages.options_game_button); songsOptionsButton.Q<Label>().text = TranslationManager.GetTranslation(R.Messages.options_songLibrary_button); soundOptionsButton.Q<Label>().text = TranslationManager.GetTranslation(R.Messages.options_sound_button); graphicsOptionsButton.Q<Label>().text = TranslationManager.GetTranslation(R.Messages.options_graphics_button); recordingOptionsButton.Q<Label>().text = TranslationManager.GetTranslation(R.Messages.options_recording_button); profileOptionsButton.Q<Label>().text = TranslationManager.GetTranslation(R.Messages.options_playerProfiles_button); designOptionsButton.Q<Label>().text = TranslationManager.GetTranslation(R.Messages.options_design_button); internetOptionsButton.Q<Label>().text = TranslationManager.GetTranslation(R.Messages.options_internet_button); appOptionsButton.Q<Label>().text = TranslationManager.GetTranslation(R.Messages.options_companionApp_button); developerOptionsButton.Q<Label>().text = TranslationManager.GetTranslation(R.Messages.options_development_button); } private void SetLanguage(SystemLanguage newValue) { settings.GameSettings.language = newValue; translationManager.currentLanguage = settings.GameSettings.language; translationManager.ReloadTranslationsAndUpdateScene(); } }
44.560976
127
0.759898
[ "MIT" ]
achimmihca/Play
UltraStar Play/Assets/Scenes/Options/OptionsOverview/OptionsOverviewSceneControl.cs
5,481
C#
using products_api.Dtos; using products_api.Models; namespace products_api.Data.Repository { public interface IBackMaterialRepository : IRepository<BackMaterial> { } }
18.2
72
0.769231
[ "MIT" ]
saqibrazzaq/SalesSystem
src/services/products-api/Data/Repository/IBackMaterialRepository.cs
184
C#
//----------------------------------------------------------------------- // <copyright file="SynchronizationContextSwitcher.cs" company="Akka.NET Project"> // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Threading; using System.Threading.Tasks; namespace Nito.AsyncEx { /// <summary> /// Utility class for temporarily switching <see cref="SynchronizationContext"/> implementations. /// </summary> public sealed class SynchronizationContextSwitcher : Disposables.SingleDisposable<object> { /// <summary> /// The previous <see cref="SynchronizationContext"/>. /// </summary> private readonly SynchronizationContext _oldContext; /// <summary> /// Initializes a new instance of the <see cref="SynchronizationContextSwitcher"/> class, installing the new <see cref="SynchronizationContext"/>. /// </summary> /// <param name="newContext">The new <see cref="SynchronizationContext"/>. This can be <c>null</c> to remove an existing <see cref="SynchronizationContext"/>.</param> public SynchronizationContextSwitcher(SynchronizationContext newContext) : base(new object()) { _oldContext = SynchronizationContext.Current; SynchronizationContext.SetSynchronizationContext(newContext); } /// <summary> /// Restores the old <see cref="SynchronizationContext"/>. /// </summary> protected override void Dispose(object context) { SynchronizationContext.SetSynchronizationContext(_oldContext); } /// <summary> /// Executes a synchronous delegate without the current <see cref="SynchronizationContext"/>. The current context is restored when this function returns. /// </summary> /// <param name="action">The delegate to execute.</param> public static void NoContext(Action action) { using (new SynchronizationContextSwitcher(null)) action(); } /// <summary> /// Executes an asynchronous delegate without the current <see cref="SynchronizationContext"/>. The current context is restored when this function returns its task. /// </summary> /// <param name="action">The delegate to execute.</param> public static Task NoContextAsync(Func<Task> action) { using (new SynchronizationContextSwitcher(null)) return action(); } } }
42.484375
174
0.613829
[ "Apache-2.0" ]
Aaronontheweb/akka.net
src/core/Akka.Tests.Shared.Internals/AsyncContext/SynchronizationContextSwitcher.cs
2,721
C#
using System; using System.Net.Http; using System.Threading.Tasks; using Microsoft.Azure.EventGrid.Models; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.EventGrid; using Microsoft.Extensions.Logging; namespace CollectCurrentWeather { public static class Collector { // HttpClient is intended to be instantiated once per application, rather than per-use private static HttpClient httpClient = new HttpClient(); [FunctionName("Collector")] [return: EventGrid(TopicEndpointUri = "WeatherDataTopicUri", TopicKeySetting = "WeatherDataTopicKey")] public static async Task<EventGridEvent> Run([TimerTrigger("*/30 * * * * *")] TimerInfo myTimer, ILogger log) { var response = await httpClient.GetAsync("https://emulatorfunctionapp98f3eeca.azurewebsites.net/api/getstationdata?device_Id=70:ee:50:1b:26:ac&code=K3fQDcXMFOSPKGV1DM8JCzvmtyQtx6C4CG4Ba6Xe1rpN9higlU5S3Q=="); return new EventGridEvent(Guid.NewGuid().ToString(), "weather", await response.Content.ReadAsStringAsync(), "devopenspace.serverless.weather", DateTime.UtcNow, "1.0"); } } }
46.2
219
0.739394
[ "MIT" ]
whiteducksoftware/ServerlessCloudNativeWorkshop
Exercises/Challenge-2-Event-Grid/Final/Collector.cs
1,155
C#
// Copyright 2016 Esri // // 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 System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Windows; namespace DistanceAndDirectionLibrary.Helpers { public static class DialogCloser { public static readonly DependencyProperty DialogResultProperty = DependencyProperty.RegisterAttached( "DialogResult", typeof(bool?), typeof(DialogCloser), new PropertyMetadata(DialogResultChanged)); private static void DialogResultChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { var window = d as Window; if (window != null) window.DialogResult = e.NewValue as bool?; } public static void SetDialogResult(Window target, bool? value) { target.SetValue(DialogResultProperty, value); } } /// <summary> /// Monitors the PropertyChanged event of an object that implements INotifyPropertyChanged, /// and executes callback methods (i.e. handlers) registered for properties of that object. /// </summary> /// <typeparam name="TPropertySource">The type of object to monitor for property changes.</typeparam> public class PropertyObserver<TPropertySource> : IWeakEventListener where TPropertySource : INotifyPropertyChanged { #region Constructor /// <summary> /// Initializes a new instance of PropertyObserver, which /// observes the 'propertySource' object for property changes. /// </summary> /// <param name="propertySource">The object to monitor for property changes.</param> public PropertyObserver(TPropertySource propertySource) { if (propertySource == null) throw new ArgumentNullException("propertySource"); _propertySourceRef = new WeakReference(propertySource); _propertyNameToHandlerMap = new Dictionary<string, Action<TPropertySource>>(); } #endregion // Constructor #region Public Methods #region RegisterHandler /// <summary> /// Registers a callback to be invoked when the PropertyChanged event has been raised for the specified property. /// </summary> /// <param name="expression">A lambda expression like 'n => n.PropertyName'.</param> /// <param name="handler">The callback to invoke when the property has changed.</param> /// <returns>The object on which this method was invoked, to allow for multiple invocations chained together.</returns> public PropertyObserver<TPropertySource> RegisterHandler( Expression<Func<TPropertySource, object>> expression, Action<TPropertySource> handler) { if (expression == null) throw new ArgumentNullException("expression"); string propertyName = GetPropertyName(expression); if (String.IsNullOrEmpty(propertyName)) throw new ArgumentException("'expression' did not provide a property name."); if (handler == null) throw new ArgumentNullException("handler"); TPropertySource propertySource = this.GetPropertySource(); if (propertySource != null) { Debug.Assert(!_propertyNameToHandlerMap.ContainsKey(propertyName), "Why is the '" + propertyName + "' property being registered again?"); _propertyNameToHandlerMap[propertyName] = handler; PropertyChangedEventManager.AddListener(propertySource, this, propertyName); } return this; } #endregion // RegisterHandler #region UnregisterHandler /// <summary> /// Removes the callback associated with the specified property. /// </summary> /// <param name="propertyName">A lambda expression like 'n => n.PropertyName'.</param> /// <returns>The object on which this method was invoked, to allow for multiple invocations chained together.</returns> public PropertyObserver<TPropertySource> UnregisterHandler(Expression<Func<TPropertySource, object>> expression) { if (expression == null) throw new ArgumentNullException("expression"); string propertyName = GetPropertyName(expression); if (String.IsNullOrEmpty(propertyName)) throw new ArgumentException("'expression' did not provide a property name."); TPropertySource propertySource = this.GetPropertySource(); if (propertySource != null) { if (_propertyNameToHandlerMap.ContainsKey(propertyName)) { _propertyNameToHandlerMap.Remove(propertyName); PropertyChangedEventManager.RemoveListener(propertySource, this, propertyName); } } return this; } #endregion // UnregisterHandler #endregion // Public Methods #region IWeakEventListener Members bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e) { bool handled = false; if (managerType == typeof(PropertyChangedEventManager)) { PropertyChangedEventArgs args = e as PropertyChangedEventArgs; if (args != null && sender is TPropertySource) { string propertyName = args.PropertyName; TPropertySource propertySource = (TPropertySource)sender; if (String.IsNullOrEmpty(propertyName)) { // When the property name is empty, all properties are considered to be invalidated. // Iterate over a copy of the list of handlers, in case a handler is registered by a callback. foreach (Action<TPropertySource> handler in _propertyNameToHandlerMap.Values.ToArray()) handler(propertySource); handled = true; } else { Action<TPropertySource> handler; if (_propertyNameToHandlerMap.TryGetValue(propertyName, out handler)) { handler(propertySource); handled = true; } } } } return handled; } #endregion // IWeakEventListener Members #region Private Helpers #region GetPropertyName static string GetPropertyName(Expression<Func<TPropertySource, object>> expression) { var lambda = expression as LambdaExpression; MemberExpression memberExpression; if (lambda.Body is UnaryExpression) { var unaryExpression = lambda.Body as UnaryExpression; memberExpression = unaryExpression.Operand as MemberExpression; } else { memberExpression = lambda.Body as MemberExpression; } Debug.Assert(memberExpression != null, "Please provide a lambda expression like 'n => n.PropertyName'"); if (memberExpression != null) { var propertyInfo = memberExpression.Member as PropertyInfo; return propertyInfo.Name; } return null; } #endregion // GetPropertyName #region GetPropertySource TPropertySource GetPropertySource() { try { return (TPropertySource)_propertySourceRef.Target; } catch { return default(TPropertySource); } } #endregion // GetPropertySource #endregion // Private Helpers #region Fields readonly Dictionary<string, Action<TPropertySource>> _propertyNameToHandlerMap; readonly WeakReference _propertySourceRef; #endregion // Fields } }
36.680328
153
0.605922
[ "Apache-2.0" ]
rjones0/distance-direction-addin-dotnet
source/DistanceAndDirection/DistanceAndDirectionLibrary/Helpers/Wpf.cs
8,952
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** 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.Azure.Media.Inputs { public sealed class StreamingLocatorContentKeyArgs : Pulumi.ResourceArgs { /// <summary> /// ID of Content Key. Changing this forces a new Streaming Locator to be created. /// </summary> [Input("contentKeyId")] public Input<string>? ContentKeyId { get; set; } /// <summary> /// Label of Content Key as specified in the Streaming Policy. Changing this forces a new Streaming Locator to be created. /// </summary> [Input("labelReferenceInStreamingPolicy")] public Input<string>? LabelReferenceInStreamingPolicy { get; set; } /// <summary> /// Content Key Policy used by Content Key. Changing this forces a new Streaming Locator to be created. /// </summary> [Input("policyName")] public Input<string>? PolicyName { get; set; } /// <summary> /// Encryption type of Content Key. Supported values are `CommonEncryptionCbcs`, `CommonEncryptionCenc` or `EnvelopeEncryption`. Changing this forces a new Streaming Locator to be created. /// </summary> [Input("type")] public Input<string>? Type { get; set; } /// <summary> /// Value of Content Key. Changing this forces a new Streaming Locator to be created. /// </summary> [Input("value")] public Input<string>? Value { get; set; } public StreamingLocatorContentKeyArgs() { } } }
36.34
196
0.640066
[ "ECL-2.0", "Apache-2.0" ]
ScriptBox99/pulumi-azure
sdk/dotnet/Media/Inputs/StreamingLocatorContentKeyArgs.cs
1,817
C#
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Rapidity.Http.Configurations; using Rapidity.Http.Serializes; using System; using System.Linq; using Rapidity.Http.Attributes; using System.Reflection; using Rapidity.Http.DynamicProxies; namespace Rapidity.Http.Extensions { /// <summary> /// /// </summary> public static class RapidityHttpExtension { public static IServiceCollection UseRapidityHttp(this IServiceCollection services) { services.TryAddTransient<IJsonContentSerializer, NewtonsoftJsonSerializer>(); services.TryAddTransient<IXmlContentSerializer, XmlContentSerializer>(); services.TryAddTransient(typeof(Lazy<>)); services.AddTransient<IHttpClientWrapper, HttpClientWrapper>() .AddTransient<IRequestBuilderFactory, RequestBuilderFactory>() .AddTransient<IResponseResolverFactory, ResponseResolverFactory>() .AddTransient<DefaultHttpRequestBuilder>() .AddTransient<JsonResponseResolver>() .AddTransient<XmlResponseResolver>() .AddTransient<IUriGenerator, UriGenerator>() .AddTransient<IRequestHeaderSetter, RequestHeaderSetter>() .AddTransient<IHttpContentGenerator, HttpContentGenerator>() .AddSingleton<IRequestDescriptionBuilder, DefaultRequestDescriptionBuilder>() .AddTransient<IRetryPolicyProcessor, DefaultRetryPolicyProcessor>() .AddTransient<IInvokeRecordStore, NullInvokeRecordStore>(); services.AddHttpClient(); return services; } /// <summary> /// 获取服务配置(如未初始化则先初始化) /// </summary> /// <param name="services"></param> /// <returns></returns> public static IHttpServiceConfiguration ServiceConfigure(this IServiceCollection services) { var configuration = (IHttpServiceConfiguration)services .FirstOrDefault(x => x.ServiceType == typeof(IHttpServiceConfiguration))?.ImplementationInstance; if (configuration == null) { configuration = new HttpServiceConfiguration(); services.AddSingleton(configuration); } return configuration; } /// <summary> /// 添加服务配置,并添加对应的httpClient /// </summary> /// <param name="services"></param> /// <param name="configure"></param> /// <returns></returns> public static HttpServiceConfigure AddService(this IServiceCollection services, HttpServiceConfigure configure) { var configuration = services.ServiceConfigure(); var config = configuration.AddConfigure(configure); services.AddHttpClient(configure.ServiceName, client => { //设置默认baseAddress if (!string.IsNullOrEmpty(config.BaseAddress)) client.BaseAddress = new Uri(config.BaseAddress, UriKind.Absolute); //设置默认headers if (config.Item.DefaultHeaders.Count > 0) { foreach (var key in config.Item.DefaultHeaders.AllKeys) client.DefaultRequestHeaders.Add(key, config.Item.DefaultHeaders.Get(key)); } //设置请求超时时间(默认30秒) client.Timeout = TimeSpan.FromSeconds(config.Timeout > 0 ? config.Timeout : 30); }); services.Replace(ServiceDescriptor.Singleton(configuration)); return config; } /// <summary> /// /// </summary> /// <param name="services"></param> /// <param name="name"></param> /// <returns></returns> public static HttpServiceConfigure AddService(this IServiceCollection services, string name) { var configure = new HttpServiceConfigure { ServiceName = name }; return services.AddService(configure); } /// <summary> /// /// </summary> /// <param name="services"></param> /// <param name="name"></param> /// <param name="action"></param> /// <returns></returns> public static HttpServiceConfigure AddService(this IServiceCollection services, string name, Action<HttpServiceConfigure> action) { var configure = new HttpServiceConfigure { ServiceName = name }; action?.Invoke(configure); return services.AddService(configure); } /// <summary> /// 为HttpService创建动态代理 /// </summary> /// <param name="services"></param> /// <returns></returns> public static IServiceCollection BuildProxy(this IServiceCollection services) { var configuration = services.ServiceConfigure(); foreach (var config in configuration) { foreach (var type in config.ForTypes) { if (!type.IsInterface) continue; if (typeof(IHttpService).IsAssignableFrom(type) || (type.GetCustomAttribute<HttpServiceAttribute>()?.GenerateProxy ?? false)) { services.AddSingleton(type, provider => ServiceProxy.Create(type, provider)); } } } return services; } /// <summary> /// /// </summary> /// <typeparam name="TRecordStore"></typeparam> /// <param name="services"></param> /// <returns></returns> public static IServiceCollection ConfigRecordStore<TRecordStore>(this IServiceCollection services) where TRecordStore : IInvokeRecordStore { return services.Replace(ServiceDescriptor.Transient(typeof(IInvokeRecordStore), typeof(TRecordStore))); } } }
39.290323
146
0.591133
[ "MIT" ]
letmego9go/RapidityHttp
src/Extensions/RapidityHttpExtension.cs
6,206
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MonoDroid.Generation { public class GenericSymbol : ISymbol { bool is_concrete; GenBase gen; string [] java_params; string tps; ISymbol [] type_params; public GenericSymbol (GenBase gen, string type_params) { this.gen = gen; java_params = GenericParameterList.Parse (type_params); } public string DefaultValue { get { return "IntPtr.Zero"; } } public string FullName { get { return gen.FullName; } } public GenBase Gen { get { return gen; } } public bool IsConcrete { get { return is_concrete; } } public string JavaName { get { return gen.JavaName; } } public string JniName { get { return gen.JniName; } } public string NativeType { get { return "IntPtr"; } } public bool IsEnum { get { return false; } } public bool IsArray { get { return false; } } public string ElementType { get { return null; } } public ISymbol [] TypeParams { get { return type_params; } } public string ReturnCast => string.Empty; public string GetObjectHandleProperty (CodeGenerationOptions opt, string variable) { return gen.GetObjectHandleProperty (opt, variable); } string MapTypeParams (Dictionary<string, string> mappings) { StringBuilder sb = new StringBuilder (); sb.Append ("<"); foreach (var tp in type_params) { if (sb.Length > 1) sb.Append (", "); if (mappings.ContainsKey (tp.FullName)) sb.Append (mappings[tp.FullName]); else sb.Append (tp.FullName); } sb.Append (">"); return sb.ToString (); } public string FromNative (CodeGenerationOptions opt, string varname, bool owned) { return gen.FromNative (opt, varname, owned); } public string GetGenericType (Dictionary<string, string> mappings) { var rgm = gen as IRequireGenericMarshal; return gen.FullName + (rgm != null && !rgm.MayHaveManagedGenericArguments ? null : mappings == null ? tps : MapTypeParams (mappings)); } public string ToNative (CodeGenerationOptions opt, string varname) { return gen.ToNative (opt, varname); } public string ToNative (CodeGenerationOptions opt, string varname, Dictionary<string, string> mappings) { return varname; } public bool Validate (CodeGenerationOptions opt, GenericParameterDefinitionList in_params, CodeGeneratorContext context) { if (!gen.Validate (opt, in_params, context)) return false; is_concrete = true; type_params = new ISymbol [java_params.Length]; for (int i = 0; i < java_params.Length; i++) { string tp = java_params [i]; var gpd = in_params != null ? in_params.FirstOrDefault (t => t.Name == tp) : null; if (gpd != null) { type_params [i] = new GenericTypeParameter (gpd); is_concrete = false; continue; } else if (tp == "?") { if (in_params != null && in_params.Count == 1) { type_params [i] = new GenericTypeParameter (in_params [0]); is_concrete = false; } else type_params [i] = new SimpleSymbol ("null", "java.lang.Object", "object", "Ljava/lang/Object;"); continue; } ISymbol psym = opt.SymbolTable.Lookup (tp, in_params); if (psym == null || !psym.Validate (opt, in_params, context)) return false; if (psym is GenericSymbol && !(psym as GenericSymbol).IsConcrete) is_concrete = false; type_params [i] = /*psym is IGeneric ? (psym as IGeneric).GetGenericType (null) : psym.FullName*/ psym; } tps = type_params == null ? null : "<" + String.Join (", ", (from tp in type_params select tp.FullName).ToArray ()) + ">"; return true; } public string[] PreCallback (CodeGenerationOptions opt, string var_name, bool owned) { return gen.PreCallback (opt, var_name, owned); } public string[] PostCallback (CodeGenerationOptions opt, string var_name) { return gen.PostCallback (opt, var_name); } public string[] PreCall (CodeGenerationOptions opt, string var_name) { return gen.PreCall (opt, var_name); } public string Call (CodeGenerationOptions opt, string var_name) { return gen.Call (opt, var_name); } public string[] PostCall (CodeGenerationOptions opt, string var_name) { return gen.PostCall (opt, var_name); } public bool NeedsPrep { get { return true; } } } }
25.091954
137
0.66743
[ "MIT" ]
Wivra/java.interop
tools/generator/Java.Interop.Tools.Generator.ObjectModel/Symbols/GenericSymbol.cs
4,366
C#
using System; using TS3QueryLib.Net.Core.Common; using TS3QueryLib.Net.Core.Common.CommandHandling; using TS3QueryLib.Net.Core.Common.Entities; namespace TS3QueryLib.Net.Core.Server.Entitities { public abstract class ChannelListEntryBase : IDump { #region Non Public Members private bool _spacerInfoChecked; private SpacerInfo _spacerInfo; #endregion #region Properties #region Always returned Properties public uint ChannelId { get; protected set; } public uint ParentChannelId { get; protected set; } public uint Order { get; protected set; } public string Name { get; protected set; } public int TotalClients { get; protected set; } public bool IsSpacer { get { return SpacerInfo != null; } } public SpacerInfo SpacerInfo { get { if (_spacerInfoChecked) return _spacerInfo; _spacerInfoChecked = true; _spacerInfo = SpacerInfo.Parse(Name); return _spacerInfo; } } #endregion #region Topic-Properties public string Topic { get; protected set; } #endregion #region Flags-Properties public bool? IsDefaultChannel { get; protected set; } public bool? IsPasswordProtected { get; protected set; } public bool? IsPermanent { get; protected set; } public bool? IsSemiPermanent { get; protected set; } #endregion #region Voice-Properties public ushort? Codec { get; protected set; } public double? CodecQuality { get; protected set; } public uint? NeededTalkPower { get; protected set; } #endregion #region Limits-Properties public int? MaxClients { get; protected set; } public int? MaxFamilyClients { get; protected set; } #endregion #region Icon-Properties public uint? ChannelIconId { get; protected set; } #endregion #endregion #region Public Methods protected void ApplyFrom(CommandParameterGroup currrentParameterGroup, CommandParameterGroup firstParameterGroup) { if (currrentParameterGroup == null) throw new ArgumentNullException(nameof(currrentParameterGroup)); ChannelId = currrentParameterGroup.GetParameterValue<uint>("cid"); ParentChannelId = currrentParameterGroup.GetParameterValue<uint>("pid"); Order = currrentParameterGroup.GetParameterValue<uint>("channel_order"); Name = currrentParameterGroup.GetParameterValue("channel_name"); TotalClients = currrentParameterGroup.GetParameterValue<int>("total_clients"); Topic = currrentParameterGroup.GetParameterValue("channel_topic"); IsDefaultChannel = currrentParameterGroup.GetParameterValue<byte?>("channel_flag_default").ToNullableBool(); IsPasswordProtected = currrentParameterGroup.GetParameterValue<byte?>("channel_flag_password").ToNullableBool(); IsPermanent = currrentParameterGroup.GetParameterValue<byte?>("channel_flag_permanent").ToNullableBool(); IsSemiPermanent = currrentParameterGroup.GetParameterValue<byte?>("channel_flag_semi_permanent").ToNullableBool(); Codec = currrentParameterGroup.GetParameterValue<ushort?>("channel_codec"); CodecQuality = currrentParameterGroup.GetParameterValue<double?>("channel_codec_quality"); NeededTalkPower = currrentParameterGroup.GetParameterValue<uint?>("channel_needed_talk_power"); MaxClients = currrentParameterGroup.GetParameterValue<int?>("channel_maxclients"); MaxFamilyClients = currrentParameterGroup.GetParameterValue<int?>("channel_maxfamilyclients"); ChannelIconId = currrentParameterGroup.GetParameterValue<uint?>("channel_icon_id"); } #endregion } }
35.442478
126
0.667416
[ "MIT" ]
Pandry/TS3QueryLib.Net.Core
TS3QueryLib.Net.Core/Server/Entitities/ChannelListEntryBase.cs
4,007
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 Microsoft.Spark.Interop.Ipc; using Microsoft.Spark.Sql.Expressions; namespace Microsoft.Spark.Sql { /// <summary> /// Column class represents a column that will be computed based on the data in a DataFrame. /// </summary> public sealed class Column : IJvmObjectReferenceProvider { private readonly JvmObjectReference _jvmObject; /// <summary> /// Constructor for Column class. /// </summary> /// <param name="jvmObject">JVM object reference</param> internal Column(JvmObjectReference jvmObject) { _jvmObject = jvmObject; } JvmObjectReference IJvmObjectReferenceProvider.Reference => _jvmObject; /// <summary> /// Negate the given column. /// </summary> /// <param name="self">Column to negate</param> /// <returns>New column after applying negation</returns> public static Column operator -(Column self) { return ApplyFunction(self, "negate"); } /// <summary> /// Apply inversion of boolean expression, i.e. NOT. /// </summary> /// <param name="self">Column to apply inversion</param> /// <returns>New column after applying inversion</returns> public static Column operator !(Column self) { return ApplyFunction(self, "not"); } /// <summary> /// Apply equality test on the given two columns. /// </summary> /// <param name="lhs">Column on the left side of equality test</param> /// <param name="rhs">Column on the right side of equality test</param> /// <returns>New column after applying equality test</returns> public static Column operator ==(Column lhs, object rhs) { return lhs.EqualTo(rhs); } /// <summary> /// Equality test. /// </summary> /// <param name="rhs">The right hand side of expression being tested for equality</param> /// <returns>New column after applying the equal to operator</returns> public Column EqualTo(object rhs) { return Apply("equalTo", rhs); } /// <summary> /// Apply inequality test. /// </summary> /// <param name="lhs">Column on the left side of inequality test</param> /// <param name="rhs">Column on the right side of inequality test</param> /// <returns>New column after applying inequality test</returns> public static Column operator !=(Column lhs, object rhs) { return lhs.NotEqual(rhs); } /// <summary> /// Inequality test. /// </summary> /// <param name="rhs"> /// The right hand side of expression being tested for inequality. /// </param> /// <returns>New column after applying not equal operator</returns> public Column NotEqual(object rhs) { return Apply("notEqual", rhs); } /// <summary> /// Apply "greater than" operator for the given two columns. /// </summary> /// <param name="lhs">Column on the left side of the operator</param> /// <param name="rhs">Column on the right side of the operator</param> /// <returns>New column after applying the operator</returns> public static Column operator >(Column lhs, object rhs) { return lhs.Gt(rhs); } /// <summary> /// Greater than. /// </summary> /// <param name="rhs"> /// The object that is in comparison to test if the left hand side is greater. /// </param> /// <returns>New column after applying the greater than operator</returns> public Column Gt(object rhs) { return Apply("gt", rhs); } /// <summary> /// Apply "less than" operator for the given two columns. /// </summary> /// <param name="lhs">Column on the left side of the operator</param> /// <param name="rhs">Column on the right side of the operator</param> /// <returns>New column after applying the operator</returns> public static Column operator <(Column lhs, object rhs) { return lhs.Lt(rhs); } /// <summary> /// Less than. /// </summary> /// <param name="rhs"> /// The object that is in comparison to test if the left hand side is lesser. /// </param> /// <returns>New column after applying the less than operator</returns> public Column Lt(object rhs) { return Apply("lt", rhs); } /// <summary> /// Apply "less than or equal to" operator for the given two columns. /// </summary> /// <param name="lhs">Column on the left side of the operator</param> /// <param name="rhs">Column on the right side of the operator</param> /// <returns>New column after applying the operator</returns> public static Column operator <=(Column lhs, object rhs) { return lhs.Leq(rhs); } /// <summary> /// Less than or equal to. /// </summary> /// <param name="rhs"> /// The object that is in comparison to test if the left hand side is less or equal to. /// </param> /// <returns>New column after applying the less than or equal to operator</returns> public Column Leq(object rhs) { return Apply("leq", rhs); } /// <summary> /// Apply "greater than or equal to" operator for the given two columns. /// </summary> /// <param name="lhs">Column on the left side of the operator</param> /// <param name="rhs">Column on the right side of the operator</param> /// <returns>New column after applying the operator</returns> public static Column operator >=(Column lhs, object rhs) { return lhs.Geq(rhs); } /// <summary> /// Greater or equal to. /// </summary> /// <param name="rhs"> /// The object that is in comparison to test if the left hand side is greater or equal to /// </param> /// <returns>New column after applying the greater or equal to operator</returns> public Column Geq(object rhs) { return Apply("geq", rhs); } /// <summary> /// Apply equality test that is safe for null values. /// </summary> /// <param name="obj">Object to apply equality test</param> /// <returns>New column after applying the equality test</returns> public Column EqNullSafe(object obj) { return Apply("eqNullSafe", obj); } /// <summary> /// Evaluates a condition and returns one of multiple possible result expressions. /// If Otherwise(object) is not defined at the end, null is returned for /// unmatched conditions. This method can be chained with other 'when' invocations in case /// multiple matches are required. /// </summary> /// <param name="condition">The condition to check</param> /// <param name="value">The value to set if the condition is true</param> /// <returns>New column after applying the when method</returns> public Column When(Column condition, object value) { return Apply("when", condition, value); } /// <summary> /// Evaluates a list of conditions and returns one of multiple possible result expressions. /// If otherwise is not defined at the end, null is returned for unmatched conditions. /// This is used when the When(Column, object) method is applied. /// </summary> /// <param name="value">The value to set</param> /// <returns>New column after applying otherwise method</returns> public Column Otherwise(object value) { return Apply("otherwise", value); } /// <summary> /// True if the current column is between the lower bound and upper bound, inclusive. /// </summary> /// <param name="lowerBound">The lower bound</param> /// <param name="upperBound">The upper bound</param> /// <returns>New column after applying the between method</returns> public Column Between(object lowerBound, object upperBound) { return Apply("between", lowerBound, upperBound); } /// <summary> /// True if the current expression is NaN. /// </summary> /// <returns> /// New column with values true if the preceding column had a NaN /// value in the same index, and false otherwise. /// </returns> public Column IsNaN() { return Apply("isNaN"); } /// <summary> /// True if the current expression is null. /// </summary> /// <returns> /// New column with values true if the preceding column had a null /// value in the same index, and false otherwise. /// </returns> public Column IsNull() { return Apply("isNull"); } /// <summary> /// True if the current expression is NOT null. /// </summary> /// <returns> /// New column with values true if the preceding column had a non-null /// value in the same index, and false otherwise. /// </returns> public Column IsNotNull() { return Apply("isNotNull"); } /// <summary> /// Apply boolean OR operator for the given two columns. /// </summary> /// <param name="lhs">Column on the left side of the operator</param> /// <param name="rhs">Column on the right side of the operator</param> /// <returns>New column after applying the operator</returns> public static Column operator |(Column lhs, Column rhs) { // Check the comment for operator & why rhs is Column instead of object. return lhs.Or(rhs); } /// <summary> /// Apply boolean OR operator with the given column. /// </summary> /// <param name="other">Column to apply OR operator</param> /// <returns>New column after applying the operator</returns> public Column Or(Column other) { return Apply("or", other); } /// <summary> /// Apply boolean AND operator for the given two columns. /// </summary> /// <param name="lhs">Column on the left side of the operator</param> /// <param name="rhs">Column on the right side of the operator</param> /// <returns>New column after applying the operator</returns> public static Column operator &(Column lhs, Column rhs) { // Note that in Spark, && is overloaded which takes "Any" for the rhs. // Since the overloaded operator on JVM cannot be reflected/called, // this is calling "and" instead, which takes in "Column" for the rhs. return lhs.And(rhs); } /// <summary> /// Apply boolean AND operator with the given column. /// </summary> /// <param name="other">Column to apply AND operator</param> /// <returns>New column after applying the operator</returns> public Column And(Column other) { return Apply("and", other); } /// <summary> /// Apply sum of two expressions. /// </summary> /// <param name="lhs">Column on the left side of the operator</param> /// <param name="rhs">Object on the right side of the operator</param> /// <returns>New column after applying the sum operation</returns> public static Column operator +(Column lhs, object rhs) { return lhs.Plus(rhs); } /// <summary> /// Sum of this expression and another expression. /// </summary> /// <param name="rhs">The expression to be summed with</param> /// <returns>New column after applying the plus operator</returns> public Column Plus(object rhs) { return Apply("plus", rhs); } /// <summary> /// Apply subtraction of two expressions. /// </summary> /// <param name="lhs">Column on the left side of the operator</param> /// <param name="rhs">Object on the right side of the operator</param> /// <returns>New column after applying the subtraction operation</returns> public static Column operator -(Column lhs, object rhs) { return lhs.Minus(rhs); } /// <summary> /// Subtraction. Subtract the other expression from this expression. /// </summary> /// <param name="rhs">The expression to be subtracted with</param> /// <returns>New column after applying the minus operator</returns> public Column Minus(object rhs) { return Apply("minus", rhs); } /// <summary> /// Apply multiplication of two expressions. /// </summary> /// <param name="lhs">Column on the left side of the operator</param> /// <param name="rhs">Object on the right side of the operator</param> /// <returns>New column after applying the multiplication operation</returns> public static Column operator *(Column lhs, object rhs) { return lhs.Multiply(rhs); } /// <summary> /// Multiplication of this expression and another expression. /// </summary> /// <param name="rhs">The expression to be multiplied with</param> /// <returns>New column after applying the multiply operator</returns> public Column Multiply(object rhs) { return Apply("multiply", rhs); } /// <summary> /// Apply division of two expressions. /// </summary> /// <param name="lhs">Column on the left side of the operator</param> /// <param name="rhs">Object on the right side of the operator</param> /// <returns>New column after applying the division operation</returns> public static Column operator /(Column lhs, object rhs) { return lhs.Divide(rhs); } /// <summary> /// Division of this expression by another expression. /// </summary> /// <param name="rhs">The expression to be divided by</param> /// <returns>New column after applying the divide operator</returns> public Column Divide(object rhs) { return Apply("divide", rhs); } /// <summary> /// Apply division of two expressions. /// </summary> /// <param name="lhs">Column on the left side of the operator</param> /// <param name="rhs">Object on the right side of the operator</param> /// <returns>New column after applying the division operation</returns> public static Column operator %(Column lhs, object rhs) { return lhs.Mod(rhs); } /// <summary> /// Modulo (a.k.a remainder) expression. /// </summary> /// <param name="rhs"> /// The expression to be divided by to get the remainder for. /// </param> /// <returns>New column after applying the mod operator</returns> public Column Mod(object rhs) { return Apply("mod", rhs); } /// <summary> /// SQL like expression. Returns a boolean column based on a SQL LIKE match. /// </summary> /// <param name="literal">The literal that is used to compute the SQL LIKE match</param> /// <returns>New column after applying the SQL LIKE match</returns> public Column Like(string literal) { return Apply("like", literal); } /// <summary> /// SQL RLIKE expression (LIKE with Regex). Returns a boolean column based on a regex /// match. /// </summary> /// <param name="literal">The literal that is used to compute the Regex match</param> /// <returns>New column after applying the regex LIKE method</returns> public Column RLike(string literal) { return Apply("rlike", literal); } /// <summary> /// An expression that gets an item at position `ordinal` out of an array, /// or gets a value by key `key` in a `MapType`. /// </summary> /// <param name="key">The key with which to identify the item</param> /// <returns>New column after getting an item given a specific key</returns> public Column GetItem(object key) { return Apply("getItem", key); } /// <summary> /// An expression that gets a field by name in a `StructType`. /// </summary> /// <param name="fieldName">The name of the field</param> /// <returns>New column after getting a field for a specific key</returns> public Column GetField(string fieldName) { return Apply("getField", fieldName); } /// <summary> /// An expression that returns a substring. /// </summary> /// <param name="startPos">Expression for the starting position</param> /// <param name="len">Expression for the length of the substring</param> /// <returns> /// New column that is bound by the start position provided, and the length. /// </returns> public Column SubStr(Column startPos, Column len) { return Apply("substr", startPos, len); } /// <summary> /// An expression that returns a substring. /// </summary> /// <param name="startPos">Starting position</param> /// <param name="len">Length of the substring</param> /// <returns> /// New column that is bound by the start position provided, and the length. /// </returns> public Column SubStr(int startPos, int len) { return Apply("substr", startPos, len); } /// <summary> /// Contains the other element. Returns a boolean column based on a string match. /// </summary> /// <param name="other"> /// The object that is used to check for existance in the current column. /// </param> /// <returns>New column after checking if the column contains object other</returns> public Column Contains(object other) { return Apply("contains", other); } /// <summary> /// String starts with. Returns a boolean column based on a string match. /// </summary> /// <param name="other"> /// The other column containing strings with which to check how values /// in this column starts. /// </param> /// <returns> /// A boolean column where entries are true if values in the current /// column does indeed start with the values in the given column. /// </returns> public Column StartsWith(Column other) { return Apply("startsWith", other); } /// <summary> /// String starts with another string literal. /// Returns a boolean column based on a string match. /// </summary> /// <param name="literal"> /// The string literal used to check how values in a column starts. /// </param> /// <returns> /// A boolean column where entries are true if values in the current column /// does indeed start with the given string literal. /// </returns> public Column StartsWith(string literal) { return Apply("startsWith", literal); } /// <summary> /// String ends with. Returns a boolean column based on a string match. /// </summary> /// <param name="other"> /// The other column containing strings with which to check how values /// in this column ends. /// </param> /// <returns> /// A boolean column where entries are true if values in the current /// column does indeed end with the values in the given column. /// </returns> public Column EndsWith(Column other) { return Apply("endsWith", other); } /// <summary> /// String ends with another string literal. Returns a boolean column based /// on a string match. /// </summary> /// <param name="literal"> /// The string literal used to check how values in a column ends. /// </param> /// <returns> /// A boolean column where entries are true if values in the current column /// does indeed end with the given string literal. /// </returns> public Column EndsWith(string literal) { return Apply("endsWith", literal); } /// <summary> /// Gives the column an alias. Same as `As()`. /// </summary> /// <param name="alias">The alias that is given</param> /// <returns>New column after applying an alias</returns> public Column Alias(string alias) { return Apply("alias", alias); } /// <summary> /// Gives the column an alias. /// </summary> /// <param name="alias">The alias that is given</param> /// <returns>New column after applying the as alias operator</returns> public Column As(string alias) { return Alias(alias); } /// <summary> /// Assigns the given aliases to the results of a table generating function. /// </summary> /// <param name="alias">A list of aliases</param> /// <returns>Column object</returns> public Column As(IEnumerable<string> alias) { return Apply("as", alias); } /// <summary> /// Gives the column a name (alias). /// </summary> /// <param name="alias">Alias column name</param> /// <returns>Column object</returns> public Column Name(string alias) { return Apply("name", alias); } /// <summary> /// Casts the column to a different data type, using the canonical string /// representation of the type. /// </summary> /// <remarks> /// The supported types are: `string`, `boolean`, `byte`, `short`, `int`, `long`, /// `float`, `double`, `decimal`, `date`, `timestamp`. /// </remarks> /// <param name="to">String version of datatype</param> /// <returns>Column object</returns> public Column Cast(string to) { return Apply("cast", to); } /// <summary> /// Returns a sort expression based on ascending order of the column, /// and null values return before non-null values. /// </summary> /// <returns>New column after applying the descending order operator</returns> public Column Desc() { return Apply("desc"); } /// <summary> /// Returns a sort expression based on the descending order of the column, /// and null values appear before non-null values. /// </summary> /// <returns>Column object</returns> public Column DescNullsFirst() { return Apply("desc_nulls_first"); } /// <summary> /// Returns a sort expression based on the descending order of the column, /// and null values appear after non-null values. /// </summary> /// <returns>Column object</returns> public Column DescNullsLast() { return Apply("desc_nulls_last"); } /// <summary> /// Returns a sort expression based on ascending order of the column. /// </summary> /// <returns>New column after applying the ascending order operator</returns> public Column Asc() { return Apply("asc"); } /// <summary> /// Returns a sort expression based on ascending order of the column, /// and null values return before non-null values. /// </summary> /// <returns></returns> public Column AscNullsFirst() { return Apply("asc_nulls_first"); } /// <summary> /// Returns a sort expression based on ascending order of the column, /// and null values appear after non-null values. /// </summary> /// <returns></returns> public Column AscNullsLast() { return Apply("asc_nulls_last"); } /// <summary> /// Prints the expression to the console for debugging purposes. /// </summary> /// <param name="extended">To print extended version or not</param> public void Explain(bool extended) { Apply("explain", extended); } /// <summary> /// Compute bitwise OR of this expression with another expression. /// </summary> /// <param name="other"> /// The other column that will be used to compute the bitwise OR. /// </param> /// <returns>New column after applying bitwise OR operator</returns> public Column BitwiseOR(object other) { return Apply("bitwiseOR", other); } /// <summary> /// Compute bitwise AND of this expression with another expression. /// </summary> /// <param name="other"> /// The other column that will be used to compute the bitwise AND. /// </param> /// <returns>New column after applying the bitwise AND operator</returns> public Column BitwiseAND(object other) { return Apply("bitwiseAND", other); } /// <summary> /// Compute bitwise XOR of this expression with another expression. /// </summary> /// <param name="other"> /// The other column that will be used to compute the bitwise XOR. /// </param> /// <returns>New column after applying bitwise XOR operator</returns> public Column BitwiseXOR(object other) { return Apply("bitwiseXOR", other); } /// <summary> /// Defines a windowing column. /// </summary> /// <param name="window"> /// A window specification that defines the partitioning, ordering, and frame boundaries. /// </param> /// <returns>Column object</returns> public Column Over(WindowSpec window) { return Apply("over", window); } /// <summary> /// Defines an empty analytic clause. In this case the analytic function is applied /// and presented for all rows in the result set. /// </summary> /// <returns>Column object</returns> public Column Over() { return Apply("over"); } /// <summary> /// Gets the underlying Expression object of the <see cref="Column"/>. /// </summary> internal JvmObjectReference Expr() { return (JvmObjectReference)_jvmObject.Invoke("expr"); } // Equals() and GetHashCode() are required to be defined when operator==/!= // are overloaded. /// <summary> /// Checks if the given object is equal to this object. /// </summary> /// <param name="obj">Object to compare to</param> /// <returns>True if the given object is equal to this object</returns> public override bool Equals(object obj) { if (obj is null) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj is Column other && this._jvmObject.Equals(other._jvmObject); } /// <summary> /// Calculates the hash code for this object. /// </summary> /// <returns>Hash code for this object</returns> public override int GetHashCode() => _jvmObject.GetHashCode(); /// <summary> /// Invokes a method under "org.apache.spark.sql.functions" with the given column. /// </summary> /// <param name="column">Column to apply function</param> /// <param name="name">Name of the function</param> /// <returns>New column after applying the function</returns> private static Column ApplyFunction(Column column, string name) { return new Column( (JvmObjectReference)column._jvmObject.Jvm.CallStaticJavaMethod( "org.apache.spark.sql.functions", name, column)); } /// <summary> /// Invokes an operator (method name) with the current column. /// </summary> /// <param name="op">Operator to invoke</param> /// <returns>New column after applying the operator</returns> private Column Apply(string op) { return new Column((JvmObjectReference)_jvmObject.Invoke(op)); } /// <summary> /// Invokes an operator (method name) with the current column with other object. /// </summary> /// <param name="op">Operator to invoke</param> /// <param name="other">Object to apply the operator with</param> /// <returns>New column after applying the operator</returns> private Column Apply(string op, object other) { return new Column((JvmObjectReference)_jvmObject.Invoke(op, other)); } /// <summary> /// Invokes a method name with the current column with two other objects as parameters. /// </summary> /// <param name="op">Method to invoke</param> /// <param name="other1">Object to apply the method with</param> /// <param name="other2">Object to apply the method with</param> /// <returns>New column after applying the operator</returns> private Column Apply(string op, object other1, object other2) { return new Column((JvmObjectReference)_jvmObject.Invoke(op, other1, other2)); } } }
37.233173
99
0.562464
[ "MIT" ]
HuangHuiAAA/doNetSpark
src/csharp/Microsoft.Spark/Sql/Column.cs
30,978
C#
using AutoMapper; using PeopleSearch.Application.Common.Behaviours; using MediatR; using Microsoft.Extensions.DependencyInjection; using System.Reflection; namespace PeopleSearch.Application { public static class DependencyInjection { public static IServiceCollection AddApplication(this IServiceCollection services) { services.AddAutoMapper(Assembly.GetExecutingAssembly()); services.AddMediatR(Assembly.GetExecutingAssembly()); services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestPerformanceBehaviour<,>)); services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestValidationBehavior<,>)); return services; } } }
33.454545
104
0.728261
[ "MIT" ]
RandallHoffpauir/PeopleSearch
src/Application/DependencyInjection.cs
738
C#
using System.Collections.Generic; namespace TimeCalc.Models { public class PersonalBestResults { public string WcaId { get; set; } public string Name { get; set; } public string AvatarUrl { get; set; } public List<PersonalBest> PersonalBests { get; set; } } }
25.333333
61
0.641447
[ "MIT" ]
michaelrp/TimeCalc
src/TimeCalc/Models/PersonalBestResults.cs
304
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Database { public class Class1 { } }
13.615385
33
0.728814
[ "MIT" ]
LucasEmanuel005/PI_3-TecInformatica
Database/Class1.cs
179
C#
 using Orleans.Runtime; using Orleans.Streams; using System; namespace Orleans.Configuration { /// <summary> /// EventHub settings for a specific hub /// </summary> public class EventHubOptions { /// <summary> /// EventHub connection string. /// </summary> [Redact] public string ConnectionString { get; set; } /// <summary> /// EventHub consumer group. /// </summary> public string ConsumerGroup { get; set; } /// <summary> /// Hub path. /// </summary> public string Path { get; set; } } public class EventHubOptionsValidator : IConfigurationValidator { private readonly EventHubOptions options; private readonly string name; public EventHubOptionsValidator(EventHubOptions options, string name) { this.options = options; this.name = name; } public void ValidateConfiguration() { if (String.IsNullOrEmpty(options.ConnectionString)) throw new OrleansConfigurationException($"{nameof(EventHubOptions)} on stream provider {this.name} is invalid. {nameof(EventHubOptions.ConnectionString)} is invalid"); if (String.IsNullOrEmpty(options.ConsumerGroup)) throw new OrleansConfigurationException($"{nameof(EventHubOptions)} on stream provider {this.name} is invalid. {nameof(EventHubOptions.ConsumerGroup)} is invalid"); if (String.IsNullOrEmpty(options.Path)) throw new OrleansConfigurationException($"{nameof(EventHubOptions)} on stream provider {this.name} is invalid. {nameof(EventHubOptions.Path)} is invalid"); } } public class StreamCheckpointerConfigurationValidator : IConfigurationValidator { private readonly IServiceProvider services; private string name; public StreamCheckpointerConfigurationValidator(IServiceProvider services, string name) { this.services = services; this.name = name; } public void ValidateConfiguration() { var checkpointerFactory = services.GetServiceByName<IStreamQueueCheckpointerFactory>(this.name); if(checkpointerFactory == null) throw new OrleansConfigurationException($"No IStreamQueueCheckpointer is configured with PersistentStreamProvider {this.name}. Please configure one."); } } public class EventHubReceiverOptions { /// <summary> /// Optional parameter that configures the receiver prefetch count. /// </summary> public int? PrefetchCount { get; set; } /// <summary> /// In cases where no checkpoint is found, this indicates if service should read from the most recent data, or from the begining of a partition. /// </summary> public bool StartFromNow { get; set; } = DEFAULT_START_FROM_NOW; public const bool DEFAULT_START_FROM_NOW = true; } public class EventHubStreamCachePressureOptions { /// <summary> /// SlowConsumingPressureMonitorConfig /// </summary> public double? SlowConsumingMonitorFlowControlThreshold { get; set; } /// <summary> /// SlowConsumingMonitorPressureWindowSize /// </summary> public TimeSpan? SlowConsumingMonitorPressureWindowSize { get; set; } /// <summary> /// AveragingCachePressureMonitorFlowControlThreshold, AveragingCachePressureMonitor is turn on by default. /// User can turn it off by setting this value to null /// </summary> public double? AveragingCachePressureMonitorFlowControlThreshold { get; set; } = DEFAULT_AVERAGING_CACHE_PRESSURE_MONITORING_THRESHOLD; public const double AVERAGING_CACHE_PRESSURE_MONITORING_OFF = 1.0; public const double DEFAULT_AVERAGING_CACHE_PRESSURE_MONITORING_THRESHOLD = 1.0 / 3.0; } }
40.612245
183
0.657035
[ "MIT" ]
DarkCow/orleans
src/Azure/Orleans.Streaming.EventHubs/Providers/Streams/EventHub/EventHubStreamOptions.cs
3,982
C#
// Copyright (c) Microsoft Corporation. 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.Linq; using System.Threading.Tasks; using Azure.Core.Testing; using Azure.Storage.Blobs.Models; using Azure.Storage.Common; using Azure.Storage.Test; using Azure.Storage.Test.Shared; using NUnit.Framework; namespace Azure.Storage.Blobs.Test { public class ServiceClientTests : BlobTestBase { public ServiceClientTests(bool async) : base(async, null /* RecordedTestMode.Record /* to re-record */) { } [Test] public void Ctor_ConnectionString() { var accountName = "accountName"; var accountKey = Convert.ToBase64String(new byte[] { 0, 1, 2, 3, 4, 5 }); var credentials = new StorageSharedKeyCredential(accountName, accountKey); var blobEndpoint = new Uri("http://127.0.0.1/" + accountName); var blobSecondaryEndpoint = new Uri("http://127.0.0.1/" + accountName + "-secondary"); var connectionString = new StorageConnectionString(credentials, (blobEndpoint, blobSecondaryEndpoint), (default, default), (default, default), (default, default)); var service = new BlobServiceClient(connectionString.ToString(true)); var builder = new BlobUriBuilder(service.Uri); Assert.AreEqual("", builder.ContainerName); Assert.AreEqual("", builder.BlobName); Assert.AreEqual("accountName", builder.AccountName); } [Test] public async Task ListContainersSegmentAsync() { // Arrange var service = this.GetServiceClient_SharedKey(); // Ensure at least one container using (this.GetNewContainer(out _, service: service)) { // Act var containers = await service.GetContainersAsync().ToListAsync(); // Assert Assert.IsTrue(containers.Count() >= 1); } } [Test] public async Task ListContainersSegmentAsync_Marker() { var service = this.GetServiceClient_SharedKey(); // Ensure at least one container using (this.GetNewContainer(out var container, service: service)) { var marker = default(string); var containers = new List<ContainerItem>(); await foreach (var page in service.GetContainersAsync().ByPage(marker)) { containers.AddRange(page.Values); } Assert.AreNotEqual(0, containers.Count); Assert.AreEqual(containers.Count, containers.Select(c => c.Name).Distinct().Count()); Assert.IsTrue(containers.Any(c => container.Uri == this.InstrumentClient(service.GetBlobContainerClient(c.Name)).Uri)); } } [Test] [AsyncOnly] public async Task ListContainersSegmentAsync_MaxResults() { var service = this.GetServiceClient_SharedKey(); // Ensure at least one container using (this.GetNewContainer(out _, service: service)) using (this.GetNewContainer(out var container, service: service)) { // Act var page = await service.GetContainersAsync() .ByPage(pageSizeHint: 1) .FirstAsync(); // Assert Assert.AreEqual(1, page.Values.Count()); } } [Test] public async Task ListContainersSegmentAsync_Prefix() { var service = this.GetServiceClient_SharedKey(); var prefix = "aaa"; var containerName = prefix + this.GetNewContainerName(); // Ensure at least one container using (this.GetNewContainer(out var container, service: service, containerName: containerName)) { // Act var containers = service.GetContainersAsync(new GetContainersOptions { Prefix = prefix }); var items = await containers.ToListAsync(); // Assert Assert.AreNotEqual(0, items.Count()); Assert.IsTrue(items.All(c => c.Value.Name.StartsWith(prefix))); Assert.IsNotNull(items.Single(c => c.Value.Name == containerName)); } } [Test] public async Task ListContainersSegmentAsync_Metadata() { var service = this.GetServiceClient_SharedKey(); // Ensure at least one container using (this.GetNewContainer(out var container, service: service)) { // Arrange var metadata = this.BuildMetadata(); await container.SetMetadataAsync(metadata); // Act var first = await service.GetContainersAsync(new GetContainersOptions { IncludeMetadata = true }).FirstAsync(); // Assert Assert.IsNotNull(first.Value.Metadata); } } [Test] [AsyncOnly] public async Task ListContainersSegmentAsync_Error() { // Arrange var service = this.GetServiceClient_SharedKey(); // Act await TestHelper.AssertExpectedExceptionAsync<StorageRequestFailedException>( service.GetContainersAsync().ByPage(continuationToken: "garbage").FirstAsync(), e => Assert.AreEqual("OutOfRangeInput", e.ErrorCode)); } [Test] public async Task GetAccountInfoAsync() { // Arrange var service = this.GetServiceClient_SharedKey(); // Act var response = await service.GetAccountInfoAsync(); // Assert Assert.IsNotNull(response.GetRawResponse().Headers.RequestId); } [Test] public async Task GetAccountInfoAsync_Error() { // Arrange var service = this.InstrumentClient( new BlobServiceClient( this.GetServiceClient_SharedKey().Uri, this.GetOptions())); // Act await TestHelper.AssertExpectedExceptionAsync<StorageRequestFailedException>( service.GetAccountInfoAsync(), e => Assert.AreEqual("ResourceNotFound", e.ErrorCode)); } [Test] public async Task GetPropertiesAsync() { // Arrange var service = this.GetServiceClient_SharedKey(); // Act var response = await service.GetPropertiesAsync(); // Assert Assert.IsFalse(String.IsNullOrWhiteSpace(response.Value.DefaultServiceVersion)); } [Test] public async Task GetPropertiesAsync_Error() { // Arrange var service = this.InstrumentClient( new BlobServiceClient( this.GetServiceClient_SharedKey().Uri, this.GetOptions())); // Act await TestHelper.AssertExpectedExceptionAsync<StorageRequestFailedException>( service.GetPropertiesAsync(), e => Assert.AreEqual("ResourceNotFound", e.ErrorCode)); } [Test] [NonParallelizable] public async Task SetPropertiesAsync() { // Arrange var service = this.GetServiceClient_SharedKey(); var properties = (await service.GetPropertiesAsync()).Value; var originalCors = properties.Cors.ToArray(); properties.Cors = new[] { new CorsRule { MaxAgeInSeconds = 1000, AllowedHeaders = "x-ms-meta-data*,x-ms-meta-target*,x-ms-meta-abc", AllowedMethods = "PUT,GET", AllowedOrigins = "*", ExposedHeaders = "x-ms-meta-*" } }; // Act await service.SetPropertiesAsync(properties); // Assert properties = (await service.GetPropertiesAsync()).Value; Assert.AreEqual(1, properties.Cors.Count()); Assert.IsTrue(properties.Cors[0].MaxAgeInSeconds == 1000); // Cleanup properties.Cors = originalCors; await service.SetPropertiesAsync(properties); properties = await service.GetPropertiesAsync(); Assert.AreEqual(originalCors.Count(), properties.Cors.Count()); } [Test] public async Task SetPropertiesAsync_Error() { // Arrange var service = this.GetServiceClient_SharedKey(); var properties = (await service.GetPropertiesAsync()).Value; var invalidService = this.InstrumentClient( new BlobServiceClient( this.GetServiceClient_SharedKey().Uri, this.GetOptions())); // Act await TestHelper.AssertExpectedExceptionAsync<StorageRequestFailedException>( invalidService.SetPropertiesAsync(properties), e => Assert.AreEqual("ResourceNotFound", e.ErrorCode)); } // Note: read-access geo-redundant replication must be enabled for test account, or this test will fail. [Test] public async Task GetStatisticsAsync() { // Arrange // "-secondary" is required by the server var service = this.InstrumentClient( new BlobServiceClient( new Uri(this.TestConfigDefault.BlobServiceSecondaryEndpoint), this.GetNewSharedKeyCredentials(), this.GetOptions())); // Act var response = await service.GetStatisticsAsync(); // Assert Assert.IsNotNull(response); } [Test] public async Task GetUserDelegationKey() { // Arrange var service = this.GetServiceClient_OauthAccount(); // Act var response = await service.GetUserDelegationKeyAsync(start: null, expiry: this.Recording.UtcNow.AddHours(1)); // Assert Assert.IsNotNull(response.Value); } [Test] public async Task GetUserDelegationKey_Error() { // Arrange var service = this.GetServiceClient_SharedKey(); // Act await TestHelper.AssertExpectedExceptionAsync<StorageRequestFailedException>( service.GetUserDelegationKeyAsync(start: null, expiry: this.Recording.UtcNow.AddHours(1)), e => Assert.AreEqual("AuthenticationFailed", e.ErrorCode.Split('\n')[0])); } [Test] public async Task GetUserDelegationKey_ArgumentException() { // Arrange var service = this.GetServiceClient_OauthAccount(); // Act await TestHelper.AssertExpectedExceptionAsync<ArgumentException>( service.GetUserDelegationKeyAsync(start: null, expiry: this.Recording.Now.AddHours(1)), e => Assert.AreEqual("expiry must be UTC", e.Message)); } [Test] public async Task CreateBlobContainerAsync() { var name = this.GetNewContainerName(); var service = this.GetServiceClient_SharedKey(); try { var container = this.InstrumentClient((await service.CreateBlobContainerAsync(name)).Value); var properties = await container.GetPropertiesAsync(); Assert.IsNotNull(properties.Value); } finally { await service.DeleteBlobContainerAsync(name); } } [Test] public async Task DeleteBlobContainerAsync() { var name = this.GetNewContainerName(); var service = this.GetServiceClient_SharedKey(); var container = this.InstrumentClient((await service.CreateBlobContainerAsync(name)).Value); await service.DeleteBlobContainerAsync(name); Assert.ThrowsAsync<StorageRequestFailedException>( async () => await container.GetPropertiesAsync()); } } }
36.246418
175
0.567431
[ "MIT" ]
Only2125/azure-sdk-for-net
sdk/storage/Azure.Storage.Blobs/tests/ServiceClientTests.cs
12,652
C#
/* The MIT License (MIT) Copyright (c) 2012-2019 Syoyo Fujita and many contributors. 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. Ported and adapted for C# from: https://github.com/syoyo/tinyobjloader by Jose Ferreira (Bazoocaze) */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using GlmSharp; namespace tinyobjloaderLib { using real_t = System.Single; public static class tinyobj { public enum texture_type_t { TEXTURE_TYPE_NONE, // default TEXTURE_TYPE_SPHERE, TEXTURE_TYPE_CUBE_TOP, TEXTURE_TYPE_CUBE_BOTTOM, TEXTURE_TYPE_CUBE_FRONT, TEXTURE_TYPE_CUBE_BACK, TEXTURE_TYPE_CUBE_LEFT, TEXTURE_TYPE_CUBE_RIGHT } public struct texture_option_t { public texture_type_t type; // -type (default TEXTURE_TYPE_NONE) public real_t sharpness; // -boost (default 1.0?) public real_t brightness; // base_value in -mm option (default 0) public real_t contrast; // gain_value in -mm option (default 1) public vec3 origin_offset; // -o u [v [w]] (default 0 0 0) public vec3 scale; // -s u [v [w]] (default 1 1 1) public vec3 turbulence; // -t u [v [w]] (default 0 0 0) // int texture_resolution; // -texres resolution (default = ?) TODO public bool clamp; // -clamp (default false) public char imfchan; // -imfchan (the default for bump is 'l' and for decal is 'm') public bool blendu; // -blendu (default on) public bool blendv; // -blendv (default on) public real_t bump_multiplier; // -bm (for bump maps only, default 1.0) } public struct material_t { public string name; public vec3 ambient; public vec3 diffuse; public vec3 specular; public vec3 transmittance; public vec3 emission; public real_t shininess; public real_t ior; // index of refraction public real_t dissolve; // 1 == opaque; 0 == fully transparent // illumination model (see http://www.fileformat.info/format/material/) public int illum; public int dummy; // Suppress padding warning. public string ambient_texname; // map_Ka public string diffuse_texname; // map_Kd public string specular_texname; // map_Ks public string specular_highlight_texname; // map_Ns public string bump_texname; // map_bump, map_Bump, bump public string displacement_texname; // disp public string alpha_texname; // map_d public string reflection_texname; // refl public texture_option_t ambient_texopt; public texture_option_t diffuse_texopt; public texture_option_t specular_texopt; public texture_option_t specular_highlight_texopt; public texture_option_t bump_texopt; public texture_option_t displacement_texopt; public texture_option_t alpha_texopt; public texture_option_t reflection_texopt; // PBR extension // http://exocortex.com/blog/extending_wavefront_mtl_to_support_pbr public real_t roughness; // [0, 1] default 0 public real_t metallic; // [0, 1] default 0 public real_t sheen; // [0, 1] default 0 public real_t clearcoat_thickness; // [0, 1] default 0 public real_t clearcoat_roughness; // [0, 1] default 0 public real_t anisotropy; // aniso. [0, 1] default 0 public real_t anisotropy_rotation; // anisor. [0, 1] default 0 public real_t pad0; public string roughness_texname; // map_Pr public string metallic_texname; // map_Pm public string sheen_texname; // map_Ps public string emissive_texname; // map_Ke public string normal_texname; // norm. For normal mapping. public texture_option_t roughness_texopt; public texture_option_t metallic_texopt; public texture_option_t sheen_texopt; public texture_option_t emissive_texopt; public texture_option_t normal_texopt; public int pad2; public Dictionary<string, string> unknown_parameter; public static material_t Create() { return new material_t() { unknown_parameter = new Dictionary<string, string>() }; } } public struct tag_t { public string name; public List<int> intValues; public List<real_t> floatValues; public List<string> stringValues; public static tag_t Create() { return new tag_t() { intValues = new List<int>(), floatValues = new List<float>(), stringValues = new List<string>() }; } } // Index struct to support different indices for vtx/normal/texcoord. // -1 means not used. public struct index_t { public int vertex_index; public int normal_index; public int texcoord_index; } public struct mesh_t { public List<index_t> indices; public List<byte> num_face_vertices; // The number of vertices per // face. 3 = polygon, 4 = quad, // ... Up to 255. public List<int> material_ids; // per-face material ID public List<uint> smoothing_group_ids; // per-face smoothing group // ID(0 = off. positive value // = group id) public List<tag_t> tags; // SubD tag public static mesh_t Create() { return new mesh_t() { indices = new List<index_t>(), num_face_vertices = new List<byte>(), material_ids = new List<int>(), smoothing_group_ids = new List<uint>(), tags = new List<tag_t>() }; } } public struct shape_t { public string name; public mesh_t mesh; public static shape_t Create() { return new shape_t() { mesh = mesh_t.Create() }; } } // Vertex attributes public struct attrib_t { public List<real_t> vertices; // 'v' public List<real_t> normals; // 'vn' public List<real_t> texcoords; // 'vt' public List<real_t> colors; // extension: vertex colors public static attrib_t Create() { return new attrib_t() { vertices = new List<float>(), normals = new List<float>(), texcoords = new List<float>(), colors = new List<float>() }; } } protected class LineReader { private TextReader m_inputLine; private bool m_EOF; public LineReader(string inputLine) { if (inputLine == null) { m_EOF = true; } else { m_inputLine = new StringReader(inputLine); } } public bool Eof { get { return m_EOF; } } public string ReadWord() { if (m_EOF) { return ""; } StringBuilder ret = new StringBuilder(); while (m_inputLine.Peek() != -1) { char c = (char)m_inputLine.Read(); if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\0') { if (ret.Length > 0) break; continue; } ret.Append(c); } if (ret.Length == 0 || m_inputLine.Peek() == -1) m_EOF = true; return ret.ToString(); } public string[] ReadWordSplit(params char[] separator) { var str = ReadWord(); if (str != null) return str.Split(separator); return new string[0]; } public int ReadInt(int default_value = 0) { return atoi(ReadWord(), default_value); } public string[] ReadSplit(params char[] separator) { var str = m_inputLine.ReadLine(); if (str == null) return new string[0]; return str.Split(separator); } public string ReadLine() { try { return m_inputLine.ReadLine(); } finally { m_EOF = (m_inputLine.Peek() == -1); } } } protected class CharReader { StringReader m_input; public CharReader(string input) { m_input = new StringReader(input); } public bool Eof { get { return m_input.Peek() == -1; } } public char Current { get { int val = m_input.Peek(); if (val == -1) return (char)0; return (char)val; } } public void MoveNext() { m_input.Read(); } } protected abstract class MaterialReader { public abstract bool Load(string matId, List<material_t> materials, Dictionary<string, int> matMap, out string err); } protected class MaterialFileReader : MaterialReader { private string m_mtlBaseDir; public MaterialFileReader(string mtl_basedir) { this.m_mtlBaseDir = mtl_basedir; } public override bool Load(string matId, List<material_t> materials, Dictionary<string, int> matMap, out string err) { string filepath; err = null; if (!string.IsNullOrWhiteSpace(m_mtlBaseDir)) { filepath = m_mtlBaseDir + matId; } else { filepath = matId; } try { using (var matIStream = new StreamReader(filepath)) { string warning; LoadMtl(matMap, materials, matIStream, out warning); if (!string.IsNullOrWhiteSpace(warning)) { err = warning; } return true; } } catch (IOException ex) { err = string.Format("WARN: Material file [ {0} ] not found: {1}", filepath, ex.Message); return false; } } } protected class MaterialStreamReader : MaterialReader { private Stream m_inStream; public MaterialStreamReader(Stream inStream) { m_inStream = inStream; } public override bool Load(string matId, List<material_t> materials, Dictionary<string, int> matMap, out string err) { err = null; if (!m_inStream.CanRead) { err = "WARN: Material stream in error state."; return false; } try { using (var matIStream = new StreamReader(m_inStream)) { string warning; LoadMtl(matMap, materials, matIStream, out warning); if (!string.IsNullOrWhiteSpace(warning)) { err = warning; } return true; } } catch (IOException ex) { err = string.Format("WARN: Material file not ready: {0}", ex.Message); return false; } } } protected struct vertex_index_t { public int v_idx; public int vt_idx; public int vn_idx; public static vertex_index_t Create() { return new vertex_index_t() { v_idx = -1, vt_idx = -1, vn_idx = -1 }; } public static vertex_index_t Create(int idx) { return new vertex_index_t() { v_idx = idx, vt_idx = idx, vn_idx = idx }; } public static vertex_index_t Create(int vidx, int vtidx, int vnidx) { return new vertex_index_t() { v_idx = vidx, vt_idx = vtidx, vn_idx = vnidx }; } } // Internal data structure for face representation // index + smoothing group. protected struct face_t { public uint smoothing_group_id; // smoothing group id. 0 = smoothing groupd is off. public int pad_; public List<vertex_index_t> vertex_indices; // face vertex indices. public static face_t Create() { return new face_t() { vertex_indices = new List<vertex_index_t>() }; } } protected struct tag_sizes { public int num_ints; public int num_reals; public int num_strings; } protected struct obj_shape { public List<real_t> v; public List<real_t> vn; public List<real_t> vt; public static obj_shape Create() { return new obj_shape() { v = new List<float>(), vn = new List<real_t>(), vt = new List<real_t>() }; } } private static bool IS_SPACE(char x) { return ((x == ' ') || (x == '\t')); } private static bool IS_DIGIT(char x) { return ((uint)(x - '0') < 10); } private static bool IS_NEW_LINE(char x) { return ((x == '\r') || (x == '\n') || (x == '\0')); } // Make index zero-base, and also support relative index. private static bool fixIndex(int idx, int n, ref int ret) { if (idx > 0) { ret = idx - 1; return true; } if (idx == 0) { // zero is not allowed according to the spec. return false; } if (idx < 0) { ret = n + idx; // negative value = relative return true; } return false; // never reach here. } private static string parseString(LineReader token) { return token.ReadWord(); } private static int parseInt(LineReader token) { return token.ReadInt(); } // Tries to parse a floating point number located at s. // // s_end should be a location in the string where reading should absolutely // stop. For example at the end of the string, to prevent buffer overflows. // // Parses the following EBNF grammar: // sign = "+" | "-" ; // END = ? anything not in digit ? // digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ; // integer = [sign] , digit , {digit} ; // decimal = integer , ["." , integer] ; // float = ( decimal , END ) | ( decimal , ("E" | "e") , integer , END ) ; // // Valid strings are for example: // -0 +3.1417e+2 -0.0E-3 1.0324 -1.41 11e2 // // If the parsing is a success, result is set to the parsed value and true // is returned. // // The function is greedy and will parse until any of the following happens: // - a non-conforming character is encountered. // - s_end is reached. // // The following situations triggers a failure: // - s >= s_end. // - parse failure. // private static bool tryParseDouble(string s, object s_end, ref double result) { double mantissa = 0.0; // This exponent is base 2 rather than 10. // However the exponent we parse is supposed to be one of ten, // thus we must take care to convert the exponent/and or the // mantissa to a * 2^E, where a is the mantissa and E is the // exponent. // To get the final double we will use ldexp, it requires the // exponent to be in base 2. int exponent = 0; // NOTE: THESE MUST BE DECLARED HERE SINCE WE ARE NOT ALLOWED // TO JUMP OVER DEFINITIONS. char sign = '+'; char exp_sign = '+'; CharReader curr = new CharReader(s); // How many characters were read in a loop. int read = 0; // Tells whether a loop terminated due to reaching s_end. bool end_not_reached = false; /* BEGIN PARSING. */ // Find out what sign we've got. if (curr.Current == '+' || curr.Current == '-') { sign = curr.Current; curr.MoveNext(); } else if (IS_DIGIT(curr.Current)) { /* Pass through. */ } else { goto fail; } // Read the integer part. while (!curr.Eof && IS_DIGIT(curr.Current)) { mantissa *= 10; mantissa += (int)(curr.Current - 0x30); curr.MoveNext(); read++; } // We must make sure we actually got something. if (read == 0) goto fail; // We allow numbers of form "#", "###" etc. if (curr.Eof) goto assemble; // Read the decimal part. if (curr.Current == '.') { curr.MoveNext(); read = 1; // end_not_reached = (curr != s_end); while ((!curr.Eof) && IS_DIGIT(curr.Current)) { double[] pow_lut = { 1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001, 0.0000001, }; int lut_entries = pow_lut.Length; // NOTE: Don't use powf here, it will absolutely murder precision. mantissa += (int)(curr.Current - 0x30) * (read < lut_entries ? pow_lut[read] : Math.Pow(10.0, -read)); read++; curr.MoveNext(); } } else if (curr.Current == 'e' || curr.Current == 'E') { } else { goto assemble; } if (curr.Eof) goto assemble; // Read the exponent part. if (curr.Current == 'e' || curr.Current == 'E') { curr.MoveNext(); // Figure out if a sign is present and if it is. if ((!curr.Eof) && (curr.Current == '+' || curr.Current == '-')) { exp_sign = curr.Current; curr.MoveNext(); } else if (IS_DIGIT(curr.Current)) { /* Pass through. */ } else { // Empty E is not allowed. goto fail; } read = 0; while ((!curr.Eof) && IS_DIGIT(curr.Current)) { exponent *= 10; exponent += (int)(curr.Current - 0x30); curr.MoveNext(); read++; end_not_reached = (curr != s_end); } exponent *= (exp_sign == '+' ? 1 : -1); if (read == 0) goto fail; } assemble: result = (sign == '+' ? 1 : -1) * (exponent != 0 ? std_ldexp(mantissa * Math.Pow(5.0, exponent), exponent) : mantissa); return true; fail: return false; } private static double std_ldexp(double number, int exponent) { // return = number * 2 ^ exponent return number * Math.Pow(2, exponent); } private static real_t parseReal(LineReader token, double default_value = 0.0) { double val = default_value; tryParseDouble(token.ReadWord(), null, ref val); return (real_t)val; } private static bool parseReal(LineReader token, ref real_t outVal) { double val = 0; bool ret = tryParseDouble(token.ReadWord(), null, ref val); if (ret) { outVal = (real_t)val; } return ret; } private static void parseReal2(out real_t x, out real_t y, LineReader token, double default_x = 0.0, double default_y = 0.0) { x = parseReal(token, default_x); y = parseReal(token, default_y); } private static void parseReal3(out real_t x, out real_t y, out real_t z, LineReader token, double default_x = 0.0, double default_y = 0.0, double default_z = 0.0) { x = parseReal(token, default_x); y = parseReal(token, default_y); z = parseReal(token, default_z); } private static void parseV(out real_t x, out real_t y, out real_t z, out real_t w, LineReader token, double default_x = 0.0, double default_y = 0.0, double default_z = 0.0, double default_w = 1.0) { x = parseReal(token, default_x); y = parseReal(token, default_y); z = parseReal(token, default_z); w = parseReal(token, default_w); } // Extension: parse vertex with colors(6 items) private static void parseVertexWithColor(out real_t x, out real_t y, out real_t z, out real_t r, out real_t g, out real_t b, LineReader token, double default_x = 0.0, double default_y = 0.0, double default_z = 0.0) { x = parseReal(token, default_x); y = parseReal(token, default_y); z = parseReal(token, default_z); r = parseReal(token, 1.0); g = parseReal(token, 1.0); b = parseReal(token, 1.0); } private static bool parseOnOff(LineReader token, bool default_value = true) { bool ret = default_value; var str = token.ReadWord(); if (str != null) { if (str == "on") ret = true; else if (str == "off") ret = false; } return ret; } private static texture_type_t parseTextureType(LineReader token, texture_type_t default_value = texture_type_t.TEXTURE_TYPE_NONE) { var str = token.ReadWord(); if (str == null) return default_value; switch (str) { case "cube_top": return texture_type_t.TEXTURE_TYPE_CUBE_TOP; case "cube_bottom": return texture_type_t.TEXTURE_TYPE_CUBE_BOTTOM; case "cube_left": return texture_type_t.TEXTURE_TYPE_CUBE_LEFT; case "cube_right": return texture_type_t.TEXTURE_TYPE_CUBE_RIGHT; case "cube_front": return texture_type_t.TEXTURE_TYPE_CUBE_FRONT; case "cube_back": return texture_type_t.TEXTURE_TYPE_CUBE_BACK; case "sphere": return texture_type_t.TEXTURE_TYPE_SPHERE; } return default_value; } private static tag_sizes parseTagTriple(LineReader token) { tag_sizes ts = new tag_sizes(); var list = token.ReadWordSplit('/'); if (list.Length >= 1) ts.num_ints = atoi(list[0]); if (list.Length >= 2) ts.num_reals = atoi(list[1]); if (list.Length >= 3) ts.num_strings = atoi(list[2]); return ts; } // Parse triples with index offsets: i, i/j/k, i//k, i/j private static bool parseTriple(LineReader token, int vsize, int vnsize, int vtsize, ref vertex_index_t ret) { vertex_index_t vi = vertex_index_t.Create(-1); var list = token.ReadWordSplit('/'); if (list.Length >= 1 && list[0].Length > 0) { if (!fixIndex(atoi(list[0]), vsize, ref vi.v_idx)) { return false; } } if (list.Length >= 2 && list[1].Length > 0) { if (!fixIndex(atoi(list[1]), vtsize, ref vi.vt_idx)) { return false; } } if (list.Length >= 3 && list[2].Length > 0) { if (!fixIndex(atoi(list[2]), vnsize, ref vi.vn_idx)) { return false; } } ret = vi; return true; } // Parse raw triples: i, i/j/k, i//k, i/j private static vertex_index_t parseRawTriple(LineReader token) { vertex_index_t vi = vertex_index_t.Create(0); // 0 is an invalid index in OBJ var list = token.ReadWordSplit('/'); if (list.Length >= 1 && list[0].Length > 0) { vi.v_idx = atoi(list[0]); } if (list.Length >= 2 && list[1].Length > 0) { vi.vt_idx = atoi(list[1]); } if (list.Length >= 1 && list[2].Length > 0) { vi.vn_idx = atoi(list[2]); } return vi; } private static bool ParseTextureNameAndOption(out string texname, ref texture_option_t texopt, LineReader linebuf, bool is_bump) { // @todo { write more robust lexer and parser. } bool found_texname = false; string texture_name = null; // Fill with default value for texopt. if (is_bump) { texopt.imfchan = 'l'; } else { texopt.imfchan = 'm'; } texopt.bump_multiplier = 1.0f; texopt.clamp = false; texopt.blendu = true; texopt.blendv = true; texopt.sharpness = 1.0f; texopt.brightness = 0.0f; texopt.contrast = 1.0f; texopt.origin_offset[0] = 0.0f; texopt.origin_offset[1] = 0.0f; texopt.origin_offset[2] = 0.0f; texopt.scale[0] = 1.0f; texopt.scale[1] = 1.0f; texopt.scale[2] = 1.0f; texopt.turbulence[0] = 0.0f; texopt.turbulence[1] = 0.0f; texopt.turbulence[2] = 0.0f; texopt.type = texture_type_t.TEXTURE_TYPE_NONE; string token; while (linebuf.Eof) { token = linebuf.ReadWord(); if (string.IsNullOrWhiteSpace(token)) break; if (token == "-blendu") { texopt.blendu = parseOnOff(linebuf, /* default */ true); } else if (token == "-blendv") { texopt.blendv = parseOnOff(linebuf, /* default */ true); } else if (token == "-clamp") { texopt.clamp = parseOnOff(linebuf, /* default */ true); } else if (token == "-boost") { texopt.sharpness = parseReal(linebuf, 1.0); } else if (token == "-bm") { texopt.bump_multiplier = parseReal(linebuf, 1.0); } else if (token == "-o") { float x, y, z; parseReal3(out x, out y, out z, linebuf); texopt.origin_offset[0] = x; texopt.origin_offset[1] = y; texopt.origin_offset[2] = z; } else if (token == "-s") { float x, y, z; parseReal3(out x, out y, out z, linebuf, 1, 1, 1); texopt.scale[0] = x; texopt.scale[1] = y; texopt.scale[2] = z; } else if (token == "-t") { float x, y, z; parseReal3(out x, out y, out z, linebuf); texopt.turbulence[0] = x; texopt.turbulence[1] = y; texopt.turbulence[2] = z; } else if (token == "-type") { texopt.type = parseTextureType(linebuf, texture_type_t.TEXTURE_TYPE_NONE); } else if (token == "-imfchan") { var str = linebuf.ReadWord(); if (str != null && str.Length >= 1) texopt.imfchan = str[0]; } else if (token == "-mm") { parseReal2(out texopt.brightness, out texopt.contrast, linebuf, 0.0, 1.0); } else { // Assume texture filename // Read filename until line end to parse filename containing whitespace // TODO(syoyo): Support parsing texture option flag after the filename. texture_name = token; found_texname = true; } } if (found_texname) { texname = texture_name; return true; } else { texname = ""; return false; } } private static void InitMaterial(ref material_t material) { material = new material_t(); material.name = ""; material.ambient_texname = ""; material.diffuse_texname = ""; material.specular_texname = ""; material.specular_highlight_texname = ""; material.bump_texname = ""; material.displacement_texname = ""; material.reflection_texname = ""; material.alpha_texname = ""; for (int i = 0; i < 3; i++) { material.ambient[i] = 0f; material.diffuse[i] = 0f; material.specular[i] = 0f; material.transmittance[i] = 0f; material.emission[i] = 0f; } material.illum = 0; material.dissolve = 1f; material.shininess = 1f; material.ior = 1f; material.roughness = 0f; material.metallic = 0f; material.sheen = 0f; material.clearcoat_thickness = 0f; material.clearcoat_roughness = 0f; material.anisotropy_rotation = 0f; material.anisotropy = 0f; material.roughness_texname = ""; material.metallic_texname = ""; material.sheen_texname = ""; material.emissive_texname = ""; material.normal_texname = ""; material.unknown_parameter.Clear(); } // code from https://wrf.ecse.rpi.edu//Research/Short_Notes/pnpoly.html private static bool pnpoly(int nvert, float[] vertx, float[] verty, float testx, float testy) { int i, j; bool c = false; for (i = 0, j = nvert - 1; i < nvert; j = i++) { if (((verty[i] > testy) != (verty[j] > testy)) && (testx < (vertx[j] - vertx[i]) * (testy - verty[i]) / (verty[j] - verty[i]) + vertx[i])) c = !c; } return c; } // TODO(syoyo): refactor function. private static bool exportFaceGroupToShape(ref shape_t shape, List<face_t> faceGroup, List<tag_t> tags, int material_id, string name, bool triangulate, List<float> v) { if (!faceGroup.Any()) { return false; } // Flatten vertices and indices for (int i = 0; i < faceGroup.Count; i++) { face_t face = faceGroup[i]; if (face.vertex_indices.Count < 3) { // Face must have 3+ vertices. continue; } vertex_index_t i0 = face.vertex_indices[0]; vertex_index_t i1 = vertex_index_t.Create(-1); vertex_index_t i2 = face.vertex_indices[1]; int npolys = face.vertex_indices.Count; if (triangulate) { // find the two axes to work in int[] axes = new int[] { 1, 2 }; for (int k = 0; k < npolys; ++k) { i0 = face.vertex_indices[(k + 0) % npolys]; i1 = face.vertex_indices[(k + 1) % npolys]; i2 = face.vertex_indices[(k + 2) % npolys]; int vi0 = i0.v_idx; int vi1 = i1.v_idx; int vi2 = i2.v_idx; real_t v0x = v[vi0 * 3 + 0]; real_t v0y = v[vi0 * 3 + 1]; real_t v0z = v[vi0 * 3 + 2]; real_t v1x = v[vi1 * 3 + 0]; real_t v1y = v[vi1 * 3 + 1]; real_t v1z = v[vi1 * 3 + 2]; real_t v2x = v[vi2 * 3 + 0]; real_t v2y = v[vi2 * 3 + 1]; real_t v2z = v[vi2 * 3 + 2]; real_t e0x = v1x - v0x; real_t e0y = v1y - v0y; real_t e0z = v1z - v0z; real_t e1x = v2x - v1x; real_t e1y = v2y - v1y; real_t e1z = v2z - v1z; float cx = Math.Abs(e0y * e1z - e0z * e1y); float cy = Math.Abs(e0z * e1x - e0x * e1z); float cz = Math.Abs(e0x * e1y - e0y * e1x); const float epsilon = 0.0001f; if (cx > epsilon || cy > epsilon || cz > epsilon) { // found a corner if (cx > cy && cx > cz) { } else { axes[0] = 0; if (cz > cx && cz > cy) axes[1] = 1; } break; } } real_t area = 0; for (int k = 0; k < npolys; ++k) { i0 = face.vertex_indices[(k + 0) % npolys]; i1 = face.vertex_indices[(k + 1) % npolys]; int vi0 = i0.v_idx; int vi1 = i1.v_idx; real_t v0x = v[vi0 * 3 + axes[0]]; real_t v0y = v[vi0 * 3 + axes[1]]; real_t v1x = v[vi1 * 3 + axes[0]]; real_t v1y = v[vi1 * 3 + axes[1]]; area += (v0x * v1y - v0y * v1x) * 0.5f; } int maxRounds = 10; // arbitrary max loop count to protect against unexpected errors face_t remainingFace = face; // copy int guess_vert = 0; vertex_index_t[] ind = new vertex_index_t[3]; real_t[] vx = new real_t[3]; real_t[] vy = new real_t[3]; while (remainingFace.vertex_indices.Count > 3 && maxRounds > 0) { npolys = remainingFace.vertex_indices.Count; if (guess_vert >= npolys) { maxRounds -= 1; guess_vert -= npolys; } for (int k = 0; k < 3; k++) { ind[k] = remainingFace.vertex_indices[(guess_vert + k) % npolys]; int vi = ind[k].v_idx; vx[k] = v[vi * 3 + axes[0]]; vy[k] = v[vi * 3 + axes[1]]; } real_t e0x = vx[1] - vx[0]; real_t e0y = vy[1] - vy[0]; real_t e1x = vx[2] - vx[1]; real_t e1y = vy[2] - vy[1]; real_t cross = e0x * e1y - e0y * e1x; // if an internal angle if (cross * area < 0.0f) { guess_vert += 1; continue; } // check all other verts in case they are inside this triangle bool overlap = false; for (int otherVert = 3; otherVert < npolys; ++otherVert) { int ovi = (int)( remainingFace.vertex_indices[(guess_vert + otherVert) % npolys] .v_idx); real_t tx = v[ovi * 3 + axes[0]]; real_t ty = v[ovi * 3 + axes[1]]; if (pnpoly(3, vx, vy, tx, ty)) { overlap = true; break; } } if (overlap) { guess_vert += 1; continue; } // this triangle is an ear { index_t idx0, idx1, idx2; idx0.vertex_index = ind[0].v_idx; idx0.normal_index = ind[0].vn_idx; idx0.texcoord_index = ind[0].vt_idx; idx1.vertex_index = ind[1].v_idx; idx1.normal_index = ind[1].vn_idx; idx1.texcoord_index = ind[1].vt_idx; idx2.vertex_index = ind[2].v_idx; idx2.normal_index = ind[2].vn_idx; idx2.texcoord_index = ind[2].vt_idx; shape.mesh.indices.Add(idx0); shape.mesh.indices.Add(idx1); shape.mesh.indices.Add(idx2); shape.mesh.num_face_vertices.Add(3); shape.mesh.material_ids.Add(material_id); shape.mesh.smoothing_group_ids.Add(face.smoothing_group_id); } // remove v1 from the list int removed_vert_index = (guess_vert + 1) % npolys; while (removed_vert_index + 1 < npolys) { remainingFace.vertex_indices[removed_vert_index] = remainingFace.vertex_indices[removed_vert_index + 1]; removed_vert_index += 1; } remainingFace.vertex_indices.RemoveAt(remainingFace.vertex_indices.Count - 1); } if (remainingFace.vertex_indices.Count == 3) { i0 = remainingFace.vertex_indices[0]; i1 = remainingFace.vertex_indices[1]; i2 = remainingFace.vertex_indices[2]; { index_t idx0, idx1, idx2; idx0.vertex_index = i0.v_idx; idx0.normal_index = i0.vn_idx; idx0.texcoord_index = i0.vt_idx; idx1.vertex_index = i1.v_idx; idx1.normal_index = i1.vn_idx; idx1.texcoord_index = i1.vt_idx; idx2.vertex_index = i2.v_idx; idx2.normal_index = i2.vn_idx; idx2.texcoord_index = i2.vt_idx; shape.mesh.indices.Add(idx0); shape.mesh.indices.Add(idx1); shape.mesh.indices.Add(idx2); shape.mesh.num_face_vertices.Add(3); shape.mesh.material_ids.Add(material_id); shape.mesh.smoothing_group_ids.Add(face.smoothing_group_id); } } } else { for (int k = 0; k < npolys; k++) { index_t idx; idx.vertex_index = face.vertex_indices[k].v_idx; idx.normal_index = face.vertex_indices[k].vn_idx; idx.texcoord_index = face.vertex_indices[k].vt_idx; shape.mesh.indices.Add(idx); } shape.mesh.num_face_vertices.Add((byte)npolys); shape.mesh.material_ids.Add(material_id); // per face shape.mesh.smoothing_group_ids.Add(face.smoothing_group_id); // per face } } shape.name = name; shape.mesh.tags = tags; return true; } private static void LoadMtl(Dictionary<string, int> material_map, List<material_t> materials, TextReader inStream, out string warning) { warning = ""; // Create a default material anyway. material_t material = material_t.Create(); InitMaterial(ref material); // Issue 43. `d` wins against `Tr` since `Tr` is not in the MTL specification. bool has_d = false; bool has_tr = false; while (inStream.Peek() != -1) { var lineData = inStream.ReadLine(); if (String.IsNullOrWhiteSpace(lineData)) continue; LineReader linebuf = new LineReader(lineData); string token = linebuf.ReadWord(); if (string.IsNullOrWhiteSpace(token)) continue; if (token.StartsWith("#")) continue; // comment line // new mtl if (token == "newmtl") { // flush previous material. if (!String.IsNullOrWhiteSpace(material.name)) { material_map.Add(material.name, materials.Count); materials.Add(material); } // initial temporary material InitMaterial(ref material); has_d = false; has_tr = false; material.name = linebuf.ReadWord(); continue; } // ambient if (token == "Ka") { real_t r, g, b; parseReal3(out r, out g, out b, linebuf); material.ambient[0] = r; material.ambient[1] = g; material.ambient[2] = b; continue; } // diffuse if (token == "Kd") { real_t r, g, b; parseReal3(out r, out g, out b, linebuf); material.diffuse[0] = r; material.diffuse[1] = g; material.diffuse[2] = b; continue; } // specular if (token == "Ks") { real_t r, g, b; parseReal3(out r, out g, out b, linebuf); material.specular[0] = r; material.specular[1] = g; material.specular[2] = b; continue; } // transmittance if (token == "Kt" || token == "Tf") { real_t r, g, b; parseReal3(out r, out g, out b, linebuf); material.transmittance[0] = r; material.transmittance[1] = g; material.transmittance[2] = b; continue; } // ior(index of refraction) if (token == "Ni") { material.ior = parseReal(linebuf); continue; } // emission if (token == "Ke") { real_t r, g, b; parseReal3(out r, out g, out b, linebuf); material.emission[0] = r; material.emission[1] = g; material.emission[2] = b; continue; } // shininess if (token == "Ns") { material.shininess = parseReal(linebuf); continue; } // illum model if (token == "illum") { material.illum = parseInt(linebuf); continue; } // dissolve if (token == "d") { material.dissolve = parseReal(linebuf); if (has_tr) { warning += "WARN: Both `d` and `Tr` parameters defined for \"" + material.name + "\". Use the value of `d` for dissolve."; } has_d = true; continue; } if (token == "Tr") { if (has_d) { // `d` wins. Ignore `Tr` value. warning += "WARN: Both `d` and `Tr` parameters defined for \"" + material.name + "\". Use the value of `d` for dissolve."; } else { // We invert value of Tr(assume Tr is in range [0, 1]) // NOTE: Interpretation of Tr is application(exporter) dependent. For // some application(e.g. 3ds max obj exporter), Tr = d(Issue 43) material.dissolve = 1.0f - parseReal(linebuf); } has_tr = true; continue; } // PBR: roughness if (token == "Pr") { material.roughness = parseReal(linebuf); continue; } // PBR: metallic if (token == "Pm") { material.metallic = parseReal(linebuf); continue; } // PBR: sheen if (token == "Ps") { material.sheen = parseReal(linebuf); continue; } // PBR: clearcoat thickness if (token == "Pc") { material.clearcoat_thickness = parseReal(linebuf); continue; } // PBR: clearcoat roughness if (token == "Pcr") { material.clearcoat_roughness = parseReal(linebuf); continue; } // PBR: anisotropy if (token == "aniso") { material.anisotropy = parseReal(linebuf); continue; } // PBR: anisotropy rotation if (token == "anisor") { material.anisotropy_rotation = parseReal(linebuf); continue; } // ambient texture if (token == "map_Ka") { ParseTextureNameAndOption( out material.ambient_texname, ref material.ambient_texopt, linebuf, /* is_bump */ false); continue; } // diffuse texture if (token == "map_Kd") { ParseTextureNameAndOption(out (material.diffuse_texname), ref (material.diffuse_texopt), linebuf, /* is_bump */ false); continue; } // specular texture if (token == "map_Ks") { ParseTextureNameAndOption(out (material.specular_texname), ref (material.specular_texopt), linebuf, /* is_bump */ false); continue; } // specular highlight texture if (token == "map_Ns") { ParseTextureNameAndOption(out (material.specular_highlight_texname), ref (material.specular_highlight_texopt), linebuf, /* is_bump */ false); continue; } // bump texture if (token == "map_bump" || token == "map_Bump" || token == "bump") { ParseTextureNameAndOption(out (material.bump_texname), ref (material.bump_texopt), linebuf, /* is_bump */ true); continue; } // alpha texture if (token == "map_d") { material.alpha_texname = linebuf.ReadWord(); ParseTextureNameAndOption(out (material.alpha_texname), ref (material.alpha_texopt), linebuf, /* is_bump */ false); continue; } // displacement texture if (token == "disp") { ParseTextureNameAndOption(out (material.displacement_texname), ref (material.displacement_texopt), linebuf, /* is_bump */ false); continue; } // reflection map if (token == "refl") { ParseTextureNameAndOption(out (material.reflection_texname), ref (material.reflection_texopt), linebuf, /* is_bump */ false); continue; } // PBR: roughness texture if (token == "map_Pr") { ParseTextureNameAndOption(out (material.roughness_texname), ref (material.roughness_texopt), linebuf, /* is_bump */ false); continue; } // PBR: metallic texture if (token == "map_Pm") { ParseTextureNameAndOption(out (material.metallic_texname), ref (material.metallic_texopt), linebuf, /* is_bump */ false); continue; } // PBR: sheen texture if (token == "map_Ps") { ParseTextureNameAndOption(out (material.sheen_texname), ref (material.sheen_texopt), linebuf, /* is_bump */ false); continue; } // PBR: emissive texture if (token == "map_Ke") { ParseTextureNameAndOption(out (material.emissive_texname), ref (material.emissive_texopt), linebuf, /* is_bump */ false); continue; } // PBR: normal map texture if (token == "norm") { ParseTextureNameAndOption( out (material.normal_texname), ref (material.normal_texopt), linebuf, /* is_bump */ false); // @fixme { is_bump will be true? } continue; } material.unknown_parameter.Add(token, linebuf.ReadLine()); } // flush last material. material_map.Add(material.name, materials.Count); materials.Add(material); } public static bool LoadObj(out attrib_t attrib, List<shape_t> shapes, List<material_t> materials, out string err, string filename, string mtl_basedir = null, bool triangulate = true) { attrib = attrib_t.Create(); shapes.Clear(); try { using (StreamReader ifs = new StreamReader(filename)) { MaterialFileReader matFileReader = new MaterialFileReader(mtl_basedir); return LoadObj(ref attrib, shapes, materials, out err, ifs, matFileReader, triangulate); } } catch (IOException ex) { err = string.Format("Cannot open file {0}: {1}", filename, ex.Message); return false; } } private static bool LoadObj(ref attrib_t attrib, List<shape_t> shapes, List<material_t> materials, out string err, TextReader inStream, MaterialReader readMatFn, bool triangulate) { List<real_t> v = new List<real_t>(); List<real_t> vn = new List<real_t>(); List<real_t> vt = new List<real_t>(); List<real_t> vc = new List<real_t>(); List<tag_t> tags = new List<tag_t>(); List<face_t> faceGroup = new List<face_t>(); string name = null; // material Dictionary<string, int> material_map = new Dictionary<string, int>(); int material = -1; // smoothing group id uint current_smoothing_id = 0; // Initial value. 0 means no smoothing. shape_t shape = shape_t.Create(); err = ""; while (inStream.Peek() != -1) { string linebuf = inStream.ReadLine(); if (string.IsNullOrWhiteSpace(linebuf)) continue; LineReader lineReader = new LineReader(linebuf); string token = lineReader.ReadWord(); if (token.StartsWith("#") || string.IsNullOrWhiteSpace(token)) { continue; } // vertex if (token == "v") { real_t x = default(real_t); real_t y = default(real_t); real_t z = default(real_t); real_t r = default(real_t); real_t g = default(real_t); real_t b = default(real_t); parseVertexWithColor(out x, out y, out z, out r, out g, out b, lineReader); v.Add(x); v.Add(y); v.Add(z); vc.Add(r); vc.Add(g); vc.Add(b); continue; } // normal if (token == "vn") { real_t x = default(real_t); real_t y = default(real_t); real_t z = default(real_t); parseReal3(out x, out y, out z, lineReader); vn.Add(x); vn.Add(y); vn.Add(z); continue; } // texcoord if (token == "vt") { real_t x = default(real_t); real_t y = default(real_t); parseReal2(out x, out y, lineReader); vt.Add(x); vt.Add(y); continue; } // face if (token == "f") { face_t face = face_t.Create(); face.smoothing_group_id = current_smoothing_id; while (!lineReader.Eof) { vertex_index_t vi = vertex_index_t.Create(); if (!parseTriple(lineReader, (int)(v.Count / 3), (int)(vn.Count / 3), (int)(vt.Count / 2), ref vi)) { err = "Failed parse 'f' line(e.g zero value for face index)."; return false; } face.vertex_indices.Add(vi); } faceGroup.Add(face); continue; } // use mtl if (token == "usemtl") { int newMaterialId = -1; token = lineReader.ReadWord(); if (material_map.ContainsKey(token)) { newMaterialId = material_map[token]; } else { // { error!! material not found } } if (newMaterialId != material) { // Create per-face material. Thus we don't add `shape` to `shapes` at // this time. // just clear `faceGroup` after `exportFaceGroupToShape()` call. exportFaceGroupToShape(ref shape, faceGroup, tags, material, name, triangulate, v); faceGroup.Clear(); material = newMaterialId; } } // load mtl if (token == "mtllib") { if (readMatFn != null) { string[] filenames = lineReader.ReadSplit(' ', '\t'); if (filenames.Length == 0) { err += "WARN: Looks like empty filename for mtllib. Use default material. "; } else { bool found = false; for (int s = 0; s < filenames.Length; s++) { string err_mtl; bool ok = readMatFn.Load(filenames[s].Trim(), materials, material_map, out err_mtl); if (!string.IsNullOrWhiteSpace(err_mtl)) { err += err_mtl; } if (ok) { found = true; break; } } if (!found) { err += "WARN: Failed to load material file(s). Use default material. "; } } } continue; } if (token == "g") { // flush previous face group; exportFaceGroupToShape(ref shape, faceGroup, tags, material, name, triangulate, v); if (shape.mesh.indices.Count > 0) { shapes.Add(shape); } // material = -1; faceGroup.Clear(); shape = shape_t.Create(); name = lineReader.ReadWord() ?? ""; continue; } // object name if (token == "o") { // flush previous face group; bool ret1 = exportFaceGroupToShape(ref shape, faceGroup, tags, material, name, triangulate, v); if (ret1) { shapes.Add(shape); } // material = -1; faceGroup.Clear(); shape = shape_t.Create(); /// TODO: { multiple object name? } name = lineReader.ReadWord() ?? ""; continue; } if (token == "t") { tag_t tag = tag_t.Create(); tag.name = parseString(lineReader); tag_sizes ts = parseTagTriple(lineReader); for (int i = 0; i < ts.num_ints; i++) { tag.intValues.Add(parseInt(lineReader)); } for (int i = 0; i < ts.num_reals; i++) { tag.floatValues.Add(parseReal(lineReader)); } for (int i = 0; i < ts.num_strings; i++) { tag.stringValues.Add(parseString(lineReader)); } tags.Add(tag); continue; } if (token == "s") { // smoothing group id token = lineReader.ReadWord(); if (string.IsNullOrWhiteSpace(token)) continue; if (token.Length >= 3) { if (token.StartsWith("off")) { current_smoothing_id = 0; } } else { // assume number int smGroupId = parseInt(new LineReader(token)); if (smGroupId < 0) { // parse error. force set to 0. // FIXME(syoyo): Report warning. current_smoothing_id = 0; } else { current_smoothing_id = (uint)smGroupId; } } continue; } // smoothing group id // Ignore unknown command. } bool ret = exportFaceGroupToShape(ref shape, faceGroup, tags, material, name, triangulate, v); // exportFaceGroupToShape return false when `usemtl` is called in the last // line. // we also add `shape` to `shapes` when `shape.mesh` has already some // faces(indices) if (ret || shape.mesh.indices.Count > 0) { shapes.Add(shape); } faceGroup.Clear(); // for safety attrib.vertices = v; attrib.normals = vn; attrib.texcoords = vt; attrib.colors = vc; return true; } private static int atoi(string input, int default_value = 0) { int ret; if (input != null && Int32.TryParse(input, out ret)) return ret; return default_value; } } }
26.321372
217
0.574991
[ "MIT" ]
bazoocaze/VulkanCpu
tinyobjloaderLib/tinyobj.cs
49,881
C#
using System; using System.IO; using System.Text; using System.Xml.Serialization; using FieldDataPluginFramework; using SxSPro.Schema; namespace SxSPro { public class SectionBySectionSerializer { public static XmlRoot DeserializeNoThrow(Stream stream, ILog logger) { try { using (var streamReader = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: 4096, leaveOpen: true)) { var xmlString = streamReader.ReadToEnd(); stream.Position = 0; var serializer = new XmlSerializer(typeof(XmlRoot)); var memoryStream = new MemoryStream((new UTF8Encoding()).GetBytes(xmlString)); return serializer.Deserialize(memoryStream) as XmlRoot; } } catch (Exception exception) { logger.Error($"Deserialization failed:{exception}"); return null; } } } }
30.222222
98
0.566176
[ "Apache-2.0" ]
AquaticInformatics/sxs-pro-field-data-plugin
src/SxSPro/SectionBySectionSerializer.cs
1,090
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; namespace PeerCastStation.Core { public static class IPAddressExtension { static public bool IsSiteLocal(this IPAddress addr) { switch (addr.AddressFamily) { case System.Net.Sockets.AddressFamily.InterNetwork: var addr_bytes = addr.GetAddressBytes(); return addr_bytes[0] == 10 || addr_bytes[0] == 127 || addr_bytes[0] == 169 && addr_bytes[1] == 254 || addr_bytes[0] == 172 && (addr_bytes[1]&0xF0) == 16 || addr_bytes[0] == 192 && addr_bytes[1] == 168; case System.Net.Sockets.AddressFamily.InterNetworkV6: return addr.IsIPv6LinkLocal || addr.IsIPv6SiteLocal || addr==IPAddress.IPv6Loopback; default: return false; } } static public int GetAddressLocality(this IPAddress addr) { switch (addr.AddressFamily) { case System.Net.Sockets.AddressFamily.InterNetwork: if (addr==IPAddress.Any || addr==IPAddress.None || addr==IPAddress.Broadcast) return -1; if (addr==IPAddress.Loopback) return 0; if (IsSiteLocal(addr)) return 1; return 2; case System.Net.Sockets.AddressFamily.InterNetworkV6: if (addr==IPAddress.IPv6Any || addr==IPAddress.IPv6None) return -1; if (addr==IPAddress.IPv6Loopback) return 0; if (IsSiteLocal(addr)) return 1; return 2; default: return -1; } } } }
30.058824
96
0.619048
[ "Apache-2.0" ]
mozsh/peercaststation
PeerCastStation/PeerCastStation.Core/IPAddressExtension.cs
1,535
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; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; namespace CommunityToolkit.Mvvm.ComponentModel; /// <summary> /// A base class for objects implementing the <see cref="INotifyDataErrorInfo"/> interface. This class /// also inherits from <see cref="ObservableObject"/>, so it can be used for observable items too. /// </summary> public abstract class ObservableValidator : ObservableObject, INotifyDataErrorInfo { /// <summary> /// The <see cref="ConditionalWeakTable{TKey,TValue}"/> instance used to track compiled delegates to validate entities. /// </summary> private static readonly ConditionalWeakTable<Type, Action<object>> EntityValidatorMap = new(); /// <summary> /// The <see cref="ConditionalWeakTable{TKey, TValue}"/> instance used to track display names for properties to validate. /// </summary> /// <remarks> /// This is necessary because we want to reuse the same <see cref="ValidationContext"/> instance for all validations, but /// with the same behavior with repsect to formatted names that new instances would have provided. The issue is that the /// <see cref="ValidationContext.DisplayName"/> property is not refreshed when we set <see cref="ValidationContext.MemberName"/>, /// so we need to replicate the same logic to retrieve the right display name for properties to validate and update that /// property manually right before passing the context to <see cref="Validator"/> and proceed with the normal functionality. /// </remarks> private static readonly ConditionalWeakTable<Type, Dictionary<string, string>> DisplayNamesMap = new(); /// <summary> /// The cached <see cref="PropertyChangedEventArgs"/> for <see cref="HasErrors"/>. /// </summary> private static readonly PropertyChangedEventArgs HasErrorsChangedEventArgs = new(nameof(HasErrors)); /// <summary> /// The <see cref="ValidationContext"/> instance currenty in use. /// </summary> private readonly ValidationContext validationContext; /// <summary> /// The <see cref="Dictionary{TKey,TValue}"/> instance used to store previous validation results. /// </summary> private readonly Dictionary<string, List<ValidationResult>> errors = new(); /// <summary> /// Indicates the total number of properties with errors (not total errors). /// This is used to allow <see cref="HasErrors"/> to operate in O(1) time, as it can just /// check whether this value is not 0 instead of having to traverse <see cref="errors"/>. /// </summary> private int totalErrors; /// <inheritdoc/> public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged; /// <summary> /// Initializes a new instance of the <see cref="ObservableValidator"/> class. /// This constructor will create a new <see cref="ValidationContext"/> that will /// be used to validate all properties, which will reference the current instance /// and no additional services or validation properties and settings. /// </summary> [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] protected ObservableValidator() { this.validationContext = new ValidationContext(this); } /// <summary> /// Initializes a new instance of the <see cref="ObservableValidator"/> class. /// This constructor will create a new <see cref="ValidationContext"/> that will /// be used to validate all properties, which will reference the current instance. /// </summary> /// <param name="items">A set of key/value pairs to make available to consumers.</param> [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] protected ObservableValidator(IDictionary<object, object?>? items) { this.validationContext = new ValidationContext(this, items); } /// <summary> /// Initializes a new instance of the <see cref="ObservableValidator"/> class. /// This constructor will create a new <see cref="ValidationContext"/> that will /// be used to validate all properties, which will reference the current instance. /// </summary> /// <param name="serviceProvider">An <see cref="IServiceProvider"/> instance to make available during validation.</param> /// <param name="items">A set of key/value pairs to make available to consumers.</param> [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] protected ObservableValidator(IServiceProvider? serviceProvider, IDictionary<object, object?>? items) { this.validationContext = new ValidationContext(this, serviceProvider, items); } /// <summary> /// Initializes a new instance of the <see cref="ObservableValidator"/> class. /// This constructor will store the input <see cref="ValidationContext"/> instance, /// and it will use it to validate all properties for the current viewmodel. /// </summary> /// <param name="validationContext"> /// The <see cref="ValidationContext"/> instance to use to validate properties. /// <para> /// This instance will be passed to all <see cref="Validator.TryValidateObject(object, ValidationContext, ICollection{ValidationResult})"/> /// calls executed by the current viewmodel, and its <see cref="ValidationContext.MemberName"/> property will be updated every time /// before the call is made to set the name of the property being validated. The property name will not be reset after that, so the /// value of <see cref="ValidationContext.MemberName"/> will always indicate the name of the last property that was validated, if any. /// </para> /// </param> /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="validationContext"/> is <see langword="null"/>.</exception> protected ObservableValidator(ValidationContext validationContext) { ArgumentNullException.ThrowIfNull(validationContext); this.validationContext = validationContext; } /// <inheritdoc/> public bool HasErrors => this.totalErrors > 0; /// <summary> /// Compares the current and new values for a given property. If the value has changed, /// raises the <see cref="ObservableObject.PropertyChanging"/> event, updates the property with /// the new value, then raises the <see cref="ObservableObject.PropertyChanged"/> event. /// </summary> /// <typeparam name="T">The type of the property that changed.</typeparam> /// <param name="field">The field storing the property's value.</param> /// <param name="newValue">The property's value after the change occurred.</param> /// <param name="validate">If <see langword="true"/>, <paramref name="newValue"/> will also be validated.</param> /// <param name="propertyName">(optional) The name of the property that changed.</param> /// <returns><see langword="true"/> if the property was changed, <see langword="false"/> otherwise.</returns> /// <remarks> /// This method is just like <see cref="ObservableObject.SetProperty{T}(ref T,T,string)"/>, just with the addition /// of the <paramref name="validate"/> parameter. If that is set to <see langword="true"/>, the new value will be /// validated and <see cref="ErrorsChanged"/> will be raised if needed. Following the behavior of the base method, /// the <see cref="ObservableObject.PropertyChanging"/> and <see cref="ObservableObject.PropertyChanged"/> events /// are not raised if the current and new value for the target property are the same. /// </remarks> /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="propertyName"/> is <see langword="null"/>.</exception> [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] protected bool SetProperty<T>([NotNullIfNotNull("newValue")] ref T field, T newValue, bool validate, [CallerMemberName] string propertyName = null!) { ArgumentNullException.ThrowIfNull(propertyName); bool propertyChanged = SetProperty(ref field, newValue, propertyName); if (propertyChanged && validate) { ValidateProperty(newValue, propertyName); } return propertyChanged; } /// <summary> /// Compares the current and new values for a given property. If the value has changed, /// raises the <see cref="ObservableObject.PropertyChanging"/> event, updates the property with /// the new value, then raises the <see cref="ObservableObject.PropertyChanged"/> event. /// See additional notes about this overload in <see cref="SetProperty{T}(ref T,T,bool,string)"/>. /// </summary> /// <typeparam name="T">The type of the property that changed.</typeparam> /// <param name="field">The field storing the property's value.</param> /// <param name="newValue">The property's value after the change occurred.</param> /// <param name="comparer">The <see cref="IEqualityComparer{T}"/> instance to use to compare the input values.</param> /// <param name="validate">If <see langword="true"/>, <paramref name="newValue"/> will also be validated.</param> /// <param name="propertyName">(optional) The name of the property that changed.</param> /// <returns><see langword="true"/> if the property was changed, <see langword="false"/> otherwise.</returns> /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="comparer"/> or <paramref name="propertyName"/> are <see langword="null"/>.</exception> [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] protected bool SetProperty<T>([NotNullIfNotNull("newValue")] ref T field, T newValue, IEqualityComparer<T> comparer, bool validate, [CallerMemberName] string propertyName = null!) { ArgumentNullException.ThrowIfNull(comparer); ArgumentNullException.ThrowIfNull(propertyName); bool propertyChanged = SetProperty(ref field, newValue, comparer, propertyName); if (propertyChanged && validate) { ValidateProperty(newValue, propertyName); } return propertyChanged; } /// <summary> /// Compares the current and new values for a given property. If the value has changed, /// raises the <see cref="ObservableObject.PropertyChanging"/> event, updates the property with /// the new value, then raises the <see cref="ObservableObject.PropertyChanged"/> event. Similarly to /// the <see cref="ObservableObject.SetProperty{T}(T,T,Action{T},string)"/> method, this overload should only be /// used when <see cref="ObservableObject.SetProperty{T}(ref T,T,string)"/> can't be used directly. /// </summary> /// <typeparam name="T">The type of the property that changed.</typeparam> /// <param name="oldValue">The current property value.</param> /// <param name="newValue">The property's value after the change occurred.</param> /// <param name="callback">A callback to invoke to update the property value.</param> /// <param name="validate">If <see langword="true"/>, <paramref name="newValue"/> will also be validated.</param> /// <param name="propertyName">(optional) The name of the property that changed.</param> /// <returns><see langword="true"/> if the property was changed, <see langword="false"/> otherwise.</returns> /// <remarks> /// This method is just like <see cref="ObservableObject.SetProperty{T}(T,T,Action{T},string)"/>, just with the addition /// of the <paramref name="validate"/> parameter. As such, following the behavior of the base method, /// the <see cref="ObservableObject.PropertyChanging"/> and <see cref="ObservableObject.PropertyChanged"/> events /// are not raised if the current and new value for the target property are the same. /// </remarks> /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="callback"/> or <paramref name="propertyName"/> are <see langword="null"/>.</exception> [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] protected bool SetProperty<T>(T oldValue, T newValue, Action<T> callback, bool validate, [CallerMemberName] string propertyName = null!) { ArgumentNullException.ThrowIfNull(callback); ArgumentNullException.ThrowIfNull(propertyName); bool propertyChanged = SetProperty(oldValue, newValue, callback, propertyName); if (propertyChanged && validate) { ValidateProperty(newValue, propertyName); } return propertyChanged; } /// <summary> /// Compares the current and new values for a given property. If the value has changed, /// raises the <see cref="ObservableObject.PropertyChanging"/> event, updates the property with /// the new value, then raises the <see cref="ObservableObject.PropertyChanged"/> event. /// See additional notes about this overload in <see cref="SetProperty{T}(T,T,Action{T},bool,string)"/>. /// </summary> /// <typeparam name="T">The type of the property that changed.</typeparam> /// <param name="oldValue">The current property value.</param> /// <param name="newValue">The property's value after the change occurred.</param> /// <param name="comparer">The <see cref="IEqualityComparer{T}"/> instance to use to compare the input values.</param> /// <param name="callback">A callback to invoke to update the property value.</param> /// <param name="validate">If <see langword="true"/>, <paramref name="newValue"/> will also be validated.</param> /// <param name="propertyName">(optional) The name of the property that changed.</param> /// <returns><see langword="true"/> if the property was changed, <see langword="false"/> otherwise.</returns> /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="comparer"/>, <paramref name="callback"/> or <paramref name="propertyName"/> are <see langword="null"/>.</exception> [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] protected bool SetProperty<T>(T oldValue, T newValue, IEqualityComparer<T> comparer, Action<T> callback, bool validate, [CallerMemberName] string propertyName = null!) { ArgumentNullException.ThrowIfNull(comparer); ArgumentNullException.ThrowIfNull(callback); ArgumentNullException.ThrowIfNull(propertyName); bool propertyChanged = SetProperty(oldValue, newValue, comparer, callback, propertyName); if (propertyChanged && validate) { ValidateProperty(newValue, propertyName); } return propertyChanged; } /// <summary> /// Compares the current and new values for a given nested property. If the value has changed, /// raises the <see cref="ObservableObject.PropertyChanging"/> event, updates the property and then raises the /// <see cref="ObservableObject.PropertyChanged"/> event. The behavior mirrors that of /// <see cref="ObservableObject.SetProperty{TModel,T}(T,T,TModel,Action{TModel,T},string)"/>, with the difference being that this /// method is used to relay properties from a wrapped model in the current instance. For more info, see the docs for /// <see cref="ObservableObject.SetProperty{TModel,T}(T,T,TModel,Action{TModel,T},string)"/>. /// </summary> /// <typeparam name="TModel">The type of model whose property (or field) to set.</typeparam> /// <typeparam name="T">The type of property (or field) to set.</typeparam> /// <param name="oldValue">The current property value.</param> /// <param name="newValue">The property's value after the change occurred.</param> /// <param name="model">The model </param> /// <param name="callback">The callback to invoke to set the target property value, if a change has occurred.</param> /// <param name="validate">If <see langword="true"/>, <paramref name="newValue"/> will also be validated.</param> /// <param name="propertyName">(optional) The name of the property that changed.</param> /// <returns><see langword="true"/> if the property was changed, <see langword="false"/> otherwise.</returns> /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="model"/>, <paramref name="callback"/> or <paramref name="propertyName"/> are <see langword="null"/>.</exception> [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] protected bool SetProperty<TModel, T>(T oldValue, T newValue, TModel model, Action<TModel, T> callback, bool validate, [CallerMemberName] string propertyName = null!) where TModel : class { ArgumentNullException.ThrowIfNull(model); ArgumentNullException.ThrowIfNull(callback); ArgumentNullException.ThrowIfNull(propertyName); bool propertyChanged = SetProperty(oldValue, newValue, model, callback, propertyName); if (propertyChanged && validate) { ValidateProperty(newValue, propertyName); } return propertyChanged; } /// <summary> /// Compares the current and new values for a given nested property. If the value has changed, /// raises the <see cref="ObservableObject.PropertyChanging"/> event, updates the property and then raises the /// <see cref="ObservableObject.PropertyChanged"/> event. The behavior mirrors that of /// <see cref="ObservableObject.SetProperty{TModel,T}(T,T,IEqualityComparer{T},TModel,Action{TModel,T},string)"/>, /// with the difference being that this method is used to relay properties from a wrapped model in the /// current instance. For more info, see the docs for /// <see cref="ObservableObject.SetProperty{TModel,T}(T,T,IEqualityComparer{T},TModel,Action{TModel,T},string)"/>. /// </summary> /// <typeparam name="TModel">The type of model whose property (or field) to set.</typeparam> /// <typeparam name="T">The type of property (or field) to set.</typeparam> /// <param name="oldValue">The current property value.</param> /// <param name="newValue">The property's value after the change occurred.</param> /// <param name="comparer">The <see cref="IEqualityComparer{T}"/> instance to use to compare the input values.</param> /// <param name="model">The model </param> /// <param name="callback">The callback to invoke to set the target property value, if a change has occurred.</param> /// <param name="validate">If <see langword="true"/>, <paramref name="newValue"/> will also be validated.</param> /// <param name="propertyName">(optional) The name of the property that changed.</param> /// <returns><see langword="true"/> if the property was changed, <see langword="false"/> otherwise.</returns> /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="comparer"/>, <paramref name="model"/>, <paramref name="callback"/> or <paramref name="propertyName"/> are <see langword="null"/>.</exception> [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] protected bool SetProperty<TModel, T>(T oldValue, T newValue, IEqualityComparer<T> comparer, TModel model, Action<TModel, T> callback, bool validate, [CallerMemberName] string propertyName = null!) where TModel : class { ArgumentNullException.ThrowIfNull(comparer); ArgumentNullException.ThrowIfNull(model); ArgumentNullException.ThrowIfNull(callback); ArgumentNullException.ThrowIfNull(propertyName); bool propertyChanged = SetProperty(oldValue, newValue, comparer, model, callback, propertyName); if (propertyChanged && validate) { ValidateProperty(newValue, propertyName); } return propertyChanged; } /// <summary> /// Tries to validate a new value for a specified property. If the validation is successful, /// <see cref="ObservableObject.SetProperty{T}(ref T,T,string?)"/> is called, otherwise no state change is performed. /// </summary> /// <typeparam name="T">The type of the property that changed.</typeparam> /// <param name="field">The field storing the property's value.</param> /// <param name="newValue">The property's value after the change occurred.</param> /// <param name="errors">The resulting validation errors, if any.</param> /// <param name="propertyName">(optional) The name of the property that changed.</param> /// <returns>Whether the validation was successful and the property value changed as well.</returns> /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="propertyName"/> is <see langword="null"/>.</exception> [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] protected bool TrySetProperty<T>(ref T field, T newValue, out IReadOnlyCollection<ValidationResult> errors, [CallerMemberName] string propertyName = null!) { ArgumentNullException.ThrowIfNull(propertyName); return TryValidateProperty(newValue, propertyName, out errors) && SetProperty(ref field, newValue, propertyName); } /// <summary> /// Tries to validate a new value for a specified property. If the validation is successful, /// <see cref="ObservableObject.SetProperty{T}(ref T,T,IEqualityComparer{T},string?)"/> is called, otherwise no state change is performed. /// </summary> /// <typeparam name="T">The type of the property that changed.</typeparam> /// <param name="field">The field storing the property's value.</param> /// <param name="newValue">The property's value after the change occurred.</param> /// <param name="comparer">The <see cref="IEqualityComparer{T}"/> instance to use to compare the input values.</param> /// <param name="errors">The resulting validation errors, if any.</param> /// <param name="propertyName">(optional) The name of the property that changed.</param> /// <returns>Whether the validation was successful and the property value changed as well.</returns> /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="comparer"/> or <paramref name="propertyName"/> are <see langword="null"/>.</exception> [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] protected bool TrySetProperty<T>(ref T field, T newValue, IEqualityComparer<T> comparer, out IReadOnlyCollection<ValidationResult> errors, [CallerMemberName] string propertyName = null!) { ArgumentNullException.ThrowIfNull(comparer); ArgumentNullException.ThrowIfNull(propertyName); return TryValidateProperty(newValue, propertyName, out errors) && SetProperty(ref field, newValue, comparer, propertyName); } /// <summary> /// Tries to validate a new value for a specified property. If the validation is successful, /// <see cref="ObservableObject.SetProperty{T}(T,T,Action{T},string?)"/> is called, otherwise no state change is performed. /// </summary> /// <typeparam name="T">The type of the property that changed.</typeparam> /// <param name="oldValue">The current property value.</param> /// <param name="newValue">The property's value after the change occurred.</param> /// <param name="callback">A callback to invoke to update the property value.</param> /// <param name="errors">The resulting validation errors, if any.</param> /// <param name="propertyName">(optional) The name of the property that changed.</param> /// <returns>Whether the validation was successful and the property value changed as well.</returns> /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="callback"/> or <paramref name="propertyName"/> are <see langword="null"/>.</exception> [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] protected bool TrySetProperty<T>(T oldValue, T newValue, Action<T> callback, out IReadOnlyCollection<ValidationResult> errors, [CallerMemberName] string propertyName = null!) { ArgumentNullException.ThrowIfNull(callback); ArgumentNullException.ThrowIfNull(propertyName); return TryValidateProperty(newValue, propertyName, out errors) && SetProperty(oldValue, newValue, callback, propertyName); } /// <summary> /// Tries to validate a new value for a specified property. If the validation is successful, /// <see cref="ObservableObject.SetProperty{T}(T,T,IEqualityComparer{T},Action{T},string?)"/> is called, otherwise no state change is performed. /// </summary> /// <typeparam name="T">The type of the property that changed.</typeparam> /// <param name="oldValue">The current property value.</param> /// <param name="newValue">The property's value after the change occurred.</param> /// <param name="comparer">The <see cref="IEqualityComparer{T}"/> instance to use to compare the input values.</param> /// <param name="callback">A callback to invoke to update the property value.</param> /// <param name="errors">The resulting validation errors, if any.</param> /// <param name="propertyName">(optional) The name of the property that changed.</param> /// <returns>Whether the validation was successful and the property value changed as well.</returns> /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="comparer"/>, <paramref name="callback"/> or <paramref name="propertyName"/> are <see langword="null"/>.</exception> [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] protected bool TrySetProperty<T>(T oldValue, T newValue, IEqualityComparer<T> comparer, Action<T> callback, out IReadOnlyCollection<ValidationResult> errors, [CallerMemberName] string propertyName = null!) { ArgumentNullException.ThrowIfNull(comparer); ArgumentNullException.ThrowIfNull(callback); ArgumentNullException.ThrowIfNull(propertyName); return TryValidateProperty(newValue, propertyName, out errors) && SetProperty(oldValue, newValue, comparer, callback, propertyName); } /// <summary> /// Tries to validate a new value for a specified property. If the validation is successful, /// <see cref="ObservableObject.SetProperty{TModel,T}(T,T,TModel,Action{TModel,T},string?)"/> is called, otherwise no state change is performed. /// </summary> /// <typeparam name="TModel">The type of model whose property (or field) to set.</typeparam> /// <typeparam name="T">The type of property (or field) to set.</typeparam> /// <param name="oldValue">The current property value.</param> /// <param name="newValue">The property's value after the change occurred.</param> /// <param name="model">The model </param> /// <param name="callback">The callback to invoke to set the target property value, if a change has occurred.</param> /// <param name="errors">The resulting validation errors, if any.</param> /// <param name="propertyName">(optional) The name of the property that changed.</param> /// <returns>Whether the validation was successful and the property value changed as well.</returns> /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="model"/>, <paramref name="callback"/> or <paramref name="propertyName"/> are <see langword="null"/>.</exception> [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] protected bool TrySetProperty<TModel, T>(T oldValue, T newValue, TModel model, Action<TModel, T> callback, out IReadOnlyCollection<ValidationResult> errors, [CallerMemberName] string propertyName = null!) where TModel : class { ArgumentNullException.ThrowIfNull(model); ArgumentNullException.ThrowIfNull(callback); ArgumentNullException.ThrowIfNull(propertyName); return TryValidateProperty(newValue, propertyName, out errors) && SetProperty(oldValue, newValue, model, callback, propertyName); } /// <summary> /// Tries to validate a new value for a specified property. If the validation is successful, /// <see cref="ObservableObject.SetProperty{TModel,T}(T,T,IEqualityComparer{T},TModel,Action{TModel,T},string?)"/> is called, otherwise no state change is performed. /// </summary> /// <typeparam name="TModel">The type of model whose property (or field) to set.</typeparam> /// <typeparam name="T">The type of property (or field) to set.</typeparam> /// <param name="oldValue">The current property value.</param> /// <param name="newValue">The property's value after the change occurred.</param> /// <param name="comparer">The <see cref="IEqualityComparer{T}"/> instance to use to compare the input values.</param> /// <param name="model">The model </param> /// <param name="callback">The callback to invoke to set the target property value, if a change has occurred.</param> /// <param name="errors">The resulting validation errors, if any.</param> /// <param name="propertyName">(optional) The name of the property that changed.</param> /// <returns>Whether the validation was successful and the property value changed as well.</returns> /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="comparer"/>, <paramref name="model"/>, <paramref name="callback"/> or <paramref name="propertyName"/> are <see langword="null"/>.</exception> [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] protected bool TrySetProperty<TModel, T>(T oldValue, T newValue, IEqualityComparer<T> comparer, TModel model, Action<TModel, T> callback, out IReadOnlyCollection<ValidationResult> errors, [CallerMemberName] string propertyName = null!) where TModel : class { ArgumentNullException.ThrowIfNull(comparer); ArgumentNullException.ThrowIfNull(model); ArgumentNullException.ThrowIfNull(callback); ArgumentNullException.ThrowIfNull(propertyName); return TryValidateProperty(newValue, propertyName, out errors) && SetProperty(oldValue, newValue, comparer, model, callback, propertyName); } /// <summary> /// Clears the validation errors for a specified property or for the entire entity. /// </summary> /// <param name="propertyName"> /// The name of the property to clear validation errors for. /// If a <see langword="null"/> or empty name is used, all entity-level errors will be cleared. /// </param> protected void ClearErrors(string? propertyName = null) { // Clear entity-level errors when the target property is null or empty if (string.IsNullOrEmpty(propertyName)) { ClearAllErrors(); } else { ClearErrorsForProperty(propertyName!); } } /// <inheritdoc cref="INotifyDataErrorInfo.GetErrors(string)"/> public IEnumerable<ValidationResult> GetErrors(string? propertyName = null) { // Get entity-level errors when the target property is null or empty if (string.IsNullOrEmpty(propertyName)) { // Local function to gather all the entity-level errors [MethodImpl(MethodImplOptions.NoInlining)] IEnumerable<ValidationResult> GetAllErrors() { return this.errors.Values.SelectMany(static errors => errors); } return GetAllErrors(); } // Property-level errors, if any if (this.errors.TryGetValue(propertyName!, out List<ValidationResult>? errors)) { return errors; } // The INotifyDataErrorInfo.GetErrors method doesn't specify exactly what to // return when the input property name is invalid, but given that the return // type is marked as a non-nullable reference type, here we're returning an // empty array to respect the contract. This also matches the behavior of // this method whenever errors for a valid properties are retrieved. return Array.Empty<ValidationResult>(); } /// <inheritdoc/> IEnumerable INotifyDataErrorInfo.GetErrors(string? propertyName) => GetErrors(propertyName); /// <summary> /// Validates all the properties in the current instance and updates all the tracked errors. /// If any changes are detected, the <see cref="ErrorsChanged"/> event will be raised. /// </summary> /// <remarks> /// Only public instance properties (excluding custom indexers) that have at least one /// <see cref="ValidationAttribute"/> applied to them will be validated. All other /// members in the current instance will be ignored. None of the processed properties /// will be modified - they will only be used to retrieve their values and validate them. /// </remarks> [RequiresUnreferencedCode( "This method requires the generated CommunityToolkit.Mvvm.ComponentModel.__Internals.__ObservableValidatorExtensions type not to be removed to use the fast path. " + "If this type is removed by the linker, or if the target recipient was created dynamically and was missed by the source generator, a slower fallback " + "path using a compiled LINQ expression will be used. This will have more overhead in the first invocation of this method for any given recipient type. " + "Additionally, due to the usage of validation APIs, the type of the current instance cannot be statically discovered.")] protected void ValidateAllProperties() { #pragma warning disable IL2026 // Fast path that tries to create a delegate from a generated type-specific method. This // is used to make this method more AOT-friendly and faster, as there is no dynamic code. static Action<object> GetValidationAction(Type type) { if (type.Assembly.GetType("CommunityToolkit.Mvvm.ComponentModel.__Internals.__ObservableValidatorExtensions") is Type extensionsType && extensionsType.GetMethod("CreateAllPropertiesValidator", new[] { type }) is MethodInfo methodInfo) { return (Action<object>)methodInfo.Invoke(null, new object?[] { null })!; } return GetValidationActionFallback(type); } #pragma warning restore IL2026 // Fallback method to create the delegate with a compiled LINQ expression static Action<object> GetValidationActionFallback(Type type) { // Get the collection of all properties to validate (string Name, MethodInfo GetMethod)[] validatableProperties = ( from property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public) where property.GetIndexParameters().Length == 0 && property.GetCustomAttributes<ValidationAttribute>(true).Any() let getMethod = property.GetMethod where getMethod is not null select (property.Name, getMethod)).ToArray(); // Short path if there are no properties to validate if (validatableProperties.Length == 0) { return static _ => { }; } // MyViewModel inst0 = (MyViewModel)arg0; ParameterExpression arg0 = Expression.Parameter(typeof(object)); UnaryExpression inst0 = Expression.Convert(arg0, type); // Get a reference to ValidateProperty(object, string) MethodInfo validateMethod = typeof(ObservableValidator).GetMethod(nameof(ValidateProperty), BindingFlags.Instance | BindingFlags.NonPublic)!; // We want a single compiled LINQ expression that validates all properties in the // actual type of the executing viewmodel at once. We do this by creating a block // expression with the unrolled invocations of all properties to validate. // Essentially, the body will contain the following code: // =============================================================================== // { // inst0.ValidateProperty(inst0.Property0, nameof(MyViewModel.Property0)); // inst0.ValidateProperty(inst0.Property1, nameof(MyViewModel.Property1)); // ... // inst0.ValidateProperty(inst0.PropertyN, nameof(MyViewModel.PropertyN)); // } // =============================================================================== // We also add an explicit object conversion to represent boxing, if a given property // is a value type. It will just be a no-op if the value is a reference type already. // Note that this generated code is technically accessing a protected method from // ObservableValidator externally, but that is fine because IL doesn't really have // a concept of member visibility, that's purely a C# build-time feature. BlockExpression body = Expression.Block( from property in validatableProperties select Expression.Call(inst0, validateMethod, new Expression[] { Expression.Convert(Expression.Call(inst0, property.GetMethod), typeof(object)), Expression.Constant(property.Name) })); return Expression.Lambda<Action<object>>(body, arg0).Compile(); } // Get or compute the cached list of properties to validate. Here we're using a static lambda to ensure the // delegate is cached by the C# compiler, see the related issue at https://github.com/dotnet/roslyn/issues/5835. EntityValidatorMap.GetValue(GetType(), static t => GetValidationAction(t))(this); } /// <summary> /// Validates a property with a specified name and a given input value. /// If any changes are detected, the <see cref="ErrorsChanged"/> event will be raised. /// </summary> /// <param name="value">The value to test for the specified property.</param> /// <param name="propertyName">The name of the property to validate.</param> /// <exception cref="ArgumentNullException">Thrown when <paramref name="propertyName"/> is <see langword="null"/>.</exception> [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] protected internal void ValidateProperty(object? value, [CallerMemberName] string propertyName = null!) { ArgumentNullException.ThrowIfNull(propertyName); // Check if the property had already been previously validated, and if so retrieve // the reusable list of validation errors from the errors dictionary. This list is // used to add new validation errors below, if any are produced by the validator. // If the property isn't present in the dictionary, add it now to avoid allocations. if (!this.errors.TryGetValue(propertyName, out List<ValidationResult>? propertyErrors)) { propertyErrors = new List<ValidationResult>(); this.errors.Add(propertyName, propertyErrors); } bool errorsChanged = false; // Clear the errors for the specified property, if any if (propertyErrors.Count > 0) { propertyErrors.Clear(); errorsChanged = true; } // Validate the property, by adding new errors to the existing list this.validationContext.MemberName = propertyName; this.validationContext.DisplayName = GetDisplayNameForProperty(propertyName); bool isValid = Validator.TryValidateProperty(value, this.validationContext, propertyErrors); // Update the shared counter for the number of errors, and raise the // property changed event if necessary. We decrement the number of total // errors if the current property is valid but it wasn't so before this // validation, and we increment it if the validation failed after being // correct before. The property changed event is raised whenever the // number of total errors is either decremented to 0, or incremented to 1. if (isValid) { if (errorsChanged) { this.totalErrors--; if (this.totalErrors == 0) { OnPropertyChanged(HasErrorsChangedEventArgs); } } } else if (!errorsChanged) { this.totalErrors++; if (this.totalErrors == 1) { OnPropertyChanged(HasErrorsChangedEventArgs); } } // Only raise the event once if needed. This happens either when the target property // had existing errors and is now valid, or if the validation has failed and there are // new errors to broadcast, regardless of the previous validation state for the property. if (errorsChanged || !isValid) { ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName)); } } /// <summary> /// Tries to validate a property with a specified name and a given input value, and returns /// the computed errors, if any. If the property is valid, it is assumed that its value is /// about to be set in the current object. Otherwise, no observable local state is modified. /// </summary> /// <param name="value">The value to test for the specified property.</param> /// <param name="propertyName">The name of the property to validate.</param> /// <param name="errors">The resulting validation errors, if any.</param> [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] private bool TryValidateProperty(object? value, string propertyName, out IReadOnlyCollection<ValidationResult> errors) { // Add the cached errors list for later use. if (!this.errors.TryGetValue(propertyName!, out List<ValidationResult>? propertyErrors)) { propertyErrors = new List<ValidationResult>(); this.errors.Add(propertyName!, propertyErrors); } bool hasErrors = propertyErrors.Count > 0; List<ValidationResult> localErrors = new(); // Validate the property, by adding new errors to the local list this.validationContext.MemberName = propertyName; this.validationContext.DisplayName = GetDisplayNameForProperty(propertyName!); bool isValid = Validator.TryValidateProperty(value, this.validationContext, localErrors); // We only modify the state if the property is valid and it wasn't so before. In this case, we // clear the cached list of errors (which is visible to consumers) and raise the necessary events. if (isValid && hasErrors) { propertyErrors.Clear(); this.totalErrors--; if (this.totalErrors == 0) { OnPropertyChanged(HasErrorsChangedEventArgs); } ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName)); } errors = localErrors; return isValid; } /// <summary> /// Clears all the current errors for the entire entity. /// </summary> private void ClearAllErrors() { if (this.totalErrors == 0) { return; } // Clear the errors for all properties with at least one error, and raise the // ErrorsChanged event for those properties. Other properties will be ignored. foreach (KeyValuePair<string, List<ValidationResult>> propertyInfo in this.errors) { bool hasErrors = propertyInfo.Value.Count > 0; propertyInfo.Value.Clear(); if (hasErrors) { ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyInfo.Key)); } } this.totalErrors = 0; OnPropertyChanged(HasErrorsChangedEventArgs); } /// <summary> /// Clears all the current errors for a target property. /// </summary> /// <param name="propertyName">The name of the property to clear errors for.</param> private void ClearErrorsForProperty(string propertyName) { if (!this.errors.TryGetValue(propertyName!, out List<ValidationResult>? propertyErrors) || propertyErrors.Count == 0) { return; } propertyErrors.Clear(); this.totalErrors--; if (this.totalErrors == 0) { OnPropertyChanged(HasErrorsChangedEventArgs); } ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName)); } /// <summary> /// Gets the display name for a given property. It could be a custom name or just the property name. /// </summary> /// <param name="propertyName">The target property name being validated.</param> /// <returns>The display name for the property.</returns> private string GetDisplayNameForProperty(string propertyName) { static Dictionary<string, string> GetDisplayNames(Type type) { Dictionary<string, string> displayNames = new(); foreach (PropertyInfo property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { if (property.GetCustomAttribute<DisplayAttribute>() is DisplayAttribute attribute && attribute.GetName() is string displayName) { displayNames.Add(property.Name, displayName); } } return displayNames; } // This method replicates the logic of DisplayName and GetDisplayName from the // ValidationContext class. See the original source in the BCL for more details. _ = DisplayNamesMap.GetValue(GetType(), static t => GetDisplayNames(t)).TryGetValue(propertyName, out string? displayName); return displayName ?? propertyName; } }
56.507229
239
0.683312
[ "MIT" ]
Avid29/dotnet
CommunityToolkit.Mvvm/ComponentModel/ObservableValidator.cs
46,901
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RotateRoom : MonoBehaviour { public Vector3 RotateAmountMax; // Update is called once per frame void Update() { Vector3 RandomRotate = new Vector3(Random.Range(0, RotateAmountMax.x), Random.Range(0, RotateAmountMax.y), Random.Range(0, RotateAmountMax.z)); transform.Rotate(RandomRotate * Time.deltaTime); } }
27.5
151
0.722727
[ "MIT" ]
KevinWagenvoort/R-D_VR_Sickness_Game
Assets/RotateRoom.cs
442
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Models.Api20170401Preview { using static Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Extensions; /// <summary>The common properties that are associated with Event Hub data sources.</summary> public partial class EventHubDataSourceProperties { /// <summary> /// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject json); /// <summary> /// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject" /// /> before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject container); /// <summary> /// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of /// the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> /// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return /// instantly.</param> partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject json, ref bool returnNow); /// <summary> /// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the /// object before it is serialized. /// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject container, ref bool returnNow); /// <summary> /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject into a new instance of <see cref="EventHubDataSourceProperties" />. /// </summary> /// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject instance to deserialize from.</param> internal EventHubDataSourceProperties(Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject json) { bool returnNow = false; BeforeFromJson(json, ref returnNow); if (returnNow) { return; } __serviceBusDataSourceProperties = new Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Models.Api20170401Preview.ServiceBusDataSourceProperties(json); {_eventHubName = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonString>("eventHubName"), out var __jsonEventHubName) ? (string)__jsonEventHubName : (string)EventHubName;} AfterFromJson(json); } /// <summary> /// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Models.Api20170401Preview.IEventHubDataSourceProperties. /// </summary> /// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonNode" /> to deserialize from.</param> /// <returns> /// an instance of Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Models.Api20170401Preview.IEventHubDataSourceProperties. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Models.Api20170401Preview.IEventHubDataSourceProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonNode node) { return node is Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject json ? new EventHubDataSourceProperties(json) : null; } /// <summary> /// Serializes this instance of <see cref="EventHubDataSourceProperties" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonNode" />. /// </summary> /// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller /// passes in <c>null</c>, a new instance will be created and returned to the caller.</param> /// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.SerializationMode"/>.</param> /// <returns> /// a serialized instance of <see cref="EventHubDataSourceProperties" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonNode" />. /// </returns> public Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.SerializationMode serializationMode) { container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject(); bool returnNow = false; BeforeToJson(ref container, ref returnNow); if (returnNow) { return container; } __serviceBusDataSourceProperties?.ToJson(container, serializationMode); AddIf( null != (((object)this._eventHubName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonString(this._eventHubName.ToString()) : null, "eventHubName" ,container.Add ); AfterToJson(ref container); return container; } } }
71.106796
298
0.701256
[ "MIT" ]
Agazoth/azure-powershell
src/StreamAnalytics/generated/api/Models/Api20170401Preview/EventHubDataSourceProperties.json.cs
7,222
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("01. Take Two")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("01. Take Two")] [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("02b4d4e2-185e-4f1a-9cfa-47cb46d08e36")] // 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.621622
84
0.743534
[ "MIT" ]
PhilipYordanov/Software-University-C-Fundamentals-track
CSharpAdvance/LINQ - Lab/LINQ - Lab/01. Take Two/Properties/AssemblyInfo.cs
1,395
C#
namespace Keras.Layers { /// <summary> /// Turns positive integers (indexes) into dense vectors of fixed size. eg. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]] /// This layer can only be used as the first layer in a model. /// </summary> /// <seealso cref="Keras.Layers.BaseLayer" /> public class Embedding : BaseLayer { /// <summary> /// Initializes a new instance of the <see cref="Embedding"/> class. /// </summary> /// <param name="input_dim"> int > 0. Size of the vocabulary, i.e. maximum integer index + 1.</param> /// <param name="output_dim"> int >= 0. Dimension of the dense embedding.</param> /// <param name="embeddings_initializer"> Initializer for the embeddings matrix (see initializers).</param> /// <param name="embeddings_regularizer"> Regularizer function applied to the embeddings matrix (see regularizer).</param> /// <param name="activity_regularizer"> Regularizer function applied to the output of the layer (its "activation"). (see regularizer).</param> /// <param name="embeddings_constraint"> Constraint function applied to the embeddings matrix (see constraints).</param> /// <param name="mask_zero"> Whether or not the input value 0 is a special "padding" value that should be masked out. This is useful when using recurrent layers which may take variable length input. If this is True then all subsequent layers in the model need to support masking or an exception will be raised. If mask_zero is set to True, as a consequence, index 0 cannot be used in the vocabulary (input_dim should equal size of vocabulary + 1).</param> /// <param name="input_length"> Length of input sequences, when it is constant. This argument is required if you are going to connect Flatten then Dense layers upstream (without it, the shape of the dense outputs cannot be computed).</param> /// <param name="input_shape">2D tensor with shape: (batch_size, sequence_length).</param> public Embedding(int input_dim, int output_dim, string embeddings_initializer= "uniform", string embeddings_regularizer= "", string activity_regularizer= "", string embeddings_constraint= "", bool mask_zero= false, int? input_length= null, Shape input_shape = null) { Parameters["input_dim"] = input_dim; Parameters["output_dim"] = output_dim; Parameters["embeddings_initializer"] = embeddings_initializer; Parameters["embeddings_regularizer"] = embeddings_regularizer; Parameters["activity_regularizer"] = activity_regularizer; Parameters["embeddings_constraint"] = embeddings_constraint; Parameters["mask_zero"] = mask_zero; Parameters["input_length"] = input_length; Parameters["input_shape"] = input_shape; PyInstance = Keras.keras.layers.Embedding; Init(); } } }
73.95
463
0.677147
[ "MIT" ]
BHoM/Keras.NET
Keras/Layers/Embedding.cs
2,978
C#
/* © Cutter Systems spol. s r.o., 2018 Author: Petr Kalandra (kalandra@cutter.cz) 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 Newtonsoft.Json; using System.Collections.Generic; using RosSharp.RosBridgeClient.Messages.Standard; namespace RosSharp.RosBridgeClient.Messages.Actionlib { public class TwoIntsActionResult { [JsonIgnore] public const string RosMessageName = "actionlib/TwoIntsActionResult"; // ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ====== public Header header; public RosSharp.RosBridgeClient.Messages.ActionLib.GoalStatus status; public TwoIntsResult result; public TwoIntsActionResult() { header = new Header(); status = new RosSharp.RosBridgeClient.Messages.ActionLib.GoalStatus(); result = new TwoIntsResult(); } } }
29.744186
73
0.770915
[ "Apache-2.0" ]
kaldap/ros-sharp
Libraries/RosBridgeClient/Messages/Actionlib/TwoIntsActionResult.cs
1,280
C#
public SimpleStepBuilder<I, O> chunk<I, O>(int chunkSize) => new SimpleStepBuilder<I, O>(this).chunk(chunkSize); //https://pt.stackoverflow.com/q/414132/101
39.5
112
0.740506
[ "MIT" ]
dilsondeveloper/SOpt
CSharp/Generics/SyntaxReturn.cs
158
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RavenGallery.Core.Views { public class ImageTagCollectionItem { public string Name { get; set; } public int Count { get; set; } } }
18.428571
40
0.678295
[ "Unlicense" ]
codeinpeace/RavenGallery
RavenGallery.Core/Views/ImageTagCollectionItem.cs
260
C#
using Microsoft.Extensions.Logging; using TopModel.Utils; namespace TopModel.Generator.Ssdt; /// <summary> /// Writer pour l'écriture de fichier. /// Spécifique pour les fichiers SQL (usage du token commentaire SQL). /// </summary> public class SqlFileWriter : FileWriter { public SqlFileWriter(string fileName, ILogger logger) : base(fileName, logger) { } /// <summary> /// Renvoie le token de début de ligne de commentaire dans le langage du fichier. /// </summary> /// <returns>Toket de début de ligne de commentaire.</returns> public override string StartCommentToken => "----"; }
29.5
86
0.66718
[ "MIT" ]
JabX/topmodel
TopModel.Generator/Ssdt/SqlFileWriter.cs
655
C#