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 |
|---|---|---|---|---|---|---|---|---|
/*
* Copyright 2010-2013 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.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using Amazon.Runtime;
namespace Amazon.IdentityManagement.Model
{
/// <summary>
/// Returns information about the ResyncMFADevice response metadata.
/// The ResyncMFADevice operation has a void result type.
/// </summary>
public partial class ResyncMFADeviceResponse : AmazonWebServiceResponse
{
}
}
| 30.969697 | 79 | 0.731898 | [
"Apache-2.0"
] | virajs/aws-sdk-net | AWSSDK_DotNet35/Amazon.IdentityManagement/Model/ResyncMFADeviceResponse.cs | 1,022 | C# |
using System;
using NetOffice;
namespace NetOffice.ExcelApi.Enums
{
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff837807.aspx </remarks>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
[EntityTypeAttribute(EntityType.IsEnum)]
public enum XlBackground
{
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>-4105</remarks>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
xlBackgroundAutomatic = -4105,
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>3</remarks>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
xlBackgroundOpaque = 3,
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>2</remarks>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
xlBackgroundTransparent = 2
}
} | 30.852941 | 119 | 0.651096 | [
"MIT"
] | brunobola/NetOffice | Source/Excel/Enums/XlBackground.cs | 1,051 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using RiskTracker.Entities;
using System.ComponentModel.DataAnnotations;
namespace RiskTracker.Models {
public class Location {
private LocationData ld_;
private IList<Guid> projectIds_;
public Location(LocationData ld) {
ld_ = ld;
projectIds_ = ld_.Projects();
} // Location
public Location() {
ld_ = new LocationData();
ld_.Address = new AddressData();
projectIds_ = new List<Guid>();
}
public Guid Id { get { return ld_.Id; } set { ld_.Id = value; } }
public string Name { get { return ld_.Name; } set { ld_.Name = value; } }
public AddressData Address { get { return ld_.Address; } }
public string Notes { get { return ld_.Notes; } set { ld_.Notes = value; } }
public IList<Guid> ProjectIds { get { return projectIds_; } }
public LocationData locationData() {
ld_.setProjects(projectIds_);
return ld_;
} // locationData
} // class Location
} // namespace RiskTracker.Models | 29.638889 | 80 | 0.662605 | [
"MIT"
] | Inside-Outcomes/Risk-Tracker | RiskMapsCore/Models/Location.cs | 1,069 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace YX
{
public static class RuntimeGizmos
{
private const int SphereSliceCount = 24;
private const int SphereStackCount = 24;
public static Color color;
public static Material mat;
private static Vector3[] _sphereV = new Vector3[(SphereSliceCount - 1) * (SphereSliceCount + 1) + 2];
private static int[] _sphereI = new int[SphereSliceCount * 3 + (SphereStackCount - 2) * SphereSliceCount * 6 + SphereSliceCount * 3];
public static void DrawSphere(Vector3 center, float radius)
{
// 球体创建方法提取自DX11龙书
float phiStep = Mathf.PI / SphereStackCount;
float thetaStep = 2.0f * Mathf.PI / SphereSliceCount;
_sphereV[0].x = center.x;
_sphereV[0].y = radius + center.y;
_sphereV[0].z = center.z;
int vidx = 1;
for (int i = 1; i <= SphereStackCount - 1; ++i)
{
float phi = i * phiStep;
for (int j = 0; j <= SphereSliceCount; ++j)
{
float theta = j * thetaStep;
_sphereV[vidx].x = radius * Mathf.Sin(phi) * Mathf.Cos(theta) + center.x;
_sphereV[vidx].y = radius * Mathf.Cos(phi) + center.y;
_sphereV[vidx].z = radius * Mathf.Sin(phi) * Mathf.Sin(theta) + center.z;
vidx++;
}
}
_sphereV[_sphereV.Length - 1].x = center.x;
_sphereV[_sphereV.Length - 1].y = -radius + center.y;
_sphereV[_sphereV.Length - 1].z = center.z;
int iidx = 0;
for (int i = 1; i <= SphereSliceCount; ++i)
{
_sphereI[iidx++] = 0;
_sphereI[iidx++] = i + 1;
_sphereI[iidx++] = i;
}
int baseIndex = 1;
int ringVertexCount = SphereSliceCount + 1;
for (int i = 0; i < SphereStackCount - 2; ++i)
{
for (int j = 0; j < SphereSliceCount; ++j)
{
_sphereI[iidx++] = (baseIndex + i * ringVertexCount + j);
_sphereI[iidx++] = (baseIndex + i * ringVertexCount + j + 1);
_sphereI[iidx++] = (baseIndex + (i + 1) * ringVertexCount + j);
_sphereI[iidx++] = (baseIndex + (i + 1) * ringVertexCount + j);
_sphereI[iidx++] = (baseIndex + i * ringVertexCount + j + 1);
_sphereI[iidx++] = (baseIndex + (i + 1) * ringVertexCount + j + 1);
}
}
int southPoleIndex = _sphereV.Length - 1;
baseIndex = southPoleIndex - ringVertexCount;
for (int i = 0; i < SphereSliceCount; ++i)
{
_sphereI[iidx++] = (southPoleIndex);
_sphereI[iidx++] = (baseIndex + i);
_sphereI[iidx++] = (baseIndex + i + 1);
}
mat.color = color;
mat.SetPass(0);
GL.Begin(GL.LINES);
GL.Color(color);
for (int i = 0; i < _sphereI.Length; i++)
{
int vi = _sphereI[i];
GL.Vertex(_sphereV[vi]);
}
GL.End();
}
public static void DrawLine(Vector3 from, Vector3 to)
{
mat.color = color;
mat.SetPass(0);
GL.Begin(GL.LINES);
GL.Color(color);
GL.Vertex(from);
GL.Vertex(to);
GL.End();
}
}
} | 35.096154 | 141 | 0.474521 | [
"Apache-2.0"
] | yangxun983323204/unity-utils | Assets/Debug/RuntimeGizmos.cs | 3,674 | C# |
using Orderino.Shared.DTOs;
using System.Threading.Tasks;
namespace Orderino.Infrastructure.Services.Interfaces
{
public interface IOrderHistoryService
{
Task Reorder(ReorderDto reoderDto);
}
}
| 19.636364 | 53 | 0.75 | [
"MIT"
] | extra8/Orderino | Orderino/Orderino.Repository/Services/Interfaces/IOrderHistoryService.cs | 218 | C# |
using System.IO;
using System.Runtime.Serialization;
using GameEstate.Formats.Red.CR2W.Reflection;
using FastMember;
using static GameEstate.Formats.Red.Records.Enums;
namespace GameEstate.Formats.Red.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class W3DamageAreaTrigger : CEntity
{
[Ordinal(1)] [RED("onlyAffectsPlayer")] public CBool OnlyAffectsPlayer { get; set;}
[Ordinal(2)] [RED("activateOnce")] public CBool ActivateOnce { get; set;}
[Ordinal(3)] [RED("checkTag")] public CBool CheckTag { get; set;}
[Ordinal(4)] [RED("isEnabled")] public CBool IsEnabled { get; set;}
[Ordinal(5)] [RED("actorTag")] public CName ActorTag { get; set;}
[Ordinal(6)] [RED("excludedActorsTags", 2,0)] public CArray<CName> ExcludedActorsTags { get; set;}
[Ordinal(7)] [RED("damage")] public CFloat Damage { get; set;}
[Ordinal(8)] [RED("useDamageFromXML")] public CName UseDamageFromXML { get; set;}
[Ordinal(9)] [RED("damageFromFXDelay")] public CFloat DamageFromFXDelay { get; set;}
[Ordinal(10)] [RED("areaRadius")] public CFloat AreaRadius { get; set;}
[Ordinal(11)] [RED("attackInterval")] public CFloat AttackInterval { get; set;}
[Ordinal(12)] [RED("preAttackDuration")] public CFloat PreAttackDuration { get; set;}
[Ordinal(13)] [RED("externalFXEntityTag")] public CName ExternalFXEntityTag { get; set;}
[Ordinal(14)] [RED("externalFXName")] public CName ExternalFXName { get; set;}
[Ordinal(15)] [RED("attackFX")] public CName AttackFX { get; set;}
[Ordinal(16)] [RED("preAttackFX")] public CName PreAttackFX { get; set;}
[Ordinal(17)] [RED("attackFXEntity")] public CHandle<CEntityTemplate> AttackFXEntity { get; set;}
[Ordinal(18)] [RED("soundFX")] public CString SoundFX { get; set;}
[Ordinal(19)] [RED("immunityFact")] public CString ImmunityFact { get; set;}
[Ordinal(20)] [RED("damageType")] public CEnum<ETriggeredDamageType> DamageType { get; set;}
[Ordinal(21)] [RED("action")] public CHandle<W3DamageAction> Action { get; set;}
[Ordinal(22)] [RED("affectedEntity")] public CHandle<CEntity> AffectedEntity { get; set;}
[Ordinal(23)] [RED("fxEntity")] public CHandle<CEntity> FxEntity { get; set;}
[Ordinal(24)] [RED("activated")] public CBool Activated { get; set;}
[Ordinal(25)] [RED("dummyGameplayEntity")] public CHandle<CGameplayEntity> DummyGameplayEntity { get; set;}
[Ordinal(26)] [RED("victim")] public CHandle<CActor> Victim { get; set;}
[Ordinal(27)] [RED("externalFXEntity")] public CHandle<CEntity> ExternalFXEntity { get; set;}
[Ordinal(28)] [RED("pos")] public Vector Pos { get; set;}
public W3DamageAreaTrigger(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new W3DamageAreaTrigger(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 39.683544 | 131 | 0.675917 | [
"MIT"
] | smorey2/GameEstate | src/GameEstate.Formats.Red/Formats/Red/W3/RTTIConvert/W3DamageAreaTrigger.cs | 3,135 | C# |
using System;
namespace MicroserviceTemplate.Domain.Models
{
public class Item
{
public Guid Id { get; set; }
public string Name { get; set; }
}
}
| 16.090909 | 44 | 0.60452 | [
"MIT"
] | albertocorrales/dotnet-template-ddd-cqrs | template/src/MicroserviceTemplate.Domain/MicroserviceTemplate.Domain/Models/ItemAggregate/Item.cs | 179 | C# |
using System.Configuration;
namespace TasksEverywhere.Utilities.Config.Sections
{
public sealed partial class LoggerSectionCollection : ConfigurationElementCollection
{
public LoggerSectionElement this[int index]
{
get
{
return base.BaseGet(index) as LoggerSectionElement;
}
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
public new LoggerSectionElement this[string responseString]
{
get { return (LoggerSectionElement)BaseGet(responseString); }
set
{
if (BaseGet(responseString) != null)
{
BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
}
BaseAdd(value);
}
}
protected override ConfigurationElement CreateNewElement()
{
return new LoggerSectionElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((LoggerSectionElement)(element)).Type;
}
}
} | 27.869565 | 88 | 0.523401 | [
"MIT"
] | Crasso91/TasksEverywhere | TasksEverywhere.Utilities/Config.Sections/LoggerSectionCollection.cs | 1,284 | C# |
using System;
namespace CodeMonkeys
{
public static partial class Argument
{
public static void GreaterThan(
long param,
long value,
string paramName,
string message = "")
{
if (param > value)
return;
if (string.IsNullOrWhiteSpace(message))
message = $"Parameter '{paramName}' is less than minimum value.";
throw new ArgumentException(
message,
paramName);
}
}
}
| 22.04 | 81 | 0.499093 | [
"MIT"
] | UltimateCodeMonkeys/CodeMonkeys | src/Core/Guards/Argument/Argument.Number.cs | 553 | C# |
using BCVP.IServices;
using BCVP.Model.Models;
using Xunit;
using System;
using System.Linq;
using Autofac;
namespace BCVP.Tests
{
public class BlogArticleService_Should
{
private IBlogArticleServices blogArticleServices;
DI_Test dI_Test = new DI_Test();
public BlogArticleService_Should()
{
//mockBlogRep.Setup(r => r.Query());
var container = dI_Test.DICollections();
blogArticleServices = container.Resolve<IBlogArticleServices>();
}
[Fact]
public void BlogArticleServices_Test()
{
Assert.NotNull(blogArticleServices);
}
[Fact]
public async void Get_Blogs_Test()
{
var data = await blogArticleServices.GetBlogs();
Assert.True(data.Any());
}
[Fact]
public async void Add_Blog_Test()
{
BlogArticle blogArticle = new BlogArticle()
{
bCreateTime = DateTime.Now,
bUpdateTime = DateTime.Now,
btitle = "xuint test title",
bcontent = "xuint test content",
bsubmitter = "xuint test submitter",
};
var BId = await blogArticleServices.Add(blogArticle);
Assert.True(BId > 0);
}
[Fact]
public async void Delete_Blog_Test()
{
var deleteModel = (await blogArticleServices.Query(d => d.btitle == "xuint test title")).FirstOrDefault();
Assert.NotNull(deleteModel);
var IsDel = await blogArticleServices.Delete(deleteModel);
Assert.True(IsDel);
}
}
}
| 23.219178 | 118 | 0.562832 | [
"Apache-2.0"
] | hottoy/BCVP.OA | BCVP.Tests/Service_Test/BlogArticleService_Should.cs | 1,695 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using System.Threading.Tasks;
using Tests.Framework;
using Elasticsearch.Net;
using FluentAssertions;
using Xunit;
namespace Tests.ClientConcepts.ServerError
{
public class ServerErrorTests : SerializationTestBase
{
[U]
public void CanDeserializeServerError()
{
var serverErrorJson = @"{
""error"": {
""root_cause"": [
{
""type"": ""parse_exception"",
""reason"": ""failed to parse source for create index""
}
],
""type"": ""parse_exception"",
""reason"": ""failed to parse source for create index"",
""caused_by"": {
""type"": ""json_parse_exception"",
""reason"": ""Unexpected character ('\""' (code 34)): was expecting a colon to separate field name and value\n at [Source: [B@1231dcb3; line: 6, column: 10]""
}
},
""status"": 400
}";
var serverError = this.Deserialize<Elasticsearch.Net.ServerError>(serverErrorJson);
serverError.Should().NotBeNull();
serverError.Status.Should().Be(400);
serverError.Error.Should().NotBeNull();
serverError.Error.RootCause.Count.Should().Be(1);
serverError.Error.CausedBy.Should().NotBeNull();
}
}
}
| 27.851064 | 164 | 0.647059 | [
"Apache-2.0"
] | RossLieberman/NEST | src/Tests/ClientConcepts/ServerError/ServerErrorTests.cs | 1,311 | C# |
using System;
using System.Management.Automation;
using System.Net.Http;
using System.Threading;
using Microsoft.Online.SharePoint.TenantAdministration;
using Microsoft.SharePoint.Client;
using PnP.Core.Services;
using PnP.PowerShell.Commands.Base;
using PnP.PowerShell.Commands.Model;
using Resources = PnP.PowerShell.Commands.Properties.Resources;
using TokenHandler = PnP.PowerShell.Commands.Base.TokenHandler;
namespace PnP.PowerShell.Commands
{
/// <summary>
/// Base class for all the PnP SharePoint related cmdlets
/// </summary>
public abstract class PnPSharePointCmdlet : PnPConnectedCmdlet
{
/// <summary>
/// Reference the the SharePoint context on the current connection. If NULL it means there is no SharePoint context available on the current connection.
/// </summary>
public ClientContext ClientContext => Connection?.Context ?? PnPConnection.Current.Context;
public PnPContext PnPContext => Connection?.PnPContext ?? PnPConnection.Current.PnPContext;
public new HttpClient HttpClient => PnP.Framework.Http.PnPHttpClient.Instance.GetHttpClient(ClientContext);
// do not remove '#!#99'
[Parameter(Mandatory = false, HelpMessage = "Optional connection to be used by the cmdlet. Retrieve the value for this parameter by either specifying -ReturnConnection on Connect-PnPOnline or by executing Get-PnPConnection.")]
public PnPConnection Connection = null;
// do not remove '#!#99'
protected override void BeginProcessing()
{
base.BeginProcessing();
if (PnPConnection.Current != null && PnPConnection.Current.ApplicationInsights != null)
{
PnPConnection.Current.ApplicationInsights.TrackEvent(MyInvocation.MyCommand.Name);
}
if (Connection == null && ClientContext == null)
{
throw new InvalidOperationException(Resources.NoSharePointConnection);
}
}
protected override void ProcessRecord()
{
try
{
var tag = PnPConnection.Current.PnPVersionTag + ":" + MyInvocation.MyCommand.Name;
if (tag.Length > 32)
{
tag = tag.Substring(0, 32);
}
ClientContext.ClientTag = tag;
ExecuteCmdlet();
}
catch (PipelineStoppedException)
{
//don't swallow pipeline stopped exception
//it makes select-object work weird
throw;
}
catch (PnP.Core.SharePointRestServiceException ex)
{
throw new PSInvalidOperationException((ex.Error as PnP.Core.SharePointRestError).Message);
}
catch (PnP.PowerShell.Commands.Model.Graph.GraphException gex)
{
throw new PSInvalidOperationException((gex.Message));
}
catch (Exception ex)
{
PnPConnection.Current.RestoreCachedContext(PnPConnection.Current.Url);
ex.Data["CorrelationId"] = PnPConnection.Current.Context.TraceCorrelationId;
ex.Data["TimeStampUtc"] = DateTime.UtcNow;
var errorDetails = new ErrorDetails(ex.Message);
errorDetails.RecommendedAction = "Use Get-PnPException for more details.";
var errorRecord = new ErrorRecord(ex, "EXCEPTION", ErrorCategory.WriteError, null);
errorRecord.ErrorDetails = errorDetails;
WriteError(errorRecord);
}
}
protected override void EndProcessing()
{
base.EndProcessing();
}
protected string AccessToken
{
get
{
if (PnPConnection.Current != null)
{
if (PnPConnection.Current.Context != null)
{
var settings = Microsoft.SharePoint.Client.InternalClientContextExtensions.GetContextSettings(PnPConnection.Current.Context);
if (settings != null)
{
var authManager = settings.AuthenticationManager;
if (authManager != null)
{
return authManager.GetAccessTokenAsync(PnPConnection.Current.Context.Url).GetAwaiter().GetResult();
}
}
}
}
return null;
}
}
public string GraphAccessToken
{
get
{
if (PnPConnection.Current?.ConnectionMethod == ConnectionMethod.ManagedIdentity)
{
return TokenHandler.GetManagedIdentityTokenAsync(this, HttpClient, $"https://graph.microsoft.com/").GetAwaiter().GetResult();
}
else
{
if (PnPConnection.Current?.Context != null)
{
return TokenHandler.GetAccessToken(GetType(), $"https://{PnPConnection.Current.GraphEndPoint}/.default");
}
}
return null;
}
}
protected void PollOperation(SpoOperation spoOperation)
{
while (true)
{
if (!spoOperation.IsComplete)
{
if (spoOperation.HasTimedout)
{
throw new TimeoutException("SharePoint Operation Timeout");
}
Thread.Sleep(spoOperation.PollingInterval);
if (Stopping)
{
break;
}
ClientContext.Load(spoOperation);
ClientContext.ExecuteQueryRetry();
continue;
}
return;
}
WriteWarning("SharePoint Operation Wait Interrupted");
}
}
}
| 37.424242 | 234 | 0.547206 | [
"MIT"
] | Jwaegebaert/powershell | src/Commands/Base/PnPSharePointCmdlet.cs | 6,177 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using NodaTime;
using SendGrid;
using SendGrid.Helpers.Mail;
using System.Collections.Generic;
using System.Globalization;
using TodoList.Web.Data;
using TodoList.Web.Models;
using TodoList.Web.Services;
using TodoList.Web.Services.Storage;
namespace TodoList.Web
{
public class Startup
{
public Startup(IHostingEnvironment environment)
{
Configuration = new ConfigurationBuilder()
.SetBasePath(environment.ContentRootPath)
.AddJsonFile("appsettings.json", false, true)
.AddJsonFile($"appsettings.{environment.EnvironmentName}.json")
.AddEnvironmentVariables()
.AddUserSecrets<Startup>()
.Build();
Environment = environment;
}
public IConfiguration Configuration { get; }
public IHostingEnvironment Environment { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add localisation
services.AddLocalization(opts => { opts.ResourcesPath = "Resources"; });
services.AddMvc()
.AddViewLocalization(
LanguageViewLocationExpanderFormat.Suffix,
opts => { opts.ResourcesPath = "Resources"; })
.AddDataAnnotationsLocalization();
services.Configure<RequestLocalizationOptions>(
opts =>
{
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("en-GB"),
new CultureInfo("el-GR")
};
opts.DefaultRequestCulture = new RequestCulture("en-GB");
// Formatting numbers, dates, etc.
opts.SupportedCultures = supportedCultures;
// UI strings that we have localized.
opts.SupportedUICultures = supportedCultures;
});
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
// Angular's default header name for sending the XSRF token.
services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
services.AddEntityFrameworkSqlServer().AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(Configuration["ConnectionStrings:Connection"]);
});
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Add storage service
var storageService = new LocalFileStorageService(Configuration["LocalFileStorageBasePath"]);
services.AddSingleton<IFileStorageService>(storageService);
// Add Nodatime IClock
services.AddSingleton<IClock>(SystemClock.Instance);
// Add application services.
services.AddSingleton<ISendGridClient>(new SendGridClient(Configuration["SendGrid:ServiceApiKey"]));
services.AddTransient<SendGridMessage, SendGridMessage>();
services.AddTransient<IEmailSender, EmailSender>();
services.AddScoped<ITodoItemService, TodoItemService>();
services.AddLogging();
services.AddMvc()
.SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
//app.UseHsts();
//app.UseHttpsRedirection();
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
//Add localisation
var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(options.Value);
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| 39.382353 | 119 | 0.609597 | [
"MIT"
] | Aman22sharma/TodoList | TodoList.Web/Startup.cs | 5,358 | C# |
/**
* © 2012-2014 Amazon Digital Services, Inc. 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.
*/
/*
* Modified by Jan Ivar Z. Carlsen.
* Added CLOUDONCE_AMAZON build symbol.
* Removed iOS support.
* Added ShowLeaderboardsOverlay overload for showing specific leaderboard.
*/
#if UNITY_ANDROID && CLOUDONCE_AMAZON
using AmazonCommon;
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// enum for the available leaderboard scopes
/// </summary>
public enum LeaderboardScope{
GlobalAllTime,
GlobalWeek,
GlobalDay,
FriendsAllTime
}
/// <summary>
/// Client used to submit and read leaderboards for the current logged in or guest player
/// </summary>
public class AGSLeaderboardsClient : MonoBehaviour{
#if UNITY_ANDROID && !UNITY_EDITOR
private static AmazonJavaWrapper JavaObject;
private static AmazonJavaWrapper JavaObjectEx;
private static readonly string PROXY_CLASS_NAME = "com.amazon.ags.api.unity.LeaderboardsClientProxyImpl";
private static readonly string EX_PROXY_CLASS_NAME = "com.amazon.ags.api.unity.LeaderboardsClientProxyExImpl";
#endif
/// <summary>
/// Occurs when submit score completed.
/// </summary>
public static event Action<AGSSubmitScoreResponse> SubmitScoreCompleted;
/// <summary>
/// Occurs when request leaderboards competed.
/// </summary>
public static event Action<AGSRequestLeaderboardsResponse> RequestLeaderboardsCompleted;
/// <summary>
/// Occurs when a request for local player score has completed.
/// </summary>
public static event Action<AGSRequestScoreResponse> RequestLocalPlayerScoreCompleted;
/// <summary>
/// Occurs when score request for a player has completed.
/// </summary>
public static event Action<AGSRequestScoreForPlayerResponse> RequestScoreForPlayerCompleted;
/// <summary>
/// Occurs when a request for scores has completed.
/// </summary>
public static event Action<AGSRequestScoresResponse> RequestScoresCompleted;
/// <summary>
/// Occurs when a percentile ranks request has completed.
/// </summary>
public static event Action<AGSRequestPercentilesResponse> RequestPercentileRanksCompleted;
/// <summary>
/// Occurs when a percentile ranks request for a player has completed.
/// </summary>
public static event Action<AGSRequestPercentilesForPlayerResponse> RequestPercentileRanksForPlayerCompleted;
#pragma warning disable 0618
/// <summary>
/// Initializes the <see cref="AGSLeaderboardsClient"/> class.
/// </summary>
static AGSLeaderboardsClient(){
#if UNITY_ANDROID && !UNITY_EDITOR
JavaObject = new AmazonJavaWrapper();
JavaObjectEx = new AmazonJavaWrapper();
using( var PluginClass = new AndroidJavaClass( PROXY_CLASS_NAME ) ){
if (PluginClass.GetRawClass() == IntPtr.Zero)
{
AGSClient.LogGameCircleWarning("No java class " + PROXY_CLASS_NAME + " present, can't use AGSLeaderboardsClient" );
return;
}
JavaObject.setAndroidJavaObject(PluginClass.CallStatic<AndroidJavaObject>( "getInstance" ));
}
using( var PluginClass = new AndroidJavaClass( EX_PROXY_CLASS_NAME ) ){
if (PluginClass.GetRawClass() == IntPtr.Zero)
{
AGSClient.LogGameCircleWarning("No java class " + EX_PROXY_CLASS_NAME + " present, can't use AGSLeaderboardsClient" );
return;
}
JavaObjectEx.setAndroidJavaObject(PluginClass.CallStatic<AndroidJavaObject>( "getInstance" ));
}
#endif
}
/// <summary>
/// submit a score to leaderboard
/// </summary>
/// <remarks>
/// SubmitScoreCompleted will be called if the event is registered.
/// </remarks>
/// <param name="leaderboardId">the id of the leaderboard for the score request</param>
/// <param name="score">player score</param>
/// <param name="userData">
/// ANDROID ONLY
/// An optional code that will be returned in the response. Used to associate a function call to its response.
/// A value of 0 is not recommended because 0 is the value returned when userData is not specified.
/// </param>
/// </remarks>
public static void SubmitScore( string leaderboardId, long score, int userData = 0 ) {
#if UNITY_EDITOR && (UNITY_ANDROID || UNITY_IOS)
// GameCircle only functions on device.
#elif UNITY_ANDROID
JavaObject.Call( "submitScore", leaderboardId, score, userData );
#else
AGSSubmitScoreResponse response = AGSSubmitScoreResponse.GetPlatformNotSupportedResponse(leaderboardId, userData);
if( SubmitScoreFailedEvent != null ){
SubmitScoreFailedEvent( response.leaderboardId, response.error );
}
if (SubmitScoreCompleted != null) {
SubmitScoreCompleted(response);
}
#endif
}
/// <summary>
/// show leaderboard in GameCircle overlay
/// </summary>
public static void ShowLeaderboardsOverlay(){
#if UNITY_EDITOR && (UNITY_ANDROID || UNITY_IOS)
// GameCircle only functions on device.
#elif UNITY_ANDROID
JavaObject.Call( "showLeaderboardsOverlay" );
#endif
}
/// <summary>
/// show leaderboard in GameCircle overlay
/// </summary>
public static void ShowLeaderboardsOverlay(string leaderboardID)
{
#if UNITY_EDITOR && (UNITY_ANDROID || UNITY_IOS)
// GameCircle only functions on device.
#elif UNITY_ANDROID
JavaObjectEx.Call( "showLeaderboardOverlay", leaderboardID );
#endif
}
/// <summary>
/// request all leaderboards for this game
/// </summary>
/// <remarks>
/// RequestLeaderboardsCompleted will be called if the event is registered.
/// </remarks>
/// <param name="userData">
/// ANDROID ONLY
/// An optional code that will be returned in the response. Used to associate a function call to its response.
/// A value of 0 is not recommended because 0 is the value returned when userData is not specified.
/// </param>
public static void RequestLeaderboards( int userData = 0 ){
#if UNITY_EDITOR && (UNITY_ANDROID || UNITY_IOS)
// GameCircle only functions on device.
#elif UNITY_ANDROID
JavaObject.Call( "requestLeaderboards", 0 );
#else
AGSRequestLeaderboardsResponse response = AGSRequestLeaderboardsResponse.GetPlatformNotSupportedResponse(userData);
if( RequestLeaderboardsFailedEvent != null ){
RequestLeaderboardsFailedEvent( response.error );
}
if (RequestLeaderboardsCompleted != null) {
RequestLeaderboardsCompleted(response);
}
#endif
}
/// <summary>
/// request current player's score for a given leaderboad and scope
/// </summary>
/// <remarks>
/// RequestLocalPlayerScoreCompleted will be called if the event is registered.
/// </remarks>
/// <param name="leaderboardId">the id of the leaderboard for the score request</param>
/// <param name="userData">
/// ANDROID ONLY
/// An optional code that will be returned in the response. Used to associate a function call to its response.
/// A value of 0 is not recommended because 0 is the value returned when userData is not specified.
/// </param>
public static void RequestLocalPlayerScore( string leaderboardId, LeaderboardScope scope, int userData = 0 ){
#if UNITY_EDITOR && (UNITY_ANDROID || UNITY_IOS)
// GameCircle only functions on device.
#elif UNITY_ANDROID
JavaObject.Call( "requestLocalPlayerScore", leaderboardId, (int)scope , 0);
#else
AGSRequestScoreResponse response = AGSRequestScoreResponse.GetPlatformNotSupportedResponse(leaderboardId, scope, userData);
if( RequestLocalPlayerScoreFailedEvent != null ){
RequestLocalPlayerScoreFailedEvent( response.leaderboardId, response.error );
}
if (RequestLocalPlayerScoreCompleted != null) {
RequestLocalPlayerScoreCompleted (response);
}
#endif
}
/// <summary>
/// ANDROID ONLY
/// Requests the score for player.
/// </summary>
/// <remarks>
/// RequestScoreForPlayerCompleted will be called if the event is registered.
/// </remarks>
/// <param name="leaderboardId">Leaderboard identifier.</param>
/// <param name="playerId">Player identifier.</param>
/// <param name="scope">Scope.</param>
/// <param name="userData">
/// An optional code that will be returned in the response. Used to associate a function call to its response.
/// A value of 0 is not recommended because 0 is the value returned when userData is not specified.
/// </param>
public static void RequestScoreForPlayer( string leaderboardId, string playerId, LeaderboardScope scope, int userData = 0 ) {
#if UNITY_EDITOR && UNITY_ANDROID
// GameCircle only functions on device.
#elif UNITY_ANDROID
JavaObject.Call( "requestScoreForPlayer" , leaderboardId, playerId, (int)scope, userData);
#else
if (RequestScoreForPlayerCompleted != null) {
RequestScoreForPlayerCompleted(AGSRequestScoreForPlayerResponse.GetPlatformNotSupportedResponse(leaderboardId, playerId, scope, userData));
}
#endif
}
/// <summary>
/// Request scores
/// </summary>
/// <remarks>
/// RequestScoresCompleted will be called if event is registered.
/// </remarks>
/// <param name="leaderboardId">the id of the leaderboard for the score request.</param>
/// <param name="scope">enum value of leaderboard scope</param>
/// <param name="userData">
/// ANDROID ONLY
/// An optional code that will be returned in the response. Used to associate a function call to its response.
/// A value of 0 is not recommended because 0 is the value returned when userData is not specified.
/// </param>
public static void RequestScores( string leaderboardId, LeaderboardScope scope, int userData = 0 ) {
#if UNITY_EDITOR && (UNITY_ANDROID || UNITY_IOS)
// GameCircle only functions on device.
#elif UNITY_ANDROID
JavaObject.Call( "requestScores", leaderboardId, (int)scope, userData );
#else
if (RequestScoresCompleted != null) {
RequestScoresCompleted(AGSRequestScoresResponse.GetPlatformNotSupportedResponse(leaderboardId, scope, userData));
}
#endif
}
/// <summary>
/// request percentile ranks
/// </summary>
/// <remarks>
/// RequestPercentileRanksCompleted will be called if the event is registered.
/// </remarks>
/// <param name="leaderboardId">the id of the leaderboard for the score request.</param>
/// <param name="scope">enum value of leaderboard scope</param>
/// <param name="userData">
/// ANDROID ONLY
/// An optional code that will be returned in the response. Used to associate a function call to its response.
/// A value of 0 is not recommended because 0 is the value returned when userData is not specified.
/// </param>
public static void RequestPercentileRanks( string leaderboardId, LeaderboardScope scope, int userData = 0 ) {
#if UNITY_EDITOR && (UNITY_ANDROID || UNITY_IOS)
// GameCircle only functions on device.
#elif UNITY_ANDROID
JavaObject.Call( "requestPercentileRanks", leaderboardId, (int)scope, userData );
#else
AGSRequestPercentilesResponse response = AGSRequestPercentilesResponse.GetPlatformNotSupportedResponse(leaderboardId, scope, userData);
if(RequestPercentileRanksFailedEvent != null ){
RequestPercentileRanksFailedEvent( response.leaderboardId, response.error );
}
if (RequestPercentileRanksCompleted != null) {
RequestPercentileRanksCompleted(response);
}
#endif
}
/// <summary>
/// ANDROID ONLY
/// Request percentile ranks for a player.
/// </summary>
/// <remarks>
/// RequestPercentileRanksForPlayerCompleted will be called if the event is registered.
/// </remarks>
/// <param name="leaderboardId">the id of the leaderboard for the score request.</param>
/// <param name="playerId">The player identifier for the request.</para>
/// <param name="scope">enum value of leaderboard scope</param>
/// <param name="userData">
/// ANDROID ONLY
/// An optional code that will be returned in the response. Used to associate a function call to its response.
/// A value of 0 is not recommended because 0 is the value returned when userData is not specified.
/// </param>
public static void RequestPercentileRanksForPlayer(string leaderboardId, string playerId, LeaderboardScope scope, int userData = 0 ) {
#if UNITY_EDITOR && UNITY_ANDROID
// GameCircle only functions on device.
#elif UNITY_ANDROID
JavaObject.Call( "requestPercentileRanksForPlayer" , leaderboardId, playerId, (int)scope, userData);
#else
if (RequestPercentileRanksForPlayerCompleted != null) {
RequestPercentileRanksForPlayerCompleted(AGSRequestPercentilesForPlayerResponse.GetPlatformNotSupportedResponse(leaderboardId, playerId, scope, userData));
}
#endif
}
#region Callbacks from native SDK
/// <summary>
/// callback method for native code to communicate events back to unity
/// </summary>
public static void SubmitScoreFailed( string json ){
AGSSubmitScoreResponse response = AGSSubmitScoreResponse.FromJSON (json);
if ( response.IsError() && SubmitScoreFailedEvent != null ){
SubmitScoreFailedEvent( response.leaderboardId , response.error);
}
if (SubmitScoreCompleted != null) {
SubmitScoreCompleted(response);
}
}
/// <summary>
/// callback method for native code to communicate events back to unity
/// </summary>
public static void SubmitScoreSucceeded( string json ){
AGSSubmitScoreResponse response = AGSSubmitScoreResponse.FromJSON (json);
if ( !response.IsError() && SubmitScoreSucceededEvent != null ){
SubmitScoreSucceededEvent( response.leaderboardId );
}
if (SubmitScoreCompleted != null) {
SubmitScoreCompleted(response);
}
}
/// <summary>
/// callback method for native code to communicate events back to unity
/// </summary>
public static void RequestLeaderboardsFailed( string json ){
AGSRequestLeaderboardsResponse response = AGSRequestLeaderboardsResponse.FromJSON (json);
if( response.IsError() && RequestLeaderboardsFailedEvent != null ){
RequestLeaderboardsFailedEvent(response.error);
}
if (RequestLeaderboardsCompleted != null) {
RequestLeaderboardsCompleted(response);
}
}
/// <summary>
/// callback method for native code to communicate events back to unity
/// </summary>
public static void RequestLeaderboardsSucceeded( string json ){
AGSRequestLeaderboardsResponse response = AGSRequestLeaderboardsResponse.FromJSON (json);
if (!response.IsError() && RequestLeaderboardsSucceededEvent != null) {
RequestLeaderboardsSucceededEvent(response.leaderboards);
}
if (RequestLeaderboardsCompleted != null) {
RequestLeaderboardsCompleted(response);
}
}
/// <summary>
/// callback method for native code to communicate events back to unity
/// </summary>
public static void RequestLocalPlayerScoreFailed( string json ){
AGSRequestScoreResponse response = AGSRequestScoreResponse.FromJSON (json);
if (response.IsError () && RequestLocalPlayerScoreFailedEvent != null) {
RequestLocalPlayerScoreFailedEvent(response.leaderboardId, response.error);
}
if (RequestLocalPlayerScoreCompleted != null) {
RequestLocalPlayerScoreCompleted(response);
}
}
/// <summary>
/// callback method for native code to communicate events back to unity
/// </summary>
public static void RequestLocalPlayerScoreSucceeded( string json ){
AGSRequestScoreResponse response = AGSRequestScoreResponse.FromJSON (json);
if (!response.IsError () && RequestLocalPlayerScoreSucceededEvent != null) {
RequestLocalPlayerScoreSucceededEvent(response.leaderboardId, response.rank, response.score);
}
if (RequestLocalPlayerScoreCompleted != null) {
RequestLocalPlayerScoreCompleted(response);
}
}
public static void RequestScoreForPlayerComplete (string json) {
if (RequestScoreForPlayerCompleted != null) {
RequestScoreForPlayerCompleted(AGSRequestScoreForPlayerResponse.FromJSON(json));
}
}
/// <summary>
/// Callback method for native to pass score information to Unity.
/// </summary>
public static void RequestScoresSucceeded(string json) {
if (RequestScoresCompleted != null) {
RequestScoresCompleted(AGSRequestScoresResponse.FromJSON (json));
}
}
/// <summary>
/// Callback method for when native failed to collect score information
/// </summary>
public static void RequestScoresFailed(string json) {
if (RequestScoresCompleted != null) {
RequestScoresCompleted(AGSRequestScoresResponse.FromJSON (json));
}
}
/// <summary>
/// callback method for native code to communicate events back to unity
/// </summary>
public static void RequestPercentileRanksFailed( string json ){
AGSRequestPercentilesResponse response = AGSRequestPercentilesResponse.FromJSON (json);
if (response.IsError () && RequestPercentileRanksFailedEvent != null) {
RequestPercentileRanksFailedEvent( response.leaderboardId, response.error );
}
if (RequestPercentileRanksCompleted != null) {
RequestPercentileRanksCompleted(response);
}
}
/// <summary>
/// callback method for native code to communicate events back to unity
/// </summary>
public static void RequestPercentileRanksSucceeded( string json ){
AGSRequestPercentilesResponse response = AGSRequestPercentilesResponse.FromJSON (json);
if ( !response.IsError() && RequestPercentileRanksSucceededEvent != null ){
RequestPercentileRanksSucceededEvent(response.leaderboard, response.percentiles, response.userIndex);
}
if (RequestPercentileRanksCompleted != null) {
RequestPercentileRanksCompleted(response);
}
}
/// <summary>
/// callback method for native code to communicate events back to unity
/// </summary>
public static void RequestPercentileRanksForPlayerComplete( string json ){
if (RequestPercentileRanksForPlayerCompleted != null) {
RequestPercentileRanksForPlayerCompleted(AGSRequestPercentilesForPlayerResponse.FromJSON (json));
}
}
#endregion
#pragma warning restore 0618
#region Obsolete events
/// <summary>
/// Event called when a score submission fails
/// </summary>
/// <param name="leaderboardId">the id of the leaderboard that failed to update</param>
/// <param name="failureReason">a string indicating the failure reason</param>
[Obsolete("SubmitScoreFailedEvent is deprecated. Use SubmitScoreCompleted instead.")]
public static event Action<string,string> SubmitScoreFailedEvent;
/// <summary>
/// Event called when a score submission succeeds
/// </summary>
/// <param name="leaderboardId">the id of the leaderboard that a score has been submitted to</param>
/// <param name="failureReason">a string indicating the failure reason</param>
[Obsolete("SubmitScoreSucceededEvent is deprecated. Use SubmitScoreCompleted instead.")]
public static event Action<string> SubmitScoreSucceededEvent;
/// <summary>
/// Event called when a request for all game leaderboards fails
/// </summary>
/// <param name="failureReason">a string indicating the failure reason</param>
[Obsolete("RequestLeaderboardsFailedEvent is deprecated. Use RequestLeaderboardsCompleted instead.")]
public static event Action<string> RequestLeaderboardsFailedEvent;
/// <summary>
/// Event called when a request for all game leaderboards succeeds
/// </summary>
/// <param name="leaderboardList">list of leaderboards for this game</param>
[Obsolete("RequestLeaderboardsSucceededEvent is deprecated. Use RequestLeaderboardsCompleted instead.")]
public static event Action<List<AGSLeaderboard>> RequestLeaderboardsSucceededEvent;
/// <summary>
/// Event called when a score request fails
/// </summary>
/// <param name="leaderboardId">the id of the leaderboard for the failed request</param>
/// <param name="failureReason">a string indicating the failure reason</param>
[Obsolete("RequestLocalPlayerScoreFailedEvent is deprecated. Use RequestLocalPlayerScoreCompleted instead.")]
public static event Action<string,string> RequestLocalPlayerScoreFailedEvent;
/// <summary>
/// Event called when a score request succeeds
/// </summary>
/// <param name="leaderboardId">the id of the leaderboard for the score request</param>
/// <param name="rank">player's rank in leaderboard</param>
/// <param name="score">player's score in leaderboard</param>
[Obsolete("RequestLocalPlayerScoreSucceededEvent is deprecated. Use RequestLocalPlayerScoreCompleted instead.")]
public static event Action<string,int,long> RequestLocalPlayerScoreSucceededEvent;
/// <summary>
/// Event called when a percentile request fails
/// </summary>
/// <param name="leaderboardId">the id of the leaderboard for the failed request</param>
/// <param name="failureReason">a string indicating the failure reason</param>
[Obsolete("RequestPercentileRanksFailedEvent is deprecated. Use RequestPercentileRanksCompleted instead.")]
public static event Action<string,string> RequestPercentileRanksFailedEvent;
/// <summary>
/// Event called when a percentile request succeeds
/// </summary>
/// <param name="leaderboard">Leaderboard object</param>
/// <param name="ranks">Player percentile rank and alias</param>
[Obsolete("RequestPercentileRanksSucceededEvent is deprecated. Use RequestPercentileRanksCompleted instead.")]
public static event Action<AGSLeaderboard, List<AGSLeaderboardPercentile>, int> RequestPercentileRanksSucceededEvent;
#endregion
}
#endif
| 42.156934 | 167 | 0.695567 | [
"MIT"
] | grigoryvp/unity_sdk_demo | CustomCameraDemo/Assets/Plugins/Amazon/AmazonGameCirclePlugin/Source/LeaderboardsClient/AGSLeaderboardsClient.cs | 23,103 | C# |
/******************************************************************************
* Copyright (C) Leap Motion, Inc. 2011-2017. *
* Leap Motion proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
******************************************************************************/
using NUnit.Framework;
namespace Leap.Unity {
public class UtilsTests {
[Test]
[Sequential]
public void TestNiceNames([Values("_privateVar",
"multBy32",
"the_key_code",
"CamelCaseToo",
"_is2_equalTo_5",
"GetTheSCUBANow",
"m_privateVar",
"kConstantVar")] string source,
[Values("Private Var",
"Mult By 32",
"The Key Code",
"Camel Case Too",
"Is 2 Equal To 5",
"Get The SCUBA Now",
"Private Var",
"Constant Var")] string result) {
Assert.That(Utils.GenerateNiceName(source), Is.EqualTo(result));
}
}
}
| 45.605263 | 80 | 0.34622 | [
"MIT"
] | DanielD2/3DMenu | Assets/LeapMotion/Core/Scripts/Utils/Editor/UtilsTests.cs | 1,733 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataTools.String
{
/// <summary>
/// The KMP (Knuth-Morris-Pratt) class finds the first occurance of a pattern string in a text string.
/// </summary>
public class KMP : StringSearchBase
{
/// <summary>
/// The KMP automatic machine.
/// </summary>
private int[][] dfa;
/// <summary>
/// Process the pattern string.
/// </summary>
/// <param name="pattern">The pattern string.</param>
public KMP(string pattern)
{
sPattern = pattern;
cPattern = pattern.ToCharArray();
// Build DFA from pattern.
int patternLength = pattern.Length;
dfa = new int[R][];
for (int i = 0; i < R; i++)
dfa[i] = new int[patternLength];
dfa[pattern[0]][0] = 1;
for (int x = 0, j = 1; j < patternLength; j++)
{
// Copy mis-match cases.
for (int c = 0; c < R; c++)
dfa[c][j] = dfa[c][x];
// Set match cases.
dfa[pattern[j]][j] = j + 1;
// Update restart state.
x = dfa[pattern[j]][x];
}
}
/// <summary>
/// Process the pattern string.
/// </summary>
/// <param name="pattern">The pattern string.</param>
public KMP(char[] pattern)
{
int patternLength = pattern.Length;
sPattern = new string(pattern);
cPattern = new char[patternLength];
for (int i = 0; i < patternLength; i++)
cPattern[i] = pattern[i];
// Build DFA from pattern.
dfa = new int[R][];
for (int i = 0; i < R; i++)
dfa[i] = new int[patternLength];
dfa[pattern[0]][0] = 1;
for (int x = 0, j = 1; j < patternLength; j++)
{
// Copy mis-match cases.
for (int c = 0; c < R; c++)
dfa[c][j] = dfa[c][x];
// Set match cases.
dfa[pattern[j]][j] = j + 1;
// Update restart state.
x = dfa[pattern[j]][x];
}
}
/// <summary>
/// Returns the index of the first occurance of the pattern string in the text.
/// </summary>
/// <param name="text">The text string.</param>
/// <returns>The index of the first occurance of the pattern string in the text.</returns>
public override int Search(string text)
{
// Simulate operation of DFA on text.
int patternLength = sPattern.Length;
int textLength = text.Length;
int i, j;
for (i = 0, j = 0; (i < textLength) && (j < patternLength); i++)
j = dfa[text[i]][j];
// Found.
if (j == patternLength)
return i - patternLength;
// Not found.
return textLength;
}
/// <summary>
/// Returns the index of the first occurace of the pattern string in the text.
/// </summary>
/// <param name="text">The text string.</param>
/// <returns>The index of the first occurace of the pattern string in the text.</returns>
public override int Search(char[] text)
{
// Simulate operation of DFA on text.
int patternLength = cPattern.Length;
int textLength = text.Length;
int i, j;
for (i = 0, j = 0; (i < textLength) && (j < patternLength); i++)
j = dfa[text[i]][j];
// Found.
if (j == patternLength)
return i - patternLength;
// Not found.
return textLength;
}
}
} | 30.953125 | 106 | 0.470217 | [
"MIT"
] | D15190304050/CSharpConsole2017 | DataTools/String/KMP.cs | 3,964 | C# |
using System;
using System.Windows;
using System.Windows.Media;
namespace Microsoft.DwayneNeed.Extensions
{
public static class PresentationSourceExtensions
{
/// <summary>
/// Convert a point from "client" coordinate space of a window into
/// the coordinate space of the specified element of the same window.
/// </summary>
public static Point TransformClientToDescendant(this PresentationSource presentationSource, Point point,
Visual descendant)
{
Point pt = TransformClientToRoot(presentationSource, point);
return presentationSource.RootVisual.TransformToDescendant(descendant).Transform(pt);
}
/// <summary>
/// Convert a rectangle from "client" coordinate space of a window
/// into the coordinate space of the specified element of the same
/// window.
/// </summary>
public static Rect TransformClientToDescendant(this PresentationSource presentationSource, Rect rect,
Visual descendant)
{
// Transform all 4 corners. Since a rectangle is convex, it will
// remain convex under affine transforms.
Point pt1 = TransformClientToDescendant(presentationSource, new Point(rect.Left, rect.Top), descendant);
Point pt2 = TransformClientToDescendant(presentationSource, new Point(rect.Right, rect.Top), descendant);
Point pt3 = TransformClientToDescendant(presentationSource, new Point(rect.Right, rect.Bottom), descendant);
Point pt4 = TransformClientToDescendant(presentationSource, new Point(rect.Left, rect.Bottom), descendant);
double minX = Math.Min(pt1.X, Math.Min(pt2.X, Math.Min(pt3.X, pt4.X)));
double minY = Math.Min(pt1.Y, Math.Min(pt2.Y, Math.Min(pt3.Y, pt4.Y)));
double maxX = Math.Max(pt1.X, Math.Max(pt2.X, Math.Max(pt3.X, pt4.X)));
double maxY = Math.Max(pt1.Y, Math.Max(pt2.Y, Math.Max(pt3.Y, pt4.Y)));
return new Rect(minX, minY, maxX - minX, maxY - minY);
}
/// <summary>
/// Convert a point from the coordinate space of the specified
/// element into the "client" coordinate space of the window.
/// </summary>
public static Point TransformDescendantToClient(this PresentationSource presentationSource, Point point,
Visual descendant)
{
Point pt = descendant.TransformToAncestor(presentationSource.RootVisual).Transform(point);
return TransformRootToClient(presentationSource, pt);
}
/// <summary>
/// Convert a rectangle from the coordinate space of the specified
/// element into the "client" coordinate space of the window.
/// </summary>
public static Rect TransformDescendantToClient(this PresentationSource presentationSource, Rect rect,
Visual descendant)
{
// Transform all 4 corners. Since a rectangle is convex, it will
// remain convex under affine transforms.
Point pt1 = TransformDescendantToClient(presentationSource, new Point(rect.Left, rect.Top), descendant);
Point pt2 = TransformDescendantToClient(presentationSource, new Point(rect.Right, rect.Top), descendant);
Point pt3 = TransformDescendantToClient(presentationSource, new Point(rect.Right, rect.Bottom), descendant);
Point pt4 = TransformDescendantToClient(presentationSource, new Point(rect.Left, rect.Bottom), descendant);
double minX = Math.Min(pt1.X, Math.Min(pt2.X, Math.Min(pt3.X, pt4.X)));
double minY = Math.Min(pt1.Y, Math.Min(pt2.Y, Math.Min(pt3.Y, pt4.Y)));
double maxX = Math.Max(pt1.X, Math.Max(pt2.X, Math.Max(pt3.X, pt4.X)));
double maxY = Math.Max(pt1.Y, Math.Max(pt2.Y, Math.Max(pt3.Y, pt4.Y)));
return new Rect(minX, minY, maxX - minX, maxY - minY);
}
/// <summary>
/// Convert a point from "client" coordinate space of a window into
/// the coordinate space of the root element of the same window.
/// </summary>
public static Point TransformClientToRoot(this PresentationSource presentationSource, Point pt)
{
// Convert from pixels into DIPs.
pt = presentationSource.CompositionTarget.TransformFromDevice.Transform(pt);
// We need to include the root element's transform.
pt = ApplyVisualTransform(presentationSource.RootVisual, pt, true);
return pt;
}
/// <summary>
/// Convert a point from the coordinate space of the root element
/// into the "client" coordinate space of the same window.
/// </summary>
public static Point TransformRootToClient(this PresentationSource presentationSource, Point pt)
{
// We need to include the root element's transform.
pt = ApplyVisualTransform(presentationSource.RootVisual, pt, false);
// Convert from DIPs into pixels.
pt = presentationSource.CompositionTarget.TransformToDevice.Transform(pt);
return pt;
}
/// <summary>
/// Convert a point from "above" the coordinate space of a
/// visual into the the coordinate space "below" the visual.
/// </summary>
private static Point ApplyVisualTransform(Visual v, Point pt, bool inverse)
{
Matrix m = GetVisualTransform(v);
if (inverse)
{
m.Invert();
}
return m.Transform(pt);
}
/// <summary>
/// Gets the matrix that will convert a point
/// from "above" the coordinate space of a visual
/// into the the coordinate space "below" the visual.
/// </summary>
private static Matrix GetVisualTransform(Visual v)
{
Matrix m = Matrix.Identity;
// A visual can currently have two properties that affect
// its coordinate space:
// 1) Transform - any matrix
// 2) Offset - a simpification for just a 2D offset.
Transform transform = VisualTreeHelper.GetTransform(v);
if (transform != null)
{
Matrix cm = transform.Value;
m = Matrix.Multiply(m, cm);
}
Vector offset = VisualTreeHelper.GetOffset(v);
m.Translate(offset.X, offset.Y);
return m;
}
}
} | 44.952703 | 120 | 0.61446 | [
"MIT"
] | PresetMagician/PresetMagician | Microsoft.DwayneNeed/Extensions/PresentationSourceExtensions.cs | 6,655 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Justin.AspNetCore.ModAuthPubTkt
{
public struct Rfc7232ForwardedHttpInfo
{
public string By { get; set; }
public string For { get; set; }
public string Host { get; set; }
public string Proto { get; set; }
}
}
| 22.625 | 42 | 0.662983 | [
"MIT"
] | jusbuc2k/dotnet_mod_auth_pubtkt | src/Justin.AspNetCore.ModAuthPubTkt/Rfc7232ForwardedHttpInfo.cs | 364 | C# |
using Business.Abstract;
using Business.Concrete;
using Core.DependencyResolvers;
using Core.Extensions;
using Core.Utilities.IoC;
using Core.Utilities.Security.Encryption;
using Core.Utilities.Security.JWT;
using DataAccess.Abstract;
using DataAccess.Concrete.EntityFramework;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebAPI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//AOP
//Autofac, Ninject,CastleWindsor, StructureMap, LightInject, DryInject -->IoC Container
//AOP
//Postsharp
services.AddControllers();
//services.AddSingleton<IProductService,ProductManager>();
//services.AddSingleton<IProductDal, EfProductDal>();
services.AddCors();
var tokenOptions = Configuration.GetSection("TokenOptions").Get<TokenOptions>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidIssuer = tokenOptions.Issuer,
ValidAudience = tokenOptions.Audience,
ValidateIssuerSigningKey = true,
IssuerSigningKey = SecurityKeyHelper.CreateSecurityKey(tokenOptions.SecurityKey)
};
});
services.AddDependencyResolvers(new ICoreModule[] {
new CoreModule()
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.ConfigureCustomExceptionMiddleware();
app.UseCors(builder => builder.WithOrigins("http://localhost:4200").AllowAnyHeader());
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| 32.909091 | 106 | 0.63229 | [
"MIT"
] | avnikasikci/RentACarPortal | WebAPICore/Startup.cs | 3,258 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace WebRTC_Internship.Data.Migrations
{
public partial class CreateIdentitySchema : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Name = table.Column<string>(maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(maxLength: 256, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
LoginProvider = table.Column<string>(nullable: false),
Name = table.Column<string>(nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Email = table.Column<string>(maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
LockoutEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
PasswordHash = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
SecurityStamp = table.Column<string>(nullable: true),
TwoFactorEnabled = table.Column<bool>(nullable: false),
UserName = table.Column<string>(maxLength: 256, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(nullable: false),
ProviderKey = table.Column<string>(nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName");
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_UserId",
table: "AspNetUserRoles",
column: "UserId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}
| 42.05 | 122 | 0.502108 | [
"MIT"
] | EljakimHerrewijnen/WebRTC_Internship_2017 | WebRTC_Internship/WebRTC_Internship/Data/Migrations/00000000000000_CreateIdentitySchema.cs | 9,253 | C# |
#region "copyright"
/*
Copyright © 2016 - 2021 Stefan Berg <isbeorn86+NINA@googlemail.com> and the N.I.N.A. contributors
This file is part of N.I.N.A. - Nighttime Imaging 'N' Astronomy.
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/.
*/
#endregion "copyright"
using NINA.Profile.Interfaces;
using System;
using System.Threading;
using System.Threading.Tasks;
using NINA.Equipment.SDK.CameraSDKs.AtikSDK;
namespace NINA.Equipment.Equipment.MyFilterWheel {
public class AtikFilterWheel : AtikFilterWheelBase {
private readonly int filterWheelDeviceId;
private IntPtr filterWheelDevice;
public AtikFilterWheel(int deviceId, IProfileService profileService) : base(profileService) {
filterWheelDeviceId = deviceId;
}
public override short Position {
get {
if (AtikCameraDll.GetCurrentEfwMoving(filterWheelDevice)) return -1;
else return AtikCameraDll.GetCurrentEfwPosition(filterWheelDevice);
}
set => AtikCameraDll.SetCurrentEfwPosition(filterWheelDevice, value);
}
public override string Id => AtikCameraDll.GetArtemisEfwType(filterWheelDeviceId).ToString() + " (" + AtikCameraDll.GetArtemisEfwSerial(filterWheelDeviceId) + ")";
public override string Name => AtikCameraDll.GetArtemisEfwType(filterWheelDeviceId).ToString() + " (" + AtikCameraDll.GetArtemisEfwSerial(filterWheelDeviceId) + ")";
public override bool Connected => AtikCameraDll.IsConnectedEfw(filterWheelDevice);
public override string Description => "Native Atik " + AtikCameraDll.GetConnectedArtemisEfwType(filterWheelDevice).ToString() + " (Serial Nr " + AtikCameraDll.GetArtemisEfwSerial(filterWheelDeviceId) + ")";
public override Task<bool> Connect(CancellationToken token) {
filterWheelDevice = AtikCameraDll.ConnectEfw(filterWheelDeviceId);
return Task.FromResult(filterWheelDevice != IntPtr.Zero);
}
public override void Disconnect() {
AtikCameraDll.DisconnectEfw(filterWheelDevice);
}
protected override int GetEfwPositions() => AtikCameraDll.GetEfwPositions(filterWheelDevice);
}
} | 41.034483 | 214 | 0.711765 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | daleghent/NINA | NINA.Equipment/Equipment/MyFilterWheel/AtikFilterWheel.cs | 2,383 | C# |
namespace Boo.Lang.Compiler.TypeSystem.Internal
{
public abstract class AbstractLocalEntity
{
public bool IsUsed { get; set; }
public bool IsShared { get; set; }
}
}
| 17.4 | 47 | 0.724138 | [
"MIT"
] | Spoiledpay/Newboo | BooLangCompiler/Boo/Lang/Compiler/TypeSystem/Internal/AbstractLocalEntity.cs | 174 | C# |
namespace HealthCare020.Core.Models
{
public class ZdravstvenoStanjeDto
{
public int Id { get; set; }
public string Opis { get; set; }
}
} | 20.875 | 40 | 0.610778 | [
"MIT"
] | fahirmdz/HealthCare020 | HealthCare020.Core/Models/ZdravstvenoStanjeDto.cs | 169 | C# |
namespace cbs.wanderOn.Configuration;
public class ProfileConfig
{
public const string Profiles = "Profiles";
public Dictionary<string, string> Keys {get; set;} = new();
} | 22.625 | 63 | 0.723757 | [
"BSD-2-Clause"
] | EdmundLewry/wander-on | wander-on-application/ProfileConfig.cs | 181 | C# |
/* _BEGIN_TEMPLATE_
{
"id": "BGS_018e",
"name": [
"猛兽之魂",
"Soul of the Beast"
],
"text": [
"+4/+4。",
"+4/+4."
],
"CardClass": "NEUTRAL",
"type": "ENCHANTMENT",
"cost": null,
"rarity": null,
"set": "BATTLEGROUNDS",
"collectible": null,
"dbfId": 59957
}
_END_TEMPLATE_ */
namespace HREngine.Bots
{
class Sim_BGS_018e : SimTemplate
{
}
} | 13.857143 | 36 | 0.53866 | [
"MIT"
] | chi-rei-den/Silverfish | cards/BATTLEGROUNDS/BGS/Sim_BGS_018e.cs | 398 | C# |
using Framework.Dependency;
using Sirenix.OdinInspector;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace Seconds.UI.Screen
{
public class ScreenTeamDisplay : Screen
{
[SerializeField, Required]
private TMP_Text labelTeamName = null;
[SerializeField, Required]
private Button buttonStart = null;
[SerializeField, Required]
private ScreenGuessing screenGuessing = null;
private GameState gameState = null;
public override void OnEnter()
{
base.OnEnter();
labelTeamName.text = gameState.currentGame.CurrentTeam.name;
}
private void Awake()
{
buttonStart.onClick.AddListener(OnButtonStartClicked);
}
protected override void Start()
{
base.Start();
gameState = SceneOrganizer.Get<GameState>();
}
private void OnDestroy()
{
buttonStart.onClick.RemoveListener(OnButtonStartClicked);
}
private void OnButtonStartClicked()
{
screenGuessing.Switch();
}
}
} | 18.134615 | 63 | 0.732768 | [
"MIT"
] | Tjakka5/30-Seconds | Game/Assets/Scripts/UI/Screen/ScreenTeamDisplay.cs | 945 | C# |
namespace Orleans.WebApi.Generator.Metas
{
public record AttributeMetaInfo
{
public AttributeMetaInfo(string nspace, string name)
{
this.Namespace = nspace;
this.Name = name;
}
public string Namespace { get; set; }
public string Name { get; set; }
public bool IsAspNetCoreAttribute { get; set; }
public List<string> ConstructorArguments { get; set; } = new List<string>();
public List<string> NamedArguments { get; set; } = new List<string>();
}
}
| 25.181818 | 84 | 0.597473 | [
"MIT"
] | RayTale/Orleans.WebApi | src/Orleans.WebApi.Generator/Metas/AttributeMetaInfo.cs | 556 | C# |
using ArbitR.Pipeline.Read;
namespace ArbitR.Internal.Pipeline.Service
{
internal interface IReadService
{
object? Handle(IQuery query);
}
} | 17.888889 | 42 | 0.701863 | [
"Apache-2.0"
] | Rhexis/ArbitR | ArbitR/Internal/Pipeline/Service/IReadService.cs | 161 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
namespace Plethora.Test.Xaml.UtilityClasses
{
public class Person
{
public class NameComparer : IComparer<Person>, IComparer
{
#region Implementation of IComparer<Person>
public int Compare(object x, object y)
{
return this.Compare((Person)x, (Person)y);
}
public int Compare(Person x, Person y)
{
int result;
result = string.Compare(x.FamilyName, y.FamilyName);
if (result != 0)
return result;
result = string.Compare(x.GivenName, y.GivenName);
return result;
}
#endregion
}
// Two "Bob Jameson"
// "Fred Carlile" and "Amy Cathson" share DateOfBirths
// "Jill Dorrman" and "Jane Doe" share IDs
public static readonly Person Bob_Jameson = new Person(0, "Jameson", "Bob", new DateTime(1964, 03, 14));
public static readonly Person Bob_Jameson2 = new Person(10, "Jameson", "Bob", new DateTime(1998, 07, 13));
public static readonly Person Fred_Carlile = new Person(1, "Carlile", "Fred", new DateTime(1975, 11, 07));
public static readonly Person Amy_Cathson = new Person(2, "Cathson", "Amy", new DateTime(1975, 11, 07));
public static readonly Person Jill_Dorrman = new Person(3, "Dorrman", "Jill", new DateTime(1978, 05, 08));
public static readonly Person Jane_Doe = new Person(3, "Doe", "Jane", new DateTime(1976, 03, 15));
public static readonly Person Katherine_Harold = new Person(4, "Harold", "Katherine", new DateTime(1984, 02, 21));
public static readonly Person Harry_Porker = new Person(5, "Porker", "Harry", new DateTime(1978, 05, 08));
private static long lastId = 0;
private readonly long id;
private readonly string familyName;
private readonly string givenName;
private readonly DateTime dateOfBirth;
public Person(string familyName, string givenName, DateTime dateOfBirth)
: this(lastId++, familyName, givenName, dateOfBirth)
{
}
public Person(long id, string familyName, string givenName, DateTime dateOfBirth)
{
this.id = id;
this.familyName = familyName;
this.givenName = givenName;
this.dateOfBirth = dateOfBirth;
}
public long ID
{
get { return this.id; }
}
public string FamilyName
{
get { return this.familyName; }
}
public string GivenName
{
get { return this.givenName; }
}
public DateTime DateOfBirth
{
get { return dateOfBirth; }
}
public int Age
{
get { return dateOfBirth.Year - DateTime.Now.Year; }
}
public override string ToString()
{
return "Person [" + ID + ": " + FamilyName + ", " + GivenName + "]";
}
}
}
| 32.635417 | 122 | 0.571018 | [
"MIT",
"BSD-3-Clause"
] | mikebarker/Plethora.NET | src/Test/Plethora.Test.Xaml/!UtilityClasses/Person.cs | 3,135 | C# |
using System.IO;
using Ducode.Wolk.Common.Utilities;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.FileProviders;
namespace Ducode.Wolk.Api.Utilities
{
public static class StartupUtilities
{
public static IApplicationBuilder UseGui(this IApplicationBuilder app, bool loadStaticFiles)
{
if (!loadStaticFiles)
{
return app;
}
var path = $"{AssemblyHelper.GetCallingAssemblyRootPath()}/gui";
if (Directory.Exists(path))
{
app.UseFileServer(new FileServerOptions
{
EnableDefaultFiles = true,
FileProvider = new PhysicalFileProvider(path)
});
}
return app;
}
}
}
| 27.225806 | 101 | 0.545024 | [
"MIT"
] | dukeofharen/wolk | src/Ducode.Wolk.Api/Utilities/StartupUtilities.cs | 844 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SharperArchitecture.Authentication.Specifications;
using SharperArchitecture.Common.Specifications;
using SharperArchitecture.Domain;
using SharperArchitecture.Validation.Attributes;
namespace SharperArchitecture.Authentication.Entities
{
[Serializable]
public partial class UserSetting : Entity
{
#region User
[ReadOnly(true)]
public virtual long? UserId
{
get
{
if (_userIdSet) return _userId;
return User == null ? default(long?) : User.Id;
}
set
{
_userIdSet = true;
_userId = value;
}
}
private long? _userId;
private bool _userIdSet;
public virtual IUser User { get; set; }
#endregion
[NotNull]
public virtual string Name { get; set; }
[NotNull]
[Length(int.MaxValue)]
public virtual string Value { get; set; }
}
}
| 22.9 | 63 | 0.599127 | [
"MIT"
] | maca88/PowerArhitecture | Source/SharperArchitecture.Authentication/Entities/UserSetting.cs | 1,147 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Text;
using Azure.Storage.Blobs.Models;
namespace Azure.Storage.Blobs.Models
{
/// <summary>
/// Specifies blob lease access conditions for a container or blob.
/// </summary>
public class BlobRequestConditions : BlobLeaseRequestConditions
{
/// <summary>
/// Optionally limit requests to resources with an active lease
/// matching this Id.
/// </summary>
public string LeaseId { get; set; }
/// <summary>
/// Converts the value of the current RequestConditions object to
/// its equivalent string representation.
/// </summary>
/// <returns>
/// A string representation of the RequestConditions.
/// </returns>
public override string ToString()
{
StringBuilder conditions = new StringBuilder();
conditions.Append('[').Append(GetType().Name);
AddConditions(conditions);
if (conditions[conditions.Length - 1] == ';')
{
conditions[conditions.Length - 1] = ']';
}
else
{
conditions.Append(']');
}
return conditions.ToString();
}
internal BlobRequestConditions WithIfMatch(ETag etag) =>
new BlobRequestConditions
{
LeaseId = LeaseId,
IfMatch = etag,
IfNoneMatch = IfNoneMatch,
IfModifiedSince = IfModifiedSince,
IfUnmodifiedSince = IfUnmodifiedSince,
TagConditions = TagConditions,
};
/// <summary>
/// Collect any request conditions. Conditions should be separated by
/// a semicolon.
/// </summary>
/// <param name="conditions">The collected conditions.</param>
internal virtual void AddConditions(StringBuilder conditions)
{
if (IfMatch != null)
{
conditions.Append(nameof(IfMatch)).Append('=').Append(IfMatch).Append(';');
}
if (IfNoneMatch != null)
{
conditions.Append(nameof(IfNoneMatch)).Append('=').Append(IfNoneMatch).Append(';');
}
if (IfModifiedSince != null)
{
conditions.Append(nameof(IfModifiedSince)).Append('=').Append(IfModifiedSince).Append(';');
}
if (IfUnmodifiedSince != null)
{
conditions.Append(nameof(IfUnmodifiedSince)).Append('=').Append(IfUnmodifiedSince).Append(';');
}
if (LeaseId != null)
{
conditions.Append(nameof(LeaseId)).Append('=').Append(LeaseId).Append(';');
}
if (TagConditions != null)
{
conditions.Append(nameof(TagConditions)).Append('=').Append(TagConditions).Append(';');
}
}
}
}
| 32.638298 | 111 | 0.535854 | [
"MIT"
] | AME-Redmond/azure-sdk-for-net | sdk/storage/Azure.Storage.Blobs/src/Models/BlobRequestConditions.cs | 3,070 | C# |
using System;
using System.IO;
using NitroSharp.NsScript;
namespace NitroSharp.Media
{
internal sealed class Sound : Entity
{
private readonly NsAudioKind _kind;
private VolumeAnimation? _volumeAnim;
private readonly PooledAudioSource _audioSource;
private bool _playbackStarted;
public Sound(
in ResolvedEntityPath path,
NsAudioKind kind,
Stream stream,
AudioContext audioContext)
: base(path)
{
_kind = kind;
_audioSource = audioContext.RentAudioSource();
Stream = new MediaStream(
stream,
graphicsDevice: null,
_audioSource.Value,
audioContext.Device.AudioParameters
);
Volume = 1.0f;
}
public Sound(in ResolvedEntityPath path, in EntitySaveData saveData)
: base(in path, in saveData)
{
}
public override EntityKind Kind => EntityKind.Sound;
public override bool IsIdle
=> (!Stream.IsPlaying && _playbackStarted) || Volume == 0 && _volumeAnim is null;
public MediaStream Stream { get; }
public void Play()
{
_playbackStarted = true;
Stream.Start();
}
public float Volume
{
get => _audioSource.Value.Volume;
set => _audioSource.Value.Volume = value * GetVolumeMultiplier();
}
private float GetVolumeMultiplier() => _kind switch
{
NsAudioKind.BackgroundMusic => 0.7f,
NsAudioKind.SoundEffect => 1.0f,
NsAudioKind.Voice => 0.9f
};
public void Update(float dt)
{
_volumeAnim?.Update(dt);
if (_volumeAnim is { HasCompleted: true })
{
_volumeAnim = null;
}
}
public void AnimateVolume(float targetVolume, TimeSpan duration)
{
if (duration > TimeSpan.Zero)
{
_volumeAnim = new VolumeAnimation(this, Volume, targetVolume, duration);
}
else
{
Volume = targetVolume;
}
}
public override void Dispose()
{
Stream.Dispose();
_audioSource.Dispose();
}
}
}
| 26.677778 | 93 | 0.526864 | [
"MIT"
] | CommitteeOfZero/nitrosharp | src/NitroSharp/Media/Sound.cs | 2,403 | C# |
using System;
using Aop.Api.Domain;
using System.Collections.Generic;
using Aop.Api.Response;
namespace Aop.Api.Request
{
/// <summary>
/// AOP API: alipay.offline.marketing.voucher.modify
/// </summary>
public class AlipayOfflineMarketingVoucherModifyRequest : IAopRequest<AlipayOfflineMarketingVoucherModifyResponse>
{
/// <summary>
/// 券修改
/// </summary>
public string BizContent { get; set; }
#region IAopRequest Members
private bool needEncrypt=false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private AopObject bizModel;
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return this.needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return this.notifyUrl;
}
public void SetTerminalType(String terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return this.terminalType;
}
public void SetTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return this.terminalInfo;
}
public void SetProdCode(String prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return this.prodCode;
}
public string GetApiName()
{
return "alipay.offline.marketing.voucher.modify";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return this.apiVersion;
}
public IDictionary<string, string> GetParameters()
{
AopDictionary parameters = new AopDictionary();
parameters.Add("biz_content", this.BizContent);
return parameters;
}
public AopObject GetBizModel()
{
return this.bizModel;
}
public void SetBizModel(AopObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.653465 | 118 | 0.61239 | [
"MIT"
] | erikzhouxin/CSharpSolution | OSS/Alipay/F2FPayDll/Projects/alipay-sdk-NET20161213174056/Request/AlipayOfflineMarketingVoucherModifyRequest.cs | 2,395 | C# |
// <auto-generated>
// 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.
// </auto-generated>
namespace Microsoft.Azure.Commands.Common.MSGraph.Version1_0.Groups
{
using Microsoft.Azure.Commands.Common.MSGraph.Version1_0;
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// GroupsOperations operations.
/// </summary>
public partial class GroupsOperations : IServiceOperations<MicrosoftGraphClient>, IGroupsOperations
{
/// <summary>
/// Initializes a new instance of the GroupsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public GroupsOperations(MicrosoftGraphClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the Groups
/// </summary>
public MicrosoftGraphClient Client { get; private set; }
/// <summary>
/// Get entities from groups
/// </summary>
/// <param name='consistencyLevel'>
/// Indicates the requested consistency level. Documentation URL:
/// https://developer.microsoft.com/en-us/office/blogs/microsoft-graph-advanced-queries-for-directory-objects-are-now-generally-available/
/// </param>
/// <param name='top'>
/// Show only the first n items
/// </param>
/// <param name='skip'>
/// Skip the first n items
/// </param>
/// <param name='search'>
/// Search items by search phrases
/// </param>
/// <param name='filter'>
/// Filter items by property values
/// </param>
/// <param name='count'>
/// Include count of items
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="OdataErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<ListGroupOKResponse>> ListGroupWithHttpMessagesAsync(string consistencyLevel = default(string), int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (top < 0)
{
throw new ValidationException(ValidationRules.InclusiveMinimum, "top", 0);
}
if (skip < 0)
{
throw new ValidationException(ValidationRules.InclusiveMinimum, "skip", 0);
}
if (orderby != null)
{
if (orderby.Count != System.Linq.Enumerable.Count(System.Linq.Enumerable.Distinct(orderby)))
{
throw new ValidationException(ValidationRules.UniqueItems, "orderby");
}
}
if (select != null)
{
if (select.Count != System.Linq.Enumerable.Count(System.Linq.Enumerable.Distinct(select)))
{
throw new ValidationException(ValidationRules.UniqueItems, "select");
}
}
if (expand != null)
{
if (expand.Count != System.Linq.Enumerable.Count(System.Linq.Enumerable.Distinct(expand)))
{
throw new ValidationException(ValidationRules.UniqueItems, "expand");
}
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("consistencyLevel", consistencyLevel);
tracingParameters.Add("top", top);
tracingParameters.Add("skip", skip);
tracingParameters.Add("search", search);
tracingParameters.Add("filter", filter);
tracingParameters.Add("count", count);
tracingParameters.Add("orderby", orderby);
tracingParameters.Add("select", select);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListGroup", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + Client.ApiVersion + "/"), "groups").ToString();
List<string> _queryParameters = new List<string>();
if (top != null)
{
_queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(top, Client.SerializationSettings).Trim('"'))));
}
if (skip != null)
{
_queryParameters.Add(string.Format("$skip={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(skip, Client.SerializationSettings).Trim('"'))));
}
if (search != null)
{
_queryParameters.Add(string.Format("$search={0}", System.Uri.EscapeDataString(search)));
}
if (filter != null)
{
_queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter)));
}
if (count != null)
{
_queryParameters.Add(string.Format("$count={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(count, Client.SerializationSettings).Trim('"'))));
}
if (orderby != null)
{
_queryParameters.Add(string.Format("$orderby={0}", System.Uri.EscapeDataString(string.Join(",", orderby))));
}
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select))));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (consistencyLevel != null)
{
if (_httpRequest.Headers.Contains("ConsistencyLevel"))
{
_httpRequest.Headers.Remove("ConsistencyLevel");
}
_httpRequest.Headers.TryAddWithoutValidation("ConsistencyLevel", consistencyLevel);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new OdataErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
OdataError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<OdataError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<ListGroupOKResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ListGroupOKResponse>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Add new entity to groups
/// </summary>
/// <param name='body'>
/// New entity
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="OdataErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<MicrosoftGraphGroup>> CreateGroupWithHttpMessagesAsync(MicrosoftGraphGroup body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (body == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "body");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateGroup", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + Client.ApiVersion + "/"), "groups").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201)
{
var ex = new OdataErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
OdataError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<OdataError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<MicrosoftGraphGroup>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftGraphGroup>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Delete entity from groups
/// </summary>
/// <remarks>
/// Represents an Azure Active Directory object. The directoryObject type is
/// the base type for many other directory entity types.
/// </remarks>
/// <param name='groupId'>
/// key: id of group
/// </param>
/// <param name='ifMatch'>
/// ETag
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="OdataErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> DeleteGroupWithHttpMessagesAsync(string groupId, string ifMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (groupId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "groupId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("groupId", groupId);
tracingParameters.Add("ifMatch", ifMatch);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "DeleteGroup", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + Client.ApiVersion + "/"), "groups/{group-id}").ToString();
_url = _url.Replace("{group-id}", System.Uri.EscapeDataString(groupId));
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (ifMatch != null)
{
if (_httpRequest.Headers.Contains("If-Match"))
{
_httpRequest.Headers.Remove("If-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
var ex = new OdataErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
OdataError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<OdataError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get entity from groups by key
/// </summary>
/// <remarks>
/// Represents an Azure Active Directory object. The directoryObject type is
/// the base type for many other directory entity types.
/// </remarks>
/// <param name='groupId'>
/// key: id of group
/// </param>
/// <param name='consistencyLevel'>
/// Indicates the requested consistency level. Documentation URL:
/// https://developer.microsoft.com/en-us/office/blogs/microsoft-graph-advanced-queries-for-directory-objects-are-now-generally-available/
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="OdataErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<MicrosoftGraphGroup>> GetGroupWithHttpMessagesAsync(string groupId, string consistencyLevel = default(string), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (groupId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "groupId");
}
if (select != null)
{
if (select.Count != System.Linq.Enumerable.Count(System.Linq.Enumerable.Distinct(select)))
{
throw new ValidationException(ValidationRules.UniqueItems, "select");
}
}
if (expand != null)
{
if (expand.Count != System.Linq.Enumerable.Count(System.Linq.Enumerable.Distinct(expand)))
{
throw new ValidationException(ValidationRules.UniqueItems, "expand");
}
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("groupId", groupId);
tracingParameters.Add("consistencyLevel", consistencyLevel);
tracingParameters.Add("select", select);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetGroup", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + Client.ApiVersion + "/"), "groups/{group-id}").ToString();
_url = _url.Replace("{group-id}", System.Uri.EscapeDataString(groupId));
List<string> _queryParameters = new List<string>();
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select))));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (consistencyLevel != null)
{
if (_httpRequest.Headers.Contains("ConsistencyLevel"))
{
_httpRequest.Headers.Remove("ConsistencyLevel");
}
_httpRequest.Headers.TryAddWithoutValidation("ConsistencyLevel", consistencyLevel);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new OdataErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
OdataError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<OdataError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<MicrosoftGraphGroup>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftGraphGroup>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Update entity in groups
/// </summary>
/// <remarks>
/// Represents an Azure Active Directory object. The directoryObject type is
/// the base type for many other directory entity types.
/// </remarks>
/// <param name='groupId'>
/// key: id of group
/// </param>
/// <param name='body'>
/// New property values
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="OdataErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> UpdateGroupWithHttpMessagesAsync(string groupId, MicrosoftGraphGroup body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (groupId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "groupId");
}
if (body == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "body");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("groupId", groupId);
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "UpdateGroup", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + Client.ApiVersion + "/"), "groups/{group-id}").ToString();
_url = _url.Replace("{group-id}", System.Uri.EscapeDataString(groupId));
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
var ex = new OdataErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
OdataError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<OdataError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 45.468191 | 556 | 0.542446 | [
"MIT"
] | Azure/azure-powershell-common | src/Graph.Rbac/MicrosoftGraph/Version1_0/Groups/GroupsOperations.cs | 45,741 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class ButtonConditions : MonoBehaviour
{
public Button MenuButton;
public TMP_InputField InputField;
public void CheckCondition()
{
if (InputField.text != null)
{
MenuButton.interactable = true;
}
else
{
MenuButton.interactable = false;
}
}
}
| 19.125 | 45 | 0.627451 | [
"MIT"
] | SunriseHirame/Home-ForTuna | Assets/Iiro/ButtonConditions.cs | 461 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Database.Common.DataOperation
{
/// <summary>
/// Represents a query against a single item.
/// </summary>
public class QueryItem
{
/// <summary>
/// The key this query is against.
/// </summary>
private readonly string _key;
/// <summary>
/// The different parts of the query.
/// </summary>
private readonly List<QueryItemPart> _parts = new List<QueryItemPart>();
/// <summary>
/// Initializes a new instance of the <see cref="QueryItem"/> class.
/// </summary>
/// <param name="entry">The entry to generate the query from.</param>
public QueryItem(DocumentEntry entry)
{
_key = entry.Key;
if (entry.ValueType != DocumentEntryType.Document)
{
_parts.Add(new QueryItemPart(QueryItemPartType.Equal, entry));
return;
}
foreach (var item in entry.ValueAsDocument)
{
GenerateQueryItem(item.Key, item.Value);
}
}
/// <summary>
/// The different types of queries.
/// </summary>
private enum QueryItemPartType
{
/// <summary>
/// A less then query.
/// </summary>
LessThen,
/// <summary>
/// A less then or equal to query.
/// </summary>
LessThenEqualTo,
/// <summary>
/// An equal to query.
/// </summary>
Equal,
/// <summary>
/// A not equal to query.
/// </summary>
NotEqual,
/// <summary>
/// A greater then query.
/// </summary>
GreaterThen,
/// <summary>
/// A greater then or equal to query.
/// </summary>
GreaterThenEqualTo,
/// <summary>
/// A contains query.
/// </summary>
Contains,
/// <summary>
/// A does not contain query.
/// </summary>
NotContains,
}
/// <summary>
/// Checks to see if the document matches the current query.
/// </summary>
/// <param name="doc">The document to test.</param>
/// <returns>True if the document matches the query, otherwise false.</returns>
public bool Match(Document doc)
{
return doc.ContainsKey(_key) && _parts.All(e => MatchItem(doc, e));
}
/// <summary>
/// Checks if a equals b.
/// </summary>
/// <param name="a">The left side of the operator.</param>
/// <param name="b">The right side of the operator.</param>
/// <returns>The result of the operator.</returns>
private bool AreEqual(DocumentEntry a, DocumentEntry b)
{
if (a.ValueType != b.ValueType)
{
return false;
}
switch (a.ValueType)
{
case DocumentEntryType.Array:
return Equals(a.ValueAsArray, b.ValueAsArray);
case DocumentEntryType.Boolean:
return a.ValueAsBoolean == b.ValueAsBoolean;
case DocumentEntryType.Document:
return Equals(a.ValueAsDocument, b.ValueAsDocument);
case DocumentEntryType.Float:
return Math.Abs(a.ValueAsFloat - b.ValueAsFloat) < float.Epsilon;
case DocumentEntryType.Integer:
return a.ValueAsInteger == b.ValueAsInteger;
case DocumentEntryType.String:
return a.ValueAsString == b.ValueAsString;
default:
return false;
}
}
/// <summary>
/// Checks if a contains b.
/// </summary>
/// <param name="a">The left side of the operator.</param>
/// <param name="b">The right side of the operator.</param>
/// <returns>The result of the operator.</returns>
private bool Contains(DocumentEntry a, DocumentEntry b)
{
if (a.ValueType != DocumentEntryType.Array)
{
return false;
}
return a.ValueAsArray.Any(item => Equals(item.Value, b.Value));
}
/// <summary>
/// Generates a query item from a document entry and adds it to the parts list.
/// </summary>
/// <param name="key">The entry's key.</param>
/// <param name="value">The entry's value.</param>
private void GenerateQueryItem(string key, DocumentEntry value)
{
switch (key)
{
case "lt":
if (value.ValueType == DocumentEntryType.Array ||
value.ValueType == DocumentEntryType.Boolean ||
value.ValueType == DocumentEntryType.Document)
{
throw new QueryException("DocumentEntryType \"" +
Enum.GetName(typeof(DocumentEntryType), value.ValueType) +
"\" is not supported on the \"lt\" query.");
}
_parts.Add(new QueryItemPart(QueryItemPartType.LessThen, value));
break;
case "lte":
if (value.ValueType == DocumentEntryType.Array ||
value.ValueType == DocumentEntryType.Boolean ||
value.ValueType == DocumentEntryType.Document)
{
throw new QueryException("DocumentEntryType \"" +
Enum.GetName(typeof(DocumentEntryType), value.ValueType) +
"\" is not supported on the \"lte\" query.");
}
_parts.Add(new QueryItemPart(QueryItemPartType.LessThenEqualTo, value));
break;
case "eq":
_parts.Add(new QueryItemPart(QueryItemPartType.Equal, value));
break;
case "neq":
_parts.Add(new QueryItemPart(QueryItemPartType.NotEqual, value));
break;
case "gt":
if (value.ValueType == DocumentEntryType.Array ||
value.ValueType == DocumentEntryType.Boolean ||
value.ValueType == DocumentEntryType.Document)
{
throw new QueryException("DocumentEntryType \"" +
Enum.GetName(typeof(DocumentEntryType), value.ValueType) +
"\" is not supported on the \"gt\" query.");
}
_parts.Add(new QueryItemPart(QueryItemPartType.GreaterThen, value));
break;
case "gte":
if (value.ValueType == DocumentEntryType.Array ||
value.ValueType == DocumentEntryType.Boolean ||
value.ValueType == DocumentEntryType.Document)
{
throw new QueryException("DocumentEntryType \"" +
Enum.GetName(typeof(DocumentEntryType), value.ValueType) +
"\" is not supported on the \"gte\" query.");
}
_parts.Add(new QueryItemPart(QueryItemPartType.GreaterThenEqualTo, value));
break;
case "in":
if (value.ValueType == DocumentEntryType.Array ||
value.ValueType == DocumentEntryType.Document)
{
throw new QueryException("DocumentEntryType \"" +
Enum.GetName(typeof(DocumentEntryType), value.ValueType) +
"\" is not supported on the \"in\" query.");
}
_parts.Add(new QueryItemPart(QueryItemPartType.Contains, value));
break;
case "nin":
if (value.ValueType == DocumentEntryType.Array ||
value.ValueType == DocumentEntryType.Document)
{
throw new QueryException("DocumentEntryType \"" +
Enum.GetName(typeof(DocumentEntryType), value.ValueType) +
"\" is not supported on the \"nin\" query.");
}
_parts.Add(new QueryItemPart(QueryItemPartType.NotContains, value));
break;
default:
throw new QueryException("Invalid query entry.");
}
}
/// <summary>
/// Checks if a is greater then b.
/// </summary>
/// <param name="a">The left side of the operator.</param>
/// <param name="b">The right side of the operator.</param>
/// <returns>The result of the operator.</returns>
private bool GreaterThen(DocumentEntry a, DocumentEntry b)
{
if (a.ValueType != b.ValueType)
{
return false;
}
switch (a.ValueType)
{
case DocumentEntryType.Float:
return a.ValueAsFloat > b.ValueAsFloat;
case DocumentEntryType.Integer:
return a.ValueAsInteger > b.ValueAsInteger;
case DocumentEntryType.String:
return string.Compare(a.ValueAsString, b.ValueAsString, StringComparison.Ordinal) > 0;
default:
return false;
}
}
/// <summary>
/// Checks if a is greater then or equal to b.
/// </summary>
/// <param name="a">The left side of the operator.</param>
/// <param name="b">The right side of the operator.</param>
/// <returns>The result of the operator.</returns>
private bool GreaterThenEqualTo(DocumentEntry a, DocumentEntry b)
{
if (a.ValueType != b.ValueType)
{
return false;
}
switch (a.ValueType)
{
case DocumentEntryType.Float:
return a.ValueAsFloat >= b.ValueAsFloat;
case DocumentEntryType.Integer:
return a.ValueAsInteger >= b.ValueAsInteger;
case DocumentEntryType.String:
return string.Compare(a.ValueAsString, b.ValueAsString, StringComparison.Ordinal) >= 0;
default:
return false;
}
}
/// <summary>
/// Checks if a is less then b.
/// </summary>
/// <param name="a">The left side of the operator.</param>
/// <param name="b">The right side of the operator.</param>
/// <returns>The result of the operator.</returns>
private bool LessThen(DocumentEntry a, DocumentEntry b)
{
if (a.ValueType != b.ValueType)
{
return false;
}
switch (a.ValueType)
{
case DocumentEntryType.Float:
return a.ValueAsFloat < b.ValueAsFloat;
case DocumentEntryType.Integer:
return a.ValueAsInteger < b.ValueAsInteger;
case DocumentEntryType.String:
return string.Compare(a.ValueAsString, b.ValueAsString, StringComparison.Ordinal) < 0;
default:
return false;
}
}
/// <summary>
/// Checks if a is less then or equal to b.
/// </summary>
/// <param name="a">The left side of the operator.</param>
/// <param name="b">The right side of the operator.</param>
/// <returns>The result of the operator.</returns>
private bool LessThenEqualTo(DocumentEntry a, DocumentEntry b)
{
if (a.ValueType != b.ValueType)
{
return false;
}
switch (a.ValueType)
{
case DocumentEntryType.Float:
return a.ValueAsFloat <= b.ValueAsFloat;
case DocumentEntryType.Integer:
return a.ValueAsInteger <= b.ValueAsInteger;
case DocumentEntryType.String:
return string.Compare(a.ValueAsString, b.ValueAsString, StringComparison.Ordinal) <= 0;
default:
return false;
}
}
/// <summary>
/// Checks to see if item at the key matches the query item.
/// </summary>
/// <param name="doc">The document to look in.</param>
/// <param name="part">The query item to match against.</param>
/// <returns>True if the document matches the query item, otherwise false.</returns>
private bool MatchItem(Document doc, QueryItemPart part)
{
switch (part.Type)
{
case QueryItemPartType.LessThen:
return LessThen(doc[_key], part.Value);
case QueryItemPartType.LessThenEqualTo:
return LessThenEqualTo(doc[_key], part.Value);
case QueryItemPartType.Equal:
return AreEqual(doc[_key], part.Value);
case QueryItemPartType.NotEqual:
return !AreEqual(doc[_key], part.Value);
case QueryItemPartType.GreaterThen:
return GreaterThen(doc[_key], part.Value);
case QueryItemPartType.GreaterThenEqualTo:
return GreaterThenEqualTo(doc[_key], part.Value);
case QueryItemPartType.Contains:
return Contains(doc[_key], part.Value);
case QueryItemPartType.NotContains:
return !Contains(doc[_key], part.Value);
default:
throw new NotImplementedException();
}
}
/// <summary>
/// Represents part of a single query.
/// </summary>
private struct QueryItemPart
{
/// <summary>
/// Initializes a new instance of the <see cref="QueryItemPart"/> struct.
/// </summary>
/// <param name="type">The type of the value.</param>
/// <param name="value">The value to be compared against.</param>
public QueryItemPart(QueryItemPartType type, DocumentEntry value)
: this()
{
Type = type;
Value = value;
}
/// <summary>
/// Gets the type.
/// </summary>
public QueryItemPartType Type { get; private set; }
/// <summary>
/// Gets the value.
/// </summary>
public DocumentEntry Value { get; private set; }
}
}
} | 35.861432 | 107 | 0.485381 | [
"MIT"
] | CaptainCow95/Database | DatabaseCommon/DataOperation/QueryItem.cs | 15,530 | C# |
using QuartzCronBuilder.Builders;
using Xunit;
namespace QuartzCronBuilder.Tests.Builders
{
internal class HoursExpressionBuilderSteps : ExpressionBuilderSteps
{
private CronExpressionBuilder cronExpressionBuilder;
private HoursExpressionBuilder expressionBuilder;
public HoursExpressionBuilderSteps()
{
base.Initialize(() =>
{
var cronExpression = this.expressionBuilder.BuildCronExpression();
var firstSpaceIndex = cronExpression.IndexOf(" ");
return cronExpression.Substring(0, firstSpaceIndex);
});
}
internal void GivenIHaveACronExpressionBuilder()
{
this.cronExpressionBuilder = new CronExpressionBuilder();
}
internal void WhenICreateANewHourExpressionBuilder()
{
this.expressionBuilder = new HoursExpressionBuilder(this.cronExpressionBuilder);
}
internal void ThenTheHourExpressionBuilderShouldNotBeNull()
{
Assert.NotNull(this.expressionBuilder);
}
internal void WhenISelectRangeOfHours(int from, int to)
{
this.expressionBuilder.RangeOfHours(from, to);
}
internal void WhenISelectAllHours()
{
this.expressionBuilder.AllHours();
}
internal void GivenIHaveAHourExpressionBuilder()
{
this.GivenIHaveACronExpressionBuilder();
this.WhenICreateANewHourExpressionBuilder();
}
internal void WhenISelectEveryXHours(int interval)
{
this.expressionBuilder.RunEveryXHours(interval);
}
internal void WhenISelectRunInHoursIncrements(int startingValue, int increment)
{
this.expressionBuilder.RunInHourIncrements(startingValue, increment);
}
internal void WhenISelectSpecificHours(int[] specificHours)
{
this.expressionBuilder.SpecificHours(specificHours);
}
internal void WhenISelectSpecificHoursAction(int[] specificHours)
{
this.testCode = () => this.expressionBuilder.SpecificHours(specificHours);
}
}
} | 30.875 | 92 | 0.642375 | [
"MIT"
] | StephenMP/QuartzCronBuilder | QuartzCronBuilder.Tests/Builders/HoursExpressionBuilderSteps.cs | 2,225 | C# |
using AzureFromTheTrenches.Commanding.Abstractions;
using FunctionMonkey.Abstractions.SignalR;
namespace Evidences.Domain.Commands.SessionCommands
{
public class StartSessionCommand : ICommand<SignalRMessage>
{
}
} | 25.222222 | 63 | 0.810573 | [
"MIT"
] | trturino/evidences | src/backend/Evidences.Domain/Commands/SessionCommands/StartSessionCommand.cs | 227 | C# |
using Etimo.Id.Entities;
using System;
using System.Threading.Tasks;
namespace Etimo.Id.Abstractions
{
public interface IUpdateApplicationService
{
Task<Application> UpdateAsync(Application updatedApplication, Guid userId);
}
}
| 20.75 | 83 | 0.759036 | [
"MIT"
] | Etimo/etimo-id | src/Etimo.Id.Abstractions/Services/ApplicationServices/IUpdateApplicationService.cs | 249 | C# |
// -----------------------------------------------------------------
// <copyright file="MapDescriptor.cs" company="2Dudes">
// Copyright (c) | Jose L. Nunez de Caceres et al.
// https://linkedin.com/in/nunezdecaceres
//
// All Rights Reserved.
//
// Licensed under the MIT License. See LICENSE in the project root for license information.
// </copyright>
// -----------------------------------------------------------------
namespace Fibula.Map
{
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
using Fibula.Common.Contracts.Enumerations;
using Fibula.Common.Contracts.Structs;
using Fibula.Common.Utilities;
using Fibula.Creatures.Contracts.Abstractions;
using Fibula.Map.Contracts;
using Fibula.Map.Contracts.Abstractions;
using Fibula.Map.Contracts.Constants;
using Serilog;
/// <summary>
/// Class that implements a standard map descriptor.
/// </summary>
public class MapDescriptor : IMapDescriptor
{
/// <summary>
/// A reference to the map.
/// </summary>
private readonly IMap map;
/// <summary>
/// A reference to the tile descriptor in use.
/// </summary>
private readonly IProtocolTileDescriptor tileDescriptor;
/// <summary>
/// Initializes a new instance of the <see cref="MapDescriptor"/> class.
/// </summary>
/// <param name="logger">A reference to the logger to use.</param>
/// <param name="map">The reference to the map in use.</param>
/// <param name="tileDescriptor">A reference to the tile descriptor in use.</param>
public MapDescriptor(ILogger logger, IMap map, IProtocolTileDescriptor tileDescriptor)
{
logger.ThrowIfNull(nameof(logger));
map.ThrowIfNull(nameof(map));
tileDescriptor.ThrowIfNull(nameof(tileDescriptor));
this.Logger = logger.ForContext<MapDescriptor>();
this.map = map;
this.tileDescriptor = tileDescriptor;
}
/// <summary>
/// Gets the reference to the current logger.
/// </summary>
public ILogger Logger { get; }
/// <summary>
/// Gets the description bytes of the map in behalf of a given player at a given location.
/// </summary>
/// <param name="player">The player for which the description is being retrieved for.</param>
/// <param name="centerLocation">The center location from which the description is being retrieved.</param>
/// <returns>A tuple containing the description metadata: a map of string to objects, and the description data: a sequence of bytes representing the description.</returns>
public (IDictionary<string, object> descriptionMetadata, ReadOnlySequence<byte> descriptionData) DescribeAt(IPlayer player, Location centerLocation)
{
player.ThrowIfNull(nameof(player));
ushort fromX = (ushort)(centerLocation.X - 8);
ushort fromY = (ushort)(centerLocation.Y - 6);
sbyte fromZ = (sbyte)(centerLocation.Z > 7 ? centerLocation.Z - 2 : 7);
sbyte toZ = (sbyte)(centerLocation.Z > 7 ? centerLocation.Z + 2 : 0);
return this.DescribeWindow(player, fromX, fromY, fromZ, toZ);
}
/// <summary>
/// Gets the description bytes of the map in behalf of a given player for the specified window.
/// </summary>
/// <param name="player">The player for which the description is being retrieved for.</param>
/// <param name="fromX">The starting X coordinate of the window.</param>
/// <param name="fromY">The starting Y coordinate of the window.</param>
/// <param name="fromZ">The starting Z coordinate of the window.</param>
/// <param name="toZ">The ending Z coordinate of the window.</param>
/// <param name="windowSizeX">The size of the window in X.</param>
/// <param name="windowSizeY">The size of the window in Y.</param>
/// <param name="customOffsetZ">Optional. A custom Z offset value used mainly for partial floor changing windows. Defaults to 0.</param>
/// <returns>A tuple containing the description metadata: a map of string to objects, and the description data: a sequence of bytes representing the description.</returns>
public (IDictionary<string, object> descriptionMetadata, ReadOnlySequence<byte> descriptionData) DescribeWindow(IPlayer player, ushort fromX, ushort fromY, sbyte fromZ, sbyte toZ, byte windowSizeX = MapConstants.DefaultWindowSizeX, byte windowSizeY = MapConstants.DefaultWindowSizeY, sbyte customOffsetZ = 0)
{
player.ThrowIfNull(nameof(player));
ushort toX = (ushort)(fromX + windowSizeX);
ushort toY = (ushort)(fromY + windowSizeY);
var firstSegment = new MapDescriptionSegment(ReadOnlyMemory<byte>.Empty);
MapDescriptionSegment lastSegment = firstSegment;
sbyte stepZ = 1;
byte currentSkipCount = byte.MaxValue;
if (fromZ > toZ)
{
// we're going up!
stepZ = -1;
}
customOffsetZ = customOffsetZ != 0 ? customOffsetZ : (sbyte)(player.Location.Z - fromZ);
if (windowSizeX > MapConstants.DefaultWindowSizeX)
{
this.Logger.Debug($"{nameof(this.DescribeWindow)} {nameof(windowSizeX)} is over {nameof(MapConstants.DefaultWindowSizeX)} ({MapConstants.DefaultWindowSizeX}).");
}
if (windowSizeY > MapConstants.DefaultWindowSizeY)
{
this.Logger.Debug($"{nameof(this.DescribeWindow)} {nameof(windowSizeY)} is over {nameof(MapConstants.DefaultWindowSizeY)} ({MapConstants.DefaultWindowSizeY}).");
}
var allCreatureIdsToLearn = new List<uint>();
var allCreatureIdsToForget = new List<uint>();
for (sbyte currentZ = fromZ; currentZ != toZ + stepZ; currentZ += stepZ)
{
var zOffset = fromZ - currentZ + customOffsetZ;
for (var nx = 0; nx < windowSizeX; nx++)
{
for (var ny = 0; ny < windowSizeY; ny++)
{
Location targetLocation = new Location
{
X = (ushort)(fromX + nx + zOffset),
Y = (ushort)(fromY + ny + zOffset),
Z = currentZ,
};
var segmentsFromTile = this.tileDescriptor.DescribeTileForPlayer(player, this.map.GetTileAt(targetLocation), out ISet<uint> creatureIdsToLearn, out ISet<uint> creatureIdsToForget);
allCreatureIdsToLearn.AddRange(creatureIdsToLearn);
allCreatureIdsToForget.AddRange(creatureIdsToForget);
// See if we actually have segments to append.
if (segmentsFromTile != null && segmentsFromTile.Any())
{
if (currentSkipCount < byte.MaxValue)
{
lastSegment = lastSegment.Append(new byte[] { currentSkipCount, byte.MaxValue });
}
foreach (var segment in segmentsFromTile)
{
lastSegment.Append(segment);
lastSegment = segment;
}
currentSkipCount = byte.MinValue;
continue;
}
if (++currentSkipCount == byte.MaxValue)
{
lastSegment = lastSegment.Append(new byte[] { byte.MaxValue, byte.MaxValue });
}
}
}
}
if (++currentSkipCount < byte.MaxValue)
{
lastSegment = lastSegment.Append(new byte[] { currentSkipCount, byte.MaxValue });
}
return (
new Dictionary<string, object>()
{
{ IMapDescriptor.CreatureIdsToLearnMetadataKeyName, allCreatureIdsToLearn.ToHashSet() },
{ IMapDescriptor.CreatureIdsToForgetMetadataKeyName, allCreatureIdsToForget.ToHashSet() },
},
new ReadOnlySequence<byte>(firstSegment, 0, lastSegment, lastSegment.Memory.Length));
}
/// <summary>
/// Gets the description bytes of a single tile of the map in behalf of a given player at a given location.
/// </summary>
/// <param name="player">The player for which the description is being retrieved for.</param>
/// <param name="location">The location from which the description of the tile is being retrieved.</param>
/// <returns>A tuple containing the description metadata: a map of string to objects, and the description data: a sequence of bytes representing the tile's description.</returns>
public (IDictionary<string, object> descriptionMetadata, ReadOnlySequence<byte> descriptionData) DescribeTile(IPlayer player, Location location)
{
player.ThrowIfNull(nameof(player));
if (location.Type != LocationType.Map)
{
throw new ArgumentException($"Invalid location {location}.", nameof(location));
}
var firstSegment = new MapDescriptionSegment(ReadOnlyMemory<byte>.Empty);
MapDescriptionSegment lastSegment = firstSegment;
var segmentsFromTile = this.tileDescriptor.DescribeTileForPlayer(player, this.map.GetTileAt(location), out ISet<uint> creatureIdsToLearn, out ISet<uint> creatureIdsToForget);
// See if we actually have segments to append.
if (segmentsFromTile != null && segmentsFromTile.Any())
{
foreach (var segment in segmentsFromTile)
{
lastSegment.Append(segment);
lastSegment = segment;
}
}
return (
new Dictionary<string, object>()
{
{ IMapDescriptor.CreatureIdsToLearnMetadataKeyName, creatureIdsToLearn },
{ IMapDescriptor.CreatureIdsToForgetMetadataKeyName, creatureIdsToForget },
},
new ReadOnlySequence<byte>(firstSegment, 0, lastSegment, lastSegment.Memory.Length));
}
}
}
| 46.133621 | 316 | 0.581145 | [
"MIT"
] | jlnunez89/fibula-mmo | src/Fibula.Map/MapDescriptor.cs | 10,705 | C# |
/*
* Copyright(c) 2019 Samsung Electronics Co., Ltd.
*
* 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.ComponentModel;
using Tizen.NUI.Binding;
namespace Tizen.NUI
{
/// <summary>
/// A four-dimensional vector.
/// </summary>
/// <since_tizen> 3 </since_tizen>
[Binding.TypeConverter(typeof(Vector4TypeConverter))]
public class Vector4 : Disposable, ICloneable
{
/// <summary>
/// The default constructor initializes the vector to 0.
/// </summary>
/// <since_tizen> 3 </since_tizen>
public Vector4() : this(Interop.Vector4.new_Vector4__SWIG_0(), true)
{
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
}
/// <summary>
/// The conversion constructor from four floats.
/// </summary>
/// <param name="x">The x (or r/s) component.</param>
/// <param name="y">The y (or g/t) component.</param>
/// <param name="z">The z (or b/p) component.</param>
/// <param name="w">The w (or a/q) component.</param>
/// <since_tizen> 3 </since_tizen>
public Vector4(float x, float y, float z, float w) : this(Interop.Vector4.new_Vector4__SWIG_1(x, y, z, w), true)
{
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
}
/// <summary>
/// The conversion constructor from an array of four floats.
/// </summary>
/// <param name="array">The array of either xyzw/rgba/stpq.</param>
/// <since_tizen> 3 </since_tizen>
public Vector4(float[] array) : this(Interop.Vector4.new_Vector4__SWIG_2(array), true)
{
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
}
/// <summary>
/// The conversion constructor from Vector2.
/// </summary>
/// <param name="vec2">Vector2 to copy from, z and w are initialized to 0.</param>
/// <since_tizen> 3 </since_tizen>
public Vector4(Vector2 vec2) : this(Interop.Vector4.new_Vector4__SWIG_3(Vector2.getCPtr(vec2)), true)
{
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
}
/// <summary>
/// The conversion constructor from Vector3.
/// </summary>
/// <param name="vec3">Vector3 to copy from, w is initialized to 0.</param>
/// <since_tizen> 3 </since_tizen>
public Vector4(Vector3 vec3) : this(Interop.Vector4.new_Vector4__SWIG_4(Vector3.getCPtr(vec3)), true)
{
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
}
internal Vector4(global::System.IntPtr cPtr, bool cMemoryOwn) : base(cPtr, cMemoryOwn)
{
}
internal Vector4(Vector4ChangedCallback cb, float x, float y, float z, float w) : this(Interop.Vector4.new_Vector4__SWIG_1(x, y, z, w), true)
{
callback = cb;
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
}
internal delegate void Vector4ChangedCallback(float x, float y, float z, float w);
private Vector4ChangedCallback callback = null;
/// <summary>
/// (1.0f,1.0f,1.0f,1.0f).
/// </summary>
/// <since_tizen> 3 </since_tizen>
public static Vector4 One
{
get
{
global::System.IntPtr cPtr = Interop.Vector4.Vector4_ONE_get();
Vector4 ret = (cPtr == global::System.IntPtr.Zero) ? null : new Vector4(cPtr, false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
}
/// <summary>
/// (1.0f,0.0f,0.0f,0.0f).
/// </summary>
/// <since_tizen> 3 </since_tizen>
public static Vector4 XAxis
{
get
{
global::System.IntPtr cPtr = Interop.Vector4.Vector4_XAXIS_get();
Vector4 ret = (cPtr == global::System.IntPtr.Zero) ? null : new Vector4(cPtr, false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
}
/// <summary>
/// (0.0f,1.0f,0.0f,0.0f).
/// </summary>
/// <since_tizen> 3 </since_tizen>
public static Vector4 YAxis
{
get
{
global::System.IntPtr cPtr = Interop.Vector4.Vector4_YAXIS_get();
Vector4 ret = (cPtr == global::System.IntPtr.Zero) ? null : new Vector4(cPtr, false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
}
/// <summary>
/// (0.0f,0.0f,1.0f,0.0f).
/// </summary>
/// <since_tizen> 3 </since_tizen>
public static Vector4 ZAxis
{
get
{
global::System.IntPtr cPtr = Interop.Vector4.Vector4_ZAXIS_get();
Vector4 ret = (cPtr == global::System.IntPtr.Zero) ? null : new Vector4(cPtr, false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
}
/// <summary>
/// (0.0f, 0.0f, 0.0f, 0.0f).
/// </summary>
/// <since_tizen> 3 </since_tizen>
public static Vector4 Zero
{
get
{
global::System.IntPtr cPtr = Interop.Vector4.Vector4_ZERO_get();
Vector4 ret = (cPtr == global::System.IntPtr.Zero) ? null : new Vector4(cPtr, false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
}
/// <summary>
/// The x component.
/// </summary>
/// <since_tizen> 3 </since_tizen>
[Obsolete("Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor")]
public float X
{
set
{
Tizen.Log.Fatal("NUI", "Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor");
Interop.Vector4.Vector4_X_set(swigCPtr, value);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
callback?.Invoke(X, Y, Z, W);
}
get
{
float ret = Interop.Vector4.Vector4_X_get(swigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
}
/// <summary>
/// The red component.
/// </summary>
/// <since_tizen> 3 </since_tizen>
[Obsolete("Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor")]
public float R
{
set
{
Tizen.Log.Fatal("NUI", "Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor");
Interop.Vector4.Vector4_r_set(swigCPtr, value);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
callback?.Invoke(X, Y, Z, W);
}
get
{
float ret = Interop.Vector4.Vector4_r_get(swigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
}
/// <summary>
/// The s component.
/// </summary>
/// <since_tizen> 3 </since_tizen>
[Obsolete("Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor")]
public float S
{
set
{
Tizen.Log.Fatal("NUI", "Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor");
Interop.Vector4.Vector4_s_set(swigCPtr, value);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
callback?.Invoke(X, Y, Z, W);
}
get
{
float ret = Interop.Vector4.Vector4_s_get(swigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
}
/// <summary>
/// The y component.
/// </summary>
/// <since_tizen> 3 </since_tizen>
[Obsolete("Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor")]
public float Y
{
set
{
Tizen.Log.Fatal("NUI", "Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor");
Interop.Vector4.Vector4_Y_set(swigCPtr, value);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
callback?.Invoke(X, Y, Z, W);
}
get
{
float ret = Interop.Vector4.Vector4_Y_get(swigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
}
/// <summary>
/// The green component.
/// </summary>
/// <since_tizen> 3 </since_tizen>
[Obsolete("Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor")]
public float G
{
set
{
Tizen.Log.Fatal("NUI", "Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor");
Interop.Vector4.Vector4_g_set(swigCPtr, value);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
callback?.Invoke(X, Y, Z, W);
}
get
{
float ret = Interop.Vector4.Vector4_g_get(swigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
}
/// <summary>
/// The t component.
/// </summary>
/// <since_tizen> 3 </since_tizen>
[Obsolete("Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor")]
public float T
{
set
{
Tizen.Log.Fatal("NUI", "Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor");
Interop.Vector4.Vector4_t_set(swigCPtr, value);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
callback?.Invoke(X, Y, Z, W);
}
get
{
float ret = Interop.Vector4.Vector4_t_get(swigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
}
/// <summary>
/// The z component.
/// </summary>
/// <since_tizen> 3 </since_tizen>
[Obsolete("Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor")]
public float Z
{
set
{
Tizen.Log.Fatal("NUI", "Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor");
Interop.Vector4.Vector4_Z_set(swigCPtr, value);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
callback?.Invoke(X, Y, Z, W);
}
get
{
float ret = Interop.Vector4.Vector4_Z_get(swigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
}
/// <summary>
/// The blue component.
/// </summary>
/// <since_tizen> 3 </since_tizen>
[Obsolete("Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor")]
public float B
{
set
{
Tizen.Log.Fatal("NUI", "Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor");
Interop.Vector4.Vector4_b_set(swigCPtr, value);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
callback?.Invoke(X, Y, Z, W);
}
get
{
float ret = Interop.Vector4.Vector4_b_get(swigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
}
/// <summary>
/// The p component.
/// </summary>
/// <since_tizen> 3 </since_tizen>
[Obsolete("Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor")]
public float P
{
set
{
Tizen.Log.Fatal("NUI", "Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor");
Interop.Vector4.Vector4_p_set(swigCPtr, value);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
callback?.Invoke(X, Y, Z, W);
}
get
{
float ret = Interop.Vector4.Vector4_p_get(swigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
}
/// <summary>
/// The w component.
/// </summary>
/// <since_tizen> 3 </since_tizen>
[Obsolete("Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor")]
public float W
{
set
{
Tizen.Log.Fatal("NUI", "Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor");
Interop.Vector4.Vector4_W_set(swigCPtr, value);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
callback?.Invoke(X, Y, Z, W);
}
get
{
float ret = Interop.Vector4.Vector4_W_get(swigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
}
/// <summary>
/// The alpha component.
/// </summary>
/// <since_tizen> 3 </since_tizen>
[Obsolete("Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor")]
public float A
{
set
{
Tizen.Log.Fatal("NUI", "Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor");
Interop.Vector4.Vector4_a_set(swigCPtr, value);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
callback?.Invoke(X, Y, Z, W);
}
get
{
float ret = Interop.Vector4.Vector4_a_get(swigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
}
/// <summary>
/// The q component.
/// </summary>
/// <since_tizen> 3 </since_tizen>
[Obsolete("Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor")]
public float Q
{
set
{
Tizen.Log.Fatal("NUI", "Please do not use this setter, Deprecated in API8, will be removed in API10. please use new Vector4(...) constructor");
Interop.Vector4.Vector4_q_set(swigCPtr, value);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
callback?.Invoke(X, Y, Z, W);
}
get
{
float ret = Interop.Vector4.Vector4_q_get(swigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
}
/// <summary>
/// The array subscript operator overload.
/// </summary>
/// <param name="index">The subscript index.</param>
/// <returns>The float at the given index.</returns>
/// <since_tizen> 3 </since_tizen>
public float this[uint index]
{
get
{
return ValueOfIndex(index);
}
}
/// <summary>
/// The addition operator.
/// </summary>
/// <param name="arg1">The first value.</param>
/// <param name="arg2">The second value.</param>
/// <returns>The vector containing the result of the addition.</returns>
/// <since_tizen> 3 </since_tizen>
public static Vector4 operator +(Vector4 arg1, Vector4 arg2)
{
return arg1.Add(arg2);
}
/// <summary>
/// The subtraction operator.
/// </summary>
/// <param name="arg1">The first value.</param>
/// <param name="arg2">The second value.</param>
/// <returns>The vector containing the result of the subtraction.</returns>
/// <since_tizen> 3 </since_tizen>
public static Vector4 operator -(Vector4 arg1, Vector4 arg2)
{
return arg1.Subtract(arg2);
}
/// <summary>
/// The unary negation operator.
/// </summary>
/// <param name="arg1">The target value.</param>
/// <returns>The vector containing the negation.</returns>
/// <since_tizen> 3 </since_tizen>
public static Vector4 operator -(Vector4 arg1)
{
return arg1.Subtract();
}
/// <summary>
/// The multiplication operator.
/// </summary>
/// <param name="arg1">The first value.</param>
/// <param name="arg2">The second value.</param>
/// <returns>The vector containing the result of the multiplication.</returns>
/// <since_tizen> 3 </since_tizen>
public static Vector4 operator *(Vector4 arg1, Vector4 arg2)
{
return arg1.Multiply(arg2);
}
/// <summary>
/// The multiplication operator.
/// </summary>
/// <param name="arg1">The first value.</param>
/// <param name="arg2">The float value to scale the vector.</param>
/// <returns>The vector containing the result of scaling.</returns>
/// <since_tizen> 3 </since_tizen>
public static Vector4 operator *(Vector4 arg1, float arg2)
{
return arg1.Multiply(arg2);
}
/// <summary>
/// The division operator.
/// </summary>
/// <param name="arg1">The first value.</param>
/// <param name="arg2">The second value.</param>
/// <returns>The vector containing the result of the division.</returns>
/// <since_tizen> 3 </since_tizen>
public static Vector4 operator /(Vector4 arg1, Vector4 arg2)
{
return arg1.Divide(arg2);
}
/// <summary>
/// The division operator.
/// </summary>
/// <param name="arg1">The first value.</param>
/// <param name="arg2">The float value to scale the vector by.</param>
/// <returns>The vector containing the result of scaling.</returns>
/// <since_tizen> 3 </since_tizen>
public static Vector4 operator /(Vector4 arg1, float arg2)
{
return arg1.Divide(arg2);
}
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// </summary>
/// <param name="obj">The object to compare with the current object.</param>
/// <returns>true if the specified object is equal to the current object; otherwise, false.</returns>
public override bool Equals(System.Object obj)
{
Vector4 vector4 = obj as Vector4;
bool equal = false;
if (X == vector4?.X && Y == vector4?.Y && Z == vector4?.Z && W == vector4?.W)
{
equal = true;
}
return equal;
}
/// <summary>
/// Gets the the hash code of this Vector4.
/// </summary>
/// <returns>The Hash Code.</returns>
/// <since_tizen> 6 </since_tizen>
public override int GetHashCode()
{
return swigCPtr.Handle.GetHashCode();
}
/// <summary>
/// Returns the length of the vector.
/// </summary>
/// <returns>The length.</returns>
/// <since_tizen> 3 </since_tizen>
public float Length()
{
float ret = Interop.Vector4.Vector4_Length(swigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
/// <summary>
/// Returns the length of the vector squared.<br />
/// This is faster than using Length() when performing
/// threshold checks as it avoids use of the square root.<br />
/// </summary>
/// <returns>The length of the vector squared.</returns>
/// <since_tizen> 3 </since_tizen>
public float LengthSquared()
{
float ret = Interop.Vector4.Vector4_LengthSquared(swigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
/// <summary>
/// Normalizes the vector.<br />
/// Sets the vector to unit length whilst maintaining its direction.<br />
/// </summary>
/// <since_tizen> 3 </since_tizen>
public void Normalize()
{
Interop.Vector4.Vector4_Normalize(swigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
}
/// <summary>
/// Clamps the vector between minimum and maximum vectors.
/// </summary>
/// <param name="min">The minimum vector.</param>
/// <param name="max">The maximum vector.</param>
/// <since_tizen> 3 </since_tizen>
public void Clamp(Vector4 min, Vector4 max)
{
Interop.Vector4.Vector4_Clamp(swigCPtr, Vector4.getCPtr(min), Vector4.getCPtr(max));
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
}
/// <inheritdoc/>
[EditorBrowsable(EditorBrowsableState.Never)]
public object Clone() => new Vector4(X, Y, Z, W);
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Vector4 obj)
{
return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
}
internal static Vector4 GetVector4FromPtr(global::System.IntPtr cPtr)
{
Vector4 ret = new Vector4(cPtr, false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
internal SWIGTYPE_p_float AsFloat()
{
global::System.IntPtr cPtr = Interop.Vector4.Vector4_AsFloat__SWIG_0(swigCPtr);
SWIGTYPE_p_float ret = (cPtr == global::System.IntPtr.Zero) ? null : new SWIGTYPE_p_float(cPtr, false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
internal float Dot(Vector3 other)
{
float ret = Interop.Vector4.Vector4_Dot__SWIG_0(swigCPtr, Vector3.getCPtr(other));
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
internal float Dot(Vector4 other)
{
float ret = Interop.Vector4.Vector4_Dot__SWIG_1(swigCPtr, Vector4.getCPtr(other));
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
internal float Dot4(Vector4 other)
{
float ret = Interop.Vector4.Vector4_Dot4(swigCPtr, Vector4.getCPtr(other));
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
internal Vector4 Cross(Vector4 other)
{
Vector4 ret = new Vector4(Interop.Vector4.Vector4_Cross(swigCPtr, Vector4.getCPtr(other)), true);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
/// This will not be public opened.
[EditorBrowsable(EditorBrowsableState.Never)]
protected override void ReleaseSwigCPtr(System.Runtime.InteropServices.HandleRef swigCPtr)
{
Interop.Vector4.delete_Vector4(swigCPtr);
}
private Vector4 Add(Vector4 rhs)
{
Vector4 ret = new Vector4(Interop.Vector4.Vector4_Add(swigCPtr, Vector4.getCPtr(rhs)), true);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
private Vector4 AddAssign(Vector4 rhs)
{
Vector4 ret = new Vector4(Interop.Vector4.Vector4_AddAssign(swigCPtr, Vector4.getCPtr(rhs)), false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
private Vector4 Subtract(Vector4 rhs)
{
Vector4 ret = new Vector4(Interop.Vector4.Vector4_Subtract__SWIG_0(swigCPtr, Vector4.getCPtr(rhs)), true);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
private Vector4 SubtractAssign(Vector4 rhs)
{
Vector4 ret = new Vector4(Interop.Vector4.Vector4_SubtractAssign(swigCPtr, Vector4.getCPtr(rhs)), false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
private Vector4 Multiply(Vector4 rhs)
{
Vector4 ret = new Vector4(Interop.Vector4.Vector4_Multiply__SWIG_0(swigCPtr, Vector4.getCPtr(rhs)), true);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
private Vector4 Multiply(float rhs)
{
Vector4 ret = new Vector4(Interop.Vector4.Vector4_Multiply__SWIG_1(swigCPtr, rhs), true);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
private Vector4 MultiplyAssign(Vector4 rhs)
{
Vector4 ret = new Vector4(Interop.Vector4.Vector4_MultiplyAssign__SWIG_0(swigCPtr, Vector4.getCPtr(rhs)), false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
private Vector4 MultiplyAssign(float rhs)
{
Vector4 ret = new Vector4(Interop.Vector4.Vector4_MultiplyAssign__SWIG_1(swigCPtr, rhs), false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
private Vector4 Divide(Vector4 rhs)
{
Vector4 ret = new Vector4(Interop.Vector4.Vector4_Divide__SWIG_0(swigCPtr, Vector4.getCPtr(rhs)), true);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
private Vector4 Divide(float rhs)
{
Vector4 ret = new Vector4(Interop.Vector4.Vector4_Divide__SWIG_1(swigCPtr, rhs), true);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
private Vector4 DivideAssign(Vector4 rhs)
{
Vector4 ret = new Vector4(Interop.Vector4.Vector4_DivideAssign__SWIG_0(swigCPtr, Vector4.getCPtr(rhs)), false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
private Vector4 DivideAssign(float rhs)
{
Vector4 ret = new Vector4(Interop.Vector4.Vector4_DivideAssign__SWIG_1(swigCPtr, rhs), false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
private Vector4 Subtract()
{
Vector4 ret = new Vector4(Interop.Vector4.Vector4_Subtract__SWIG_1(swigCPtr), true);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
private bool EqualTo(Vector4 rhs)
{
bool ret = Interop.Vector4.Vector4_EqualTo(swigCPtr, Vector4.getCPtr(rhs));
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
private bool NotEqualTo(Vector4 rhs)
{
bool ret = Interop.Vector4.Vector4_NotEqualTo(swigCPtr, Vector4.getCPtr(rhs));
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
private float ValueOfIndex(uint index)
{
float ret = Interop.Vector4.Vector4_ValueOfIndex__SWIG_0(swigCPtr, index);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
}
} | 40.525466 | 159 | 0.589737 | [
"Apache-2.0",
"MIT"
] | Ali-Alzyoud/TizenFX | src/Tizen.NUI/src/public/Vector4.cs | 32,623 | C# |
using Newtonsoft.Json;
namespace FreeAgentSniper.Models
{
public class PlayerResponse
{
[JsonProperty("player_key")]
public string PlayerKey { get; set; }
[JsonProperty("player_id")]
public int PlayerId { get; set; }
public PlayerName Name { get; set; }
public class PlayerName
{
public string Full { get; set; }
public string First { get; set; }
public string Last { get; set; }
}
[JsonProperty("editorial_team_full_name")]
public string TeamFullName { get; set; }
[JsonProperty("editorial_team_abbr")]
public string TeamAbbr { get; set; }
[JsonProperty("display_position")]
public string Position { get; set; }
}
} | 31.12 | 50 | 0.588689 | [
"MIT"
] | jmbledsoe/FreeAgentSniper | src/Models/PlayerResponse.cs | 778 | C# |
using System.Collections.Generic;
using Newtonsoft.Json;
namespace PddOpenSdk.Models.Response.Ad
{
public class AdUnitHistoryReportGetResponse
{
/// <summary>
/// Examples: 0
/// </summary>
[JsonProperty("total")]
public int Total { get; set; }
/// <summary>
/// Examples: []
/// </summary>
[JsonProperty("result")]
public IList<object> Result { get; set; }
}
public class GetAdHistoryUnitReportResponseModel
{
/// <summary>
/// Examples: {"total":0,"result":[]}
/// </summary>
[JsonProperty("ad_unit_history_report_get_response")]
public AdUnitHistoryReportGetResponse AdUnitHistoryReportGetResponse { get; set; }
}
}
| 23.30303 | 90 | 0.587776 | [
"Apache-2.0"
] | gitter-badger/open-pdd-net-sdk | PddOpenSdk/PddOpenSdk/Models/Response/Ad/GetAdHistoryUnitReportResponseModel.cs | 769 | C# |
using System;
using Grasshopper.Kernel;
using PterodactylEngine;
namespace Pterodactyl
{
public class HeadingGH : GH_Component
{
public HeadingGH()
: base("Heading", "Heading",
"Creates heading",
"Pterodactyl", "Parts")
{
}
public override bool IsBakeCapable => false;
protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager)
{
pManager.AddTextParameter("Text", "Text", "Text for the heading",
GH_ParamAccess.item, "Sample text for heading");
pManager.AddIntegerParameter("Level", "Level", "Level of the heading as integer. Should be between 1 and 6.",
GH_ParamAccess.item, 1);
}
protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager)
{
pManager.AddTextParameter("Report Part", "Report Part", "Created part of the report (Markdown text)", GH_ParamAccess.item);
}
protected override void SolveInstance(IGH_DataAccess DA)
{
string text = string.Empty;
int level = 0;
DA.GetData(0, ref text);
DA.GetData(1, ref level);
string reportPart;
Heading reportObject = new Heading(text, level);
reportPart = reportObject.Create();
DA.SetData(0, reportPart);
}
protected override System.Drawing.Bitmap Icon
{
get
{
return Properties.Resources.PterodactylHeading;
}
}
public override Guid ComponentGuid
{
get { return new Guid("6d67b19c-bd15-44eb-9524-e0856ff55d1a"); }
}
}
} | 32.740741 | 135 | 0.585407 | [
"MIT"
] | shapediver/Pterodactyl | Pterodactyl/HeadingGH.cs | 1,770 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Zad5
{
class Program
{
static void Main(string[] args)
{
string text = Console.ReadLine();
StringBuilder changedText = new StringBuilder();
while (text.IndexOf("<upcase>") != -1)
{
changedText.Append(text.Substring(0, text.IndexOf("<upcase>")));
text = text.Remove(0, text.IndexOf("<upcase>") + 8);
changedText.Append(text.Substring(0, text.IndexOf("</upcase>")).ToUpper());
text = text.Remove(0, text.IndexOf("</upcase>") + 9);
}
changedText.Append(text);
Console.WriteLine(changedText);
}
}
}
| 28.857143 | 91 | 0.555693 | [
"MIT"
] | Kassomats/TelerikAcademy | StringsHomework/Zad5/Program.cs | 810 | C# |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion License
namespace Irony.Interpreter
{
public class ScriptStackTrace
{ }
}
| 33 | 93 | 0.554545 | [
"MIT"
] | Tyelpion/irony | Irony.Interpreter/Diagnostics/ScriptStackTrace.cs | 660 | C# |
using System;
namespace _2_2_10_2_operatori
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Operatori:");
int x = 2;
x += 1; // x = x + 1 ili x++
Console.WriteLine("X je "+x);
x -= 7; // x = x - 7
Console.WriteLine("X je " + x);
x = 1;
int y;
y = x++; // povećaj x za 1
Console.WriteLine("Y je " + y);
x = 1;
y = ++x; // povećaj x za 1
Console.WriteLine("Y je " + y);
// string s1 = (string)x; // ivo ne radi castanjem
string s1 = Convert.ToString(x);
Console.WriteLine("vrijednost stringa s1 je " + s1);
}
}
}
| 22.314286 | 64 | 0.421255 | [
"MIT"
] | Csharp2020/csharp2020 | FVidovic/2_2_10_2_operatori/Program.cs | 785 | C# |
#region License
/*
MIT License
Copyright © 2006-2007 The Mono.Xna Team
All rights reserved.
Authors: Isaac Llopis (neozack@gmail.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#endregion
#if !MSXNAONLY
using System;
using System.Diagnostics;
using NUnit.Framework;
namespace Tests.Microsoft.Xna.Framework
{
[TestFixture]
public class GameTests
{
#region Setup
[SetUp]
public void Setup()
{
// Reset clock before each test
TestClock.Instance.Reset();
}
#endregion
#region Public Constructors
[Test]
public void Constructors()
{
TestGame game = new TestGame();
Assert.IsNotNull(game, "Failed to create TestGame");
}
#endregion
#region Public Fields Tests
#endregion
#region Protected Fields Tests
#endregion
#region Public Properties Tests
[Test]
public void GameWindowSetTest()
{
TestGame game = new TestGame();
Assert.IsNotNull(game.Window, "Window is not set");
Assert.IsInstanceOfType(typeof (TestGameWindow), game.Window);
}
[Test]
public void IsActiveDefaultTrueTest()
{
TestGame game = new TestGame();
Assert.IsTrue(game.IsActive, "IsActive should be true");
}
[Test]
public void IsFixedTimeStepDefaultTrueTest()
{
TestGame game = new TestGame();
Assert.IsTrue(game.IsFixedTimeStep, "IsFixedTimeStep should be true");
}
#endregion Public Properties Tests
#region Protected Properties Tests
#endregion
#region Public Methods Tests
[Test]
public void InitializeCalledOnceTest()
{
TestGame game = new TestGame(new NullEventSource());
game.Run();
Assert.AreEqual(1, game.CountInitialize, "Initialize was called an incorrect number of times.");
}
[Test]
public void BeginRunCalledOnceTest()
{
TestGame game = new TestGame(new NullEventSource());
game.Run();
Assert.AreEqual(1, game.CountBeginRun, "BeginRun was called an incorrect number of times.");
}
[Test]
public void EndRunCalledOnceTest()
{
TestGame game = new TestGame(new NullEventSource());
game.Run();
Assert.AreEqual(1, game.CountEndRun, "EndRun was called an incorrect number of times.");
}
[Test]
public void UpdateCalledOnceTest()
{
TestGame game = new TestGame(new NullEventSource());
game.Run();
Assert.AreEqual(1, game.CountUpdate, "Update was called an incorrect number of times.");
}
[Test]
public void BeginDrawCalledOnceTest()
{
DelegateBasedEventSource evt = new DelegateBasedEventSource(delegate(DelegateBasedEventSource e) { e.Game.Tick(); });
TestGame game = new TestGame(evt);
((TestGameWindow)game.Window).RaiseVisibleChanged(true);
game.Run();
Assert.AreEqual(1, game.CountBeginDraw, "BeginDraw was called an unexpected number of times.");
}
[Test]
public void DrawCalledOnceTest()
{
DelegateBasedEventSource evt = new DelegateBasedEventSource(delegate(DelegateBasedEventSource e) { e.Game.Tick(); });
TestGame game = new TestGame(evt);
((TestGameWindow)game.Window).RaiseVisibleChanged(true);
game.Run();
Assert.AreEqual(1, game.CountDraw, "Draw was called an unexpected number of times.");
}
[Test]
public void DrawNotCalledIfBeginDrawReturnsFalseTest()
{
DelegateBasedEventSource evt = new DelegateBasedEventSource(delegate(DelegateBasedEventSource e) { e.Game.Tick(); });
TestGame game = new TestGame(evt);
((TestGameWindow)game.Window).RaiseVisibleChanged(true);
DummyGraphicsDeviceManager gdm = (DummyGraphicsDeviceManager)game.GraphicsDeviceManager;
gdm.BeginDrawResult = false;
game.Run();
Assert.AreEqual(0, game.CountDraw, "Draw was called an unexpected number of times.");
}
[Test]
public void DrawNotCalledIfWindowIsNotVisibleTest()
{
DelegateBasedEventSource evt = new DelegateBasedEventSource(delegate(DelegateBasedEventSource e) { e.Game.Tick(); });
TestGame game = new TestGame(evt);
((TestGameWindow)game.Window).RaiseVisibleChanged(false);
DummyGraphicsDeviceManager gdm = (DummyGraphicsDeviceManager)game.GraphicsDeviceManager;
gdm.BeginDrawResult = false;
game.Run();
Assert.AreEqual(0, game.CountDraw, "Draw was called an unexpected number of times.");
}
[Test]
public void EndDrawNotCalledIfWindowIsNotVisibleTest()
{
DelegateBasedEventSource evt = new DelegateBasedEventSource(delegate(DelegateBasedEventSource e) { e.Game.Tick(); });
TestGame game = new TestGame(evt);
((TestGameWindow)game.Window).RaiseVisibleChanged(false);
DummyGraphicsDeviceManager gdm = (DummyGraphicsDeviceManager)game.GraphicsDeviceManager;
gdm.BeginDrawResult = false;
game.Run();
Assert.AreEqual(0, game.CountEndDraw, "EndDraw was called an unexpected number of times.");
}
[Test]
public void EndDrawNotCalledIfBeginDrawReturnsFalseTest()
{
DelegateBasedEventSource evt = new DelegateBasedEventSource(delegate(DelegateBasedEventSource e) { e.Game.Tick(); });
TestGame game = new TestGame(evt);
((TestGameWindow)game.Window).RaiseVisibleChanged(true);
DummyGraphicsDeviceManager gdm = (DummyGraphicsDeviceManager)game.GraphicsDeviceManager;
gdm.BeginDrawResult = false;
game.Run();
Assert.AreEqual(0, game.CountEndDraw, "EndDraw was called an unexpected number of times.");
}
[Test]
public void EndDrawCalledOnceTest()
{
DelegateBasedEventSource evt = new DelegateBasedEventSource(delegate(DelegateBasedEventSource e) { e.Game.Tick(); });
TestGame game = new TestGame(evt);
((TestGameWindow)game.Window).RaiseVisibleChanged(true);
game.Run();
Assert.AreEqual(1, game.CountEndDraw, "EndDraw was called an unexpected number of times.");
}
/// <summary>
/// This test verifies that Update is called 1 + LOOP_COUNT * STEP_RATE(ms) / Game.TargetElapsedTime.Milliseconds
/// where STEP_RATE less than TargetElapsedTime, so no catchup calls are made
/// </summary>
[Test]
public void UpdateLoopForFixedTimeStepGameTest()
{
const int LOOP_COUNT = 5;
const int STEP_RATE = 50; // milliseconds per step
const int TARGET_UPDATE_RATE = 100; // update called every 100 ms
DelegateBasedEventSource evt = new DelegateBasedEventSource(delegate(DelegateBasedEventSource e)
{
int i = LOOP_COUNT;
while (i-- > 0)
{
TestClock.Instance.Step(STEP_RATE);
e.Game.Tick();
}
});
TestGame gd = new TestGame(evt, true);
gd.TargetElapsedTime = TimeSpan.FromMilliseconds(TARGET_UPDATE_RATE);
gd.Run();
Assert.AreEqual(1 + LOOP_COUNT*STEP_RATE/TARGET_UPDATE_RATE, gd.CountUpdate);
}
/// <summary>
/// This test verifies that Update is called 1 + Draw times (since Update is called once prior to the main loop beginning
/// </summary>
[Test]
public void UpdateLoopForVariableTimeStepGameTest()
{
const int LOOP_COUNT = 5;
const int STEP_RATE = 50; // milliseconds per step
const int TARGET_UPDATE_RATE = 100; // update called every 100 ms
DelegateBasedEventSource evt = new DelegateBasedEventSource(delegate(DelegateBasedEventSource e)
{
int i = LOOP_COUNT;
while (i-- > 0)
{
TestClock.Instance.Step(STEP_RATE);
e.Game.Tick();
}
});
TestGame gd = new TestGame(evt, true);
gd.TargetElapsedTime = TimeSpan.FromMilliseconds(TARGET_UPDATE_RATE);
gd.IsFixedTimeStep = false;
((TestGameWindow)gd.Window).RaiseVisibleChanged(true);
gd.Run();
Assert.AreEqual(gd.CountUpdate, gd.CountDraw + 1);
}
/// <summary>
/// This test verifies that Update is called 1 + LOOP_COUNT * STEP_RATE(ms) / Game.TargetElapsedTime.Milliseconds
/// where STEP_RATE less than <see cref="TestClock.MAX_ELAPSED"/>, ensuring all catch-up calls to update are called
/// </summary>
[Test]
public void UpdateLoopCatchupForFixedTimeStepGameTest()
{
const int LOOP_COUNT = 5;
const int STEP_RATE = 200; // milliseconds per step
const int TARGET_UPDATE_RATE = 100; // update called every 100 ms
DelegateBasedEventSource evt = new DelegateBasedEventSource(delegate(DelegateBasedEventSource e)
{
int i = LOOP_COUNT;
while (i-- > 0)
{
TestClock.Instance.Step(STEP_RATE);
e.Game.Tick();
}
});
TestGame gd = new TestGame(evt, true);
gd.TargetElapsedTime = TimeSpan.FromMilliseconds(TARGET_UPDATE_RATE);
gd.Run();
Assert.AreEqual(1 + LOOP_COUNT*STEP_RATE/TARGET_UPDATE_RATE, gd.CountUpdate);
}
/// <summary>
/// This test verifies that Update is called 1 + LOOP_COUNT * TestClock.MAX_ELAPSED (ms) / Game.TargetElapsedTime.Milliseconds
/// where STEP_RATE is greater than <see cref="TestClock.MAX_ELAPSED"/>, ensuring a maximum of MAX_ELAPSED / Game.TargetElapsedTime.Milliseconds
/// catch-up calls to Update are called per <see cref="Game.Tick"/>
/// </summary>
[Test]
public void UpdateLoopCatchupForFixedTimeStepGameWhereStepRateExceedsMAX_ELAPSEDTest()
{
const int LOOP_COUNT = 5;
const int STEP_RATE = 1000; // milliseconds per step
const int TARGET_UPDATE_RATE = 100; // update called every 100 ms
Assert.Greater((double)STEP_RATE, (double)TestClock.MAX_ELAPSED, "STEP_RATE should be greater than TestClock.MAX_ELAPSED for this test");
DelegateBasedEventSource evt = new DelegateBasedEventSource(delegate(DelegateBasedEventSource e)
{
int i = LOOP_COUNT;
while (i-- > 0)
{
TestClock.Instance.Step(STEP_RATE);
e.Game.Tick();
}
});
TestGame gd = new TestGame(evt, true);
gd.TargetElapsedTime = TimeSpan.FromMilliseconds(TARGET_UPDATE_RATE);
gd.Run();
Assert.AreEqual(1 + LOOP_COUNT*TestClock.MAX_ELAPSED/TARGET_UPDATE_RATE, gd.CountUpdate);
}
#endregion Public Methods Tests
#region Game Events
[Test]
public void GameRaisesExitingEventTest()
{
DelegateBasedEventSource evt = new DelegateBasedEventSource(delegate(DelegateBasedEventSource e)
{
((TestGameWindow)e.Game.Window).RaiseExiting();
});
Game gd = new TestGame(evt, true);
bool fired = false;
gd.Exiting += delegate { fired = true; };
gd.Run();
Assert.IsTrue(fired, "Exiting event was not raised.");
}
[Test]
public void GameRaisesOnActivatedEventTest()
{
DelegateBasedEventSource evt = new DelegateBasedEventSource(delegate(DelegateBasedEventSource e)
{
((TestGameWindow)e.Game.Window).RaiseActivating();
});
Game gd = new TestGame(evt, true);
bool fired = false;
gd.Activated += delegate { fired = true; };
gd.Run();
Assert.IsTrue(fired, "Activated event was not raised.");
}
[Test]
public void GameRaisesOnDeactivatedEventTest()
{
DelegateBasedEventSource evt = new DelegateBasedEventSource(delegate(DelegateBasedEventSource e) { ((TestGameWindow)e.Game.Window).RaiseDeactivating(); });
Game gd = new TestGame(evt, true);
bool fired = false;
gd.Deactivated += delegate { fired = true; };
gd.Run();
Assert.IsTrue(fired, "Deactivated event was not raised.");
}
/// <summary>
/// Verifies that the game loop (Tick) sleeps for the time specified by
/// <see cref="Game.InactiveSleepTime"/> if <see cref="Game.IsActive"/> = <c>false</c>
/// </summary>
[Test]
public void GameSleepsWhenDeactivatedTest()
{
DelegateBasedEventSource evt = new DelegateBasedEventSource(delegate(DelegateBasedEventSource e)
{
((TestGameWindow)e.Game.Window).RaiseDeactivating();
Assert.IsFalse(e.Game.IsActive, "Game should be inactive.");
e.Game.Tick();
});
TestGame gd = new TestGame(evt, true);
gd.InactiveSleepTime = TimeSpan.FromMilliseconds(500);
Stopwatch sw = Stopwatch.StartNew();
gd.Run();
sw.Stop();
Assert.IsTrue(sw.ElapsedMilliseconds >= 500, "Time elapsed should be at least 500ms");
}
#endregion Game Events
#region Verifies IGameComponent components are correctly initialized
/// <summary>
/// Verifies Update is called on game component where Enabled = true
/// </summary>
[Category("Game.IGameComponent")]
[Test]
public void InitializeCalledOnIGameComponentTest()
{
TestGame game = new TestGame(new NullEventSource());
GameComponentTestBase gc = new GameComponentTestBase(game);
game.Components.Add(gc);
game.Run();
Assert.AreEqual(1, gc.CountInitialize);
}
#endregion Verifies IGameComponent components are correctly initialized
#region Verfies IUpdatable components are correctly called
/// <summary>
/// Verifies Update is called on game component where Enabled = true
/// </summary>
[Category("Game.IUpdatable")]
[Test]
public void UpdateCalledOnEnabledIUpdatableGameComponent()
{
TestGame game = new TestGame(new NullEventSource());
GameComponentTestBase gc = new GameComponentTestBase(game);
game.Components.Add(gc);
game.Run();
Assert.AreEqual(1, gc.CountUpdate);
}
/// <summary>
/// Verifies Update is not called on game component where Enabled = false
/// </summary>
[Category("Game.IUpdatable")]
[Test]
public void UpdateNotCalledOnDisabledIUpdatableGameComponent()
{
TestGame game = new TestGame(new NullEventSource());
GameComponentTestBase gc = new GameComponentTestBase(game);
game.Components.Add(gc);
gc.Enabled = false;
game.Run();
Assert.AreEqual(0, gc.CountUpdate);
}
/// <summary>
/// Verifies Update is called on first iteration but not remaing iterations, where component is enabled for first iteration and disable for rest
/// </summary>
[Category("Game.IUpdatable")]
[Test]
public void UpdateCalledOnceForIUpdatableGameComponent()
{
DelegateBasedEventSource evt = new DelegateBasedEventSource(delegate(DelegateBasedEventSource e)
{
GameComponentTestBase u = (GameComponentTestBase)e.Game.Components[0];
u.Enabled = false;
for (int i = 0; i < 5; i++)
{
TestClock.Instance.Step(100);
e.Game.Tick();
}
});
TestGame game = new TestGame(evt);
GameComponentTestBase gc = new GameComponentTestBase(game);
game.Components.Add(gc);
game.Run();
Assert.AreEqual(1, gc.CountUpdate);
}
#endregion Verfies IUpdatable components are correctly called
#region Verfies IDrawable components are correctly called
/// <summary>
/// Verifies Draw is called, given IDrawable.Visible = true;
/// </summary>
[Category("Game.IDrawable")]
[Test]
public void DrawCalledOnVisibleIDrawableGameComponent()
{
DelegateBasedEventSource evt = new DelegateBasedEventSource(delegate(DelegateBasedEventSource e) { e.Game.Tick(); });
TestGame game = new TestGame(evt);
((TestGameWindow)game.Window).RaiseVisibleChanged(true);
DrawableGameComponentTestBase gc = new DrawableGameComponentTestBase(game);
game.Components.Add(gc);
game.Run();
Assert.AreEqual(1, gc.CountDraw);
}
/// <summary>
/// Verifies Draw is not called, given IDrawable.Visible = false
/// </summary>
[Category("Game.IDrawable")]
[Test]
public void DrawNotCalledOnNonVisibleIDrawableGameComponent()
{
DelegateBasedEventSource evt = new DelegateBasedEventSource(delegate(DelegateBasedEventSource e) { e.Game.Tick(); });
TestGame game = new TestGame(evt);
((TestGameWindow)game.Window).RaiseVisibleChanged(true);
DrawableGameComponentTestBase gc = new DrawableGameComponentTestBase(game);
game.Components.Add(gc);
gc.Visible = false;
game.Run();
Assert.AreEqual(0, gc.CountDraw);
}
/// <summary>
/// Verifies Draw is called only when IDrawable.Visible=true
/// </summary>
[Category("Game.IDrawable")]
[Test]
public void DrawCalledWhenIDrawableGameComponentIsVisibleTest()
{
DelegateBasedEventSource evt = new DelegateBasedEventSource(delegate(DelegateBasedEventSource e)
{
DrawableGameComponentTestBase u = (DrawableGameComponentTestBase)e.Game.Components[0];
for (int i = 1; i < 6; i++)
{
TestClock.Instance.Step(100);
e.Game.Tick();
u.Visible = i%2 == 0;
}
});
TestGame game = new TestGame(evt);
((TestGameWindow)game.Window).RaiseVisibleChanged(true);
DrawableGameComponentTestBase gc = new DrawableGameComponentTestBase(game);
game.Components.Add(gc);
game.Run();
Assert.AreEqual(3, gc.CountDraw, "Unexpected draw count");
Assert.AreEqual(6, gc.CountUpdate, "Unexpected update count");
}
#endregion Verfies IDrawable components are correctly called
}
}
#endif
| 43.276896 | 167 | 0.507091 | [
"MIT"
] | djkhz/monoxna | tests/Microsoft.Xna.Framework/GameTests.cs | 24,539 | 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 securityhub-2018-10-26.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.SecurityHub.Model
{
/// <summary>
/// Contains information about a version 2 stage for Amazon API Gateway.
/// </summary>
public partial class AwsApiGatewayV2StageDetails
{
private AwsApiGatewayAccessLogSettings _accessLogSettings;
private bool? _apiGatewayManaged;
private bool? _autoDeploy;
private string _clientCertificateId;
private string _createdDate;
private AwsApiGatewayV2RouteSettings _defaultRouteSettings;
private string _deploymentId;
private string _description;
private string _lastDeploymentStatusMessage;
private string _lastUpdatedDate;
private AwsApiGatewayV2RouteSettings _routeSettings;
private string _stageName;
private Dictionary<string, string> _stageVariables = new Dictionary<string, string>();
/// <summary>
/// Gets and sets the property AccessLogSettings.
/// <para>
/// Information about settings for logging access for the stage.
/// </para>
/// </summary>
public AwsApiGatewayAccessLogSettings AccessLogSettings
{
get { return this._accessLogSettings; }
set { this._accessLogSettings = value; }
}
// Check to see if AccessLogSettings property is set
internal bool IsSetAccessLogSettings()
{
return this._accessLogSettings != null;
}
/// <summary>
/// Gets and sets the property ApiGatewayManaged.
/// <para>
/// Indicates whether the stage is managed by API Gateway.
/// </para>
/// </summary>
public bool ApiGatewayManaged
{
get { return this._apiGatewayManaged.GetValueOrDefault(); }
set { this._apiGatewayManaged = value; }
}
// Check to see if ApiGatewayManaged property is set
internal bool IsSetApiGatewayManaged()
{
return this._apiGatewayManaged.HasValue;
}
/// <summary>
/// Gets and sets the property AutoDeploy.
/// <para>
/// Indicates whether updates to an API automatically trigger a new deployment.
/// </para>
/// </summary>
public bool AutoDeploy
{
get { return this._autoDeploy.GetValueOrDefault(); }
set { this._autoDeploy = value; }
}
// Check to see if AutoDeploy property is set
internal bool IsSetAutoDeploy()
{
return this._autoDeploy.HasValue;
}
/// <summary>
/// Gets and sets the property ClientCertificateId.
/// <para>
/// The identifier of a client certificate for a stage. Supported only for WebSocket API
/// calls.
/// </para>
/// </summary>
public string ClientCertificateId
{
get { return this._clientCertificateId; }
set { this._clientCertificateId = value; }
}
// Check to see if ClientCertificateId property is set
internal bool IsSetClientCertificateId()
{
return this._clientCertificateId != null;
}
/// <summary>
/// Gets and sets the property CreatedDate.
/// <para>
/// Indicates when the stage was created.
/// </para>
///
/// <para>
/// Uses the <code>date-time</code> format specified in <a href="https://tools.ietf.org/html/rfc3339#section-5.6">RFC
/// 3339 section 5.6, Internet Date/Time Format</a>. The value cannot contain spaces.
/// For example, <code>2020-03-22T13:22:13.933Z</code>.
/// </para>
/// </summary>
public string CreatedDate
{
get { return this._createdDate; }
set { this._createdDate = value; }
}
// Check to see if CreatedDate property is set
internal bool IsSetCreatedDate()
{
return this._createdDate != null;
}
/// <summary>
/// Gets and sets the property DefaultRouteSettings.
/// <para>
/// Default route settings for the stage.
/// </para>
/// </summary>
public AwsApiGatewayV2RouteSettings DefaultRouteSettings
{
get { return this._defaultRouteSettings; }
set { this._defaultRouteSettings = value; }
}
// Check to see if DefaultRouteSettings property is set
internal bool IsSetDefaultRouteSettings()
{
return this._defaultRouteSettings != null;
}
/// <summary>
/// Gets and sets the property DeploymentId.
/// <para>
/// The identifier of the deployment that the stage is associated with.
/// </para>
/// </summary>
public string DeploymentId
{
get { return this._deploymentId; }
set { this._deploymentId = value; }
}
// Check to see if DeploymentId property is set
internal bool IsSetDeploymentId()
{
return this._deploymentId != null;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// The description of the stage.
/// </para>
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property LastDeploymentStatusMessage.
/// <para>
/// The status of the last deployment of a stage. Supported only if the stage has automatic
/// deployment enabled.
/// </para>
/// </summary>
public string LastDeploymentStatusMessage
{
get { return this._lastDeploymentStatusMessage; }
set { this._lastDeploymentStatusMessage = value; }
}
// Check to see if LastDeploymentStatusMessage property is set
internal bool IsSetLastDeploymentStatusMessage()
{
return this._lastDeploymentStatusMessage != null;
}
/// <summary>
/// Gets and sets the property LastUpdatedDate.
/// <para>
/// Indicates when the stage was most recently updated.
/// </para>
///
/// <para>
/// Uses the <code>date-time</code> format specified in <a href="https://tools.ietf.org/html/rfc3339#section-5.6">RFC
/// 3339 section 5.6, Internet Date/Time Format</a>. The value cannot contain spaces.
/// For example, <code>2020-03-22T13:22:13.933Z</code>.
/// </para>
/// </summary>
public string LastUpdatedDate
{
get { return this._lastUpdatedDate; }
set { this._lastUpdatedDate = value; }
}
// Check to see if LastUpdatedDate property is set
internal bool IsSetLastUpdatedDate()
{
return this._lastUpdatedDate != null;
}
/// <summary>
/// Gets and sets the property RouteSettings.
/// <para>
/// The route settings for the stage.
/// </para>
/// </summary>
public AwsApiGatewayV2RouteSettings RouteSettings
{
get { return this._routeSettings; }
set { this._routeSettings = value; }
}
// Check to see if RouteSettings property is set
internal bool IsSetRouteSettings()
{
return this._routeSettings != null;
}
/// <summary>
/// Gets and sets the property StageName.
/// <para>
/// The name of the stage.
/// </para>
/// </summary>
public string StageName
{
get { return this._stageName; }
set { this._stageName = value; }
}
// Check to see if StageName property is set
internal bool IsSetStageName()
{
return this._stageName != null;
}
/// <summary>
/// Gets and sets the property StageVariables.
/// <para>
/// A map that defines the stage variables for the stage.
/// </para>
///
/// <para>
/// Variable names can have alphanumeric and underscore characters.
/// </para>
///
/// <para>
/// Variable values can contain the following characters:
/// </para>
/// <ul> <li>
/// <para>
/// Uppercase and lowercase letters
/// </para>
/// </li> <li>
/// <para>
/// Numbers
/// </para>
/// </li> <li>
/// <para>
/// Special characters -._~:/?#&=,
/// </para>
/// </li> </ul>
/// </summary>
public Dictionary<string, string> StageVariables
{
get { return this._stageVariables; }
set { this._stageVariables = value; }
}
// Check to see if StageVariables property is set
internal bool IsSetStageVariables()
{
return this._stageVariables != null && this._stageVariables.Count > 0;
}
}
} | 32.084375 | 125 | 0.566378 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/SecurityHub/Generated/Model/AwsApiGatewayV2StageDetails.cs | 10,267 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace FedagoApp.Managers
{
public class TunnelManager : IDisposable
{
private const string ngrokUrl = "http://localhost:4040/api/tunnels";
//private static SynchronizationContext _syncContext;
private bool _ready = false;
private string _ngrokAuthToken;
private Process _ngrokProcess;
public TunnelManager()
{
}
public void CreateTunnel(string ngrokAuthToken = null)
{
_ready = false;
_ngrokAuthToken = ngrokAuthToken;
ThreadStart threadStart = new ThreadStart(RunNgrok);
Thread commandThread = new Thread(threadStart);
commandThread.IsBackground = true;
commandThread.Start();
}
private void RunNgrok()
{
string currentDirectory = Directory.GetCurrentDirectory();
string ngrokFile = string.Format(@"{0}\{1}\{2}", currentDirectory, @"Assets\ngrok\",
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"Win64\ngrok.exe" :
RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? @"Mac64\ngrok" : null);
string configFile = string.Format(@"{0}\{1}", currentDirectory, @"Assets\ngrok\fedago.yml");
var authProcess = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = ngrokFile,
Arguments = string.Format("authtoken \"{0}\" -config=\"" + configFile + "\"", string.IsNullOrEmpty(_ngrokAuthToken) ? string.Empty : _ngrokAuthToken),
//RedirectStandardOutput = true,
//RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
}
};
authProcess.Start();
authProcess.WaitForExit();
if (_ngrokProcess != null)
{
_ngrokProcess.Kill();
}
_ngrokProcess = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = ngrokFile,
Arguments = "http 49424 -host-header=\"localhost:49424\" -config=\"" + configFile + "\"",
//RedirectStandardOutput = true,
//RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
}
};
//process.EnableRaisingEvents = true;
//process.OutputDataReceived += (sender, args) => Display(args.Data);
//process.ErrorDataReceived += (sender, args) => Display(args.Data);
_ngrokProcess.Start();
//process.BeginOutputReadLine();
//process.BeginErrorReadLine();
_ngrokProcess.WaitForExit();
}
public string PublicUrl
{
get
{
string publicUrl;
try
{
HttpClient httpClient = new HttpClient();
Task<string> response = httpClient.GetStringAsync(ngrokUrl);
response.Wait();
string ngrokSite = response.Result;
//Regex regex = new Regex("<PublicURL>(.*)</PublicURL>");
//Match match = regex.Match(ngrokSite);
//string publicUrl = match.Value;
dynamic deserializedObject = JsonConvert.DeserializeObject(ngrokSite);
publicUrl = deserializedObject.tunnels[0].public_url.ToString(); //get https
if (!publicUrl.ToLower().StartsWith("https"))
{
publicUrl = publicUrl.ToLower().Replace("http", "https");
}
}
catch(Exception ex)
{
publicUrl = string.Empty;
}
return publicUrl;
}
}
public bool IsReady
{
get
{
if (!_ready)
{
lock(this)
{
if (!_ready)
{
_ready = Uri.IsWellFormedUriString(PublicUrl, UriKind.RelativeOrAbsolute);
}
}
}
return _ready;
}
}
//private static void Display(string output)
//{
// _syncContext.Post(lmb => Debug.WriteLine(output), null);
//}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects).
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~TunnelManager() {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
}
}
| 34.909091 | 170 | 0.513346 | [
"MIT"
] | Radovici/Fedago | FedagoClient/Managers/TunnelManager.cs | 6,146 | C# |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
namespace NPOI.OpenXmlFormats.Dml.Diagram
{
[Serializable]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/diagram")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/diagram", IsNullable = true)]
[DebuggerStepThrough]
public class CT_ChildMax
{
private int valField;
[DefaultValue(-1)]
[XmlAttribute]
public int val
{
get
{
return valField;
}
set
{
valField = value;
}
}
public CT_ChildMax()
{
valField = -1;
}
}
}
| 17.486486 | 101 | 0.697063 | [
"MIT"
] | iNeverSleeeeep/NPOI-For-Unity | NPOI.OpenXmlFormats.Dml.Diagram/CT_ChildMax.cs | 647 | C# |
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Gov.Jag.PillPressRegistry.Public.Models
{
/// <summary>
/// Role Database Model
/// </summary>
public sealed partial class VoteOption : IEquatable<VoteOption>
{
/// <summary>
/// Initializes a new instance of the <see cref="Role" /> class.
/// </summary>
/// <param name="id">A system-generated unique identifier for a Role (required).</param>
/// <param name="name">The name of the Role, as established by the user creating the role. (required).</param>
/// <param name="description">A description of the role as set by the user creating&#x2F;updating the role. (required).</param>
/// <param name="rolePermissions">RolePermissions.</param>
/// <param name="userRoles">UserRoles.</param>
public VoteOption(Guid id, string question, int totalVotes, int displayOrder)
{
Id = id;
Option = question;
TotalVotes = totalVotes;
DisplayOrder = displayOrder;
}
public VoteOption()
{
}
/// <summary>
/// A system-generated unique identifier for a Role
/// </summary>
/// <value>A system-generated unique identifier for a Role</value>
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
/// <summary>
/// The name of the Role, as established by the user creating the role.
/// </summary>
/// <value>The name of the Role, as established by the user creating the role.</value>
[MaxLength(512)]
public string Option { get; set; }
public int TotalVotes { get; set; }
public int DisplayOrder { 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 VoteOption {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Option: ").Append(Option).Append("\n");
sb.Append(" TotalVotes: ").Append(TotalVotes).Append("\n");
sb.Append(" DisplayOrder: ").Append(DisplayOrder).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, 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)
{
if (obj is null) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
return obj.GetType() == GetType() && Equals((VoteOption)obj);
}
/// <summary>
/// Returns true if Role instances are equal
/// </summary>
/// <param name="other">Instance of Role to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(VoteOption other)
{
if (other is null) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
Id == other.Id ||
Id.Equals(other.Id)
) &&
(
Option == other.Option ||
Option != null &&
Option.Equals(other.Option)
) &&
(
TotalVotes == other.TotalVotes ||
TotalVotes.Equals(other.TotalVotes)
) &&
(
DisplayOrder == other.DisplayOrder ||
DisplayOrder.Equals(other.DisplayOrder)
);
}
/// <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
hash = hash * 59 + Id.GetHashCode();
if (Option != null)
{
hash = hash * 59 + Option.GetHashCode();
}
// TotalVotes is never null
hash = hash * 59 + TotalVotes.GetHashCode();
// DisplayOrder is never null, so no null check.
hash = hash * 59 + DisplayOrder.GetHashCode();
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(VoteOption left, VoteOption right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(VoteOption left, VoteOption right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| 33 | 139 | 0.505713 | [
"Apache-2.0"
] | GeorgeWalker/jag-pill-press-registry | pill-press-app/Models/VoteOption.cs | 6,039 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Momentum.cs" company="Hukano">
// Copyright (c) Hukano. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Sundew.Quantities
{
using Sundew.Quantities.Core;
/// <summary>
/// Represents a momentum quantity.
/// </summary>
public partial struct Momentum
{
/// <summary>
/// Multiplies the specified LHS and RHS.
/// </summary>
/// <param name="lhs">The LHS.</param>
/// <param name="rhs">The RHS.</param>
/// <returns>
/// The result of the operator.
/// </returns>
public static Squared<Momentum> operator *(Momentum lhs, Momentum rhs)
{
return new Squared<Momentum>(new Momentum(QuantityOperations.Multiply(lhs, rhs).Value, lhs.Unit));
}
}
} | 37.7 | 120 | 0.477454 | [
"MIT"
] | cdrnet/Sundew.Quantities | Source/Sundew.Quantities/Momentum.cs | 1,133 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Bet.Extensions.Resilience.Abstractions.Executor
{
/// <summary>
/// <para>
/// The policy async executor for wrapped Polly policies.</para>
/// <para>
/// Polly doesn't support async void methods. So you can't pass an Action.
/// http://www.thepollyproject.org/2017/06/09/polly-and-synchronous-versus-asynchronous-policies/
/// Returns a Task in order to avoid execution of void methods asynchronously, which causes unexpected out-of-sequence execution of policy hooks and continuing policy actions, and a risk of unobserved exceptions.
/// https://msdn.microsoft.com/en-us/magazine/jj991977.aspx
/// https://github.com/App-vNext/Polly/issues/107#issuecomment-218835218.
/// </para>
/// </summary>
public interface IPolicyAsyncExecutor
{
/// <summary>
/// Executes Async function delegate with specified Polly policies.
/// </summary>
/// <typeparam name="T">The type of the task to be executed.</typeparam>
/// <param name="action">The function to be executed.</param>
/// <returns>task of type.</returns>
Task<T> ExecuteAsync<T>(Func<Task<T>> action);
/// <summary>
/// Executes Async the function delegate with specified Polly policies.
/// </summary>
/// <param name="action">The function to be executed.</param>
/// <returns>task.</returns>
Task ExecuteAsync(Func<Task> action);
/// <summary>
/// Executes Async the function delegate with cancellation token.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="action"></param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns></returns>
Task<T> ExecuteAsync<T>(Func<CancellationToken, Task<T>> action, CancellationToken cancellationToken);
}
}
| 43.444444 | 216 | 0.649105 | [
"MIT"
] | kdcllc/Bet.Extensions.Resilience | src/Bet.Extensions.Resilience.Abstractions/Executor/IPolicyAsyncExecutor.cs | 1,957 | C# |
using System;
namespace enki.common.core.WebUtils
{
[Obsolete("Use Tuple<> instead, this will be serializable.")]
public class KeyValueSerializable
{
public string key { get; set; }
public object value { get; set; }
public KeyValueSerializable() { }
public KeyValueSerializable(string key, string value)
{
this.key = key;
this.value = value;
}
}
}
| 23.105263 | 65 | 0.587699 | [
"MIT"
] | encontact/Enki.Common | src/enki.common.core/WebUtils/KeyValueSerializable.cs | 441 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Controls.WpfPropertyGrid.Attributes;
using Hawk.Core.Utils;
using Hawk.Core.Utils.Plugins;
using EncodingType = Hawk.Core.Utils.EncodingType;
namespace Hawk.Core.Connectors
{
[XFrmWork("文本导入导出器", "输出制表符文本文件", "对基本文本文件进行导入和导出的工具")]
public class FileConnectorTable : FileConnector
{
#region Properties
private FileStream fileStream;
private StreamWriter streamWriter;
public FileConnectorTable()
{
EncodingType = EncodingType.UTF8;
SplitString = "\t";
ContainHeader = true;
}
public override FreeDocument DictSerialize(Scenario scenario = Scenario.Database)
{
var dict = base.DictSerialize(scenario);
dict.Add("ContainHeader", ContainHeader);
dict.Add("SplitString", SplitString);
return dict;
}
public override void DictDeserialize(IDictionary<string, object> docu, Scenario scenario = Scenario.Database)
{
base.DictDeserialize(docu, scenario);
ContainHeader = docu.Set("ContainHeader", ContainHeader);
SplitString = docu.Set("SplitString", SplitString);
}
[LocalizedDisplayName("列分割符")]
public string SplitString { get; set; }
[LocalizedDisplayName("包含头信息")]
public bool ContainHeader { get; set; }
protected virtual string SplitChar => SplitString;
public override string ExtentFileName => ".txt";
public static string ReplaceSplitString(string input, string splitchar)
{
if (input == null)
return "";
input = input.Replace("\"", "\"\"");
input = input.Replace("\n", "\\n");
if (input.Contains(splitchar))
{
input = "\"" + input + "\"";
}
return input;
}
public static string ReplaceSplitString2(string input, string splitchar)
{
if (input == null)
return "";
input = input.Replace("\"\"", "\"");
return input.Trim('"');
}
public void Save()
{
streamWriter.Close();
streamWriter.Close();
}
public void Start(ICollection<string> titles)
{
fileStream = new FileStream(FileName, FileMode.OpenOrCreate);
streamWriter = new StreamWriter(new BufferedStream(fileStream), AttributeHelper.GetEncoding(EncodingType));
//var title = titles.Aggregate("", (current, title1) => current + (title1 + SplitChar));
var title = SplitChar.Join(titles.Select(d => ReplaceSplitString(d, SplitChar))) + "\n";
//title = title.Substring(0, title.Length - 1) + "\n";
streamWriter.Write(title);
}
public void WriteData(IEnumerable<object[]> datas)
{
foreach (var rows in datas)
{
WriteData(rows);
}
}
/// <summary>
/// 导出到CSV文件
/// </summary>
/// <param name="titles">文件标题</param>
/// <param name="datas">数据</param>
/// <param name="fileName">要保存的文件名</param>
public static void DataTableToCSV(ICollection<string> titles, IEnumerable<object[]> datas, string fileName,
char split = ',', Encoding encoding = null)
{
if (encoding == null)
encoding = Encoding.UTF8;
var fs = new FileStream(fileName, FileMode.OpenOrCreate);
var sw = new StreamWriter(new BufferedStream(fs), encoding);
var title = titles.Aggregate("", (current, title1) => current + (title1 + split));
title = title.Substring(0, title.Length - 1) + "\n";
sw.Write(title);
foreach (var rows in datas)
{
var line = new StringBuilder();
foreach (var row in rows)
{
if (row != null)
{
line.Append(row.ToString().Trim());
}
else
{
line.Append(" ");
}
line.Append(split);
}
var result = line.ToString().Substring(0, line.Length - 1) + "\n";
sw.Write(result);
}
sw.Close();
fs.Close();
}
public void WriteData(object[] datas)
{
var line = SplitChar.Join(datas.Select(d => ReplaceSplitString(d?.ToString(), SplitChar))) + "\n";
streamWriter.Write(line);
}
//这段代码像屎一样又臭又长
//English Edition: This code like shit.
//不要怪我,我就是懒
public override IEnumerable<FreeDocument> ReadFile(Action<int> alreadyGetSize = null)
{
var titles = new List<string>();
var intColCount = 0;
var blnFlag = true;
var builder = new StringBuilder();
foreach (var strline in FileEx.LineRead(FileName, AttributeHelper.GetEncoding(EncodingType)))
{
if (string.IsNullOrWhiteSpace(strline))
continue;
builder.Clear();
var comma = false;
var array = strline.ToCharArray();
var values = new List<string>();
var length = array.Length;
var index = 0;
while (index < length)
{
var item = array[index++];
if (item.ToString() == SplitChar)
if (comma)
{
builder.Append(item);
}
else
{
values.Add(builder.ToString());
builder.Clear();
}
else if (item == '"')
{
comma = !comma;
}
else
{
builder.Append(item);
}
}
if (builder.Length > 0)
values.Add(builder.ToString());
var count = values.Count;
if (count == 0) continue;
//给datatable加上列名
if (blnFlag)
{
blnFlag = false;
intColCount = values.Count;
if (ContainHeader)
{
titles.AddRange(values);
continue;
}
for (var i = 0; i < intColCount; i++)
{
titles.Add("属性" + i);
}
}
var data = new FreeDocument();
var dict = new Dictionary<string, object>();
for (index = 0; index < Math.Min(titles.Count, values.Count); index++)
{
if (index == 0 && PropertyNames.Any() == false)
{
PropertyNames = titles.ToDictionary(d => d, d => d);
}
var title = titles[index];
var key = PropertyNames.FirstOrDefault(d => d.Value == title).Key;
if (key != null)
{
dict.Add(key, values[index]);
}
}
data.DictDeserialize(dict);
yield return data;
}
}
public override bool ShouldConfig => true;
public override IEnumerable<IFreeDocument> WriteData(IEnumerable<IFreeDocument> datas)
{
if (datas.Any() == false) yield break;
using (var dis = new DisposeHelper(Save))
{
if (PropertyNames == null || PropertyNames.Count == 0)
{
PropertyNames = datas.GetKeys().ToDictionary(d => d, d => d);
}
Start(PropertyNames.Values);
var i = 0;
foreach (var computeable in datas)
{
IDictionary<string, object> data = computeable.DictSerialize(Scenario.Report);
var objects = PropertyNames.Select(name => data[name.Key]).ToArray();
WriteData(objects);
i++;
yield return computeable;
}
}
}
#endregion
}
} | 33.307692 | 120 | 0.452986 | [
"Apache-2.0"
] | az0day/Hawk | Hawk.Core/Connectors/FileConnectorTable.cs | 9,271 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TwilioWithThinq;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
TwilioWrapper wrapper = new TwilioWrapper("ACa5a21802beff96f147d40bf98c957038", "7852c807435af28d468344ca57a49d2a", "11001", "0c82a54f22f775a3ed8b97b2dea74036");
Console.WriteLine("Call sid: " + wrapper.call("19193365890", "19192334784"));
Console.ReadLine();
}
}
}
| 28.25 | 174 | 0.661947 | [
"MIT"
] | harouf/twilio-thinQLCR-dotnet | Demo/Program.cs | 567 | C# |
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Mvc;
using GenericPayment.Database;
using GenericPayment.Models;
using Newtonsoft.Json;
namespace GenericPayment.Controllers
{
public class CashController : Controller
{
public async Task<ActionResult> Agreement(string paykey)
{
var marketplaceUrl = "http://localhost";
if (Request.UrlReferrer != null)
{
marketplaceUrl = Request.UrlReferrer.ToString();
}
var uri = new Uri(marketplaceUrl);
marketplaceUrl = uri.Scheme + Uri.SchemeDelimiter + uri.Authority;
var db = new DbContext();
try
{
var details = db.GetDetails(paykey);
if (details != null)
{
// Update details for the valid record
PaymentDetails vm = new PaymentDetails();
vm.CashKey = details.PayKey;
vm.Currency = details.Currency;
decimal total;
if (!decimal.TryParse(details.Total, out total))
{
total = 0m;
}
vm.Total = total;
vm.Note = "";
// Call Arcadier api to get the details
using (var httpClient = new HttpClient())
{
var url = marketplaceUrl + "/user/checkout/order-details" + "?gateway=" + details.Gateway + "&invoiceNo=" + details.InvoiceNo + "&paykey=" + paykey + "&hashkey=" + details.Hashkey;
HttpResponseMessage tokenResponse = await httpClient.GetAsync(url);
tokenResponse.EnsureSuccessStatusCode();
string text = await tokenResponse.Content.ReadAsStringAsync();
GenericPayments response = JsonConvert.DeserializeObject<GenericPayments>(text);
details.PayeeInfos = response.PayeeInfos;
details.MarketplaceUrl = marketplaceUrl;
db.SetDetails(paykey, details);
}
return View("Index", vm);
}
}
catch (Exception ex)
{
ViewBag.ErrorMessage = ex.Message;
}
return View("Error");
}
public JsonResult AgreeToPay(AgreementViewModel vm)
{
// Build the success url and redirect back to Arcadier
var url = DbContext.SuccessUrl(vm.CashKey, vm.Note);
return Json(new { result = url }, JsonRequestBehavior.AllowGet);
}
public JsonResult CancelToPay(AgreementViewModel vm)
{
// Build the failure url and redirect back to Arcadier
var url = DbContext.CancelUrl(vm.CashKey);
return Json(new { result = url }, JsonRequestBehavior.AllowGet);
}
}
}
| 38.405063 | 204 | 0.526697 | [
"Unlicense"
] | iOS-Arcadier/Sample-Generic-Payments | GenericPayment/Controllers/CashController.cs | 3,036 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.17929
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WpfTextBoxMasked.Properties
{
/// <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 ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WpfTextBoxMasked.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;
}
}
}
}
| 38.736111 | 182 | 0.604518 | [
"Apache-2.0"
] | rikkimongoose/wpf-textboxmasked | WpfTextBoxMasked/Properties/Resources.Designer.cs | 2,791 | 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 BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Extensions;
using MicroBenchmarks;
using System.Collections.Generic;
namespace System.Collections
{
// the concurrent collections are covered with benchmarks in Add_Remove_SteadyState.cs
[BenchmarkCategory(Categories.CoreFX, Categories.Collections, Categories.GenericCollections)]
[GenericTypeArguments(typeof(int))] // value type
[GenericTypeArguments(typeof(string))] // reference type
public class CreateAddAndRemove<T>
{
[Params(Utils.DefaultCollectionSize)]
public int Size;
private T[] _keys;
[GlobalSetup]
public void Setup() => _keys = ValuesGenerator.ArrayOfUniqueValues<T>(Size);
[Benchmark]
public List<T> List()
{
List<T> list = new List<T>();
foreach (T uniqueKey in _keys)
{
list.Add(uniqueKey);
}
foreach (T uniqueKey in _keys)
{
list.Remove(uniqueKey);
}
return list;
}
[Benchmark]
public LinkedList<T> LinkedList()
{
LinkedList<T> linkedList = new LinkedList<T>();
foreach (T item in _keys)
{
linkedList.AddLast(item);
}
foreach (T item in _keys)
{
linkedList.Remove(item);
}
return linkedList;
}
[Benchmark]
public HashSet<T> HashSet()
{
HashSet<T> hashSet = new HashSet<T>();
foreach (T uniqueKey in _keys)
{
hashSet.Add(uniqueKey);
}
foreach (T uniqueKey in _keys)
{
hashSet.Remove(uniqueKey);
}
return hashSet;
}
[Benchmark]
public Dictionary<T, T> Dictionary()
{
Dictionary<T, T> dictionary = new Dictionary<T, T>();
foreach (T uniqueKey in _keys)
{
dictionary.Add(uniqueKey, uniqueKey);
}
foreach (T uniqueKey in _keys)
{
dictionary.Remove(uniqueKey);
}
return dictionary;
}
[Benchmark]
public SortedList<T, T> SortedList()
{
SortedList<T, T> sortedList = new SortedList<T, T>();
foreach (T uniqueKey in _keys)
{
sortedList.Add(uniqueKey, uniqueKey);
}
foreach (T uniqueKey in _keys)
{
sortedList.Remove(uniqueKey);
}
return sortedList;
}
[Benchmark]
public SortedSet<T> SortedSet()
{
SortedSet<T> sortedSet = new SortedSet<T>();
foreach (T uniqueKey in _keys)
{
sortedSet.Add(uniqueKey);
}
foreach (T uniqueKey in _keys)
{
sortedSet.Remove(uniqueKey);
}
return sortedSet;
}
[Benchmark]
public SortedDictionary<T, T> SortedDictionary()
{
SortedDictionary<T, T> sortedDictionary = new SortedDictionary<T, T>();
foreach (T uniqueKey in _keys)
{
sortedDictionary.Add(uniqueKey, uniqueKey);
}
foreach (T uniqueKey in _keys)
{
sortedDictionary.Remove(uniqueKey);
}
return sortedDictionary;
}
[Benchmark]
public Stack<T> Stack()
{
Stack<T> stack = new Stack<T>();
foreach (T uniqueKey in _keys)
{
stack.Push(uniqueKey);
}
foreach (T uniqueKey in _keys)
{
stack.Pop();
}
return stack;
}
[Benchmark]
public Queue<T> Queue()
{
Queue<T> queue = new Queue<T>();
foreach (T uniqueKey in _keys)
{
queue.Enqueue(uniqueKey);
}
foreach (T uniqueKey in _keys)
{
queue.Dequeue();
}
return queue;
}
}
} | 27.869565 | 97 | 0.49454 | [
"MIT"
] | GrabYourPitchforks/performance | src/benchmarks/micro/corefx/System.Collections/CreateAddAndRemove.cs | 4,489 | C# |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public class PinchRecognizer : AbstractRecognizer
{
public event Action<PinchRecognizer> gestureBeginEvent;
public event Action<PinchRecognizer> gestureRecognizedEvent;
public event Action<PinchRecognizer> gestureEndEvent;
public float startDistance;
public float distance;
public float deltaDistance;
private float minMoveDistance;
public PinchRecognizer(float minPanDistance = 0.5f)
{
minMoveDistance = minPanDistance;
}
#region event
internal void emitBeginEvent()
{
if (gestureBeginEvent != null)
gestureBeginEvent(this);
}
internal void emitRecognizedEvent()
{
if (gestureRecognizedEvent != null)
gestureRecognizedEvent(this);
}
internal void emitEndEvent()
{
if (gestureEndEvent != null)
gestureEndEvent(this);
}
#endregion
internal override bool canTrigger(List<TSTouch> touches)
{
if (touches.Count == 2)
{
bool result = true;
for (int i = 0; i < 2; i++)
{
TSTouch touch = touches[i];
if (touch.phase != TouchPhase.Ended && touch.deltaPosition.magnitude > minMoveDistance)
{
}
else
{
result = false;
}
}
if (result)
return isOpposite(touches);
}
return false;
}
internal override void touchesBegan(List<TSTouch> touches)
{
if (touches.Count != 2)
{
gestureEnd();
}
}
internal override void touchesMoved(List<TSTouch> touches)
{
if (touches.Count == 2)
{
// if (!isOpposite(touches))
// {
// gestureEnd();
// }
if (state == RecognizerState.Possible)
{
state = RecognizerState.Began;
for (int i = 0; i < 2; i++)
{
TSTouch touch = touches[i];
tracingTouches.Add(touch);
}
TSTouch touch0 = tracingTouches[0];
TSTouch touch1 = tracingTouches[1];
startDistance = vector2Distance(touch0, touch1);
distance = startDistance;
deltaDistance = 0;
emitBeginEvent();
}
else if (state == RecognizerState.Began)
{
state = RecognizerState.Recognized;
gestureRecognized();
}
else if (state == RecognizerState.Recognized)
{
gestureRecognized();
}
}
}
internal override void touchesEnded(List<TSTouch> touches)
{
gestureEnd();
}
private void gestureRecognized()
{
TSTouch touch0 = tracingTouches[0];
TSTouch touch1 = tracingTouches[1];
float currentDistance = vector2Distance(touch0, touch1);
deltaDistance = currentDistance - distance;
distance = currentDistance;
emitRecognizedEvent();
}
private void gestureEnd()
{
if (state == RecognizerState.Recognized || state == RecognizerState.Began)
{
state = RecognizerState.Ended;
TSTouch touch0 = tracingTouches[0];
TSTouch touch1 = tracingTouches[1];
float currentDistance = vector2Distance(touch0, touch1);
deltaDistance = currentDistance - distance;
distance = currentDistance;
emitEndEvent();
end();
reset();
}
}
public override string ToString()
{
return string.Format("[{0}] state: {1}, deltaDistance: {2}", this.GetType(), state, deltaDistance);
}
#region Fuction
private bool isOpposite(List<TSTouch> touches)
{
if (touches.Count != 2)
return false;
Vector2 delta0 = touches[0].position - touches[0].startPosition;
Vector2 delta1 = touches[1].position - touches[1].startPosition;
bool x0 = delta0.x > 0;
bool y0 = delta0.y > 0;
bool x1 = delta1.x > 0;
bool y1 = delta1.y > 0;
return x0 ^ x1 && y0 ^ y1;
}
private float vector2Distance(TSTouch t1, TSTouch t2)
{
return Vector2.Distance(t1.position, t2.position);
}
#endregion
}
| 24 | 107 | 0.538816 | [
"MIT"
] | VivekSingal98/financeSimulationGame | Assets/Plugins/TouchSystem/Recognizer/PinchRecognizer.cs | 4,560 | C# |
// 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.
//
// Copyright (c) 2007 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Chris Toshok (toshok@ximian.com)
//
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Markup;
using System.Windows.Media.Converters;
using System.Windows.Threading;
namespace System.Windows.Media {
[Serializable]
[TypeConverter (typeof(MatrixConverter))]
[ValueSerializer (typeof (MatrixValueSerializer))]
public struct Matrix : IFormattable {
double _m11;
double _m12;
double _m21;
double _m22;
double _offsetX;
double _offsetY;
public Matrix (double m11,
double m12,
double m21,
double m22,
double offsetX,
double offsetY)
{
this._m11 = m11;
this._m12 = m12;
this._m21 = m21;
this._m22 = m22;
this._offsetX = offsetX;
this._offsetY = offsetY;
}
public void Append (Matrix matrix)
{
double _m11;
double _m21;
double _m12;
double _m22;
double _offsetX;
double _offsetY;
_m11 = this._m11 * matrix.M11 + this._m12 * matrix.M21;
_m12 = this._m11 * matrix.M12 + this._m12 * matrix.M22;
_m21 = this._m21 * matrix.M11 + this._m22 * matrix.M21;
_m22 = this._m21 * matrix.M12 + this._m22 * matrix.M22;
_offsetX = this._offsetX * matrix.M11 + this._offsetY * matrix.M21 + matrix.OffsetX;
_offsetY = this._offsetX * matrix.M12 + this._offsetY * matrix.M22 + matrix.OffsetY;
this._m11 = _m11;
this._m12 = _m12;
this._m21 = _m21;
this._m22 = _m22;
this._offsetX = _offsetX;
this._offsetY = _offsetY;
}
public bool Equals (Matrix value)
{
return (_m11 == value.M11 &&
_m12 == value.M12 &&
_m21 == value.M21 &&
_m22 == value.M22 &&
_offsetX == value.OffsetX &&
_offsetY == value.OffsetY);
}
public override bool Equals (object o)
{
if (!(o is Matrix))
return false;
return Equals ((Matrix)o);
}
public static bool Equals (Matrix matrix1,
Matrix matrix2)
{
return matrix1.Equals (matrix2);
}
public override int GetHashCode ()
{
unchecked
{
var hashCode = _m11.GetHashCode ();
hashCode = (hashCode * 397) ^ _m12.GetHashCode ();
hashCode = (hashCode * 397) ^ _m21.GetHashCode ();
hashCode = (hashCode * 397) ^ _m22.GetHashCode ();
hashCode = (hashCode * 397) ^ _offsetX.GetHashCode ();
hashCode = (hashCode * 397) ^ _offsetY.GetHashCode ();
return hashCode;
}
}
public void Invert ()
{
if (!HasInverse)
throw new InvalidOperationException ("Transform is not invertible.");
double d = Determinant;
/* 1/(ad-bc)[d -b; -c a] */
double _m11 = this._m22;
double _m12 = -this._m12;
double _m21 = -this._m21;
double _m22 = this._m11;
double _offsetX = this._m21 * this._offsetY - this._m22 * this._offsetX;
double _offsetY = this._m12 * this._offsetX - this._m11 * this._offsetY;
this._m11 = _m11 / d;
this._m12 = _m12 / d;
this._m21 = _m21 / d;
this._m22 = _m22 / d;
this._offsetX = _offsetX / d;
this._offsetY = _offsetY / d;
}
public static Matrix Multiply (Matrix trans1,
Matrix trans2)
{
Matrix m = trans1;
m.Append (trans2);
return m;
}
public static bool operator == (Matrix matrix1,
Matrix matrix2)
{
return matrix1.Equals (matrix2);
}
public static bool operator != (Matrix matrix1,
Matrix matrix2)
{
return !matrix1.Equals (matrix2);
}
public static Matrix operator * (Matrix trans1,
Matrix trans2)
{
Matrix result = trans1;
result.Append (trans2);
return result;
}
public static Matrix Parse (string source)
{
if (source == null)
throw new ArgumentNullException ("source");
Matrix value;
if (source.Trim () == "Identity")
{
value = Identity;
}
else
{
var tokenizer = new NumericListTokenizer (source, CultureInfo.InvariantCulture);
double m11;
double m12;
double m21;
double m22;
double offsetX;
double offsetY;
if (double.TryParse (tokenizer.GetNextToken (), NumberStyles.Float, CultureInfo.InvariantCulture, out m11)
&& double.TryParse (tokenizer.GetNextToken (), NumberStyles.Float, CultureInfo.InvariantCulture, out m12)
&& double.TryParse (tokenizer.GetNextToken (), NumberStyles.Float, CultureInfo.InvariantCulture, out m21)
&& double.TryParse (tokenizer.GetNextToken (), NumberStyles.Float, CultureInfo.InvariantCulture, out m22)
&& double.TryParse (tokenizer.GetNextToken (), NumberStyles.Float, CultureInfo.InvariantCulture, out offsetX)
&& double.TryParse (tokenizer.GetNextToken (), NumberStyles.Float, CultureInfo.InvariantCulture, out offsetY))
{
if (!tokenizer.HasNoMoreTokens ())
{
throw new InvalidOperationException ("Invalid Matrix format: " + source);
}
value = new Matrix (m11, m12, m21, m22, offsetX, offsetY);
}
else
{
throw new FormatException (string.Format ("Invalid Matrix format: {0}", source));
}
}
return value;
}
public void Prepend (Matrix matrix)
{
double _m11;
double _m21;
double _m12;
double _m22;
double _offsetX;
double _offsetY;
_m11 = matrix.M11 * this._m11 + matrix.M12 * this._m21;
_m12 = matrix.M11 * this._m12 + matrix.M12 * this._m22;
_m21 = matrix.M21 * this._m11 + matrix.M22 * this._m21;
_m22 = matrix.M21 * this._m12 + matrix.M22 * this._m22;
_offsetX = matrix.OffsetX * this._m11 + matrix.OffsetY * this._m21 + this._offsetX;
_offsetY = matrix.OffsetX * this._m12 + matrix.OffsetY * this._m22 + this._offsetY;
this._m11 = _m11;
this._m12 = _m12;
this._m21 = _m21;
this._m22 = _m22;
this._offsetX = _offsetX;
this._offsetY = _offsetY;
}
public void Rotate (double angle)
{
// R_theta==[costheta -sintheta; sintheta costheta],
double theta = angle * Math.PI / 180;
Matrix r_theta = new Matrix (Math.Cos (theta), Math.Sin(theta),
-Math.Sin (theta), Math.Cos(theta),
0, 0);
Append (r_theta);
}
public void RotateAt (double angle,
double centerX,
double centerY)
{
Translate (-centerX, -centerY);
Rotate (angle);
Translate (centerX, centerY);
}
public void RotateAtPrepend (double angle,
double centerX,
double centerY)
{
Matrix m = Matrix.Identity;
m.RotateAt (angle, centerX, centerY);
Prepend (m);
}
public void RotatePrepend (double angle)
{
Matrix m = Matrix.Identity;
m.Rotate (angle);
Prepend (m);
}
public void Scale (double scaleX,
double scaleY)
{
Matrix scale = new Matrix (scaleX, 0,
0, scaleY,
0, 0);
Append (scale);
}
public void ScaleAt (double scaleX,
double scaleY,
double centerX,
double centerY)
{
Translate (-centerX, -centerY);
Scale (scaleX, scaleY);
Translate (centerX, centerY);
}
public void ScaleAtPrepend (double scaleX,
double scaleY,
double centerX,
double centerY)
{
Matrix m = Matrix.Identity;
m.ScaleAt (scaleX, scaleY, centerX, centerY);
Prepend (m);
}
public void ScalePrepend (double scaleX,
double scaleY)
{
Matrix m = Matrix.Identity;
m.Scale (scaleX, scaleY);
Prepend (m);
}
public void SetIdentity ()
{
_m11 = _m22 = 1.0;
_m12 = _m21 = 0.0;
_offsetX = _offsetY = 0.0;
}
public void Skew (double skewX,
double skewY)
{
Matrix skew_m = new Matrix (1, Math.Tan (skewY * Math.PI / 180),
Math.Tan (skewX * Math.PI / 180), 1,
0, 0);
Append (skew_m);
}
public void SkewPrepend (double skewX,
double skewY)
{
Matrix m = Matrix.Identity;
m.Skew (skewX, skewY);
Prepend (m);
}
public override string ToString ()
{
return ToString (null);
}
public string ToString (IFormatProvider provider)
{
return ToString (null, provider);
}
string IFormattable.ToString (string format,
IFormatProvider provider)
{
return ToString (provider);
}
private string ToString (string format, IFormatProvider provider)
{
if (IsIdentity)
return "Identity";
if (provider == null)
provider = CultureInfo.CurrentCulture;
if (format == null)
format = string.Empty;
var separator = NumericListTokenizer.GetSeparator (provider);
var matrixFormat = string.Format (
"{{0:{0}}}{1}{{1:{0}}}{1}{{2:{0}}}{1}{{3:{0}}}{1}{{4:{0}}}{1}{{5:{0}}}",
format, separator);
return string.Format (provider, matrixFormat,
_m11, _m12, _m21, _m22, _offsetX, _offsetY);
}
public Point Transform (Point point)
{
return Point.Multiply (point, this);
}
public void Transform (Point[] points)
{
for (int i = 0; i < points.Length; i ++)
points[i] = Transform (points[i]);
}
public Vector Transform (Vector vector)
{
return Vector.Multiply (vector, this);
}
public void Transform (Vector[] vectors)
{
for (int i = 0; i < vectors.Length; i ++)
vectors[i] = Transform (vectors[i]);
}
public void Translate (double offsetX,
double offsetY)
{
this._offsetX += offsetX;
this._offsetY += offsetY;
}
public void TranslatePrepend (double offsetX,
double offsetY)
{
Matrix m = Matrix.Identity;
m.Translate (offsetX, offsetY);
Prepend (m);
}
public double Determinant {
get { return _m11 * _m22 - _m12 * _m21; }
}
public bool HasInverse {
get { return Determinant != 0; }
}
public static Matrix Identity {
get { return new Matrix (1.0, 0.0, 0.0, 1.0, 0.0, 0.0); }
}
public bool IsIdentity {
get { return Equals (Matrix.Identity); }
}
public double M11 {
get { return _m11; }
set { _m11 = value; }
}
public double M12 {
get { return _m12; }
set { _m12 = value; }
}
public double M21 {
get { return _m21; }
set { _m21 = value; }
}
public double M22 {
get { return _m22; }
set { _m22 = value; }
}
public double OffsetX {
get { return _offsetX; }
set { _offsetX = value; }
}
public double OffsetY {
get { return _offsetY; }
set { _offsetY = value; }
}
}
}
| 24.579869 | 118 | 0.641236 | [
"MIT"
] | AmadeusW/vs-editor-api | src/FPF/WindowsBase/System.Windows.Media/Matrix.cs | 11,233 | C# |
//
// System.Xml.Schema.XmlSchemaValidity.cs
//
// Author:
// Atsushi Enomoto <ginga@kit.hi-ho.ne.jp>
//
//
// 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.
//
#if NET_2_0
namespace System.Xml.Schema
{
public enum XmlSchemaValidity
{
NotKnown,
Valid,
Invalid,
}
}
#endif
| 31.97561 | 73 | 0.748284 | [
"Apache-2.0"
] | 121468615/mono | mcs/class/System.XML/System.Xml.Schema/XmlSchemaValidity.cs | 1,311 | C# |
// Auto-Generated by FAKE; do not edit
// <auto-generated/>
using System.Reflection;
[assembly: AssemblyTitle("Okanshi.SplunkObserver")]
[assembly: AssemblyProduct("Okanshi")]
[assembly: AssemblyDescription("In-process monitoring library")]
[assembly: AssemblyVersion("7.0.0")]
[assembly: AssemblyFileVersion("7.0.0")]
[assembly: AssemblyConfiguration("Release")]
namespace System {
internal static class AssemblyVersionInformation {
internal const System.String AssemblyTitle = "Okanshi.SplunkObserver";
internal const System.String AssemblyProduct = "Okanshi";
internal const System.String AssemblyDescription = "In-process monitoring library";
internal const System.String AssemblyVersion = "7.0.0";
internal const System.String AssemblyFileVersion = "7.0.0";
internal const System.String AssemblyConfiguration = "Release";
}
}
| 42.333333 | 91 | 0.740157 | [
"MIT"
] | JTOne123/Okanshi | src/Okanshi.SplunkObserver/Properties/AssemblyInfo.cs | 891 | C# |
using System;
using System.Runtime.Serialization;
namespace Rebus.Exceptions
{
/// <summary>
/// Special exception that signals that some kind of optimistic lock has been violated, and work must most likely be aborted & retried
/// </summary>
[Serializable]
public class ConcurrencyException : Exception
{
/// <summary>
/// Constructs the exception
/// </summary>
public ConcurrencyException(string message)
: base(message)
{
}
/// <summary>
/// Constructs the exception
/// </summary>
public ConcurrencyException(Exception innerException, string message)
: base(message, innerException)
{
}
/// <summary>
/// Constructs the exception
/// </summary>
public ConcurrencyException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
} | 27.027778 | 142 | 0.587873 | [
"MIT"
] | AndoxADX/Rebus | Rebus/Exceptions/ConcurrencyException.cs | 975 | C# |
namespace MaterialSkin
{
using MaterialSkin.Controls;
using MaterialSkin.Properties;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
/// <summary>
/// Defines the <see cref="MaterialSkinManager" />
/// </summary>
public class MaterialSkinManager
{
/// <summary>
/// Defines the _instance
/// </summary>
private static MaterialSkinManager _instance;
/// <summary>
/// Defines the _formsToManage
/// </summary>
private readonly List<MaterialForm> _formsToManage = new List<MaterialForm>();
/// <summary>
/// Defines the _theme
/// </summary>
private Themes _theme;
/// <summary>
/// Gets or sets the Theme
/// </summary>
public Themes Theme
{
get { return _theme; }
set
{
_theme = value;
UpdateBackgrounds();
}
}
/// <summary>
/// Defines the _colorScheme
/// </summary>
private ColorScheme _colorScheme;
/// <summary>
/// Gets or sets the ColorScheme
/// </summary>
public ColorScheme ColorScheme
{
get { return _colorScheme; }
set
{
_colorScheme = value;
UpdateBackgrounds();
}
}
/// <summary>
/// Defines the Themes
/// </summary>
public enum Themes : byte
{
/// <summary>
/// Defines the LIGHT
/// </summary>
LIGHT,
/// <summary>
/// Defines the DARK
/// </summary>
DARK
}
/// <summary>
/// Defines the PRIMARY_TEXT_BLACK
/// </summary>
private static readonly Color PRIMARY_TEXT_BLACK = Color.FromArgb(222, 0, 0, 0);
/// <summary>
/// Defines the PRIMARY_TEXT_BLACK_BRUSH
/// </summary>
private static readonly Brush PRIMARY_TEXT_BLACK_BRUSH = new SolidBrush(PRIMARY_TEXT_BLACK);
/// <summary>
/// Defines the SECONDARY_TEXT_BLACK
/// </summary>
public static Color SECONDARY_TEXT_BLACK = Color.FromArgb(138, 0, 0, 0);
/// <summary>
/// Defines the SECONDARY_TEXT_BLACK_BRUSH
/// </summary>
public static Brush SECONDARY_TEXT_BLACK_BRUSH = new SolidBrush(SECONDARY_TEXT_BLACK);
/// <summary>
/// Defines the DISABLED_OR_HINT_TEXT_BLACK
/// </summary>
private static readonly Color DISABLED_OR_HINT_TEXT_BLACK = Color.FromArgb(66, 0, 0, 0);
/// <summary>
/// Defines the DISABLED_OR_HINT_TEXT_BLACK_BRUSH
/// </summary>
private static readonly Brush DISABLED_OR_HINT_TEXT_BLACK_BRUSH = new SolidBrush(DISABLED_OR_HINT_TEXT_BLACK);
/// <summary>
/// Defines the DIVIDERS_BLACK
/// </summary>
private static readonly Color DIVIDERS_BLACK = Color.FromArgb(31, 0, 0, 0);
/// <summary>
/// Defines the DIVIDERS_BLACK_BRUSH
/// </summary>
private static readonly Brush DIVIDERS_BLACK_BRUSH = new SolidBrush(DIVIDERS_BLACK);
/// <summary>
/// Defines the PRIMARY_TEXT_WHITE
/// </summary>
private static readonly Color PRIMARY_TEXT_WHITE = Color.FromArgb(255, 255, 255, 255);
/// <summary>
/// Defines the PRIMARY_TEXT_WHITE_BRUSH
/// </summary>
private static readonly Brush PRIMARY_TEXT_WHITE_BRUSH = new SolidBrush(PRIMARY_TEXT_WHITE);
/// <summary>
/// Defines the SECONDARY_TEXT_WHITE
/// </summary>
public static Color SECONDARY_TEXT_WHITE = Color.FromArgb(179, 255, 255, 255);
/// <summary>
/// Defines the SECONDARY_TEXT_WHITE_BRUSH
/// </summary>
public static Brush SECONDARY_TEXT_WHITE_BRUSH = new SolidBrush(SECONDARY_TEXT_WHITE);
/// <summary>
/// Defines the DISABLED_OR_HINT_TEXT_WHITE
/// </summary>
private static readonly Color DISABLED_OR_HINT_TEXT_WHITE = Color.FromArgb(77, 255, 255, 255);
/// <summary>
/// Defines the DISABLED_OR_HINT_TEXT_WHITE_BRUSH
/// </summary>
private static readonly Brush DISABLED_OR_HINT_TEXT_WHITE_BRUSH = new SolidBrush(DISABLED_OR_HINT_TEXT_WHITE);
/// <summary>
/// Defines the DIVIDERS_WHITE
/// </summary>
private static readonly Color DIVIDERS_WHITE = Color.FromArgb(31, 255, 255, 255);
/// <summary>
/// Defines the DIVIDERS_WHITE_BRUSH
/// </summary>
private static readonly Brush DIVIDERS_WHITE_BRUSH = new SolidBrush(DIVIDERS_WHITE);
/// <summary>
/// Defines the CHECKBOX_OFF_LIGHT
/// </summary>
private static readonly Color CHECKBOX_OFF_LIGHT = Color.FromArgb(138, 0, 0, 0);
/// <summary>
/// Defines the CHECKBOX_OFF_LIGHT_BRUSH
/// </summary>
private static readonly Brush CHECKBOX_OFF_LIGHT_BRUSH = new SolidBrush(CHECKBOX_OFF_LIGHT);
/// <summary>
/// Defines the CHECKBOX_OFF_DISABLED_LIGHT
/// </summary>
private static readonly Color CHECKBOX_OFF_DISABLED_LIGHT = Color.FromArgb(66, 0, 0, 0);
/// <summary>
/// Defines the CHECKBOX_OFF_DISABLED_LIGHT_BRUSH
/// </summary>
private static readonly Brush CHECKBOX_OFF_DISABLED_LIGHT_BRUSH = new SolidBrush(CHECKBOX_OFF_DISABLED_LIGHT);
/// <summary>
/// Defines the CHECKBOX_OFF_DARK
/// </summary>
private static readonly Color CHECKBOX_OFF_DARK = Color.FromArgb(179, 255, 255, 255);
/// <summary>
/// Defines the CHECKBOX_OFF_DARK_BRUSH
/// </summary>
private static readonly Brush CHECKBOX_OFF_DARK_BRUSH = new SolidBrush(CHECKBOX_OFF_DARK);
/// <summary>
/// Defines the CHECKBOX_OFF_DISABLED_DARK
/// </summary>
private static readonly Color CHECKBOX_OFF_DISABLED_DARK = Color.FromArgb(77, 255, 255, 255);
/// <summary>
/// Defines the CHECKBOX_OFF_DISABLED_DARK_BRUSH
/// </summary>
private static readonly Brush CHECKBOX_OFF_DISABLED_DARK_BRUSH = new SolidBrush(CHECKBOX_OFF_DISABLED_DARK);
/// <summary>
/// Defines the RAISED_BUTTON_BACKGROUND
/// </summary>
private static readonly Color RAISED_BUTTON_BACKGROUND = Color.FromArgb(255, 255, 255, 255);
/// <summary>
/// Defines the RAISED_BUTTON_BACKGROUND_BRUSH
/// </summary>
private static readonly Brush RAISED_BUTTON_BACKGROUND_BRUSH = new SolidBrush(RAISED_BUTTON_BACKGROUND);
/// <summary>
/// Defines the RAISED_BUTTON_TEXT_LIGHT
/// </summary>
private static readonly Color RAISED_BUTTON_TEXT_LIGHT = PRIMARY_TEXT_WHITE;
/// <summary>
/// Defines the RAISED_BUTTON_TEXT_LIGHT_BRUSH
/// </summary>
private static readonly Brush RAISED_BUTTON_TEXT_LIGHT_BRUSH = new SolidBrush(RAISED_BUTTON_TEXT_LIGHT);
/// <summary>
/// Defines the RAISED_BUTTON_TEXT_DARK
/// </summary>
private static readonly Color RAISED_BUTTON_TEXT_DARK = PRIMARY_TEXT_BLACK;
/// <summary>
/// Defines the RAISED_BUTTON_TEXT_DARK_BRUSH
/// </summary>
private static readonly Brush RAISED_BUTTON_TEXT_DARK_BRUSH = new SolidBrush(RAISED_BUTTON_TEXT_DARK);
/// <summary>
/// Defines the FLAT_BUTTON_BACKGROUND_HOVER_LIGHT
/// </summary>
private static readonly Color FLAT_BUTTON_BACKGROUND_HOVER_LIGHT = Color.FromArgb(20.PercentageToColorComponent(), 0x999999.ToColor());
/// <summary>
/// Defines the FLAT_BUTTON_BACKGROUND_HOVER_LIGHT_BRUSH
/// </summary>
private static readonly Brush FLAT_BUTTON_BACKGROUND_HOVER_LIGHT_BRUSH = new SolidBrush(FLAT_BUTTON_BACKGROUND_HOVER_LIGHT);
/// <summary>
/// Defines the FLAT_BUTTON_BACKGROUND_PRESSED_LIGHT
/// </summary>
private static readonly Color FLAT_BUTTON_BACKGROUND_PRESSED_LIGHT = Color.FromArgb(40.PercentageToColorComponent(), 0x999999.ToColor());
/// <summary>
/// Defines the FLAT_BUTTON_BACKGROUND_PRESSED_LIGHT_BRUSH
/// </summary>
private static readonly Brush FLAT_BUTTON_BACKGROUND_PRESSED_LIGHT_BRUSH = new SolidBrush(FLAT_BUTTON_BACKGROUND_PRESSED_LIGHT);
/// <summary>
/// Defines the FLAT_BUTTON_DISABLEDTEXT_LIGHT
/// </summary>
private static readonly Color FLAT_BUTTON_DISABLEDTEXT_LIGHT = Color.FromArgb(26.PercentageToColorComponent(), 0x000000.ToColor());
/// <summary>
/// Defines the FLAT_BUTTON_DISABLEDTEXT_LIGHT_BRUSH
/// </summary>
private static readonly Brush FLAT_BUTTON_DISABLEDTEXT_LIGHT_BRUSH = new SolidBrush(FLAT_BUTTON_DISABLEDTEXT_LIGHT);
/// <summary>
/// Defines the FLAT_BUTTON_BACKGROUND_HOVER_DARK
/// </summary>
private static readonly Color FLAT_BUTTON_BACKGROUND_HOVER_DARK = Color.FromArgb(15.PercentageToColorComponent(), 0xCCCCCC.ToColor());
/// <summary>
/// Defines the FLAT_BUTTON_BACKGROUND_HOVER_DARK_BRUSH
/// </summary>
private static readonly Brush FLAT_BUTTON_BACKGROUND_HOVER_DARK_BRUSH = new SolidBrush(FLAT_BUTTON_BACKGROUND_HOVER_DARK);
/// <summary>
/// Defines the FLAT_BUTTON_BACKGROUND_PRESSED_DARK
/// </summary>
private static readonly Color FLAT_BUTTON_BACKGROUND_PRESSED_DARK = Color.FromArgb(25.PercentageToColorComponent(), 0xCCCCCC.ToColor());
/// <summary>
/// Defines the FLAT_BUTTON_BACKGROUND_PRESSED_DARK_BRUSH
/// </summary>
private static readonly Brush FLAT_BUTTON_BACKGROUND_PRESSED_DARK_BRUSH = new SolidBrush(FLAT_BUTTON_BACKGROUND_PRESSED_DARK);
/// <summary>
/// Defines the FLAT_BUTTON_DISABLEDTEXT_DARK
/// </summary>
private static readonly Color FLAT_BUTTON_DISABLEDTEXT_DARK = Color.FromArgb(30.PercentageToColorComponent(), 0xFFFFFF.ToColor());
/// <summary>
/// Defines the FLAT_BUTTON_DISABLEDTEXT_DARK_BRUSH
/// </summary>
private static readonly Brush FLAT_BUTTON_DISABLEDTEXT_DARK_BRUSH = new SolidBrush(FLAT_BUTTON_DISABLEDTEXT_DARK);
/// <summary>
/// Defines the CMS_BACKGROUND_LIGHT_HOVER
/// </summary>
private static readonly Color CMS_BACKGROUND_LIGHT_HOVER = Color.FromArgb(255, 238, 238, 238);
/// <summary>
/// Defines the CMS_BACKGROUND_HOVER_LIGHT_BRUSH
/// </summary>
private static readonly Brush CMS_BACKGROUND_HOVER_LIGHT_BRUSH = new SolidBrush(CMS_BACKGROUND_LIGHT_HOVER);
/// <summary>
/// Defines the CMS_BACKGROUND_DARK_HOVER
/// </summary>
private static readonly Color CMS_BACKGROUND_DARK_HOVER = Color.FromArgb(38, 204, 204, 204);
/// <summary>
/// Defines the CMS_BACKGROUND_HOVER_DARK_BRUSH
/// </summary>
private static readonly Brush CMS_BACKGROUND_HOVER_DARK_BRUSH = new SolidBrush(CMS_BACKGROUND_DARK_HOVER);
/// <summary>
/// Defines the BACKGROUND_LIGHT
/// </summary>
private static readonly Color BACKGROUND_LIGHT = Color.FromArgb(255, 255, 255, 255);
/// <summary>
/// Defines the BACKGROUND_LIGHT_BRUSH
/// </summary>
private static Brush BACKGROUND_LIGHT_BRUSH = new SolidBrush(BACKGROUND_LIGHT);
/// <summary>
/// Defines the BACKGROUND_DARK
/// </summary>
private static readonly Color BACKGROUND_DARK = Color.FromArgb(255, 51, 51, 51);
/// <summary>
/// Defines the BACKGROUND_DARK_BRUSH
/// </summary>
private static Brush BACKGROUND_DARK_BRUSH = new SolidBrush(BACKGROUND_DARK);
/// <summary>
/// Defines the ACTION_BAR_TEXT
/// </summary>
public readonly Color ACTION_BAR_TEXT = Color.FromArgb(255, 255, 255, 255);
/// <summary>
/// Defines the ACTION_BAR_TEXT_BRUSH
/// </summary>
public readonly Brush ACTION_BAR_TEXT_BRUSH = new SolidBrush(Color.FromArgb(255, 255, 255, 255));
/// <summary>
/// Defines the ACTION_BAR_TEXT_SECONDARY
/// </summary>
public readonly Color ACTION_BAR_TEXT_SECONDARY = Color.FromArgb(153, 255, 255, 255);
/// <summary>
/// Defines the ACTION_BAR_TEXT_SECONDARY_BRUSH
/// </summary>
public readonly Brush ACTION_BAR_TEXT_SECONDARY_BRUSH = new SolidBrush(Color.FromArgb(153, 255, 255, 255));
/// <summary>
/// The GetPrimaryTextColor
/// </summary>
/// <returns>The <see cref="Color"/></returns>
public Color GetPrimaryTextColor()
{
return Theme == Themes.LIGHT ? PRIMARY_TEXT_BLACK : PRIMARY_TEXT_WHITE;
}
/// <summary>
/// The GetPrimaryTextBrush
/// </summary>
/// <returns>The <see cref="Brush"/></returns>
public Brush GetPrimaryTextBrush()
{
return Theme == Themes.LIGHT ? PRIMARY_TEXT_BLACK_BRUSH : PRIMARY_TEXT_WHITE_BRUSH;
}
/// <summary>
/// The GetSecondaryTextColor
/// </summary>
/// <returns>The <see cref="Color"/></returns>
public Color GetSecondaryTextColor()
{
return Theme == Themes.LIGHT ? SECONDARY_TEXT_BLACK : SECONDARY_TEXT_WHITE;
}
/// <summary>
/// The GetSecondaryTextBrush
/// </summary>
/// <returns>The <see cref="Brush"/></returns>
public Brush GetSecondaryTextBrush()
{
return Theme == Themes.LIGHT ? PRIMARY_TEXT_BLACK_BRUSH : SECONDARY_TEXT_WHITE_BRUSH;
}
/// <summary>
/// The GetDisabledOrHintColor
/// </summary>
/// <returns>The <see cref="Color"/></returns>
public Color GetDisabledOrHintColor()
{
return Theme == Themes.LIGHT ? DISABLED_OR_HINT_TEXT_BLACK : DISABLED_OR_HINT_TEXT_WHITE;
}
/// <summary>
/// The GetDisabledOrHintBrush
/// </summary>
/// <returns>The <see cref="Brush"/></returns>
public Brush GetDisabledOrHintBrush()
{
return Theme == Themes.LIGHT ? DISABLED_OR_HINT_TEXT_BLACK_BRUSH : DISABLED_OR_HINT_TEXT_WHITE_BRUSH;
}
/// <summary>
/// The GetDividersColor
/// </summary>
/// <returns>The <see cref="Color"/></returns>
public Color GetDividersColor()
{
return Theme == Themes.LIGHT ? DIVIDERS_BLACK : DIVIDERS_WHITE;
}
/// <summary>
/// The GetDividersBrush
/// </summary>
/// <returns>The <see cref="Brush"/></returns>
public Brush GetDividersBrush()
{
return Theme == Themes.LIGHT ? DIVIDERS_BLACK_BRUSH : DIVIDERS_WHITE_BRUSH;
}
/// <summary>
/// The GetCheckboxOffColor
/// </summary>
/// <returns>The <see cref="Color"/></returns>
public Color GetCheckboxOffColor()
{
return Theme == Themes.LIGHT ? CHECKBOX_OFF_LIGHT : CHECKBOX_OFF_DARK;
}
/// <summary>
/// The GetCheckboxOffBrush
/// </summary>
/// <returns>The <see cref="Brush"/></returns>
public Brush GetCheckboxOffBrush()
{
return Theme == Themes.LIGHT ? CHECKBOX_OFF_LIGHT_BRUSH : CHECKBOX_OFF_DARK_BRUSH;
}
/// <summary>
/// The GetCheckBoxOffDisabledColor
/// </summary>
/// <returns>The <see cref="Color"/></returns>
public Color GetCheckBoxOffDisabledColor()
{
return Theme == Themes.LIGHT ? CHECKBOX_OFF_DISABLED_LIGHT : CHECKBOX_OFF_DISABLED_DARK;
}
/// <summary>
/// The GetCheckBoxOffDisabledBrush
/// </summary>
/// <returns>The <see cref="Brush"/></returns>
public Brush GetCheckBoxOffDisabledBrush()
{
return Theme == Themes.LIGHT ? CHECKBOX_OFF_DISABLED_LIGHT_BRUSH : CHECKBOX_OFF_DISABLED_DARK_BRUSH;
}
/// <summary>
/// The GetRaisedButtonBackgroundBrush
/// </summary>
/// <returns>The <see cref="Brush"/></returns>
public Brush GetRaisedButtonBackgroundBrush()
{
return RAISED_BUTTON_BACKGROUND_BRUSH;
}
/// <summary>
/// The GetRaisedButtonTextBrush
/// </summary>
/// <param name="primary">The primary<see cref="bool"/></param>
/// <returns>The <see cref="Brush"/></returns>
public Brush GetRaisedButtonTextBrush(bool primary)
{
return primary ? RAISED_BUTTON_TEXT_LIGHT_BRUSH : RAISED_BUTTON_TEXT_DARK_BRUSH;
}
/// <summary>
/// The GetFlatButtonHoverBackgroundColor
/// </summary>
/// <returns>The <see cref="Color"/></returns>
public Color GetFlatButtonHoverBackgroundColor()
{
return Theme == Themes.LIGHT ? FLAT_BUTTON_BACKGROUND_HOVER_LIGHT : FLAT_BUTTON_BACKGROUND_HOVER_DARK;
}
/// <summary>
/// The GetFlatButtonHoverBackgroundBrush
/// </summary>
/// <returns>The <see cref="Brush"/></returns>
public Brush GetFlatButtonHoverBackgroundBrush()
{
return Theme == Themes.LIGHT ? FLAT_BUTTON_BACKGROUND_HOVER_LIGHT_BRUSH : FLAT_BUTTON_BACKGROUND_HOVER_DARK_BRUSH;
}
/// <summary>
/// The GetFlatButtonPressedBackgroundColor
/// </summary>
/// <returns>The <see cref="Color"/></returns>
public Color GetFlatButtonPressedBackgroundColor()
{
return Theme == Themes.LIGHT ? FLAT_BUTTON_BACKGROUND_PRESSED_LIGHT : FLAT_BUTTON_BACKGROUND_PRESSED_DARK;
}
/// <summary>
/// The GetFlatButtonPressedBackgroundBrush
/// </summary>
/// <returns>The <see cref="Brush"/></returns>
public Brush GetFlatButtonPressedBackgroundBrush()
{
return Theme == Themes.LIGHT ? FLAT_BUTTON_BACKGROUND_PRESSED_LIGHT_BRUSH : FLAT_BUTTON_BACKGROUND_PRESSED_DARK_BRUSH;
}
/// <summary>
/// The GetFlatButtonDisabledTextBrush
/// </summary>
/// <returns>The <see cref="Brush"/></returns>
public Brush GetFlatButtonDisabledTextBrush()
{
return Theme == Themes.LIGHT ? FLAT_BUTTON_DISABLEDTEXT_LIGHT_BRUSH : FLAT_BUTTON_DISABLEDTEXT_DARK_BRUSH;
}
/// <summary>
/// The GetCmsSelectedItemBrush
/// </summary>
/// <returns>The <see cref="Brush"/></returns>
public Brush GetCmsSelectedItemBrush()
{
return Theme == Themes.LIGHT ? CMS_BACKGROUND_HOVER_LIGHT_BRUSH : CMS_BACKGROUND_HOVER_DARK_BRUSH;
}
/// <summary>
/// The GetApplicationBackgroundColor
/// </summary>
/// <returns>The <see cref="Color"/></returns>
public Color GetApplicationBackgroundColor()
{
return Theme == Themes.LIGHT ? BACKGROUND_LIGHT : BACKGROUND_DARK;
}
//Roboto font
public Font ROBOTO_REGULAR_12;
public Font ROBOTO_REGULAR_10;
public Font ROBOTO_REGULAR_08;
public Font ROBOTO_REGULAR_06;
/// <summary>
/// The GetControlBackgroundColor
/// </summary>
/// <returns>The <see cref="Color"/></returns>
public Color GetControlBackgroundColor()
{
return Theme == Themes.LIGHT ? BACKGROUND_LIGHT.Darken((float)0.02) : BACKGROUND_DARK.Lighten((float)0.05);
}
/// <summary>
/// Defines the ROBOTO_MEDIUM_12
/// </summary>
public Font ROBOTO_MEDIUM_12;
/// <summary>
/// Defines the ROBOTO_REGULAR_11
/// </summary>
public Font ROBOTO_REGULAR_11;
/// <summary>
/// Defines the ROBOTO_MEDIUM_11
/// </summary>
public Font ROBOTO_MEDIUM_11;
/// <summary>
/// Defines the ROBOTO_MEDIUM_10
/// </summary>
public Font ROBOTO_MEDIUM_10;
public Font ROBOTO_MEDIUM_08;
public Font ROBOTO_MEDIUM_06;
//Other constants
/// <summary>
/// Defines the FORM_PADDING
/// </summary>
public int FORM_PADDING = 14;
/// <summary>
/// The AddFontMemResourceEx
/// </summary>
/// <param name="pbFont">The pbFont<see cref="IntPtr"/></param>
/// <param name="cbFont">The cbFont<see cref="uint"/></param>
/// <param name="pvd">The pvd<see cref="IntPtr"/></param>
/// <param name="pcFonts">The pcFonts<see cref="uint"/></param>
/// <returns>The <see cref="IntPtr"/></returns>
[DllImport("gdi32.dll")]
private static extern IntPtr AddFontMemResourceEx(IntPtr pbFont, uint cbFont, IntPtr pvd, [In] ref uint pcFonts);
/// <summary>
/// Prevents a default instance of the <see cref="MaterialSkinManager"/> class from being created.
/// </summary>
private MaterialSkinManager()
{
ROBOTO_MEDIUM_12 = new Font(LoadFont(Resources.Roboto_Medium), 12f);
ROBOTO_MEDIUM_11 = new Font(LoadFont(Resources.Roboto_Medium), 11f);
ROBOTO_MEDIUM_10 = new Font(LoadFont(Resources.Roboto_Medium), 10f);
ROBOTO_MEDIUM_08 = new Font(LoadFont(Resources.Roboto_Medium), 8f);
ROBOTO_MEDIUM_06 = new Font(LoadFont(Resources.Roboto_Medium), 6f);
ROBOTO_REGULAR_12 = new Font(LoadFont(Resources.Roboto_Regular), 12f);
ROBOTO_REGULAR_11 = new Font(LoadFont(Resources.Roboto_Regular), 11f);
ROBOTO_REGULAR_10 = new Font(LoadFont(Resources.Roboto_Regular), 10f);
ROBOTO_REGULAR_08 = new Font(LoadFont(Resources.Roboto_Regular), 8f);
ROBOTO_REGULAR_06 = new Font(LoadFont(Resources.Roboto_Regular), 6f);
Theme = Themes.LIGHT;
ColorScheme = new ColorScheme(Primary.BlueGrey800, Primary.BlueGrey900, Primary.BlueGrey500, Accent.LightBlue200, TextShade.WHITE);
}
/// <summary>
/// Gets the Instance
/// </summary>
public static MaterialSkinManager Instance => _instance ?? (_instance = new MaterialSkinManager());
/// <summary>
/// The AddFormToManage
/// </summary>
/// <param name="materialForm">The materialForm<see cref="MaterialForm"/></param>
public void AddFormToManage(MaterialForm materialForm)
{
_formsToManage.Add(materialForm);
UpdateBackgrounds();
}
/// <summary>
/// The RemoveFormToManage
/// </summary>
/// <param name="materialForm">The materialForm<see cref="MaterialForm"/></param>
public void RemoveFormToManage(MaterialForm materialForm)
{
_formsToManage.Remove(materialForm);
}
/// <summary>
/// Defines the privateFontCollection
/// </summary>
private readonly PrivateFontCollection privateFontCollection = new PrivateFontCollection();
/// <summary>
/// The LoadFont
/// </summary>
/// <param name="fontResource">The fontResource<see cref="byte[]"/></param>
/// <returns>The <see cref="FontFamily"/></returns>
private FontFamily LoadFont(byte[] fontResource)
{
int dataLength = fontResource.Length;
IntPtr fontPtr = Marshal.AllocCoTaskMem(dataLength);
Marshal.Copy(fontResource, 0, fontPtr, dataLength);
uint cFonts = 0;
AddFontMemResourceEx(fontPtr, (uint)fontResource.Length, IntPtr.Zero, ref cFonts);
privateFontCollection.AddMemoryFont(fontPtr, dataLength);
return privateFontCollection.Families.Last();
}
/// <summary>
/// The UpdateBackgrounds
/// </summary>
private void UpdateBackgrounds()
{
var newBackColor = GetApplicationBackgroundColor();
foreach (var materialForm in _formsToManage)
{
materialForm.BackColor = newBackColor;
UpdateControl(materialForm, newBackColor);
}
}
/// <summary>
/// The UpdateToolStrip
/// </summary>
/// <param name="toolStrip">The toolStrip<see cref="ToolStrip"/></param>
/// <param name="newBackColor">The newBackColor<see cref="Color"/></param>
private void UpdateToolStrip(ToolStrip toolStrip, Color newBackColor)
{
if (toolStrip == null)
{
return;
}
toolStrip.BackColor = newBackColor;
foreach (ToolStripItem control in toolStrip.Items)
{
control.BackColor = newBackColor;
if (control is MaterialToolStripMenuItem && (control as MaterialToolStripMenuItem).HasDropDown)
{
//recursive call
UpdateToolStrip((control as MaterialToolStripMenuItem).DropDown, newBackColor);
}
}
}
/// <summary>
/// The UpdateControl
/// </summary>
/// <param name="controlToUpdate">The controlToUpdate<see cref="Control"/></param>
public void UpdateControl(Control controlToUpdate)
{
UpdateControl(controlToUpdate, GetApplicationBackgroundColor());
}
/// <summary>
/// The UpdateControl
/// </summary>
/// <param name="controlToUpdate">The controlToUpdate<see cref="Control"/></param>
/// <param name="newBackColor">The newBackColor<see cref="Color"/></param>
private void UpdateControl(Control controlToUpdate, Color newBackColor)
{
if (controlToUpdate == null)
{
return;
}
if (controlToUpdate.Name == "TrackMe")
{
//Debugger.Break();
}
var tabControl = controlToUpdate as MaterialTabControl;
var CurrentTabPage = controlToUpdate as TabPage;
if (controlToUpdate.ContextMenuStrip != null)
{
UpdateToolStrip(controlToUpdate.ContextMenuStrip, newBackColor);
}
if (tabControl != null)
{
foreach (TabPage tabPage in tabControl.TabPages)
{
tabPage.BackColor = newBackColor;
}
}
else if (controlToUpdate is MaterialDivider)
{
controlToUpdate.BackColor = GetDividersColor();
}
else if (controlToUpdate.HasProperty("BackColor") && CurrentTabPage == null && !controlToUpdate.IsMaterialControl())
{ // if the control has a backcolor property set the colors
if (controlToUpdate.BackColor != GetControlBackgroundColor())
{
controlToUpdate.BackColor = GetControlBackgroundColor();
if (controlToUpdate.HasProperty("ForeColor") && controlToUpdate.ForeColor != GetPrimaryTextColor())
{
controlToUpdate.ForeColor = GetPrimaryTextColor();
if (controlToUpdate.Font == SystemFonts.DefaultFont) // if the control has not had the font changed from default, set a default
{
controlToUpdate.Font = ROBOTO_REGULAR_11;
}
}
}
}
else if (controlToUpdate.IsMaterialControl())
{
controlToUpdate.BackColor = newBackColor;
controlToUpdate.ForeColor = GetPrimaryTextColor();
}
//recursive call
foreach (Control control in controlToUpdate.Controls)
{
UpdateControl(control, newBackColor);
}
controlToUpdate.Invalidate();
}
}
}
| 36.674359 | 151 | 0.601272 | [
"MIT"
] | maikebing/MaterialSkin | MaterialSkin/MaterialSkinManager.cs | 28,608 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ImageDescrypt.Entity
{
class ResBackDamageMessage : ResAttackResultMessage
{
private int _back;
override public void reading()
{
base.reading();
this._back = readInt();
}
public override string getPrintStr()
{
return base.getPrintStr();
}
}
public class ResAttackResultMessage :Bean
{
private AttackResultInfo _state;
override public void reading()
{
this._state = readBean<AttackResultInfo>();// as AttackResultInfo;
}
public override string getPrintStr()
{
return _state.getPrintStr();//base.getPrintStr();
}
}
public class AttackResultInfo : Bean
{
private LongC _entityId;
private LongC _sourceId;
private int _skillId;
private int _fightResult;
private LongC _damage;
private LongC _currentHP;
private int _fightSpecialRes;
override public void reading()
{
this._entityId = readLong();
this._sourceId = readLong();
this._skillId = readInt();
this._fightResult = readByte();
this._damage = readLong();
this._currentHP = readLong();
this._fightSpecialRes = readShort();
}
public override string getPrintStr()
{
string outstr = string.Format("_entityId={0};_sourceId={1};_skillId={2};_fightResult={3};_damage={4};_currentHP={5};_fightSpecialRes={6};"
, _entityId.toString(), _sourceId.toString(), _skillId, _fightResult, _damage.toString(), _currentHP.toString(), _fightSpecialRes);
return outstr;
}
}
}
| 25.108108 | 150 | 0.596878 | [
"MIT"
] | foreachzh/Divine-Sword-of-Archangel | ImageDescrypt/ImageDescrypt/Entity/ResBackDamageMessage.cs | 1,860 | 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.
#nullable enable
using System.Buffers;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography.Asn1;
namespace System.Security.Cryptography
{
internal static class KeyFormatHelper
{
internal delegate void KeyReader<TRet>(ReadOnlyMemory<byte> key, in AlgorithmIdentifierAsn algId, out TRet ret);
internal static unsafe void ReadSubjectPublicKeyInfo<TRet>(
string[] validOids,
ReadOnlySpan<byte> source,
KeyReader<TRet> keyReader,
out int bytesRead,
out TRet ret)
{
fixed (byte* ptr = &MemoryMarshal.GetReference(source))
{
using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length))
{
ReadSubjectPublicKeyInfo(validOids, manager.Memory, keyReader, out bytesRead, out ret);
}
}
}
internal static ReadOnlyMemory<byte> ReadSubjectPublicKeyInfo(
string[] validOids,
ReadOnlyMemory<byte> source,
out int bytesRead)
{
// X.509 SubjectPublicKeyInfo is described as DER.
AsnValueReader reader = new AsnValueReader(source.Span, AsnEncodingRules.DER);
int read = reader.PeekEncodedValue().Length;
SubjectPublicKeyInfoAsn.Decode(ref reader, source, out SubjectPublicKeyInfoAsn spki);
if (Array.IndexOf(validOids, spki.Algorithm.Algorithm.Value) < 0)
{
throw new CryptographicException(SR.Cryptography_NotValidPublicOrPrivateKey);
}
bytesRead = read;
return spki.SubjectPublicKey;
}
private static void ReadSubjectPublicKeyInfo<TRet>(
string[] validOids,
ReadOnlyMemory<byte> source,
KeyReader<TRet> keyReader,
out int bytesRead,
out TRet ret)
{
// X.509 SubjectPublicKeyInfo is described as DER.
AsnValueReader reader = new AsnValueReader(source.Span, AsnEncodingRules.DER);
int read = reader.PeekEncodedValue().Length;
SubjectPublicKeyInfoAsn.Decode(ref reader, source, out SubjectPublicKeyInfoAsn spki);
if (Array.IndexOf(validOids, spki.Algorithm.Algorithm.Value) < 0)
{
throw new CryptographicException(SR.Cryptography_NotValidPublicOrPrivateKey);
}
keyReader(spki.SubjectPublicKey, spki.Algorithm, out ret);
bytesRead = read;
}
internal static unsafe void ReadPkcs8<TRet>(
string[] validOids,
ReadOnlySpan<byte> source,
KeyReader<TRet> keyReader,
out int bytesRead,
out TRet ret)
{
fixed (byte* ptr = &MemoryMarshal.GetReference(source))
{
using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length))
{
ReadPkcs8(validOids, manager.Memory, keyReader, out bytesRead, out ret);
}
}
}
internal static ReadOnlyMemory<byte> ReadPkcs8(
string[] validOids,
ReadOnlyMemory<byte> source,
out int bytesRead)
{
AsnValueReader reader = new AsnValueReader(source.Span, AsnEncodingRules.BER);
int read = reader.PeekEncodedValue().Length;
PrivateKeyInfoAsn.Decode(ref reader, source, out PrivateKeyInfoAsn privateKeyInfo);
if (Array.IndexOf(validOids, privateKeyInfo.PrivateKeyAlgorithm.Algorithm.Value) < 0)
{
throw new CryptographicException(SR.Cryptography_NotValidPublicOrPrivateKey);
}
bytesRead = read;
return privateKeyInfo.PrivateKey;
}
private static void ReadPkcs8<TRet>(
string[] validOids,
ReadOnlyMemory<byte> source,
KeyReader<TRet> keyReader,
out int bytesRead,
out TRet ret)
{
AsnValueReader reader = new AsnValueReader(source.Span, AsnEncodingRules.BER);
int read = reader.PeekEncodedValue().Length;
PrivateKeyInfoAsn.Decode(ref reader, source, out PrivateKeyInfoAsn privateKeyInfo);
if (Array.IndexOf(validOids, privateKeyInfo.PrivateKeyAlgorithm.Algorithm.Value) < 0)
{
throw new CryptographicException(SR.Cryptography_NotValidPublicOrPrivateKey);
}
// Fails if there are unconsumed bytes.
keyReader(privateKeyInfo.PrivateKey, privateKeyInfo.PrivateKeyAlgorithm, out ret);
bytesRead = read;
}
internal static unsafe void ReadEncryptedPkcs8<TRet>(
string[] validOids,
ReadOnlySpan<byte> source,
ReadOnlySpan<char> password,
KeyReader<TRet> keyReader,
out int bytesRead,
out TRet ret)
{
fixed (byte* ptr = &MemoryMarshal.GetReference(source))
{
using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length))
{
ReadEncryptedPkcs8(validOids, manager.Memory, password, keyReader, out bytesRead, out ret);
}
}
}
internal static unsafe void ReadEncryptedPkcs8<TRet>(
string[] validOids,
ReadOnlySpan<byte> source,
ReadOnlySpan<byte> passwordBytes,
KeyReader<TRet> keyReader,
out int bytesRead,
out TRet ret)
{
fixed (byte* ptr = &MemoryMarshal.GetReference(source))
{
using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length))
{
ReadEncryptedPkcs8(validOids, manager.Memory, passwordBytes, keyReader, out bytesRead, out ret);
}
}
}
private static void ReadEncryptedPkcs8<TRet>(
string[] validOids,
ReadOnlyMemory<byte> source,
ReadOnlySpan<char> password,
KeyReader<TRet> keyReader,
out int bytesRead,
out TRet ret)
{
ReadEncryptedPkcs8(
validOids,
source,
password,
ReadOnlySpan<byte>.Empty,
keyReader,
out bytesRead,
out ret);
}
private static void ReadEncryptedPkcs8<TRet>(
string[] validOids,
ReadOnlyMemory<byte> source,
ReadOnlySpan<byte> passwordBytes,
KeyReader<TRet> keyReader,
out int bytesRead,
out TRet ret)
{
ReadEncryptedPkcs8(
validOids,
source,
ReadOnlySpan<char>.Empty,
passwordBytes,
keyReader,
out bytesRead,
out ret);
}
private static void ReadEncryptedPkcs8<TRet>(
string[] validOids,
ReadOnlyMemory<byte> source,
ReadOnlySpan<char> password,
ReadOnlySpan<byte> passwordBytes,
KeyReader<TRet> keyReader,
out int bytesRead,
out TRet ret)
{
AsnValueReader reader = new AsnValueReader(source.Span, AsnEncodingRules.BER);
int read = reader.PeekEncodedValue().Length;
EncryptedPrivateKeyInfoAsn.Decode(ref reader, source, out EncryptedPrivateKeyInfoAsn epki);
// No supported encryption algorithms produce more bytes of decryption output than there
// were of decryption input.
byte[] decrypted = CryptoPool.Rent(epki.EncryptedData.Length);
Memory<byte> decryptedMemory = decrypted;
try
{
int decryptedBytes = PasswordBasedEncryption.Decrypt(
epki.EncryptionAlgorithm,
password,
passwordBytes,
epki.EncryptedData.Span,
decrypted);
decryptedMemory = decryptedMemory.Slice(0, decryptedBytes);
ReadPkcs8(
validOids,
decryptedMemory,
keyReader,
out int innerRead,
out ret);
if (innerRead != decryptedMemory.Length)
{
ret = default!;
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
bytesRead = read;
}
catch (CryptographicException e)
{
throw new CryptographicException(SR.Cryptography_Pkcs8_EncryptedReadFailed, e);
}
finally
{
CryptographicOperations.ZeroMemory(decryptedMemory.Span);
CryptoPool.Return(decrypted, clearSize: 0);
}
}
internal static AsnWriter WritePkcs8(
AsnWriter algorithmIdentifierWriter,
AsnWriter privateKeyWriter,
AsnWriter? attributesWriter = null)
{
// Ensure both algorithm identifier and key writers are balanced.
ReadOnlySpan<byte> algorithmIdentifier = algorithmIdentifierWriter.EncodeAsSpan();
ReadOnlySpan<byte> privateKey = privateKeyWriter.EncodeAsSpan();
Debug.Assert(algorithmIdentifier.Length > 0, "algorithmIdentifier was empty");
Debug.Assert(algorithmIdentifier[0] == 0x30, "algorithmIdentifier is not a constructed sequence");
Debug.Assert(privateKey.Length > 0, "privateKey was empty");
// https://tools.ietf.org/html/rfc5208#section-5
//
// PrivateKeyInfo ::= SEQUENCE {
// version Version,
// privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
// privateKey PrivateKey,
// attributes [0] IMPLICIT Attributes OPTIONAL }
//
// Version ::= INTEGER
// PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
// PrivateKey ::= OCTET STRING
AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);
// PrivateKeyInfo
writer.PushSequence();
// https://tools.ietf.org/html/rfc5208#section-5 says the current version is 0.
writer.WriteInteger(0);
// PKI.Algorithm (AlgorithmIdentifier)
writer.WriteEncodedValue(algorithmIdentifier);
// PKI.privateKey
writer.WriteOctetString(privateKey);
// PKI.Attributes
if (attributesWriter != null)
{
ReadOnlySpan<byte> attributes = attributesWriter.EncodeAsSpan();
writer.WriteEncodedValue(attributes);
}
writer.PopSequence();
return writer;
}
internal static unsafe AsnWriter WriteEncryptedPkcs8(
ReadOnlySpan<char> password,
AsnWriter pkcs8Writer,
PbeParameters pbeParameters)
{
return WriteEncryptedPkcs8(
password,
ReadOnlySpan<byte>.Empty,
pkcs8Writer,
pbeParameters);
}
internal static AsnWriter WriteEncryptedPkcs8(
ReadOnlySpan<byte> passwordBytes,
AsnWriter pkcs8Writer,
PbeParameters pbeParameters)
{
return WriteEncryptedPkcs8(
ReadOnlySpan<char>.Empty,
passwordBytes,
pkcs8Writer,
pbeParameters);
}
private static unsafe AsnWriter WriteEncryptedPkcs8(
ReadOnlySpan<char> password,
ReadOnlySpan<byte> passwordBytes,
AsnWriter pkcs8Writer,
PbeParameters pbeParameters)
{
ReadOnlySpan<byte> pkcs8Span = pkcs8Writer.EncodeAsSpan();
PasswordBasedEncryption.InitiateEncryption(
pbeParameters,
out SymmetricAlgorithm cipher,
out string hmacOid,
out string encryptionAlgorithmOid,
out bool isPkcs12);
byte[]? encryptedRent = null;
Span<byte> encryptedSpan = default;
AsnWriter? writer = null;
try
{
Debug.Assert(cipher.BlockSize <= 128, $"Encountered unexpected block size: {cipher.BlockSize}");
Span<byte> iv = stackalloc byte[cipher.BlockSize / 8];
Span<byte> salt = stackalloc byte[16];
// We need at least one block size beyond the input data size.
encryptedRent = CryptoPool.Rent(
checked(pkcs8Span.Length + (cipher.BlockSize / 8)));
RandomNumberGenerator.Fill(salt);
int written = PasswordBasedEncryption.Encrypt(
password,
passwordBytes,
cipher,
isPkcs12,
pkcs8Span,
pbeParameters,
salt,
encryptedRent,
iv);
encryptedSpan = encryptedRent.AsSpan(0, written);
writer = new AsnWriter(AsnEncodingRules.DER);
// PKCS8 EncryptedPrivateKeyInfo
writer.PushSequence();
// EncryptedPrivateKeyInfo.encryptionAlgorithm
PasswordBasedEncryption.WritePbeAlgorithmIdentifier(
writer,
isPkcs12,
encryptionAlgorithmOid,
salt,
pbeParameters.IterationCount,
hmacOid,
iv);
// encryptedData
writer.WriteOctetString(encryptedSpan);
writer.PopSequence();
AsnWriter ret = writer;
// Don't dispose writer on the way out.
writer = null;
return ret;
}
finally
{
CryptographicOperations.ZeroMemory(encryptedSpan);
CryptoPool.Return(encryptedRent!, clearSize: 0);
writer?.Dispose();
cipher.Dispose();
}
}
internal static ArraySegment<byte> DecryptPkcs8(
ReadOnlySpan<char> inputPassword,
ReadOnlyMemory<byte> source,
out int bytesRead)
{
return DecryptPkcs8(
inputPassword,
ReadOnlySpan<byte>.Empty,
source,
out bytesRead);
}
internal static ArraySegment<byte> DecryptPkcs8(
ReadOnlySpan<byte> inputPasswordBytes,
ReadOnlyMemory<byte> source,
out int bytesRead)
{
return DecryptPkcs8(
ReadOnlySpan<char>.Empty,
inputPasswordBytes,
source,
out bytesRead);
}
private static ArraySegment<byte> DecryptPkcs8(
ReadOnlySpan<char> inputPassword,
ReadOnlySpan<byte> inputPasswordBytes,
ReadOnlyMemory<byte> source,
out int bytesRead)
{
AsnValueReader reader = new AsnValueReader(source.Span, AsnEncodingRules.BER);
int localRead = reader.PeekEncodedValue().Length;
EncryptedPrivateKeyInfoAsn.Decode(ref reader, source, out EncryptedPrivateKeyInfoAsn epki);
// No supported encryption algorithms produce more bytes of decryption output than there
// were of decryption input.
byte[] decrypted = CryptoPool.Rent(epki.EncryptedData.Length);
try
{
int decryptedBytes = PasswordBasedEncryption.Decrypt(
epki.EncryptionAlgorithm,
inputPassword,
inputPasswordBytes,
epki.EncryptedData.Span,
decrypted);
bytesRead = localRead;
return new ArraySegment<byte>(decrypted, 0, decryptedBytes);
}
catch (CryptographicException e)
{
CryptoPool.Return(decrypted);
throw new CryptographicException(SR.Cryptography_Pkcs8_EncryptedReadFailed, e);
}
}
internal static AsnWriter ReencryptPkcs8(
ReadOnlySpan<char> inputPassword,
ReadOnlyMemory<byte> current,
ReadOnlySpan<char> newPassword,
PbeParameters pbeParameters)
{
ArraySegment<byte> decrypted = DecryptPkcs8(
inputPassword,
current,
out int bytesRead);
try
{
if (bytesRead != current.Length)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
using (AsnWriter pkcs8Writer = new AsnWriter(AsnEncodingRules.BER))
{
pkcs8Writer.WriteEncodedValue(decrypted);
return WriteEncryptedPkcs8(
newPassword,
pkcs8Writer,
pbeParameters);
}
}
catch (CryptographicException e)
{
throw new CryptographicException(SR.Cryptography_Pkcs8_EncryptedReadFailed, e);
}
finally
{
CryptographicOperations.ZeroMemory(decrypted);
CryptoPool.Return(decrypted.Array!, clearSize: 0);
}
}
internal static AsnWriter ReencryptPkcs8(
ReadOnlySpan<char> inputPassword,
ReadOnlyMemory<byte> current,
ReadOnlySpan<byte> newPasswordBytes,
PbeParameters pbeParameters)
{
ArraySegment<byte> decrypted = DecryptPkcs8(
inputPassword,
current,
out int bytesRead);
try
{
if (bytesRead != current.Length)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
using (AsnWriter pkcs8Writer = new AsnWriter(AsnEncodingRules.BER))
{
pkcs8Writer.WriteEncodedValue(decrypted);
return WriteEncryptedPkcs8(
newPasswordBytes,
pkcs8Writer,
pbeParameters);
}
}
catch (CryptographicException e)
{
throw new CryptographicException(SR.Cryptography_Pkcs8_EncryptedReadFailed, e);
}
finally
{
CryptographicOperations.ZeroMemory(decrypted);
CryptoPool.Return(decrypted.Array!, clearSize: 0);
}
}
}
}
| 36.12523 | 120 | 0.550673 | [
"MIT"
] | 1shekhar/runtime | src/libraries/Common/src/System/Security/Cryptography/KeyFormatHelper.cs | 19,616 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace ModernSlavery.Hosts.IdServer.Models
{
public class ProcessConsentResult
{
public bool IsRedirect => RedirectUri != null;
public string RedirectUri { get; set; }
public bool ShowView => ViewModel != null;
public ConsentViewModel ViewModel { get; set; }
public bool HasValidationError => ValidationError != null;
public string ValidationError { get; set; }
}
} | 33.833333 | 107 | 0.688013 | [
"MIT"
] | UKHomeOffice/Modern-Slavery-Alpha | ModernSlavery.Hosts.IdServer/Models/ProcessConsentResult.cs | 611 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SuperDevStore
{
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
} | 18.470588 | 60 | 0.687898 | [
"MIT"
] | GoncaloRod/SuperDevStore | SuperDevStore/Index.aspx.cs | 316 | C# |
using System;
using System.Linq;
namespace _05.AppliedArithmetics
{
class Program
{
static void Main()
{
var numbers = Console.ReadLine().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
string command = "";
Func<int, int> addition = x => x += 1;
Func<int, int> subtract = x => x -= 1;
Func<int, int> multiply = x => x *= 2;
Action<int[]> print = x => Console.WriteLine(string.Join(" ", x));
while ((command = Console.ReadLine()) != "end")
{
switch (command)
{
case "add":
numbers = numbers.Select(addition).ToArray();
break;
case "subtract":
numbers = numbers.Select(subtract).ToArray();
break;
case "multiply":
numbers = numbers.Select(multiply).ToArray();
break;
case "print":
print(numbers);
break;
}
}
}
}
}
| 30.071429 | 111 | 0.408551 | [
"MIT"
] | spacex13/CSharp-Fundamentals | CSharp-Advanced/FunctionalProgramming-Exercises/05.AppliedArithmetics/Program.cs | 1,265 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("06. TargetPractice")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("06. TargetPractice")]
[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("f2395b41-843f-45b3-97b2-5ea2b521b0af")]
// 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")]
| 38.081081 | 84 | 0.7445 | [
"MIT"
] | nikolaydechev/CSharp-Advanced | 03 Matrices/06. TargetPractice/Properties/AssemblyInfo.cs | 1,412 | C# |
using System;
using System.Collections.Generic;
namespace UnityEngine.Experimental.Rendering.RenderGraphModule
{
/// <summary>
/// Helper class provided in the RenderGraphContext to all Render Passes.
/// It allows you to do temporary allocations of various objects during a Render Pass.
/// </summary>
public sealed class RenderGraphObjectPool
{
class SharedObjectPool<T> where T : new()
{
Stack<T> m_Pool = new Stack<T>();
public T Get()
{
var result = m_Pool.Count == 0 ? new T() : m_Pool.Pop();
return result;
}
public void Release(T value)
{
m_Pool.Push(value);
}
static readonly Lazy<SharedObjectPool<T>> s_Instance = new Lazy<SharedObjectPool<T>>();
public static SharedObjectPool<T> sharedPool => s_Instance.Value;
}
Dictionary<(Type, int), Stack<object>> m_ArrayPool = new Dictionary<(Type, int), Stack<object>>();
List<(object, (Type, int))> m_AllocatedArrays = new List<(object, (Type, int))>();
List<MaterialPropertyBlock> m_AllocatedMaterialPropertyBlocks = new List<MaterialPropertyBlock>();
internal RenderGraphObjectPool() { }
/// <summary>
/// Allocate a temporary typed array of a specific size.
/// Unity releases the array at the end of the Render Pass.
/// </summary>
/// <typeparam name="T">Type of the array to be allocated.</typeparam>
/// <param name="size">Number of element in the array.</param>
/// <returns>A new array of type T with size number of elements.</returns>
public T[] GetTempArray<T>(int size)
{
if (!m_ArrayPool.TryGetValue((typeof(T), size), out var stack))
{
stack = new Stack<object>();
m_ArrayPool.Add((typeof(T), size), stack);
}
var result = stack.Count > 0 ? (T[])stack.Pop() : new T[size];
m_AllocatedArrays.Add((result, (typeof(T), size)));
return result;
}
/// <summary>
/// Allocate a temporary MaterialPropertyBlock for the Render Pass.
/// </summary>
/// <returns>A new clean MaterialPropertyBlock.</returns>
public MaterialPropertyBlock GetTempMaterialPropertyBlock()
{
var result = SharedObjectPool<MaterialPropertyBlock>.sharedPool.Get();
result.Clear();
m_AllocatedMaterialPropertyBlocks.Add(result);
return result;
}
internal void ReleaseAllTempAlloc()
{
foreach(var arrayDesc in m_AllocatedArrays)
{
bool result = m_ArrayPool.TryGetValue(arrayDesc.Item2, out var stack);
Debug.Assert(result, "Correct stack type should always be allocated.");
stack.Push(arrayDesc.Item1);
}
m_AllocatedArrays.Clear();
foreach(var mpb in m_AllocatedMaterialPropertyBlocks)
{
SharedObjectPool<MaterialPropertyBlock>.sharedPool.Release(mpb);
}
m_AllocatedMaterialPropertyBlocks.Clear();
}
// Regular pooling API. Only internal use for now
internal T Get<T>() where T : new()
{
var toto = SharedObjectPool<T>.sharedPool;
return toto.Get();
}
internal void Release<T>(T value) where T : new()
{
var toto = SharedObjectPool<T>.sharedPool;
toto.Release(value);
}
}
}
| 35.882353 | 118 | 0.572404 | [
"MIT"
] | Agameofscones/2d_slipsworth_sim | 2d_Slipsworth_Sim/Library/PackageCache/com.unity.render-pipelines.core@7.3.1/Runtime/RenderGraph/RenderGraphObjectPool.cs | 3,660 | C# |
using VaultLib.Core.Types;
namespace VaultLib.Support.World.VLT.Csis
{
[VLTTypeInfo("Csis::Type_P_Breaker_Code")]
public enum Type_P_Breaker_Code
{
Invalid_Type_P_Breaker_Code = 0x0,
Type_P_Breaker_Code_CODE_A = 0x1,
Type_P_Breaker_Code_CODE_B = 0x2,
Type_P_Breaker_Code_CODE_C = 0x4,
Type_P_Breaker_Code_CODE_D = 0x8,
Type_P_Breaker_Code_CODE_E = 0x10,
Type_P_Breaker_Code_CODE_F = 0x20,
Type_P_Breaker_Code_CODE_G = 0x40,
Type_P_Breaker_Code_CODE_H = 0x80,
Type_P_Breaker_Code_CODE_I = 0x100,
Type_P_Breaker_Code_CODE_J = 0x200,
}
}
| 30.52381 | 46 | 0.700468 | [
"MIT"
] | BreakinBenny/VaultLib | VaultLib.Support.World/VLT/Csis/Type_P_Breaker_Code.cs | 643 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using WebXR;
public class SmoothLocomotion : MonoBehaviour
{
public bool fly = false;
public float speed = 1.0f;
public float scale = 0.01f;
private GameObject player;
private WebXRCamera cameraGroup;
private Transform camera;
private WebXRController controller;
private Vector3 moveVector = new Vector3();
private Quaternion orientation = new Quaternion();
private Vector3 orientationEuler = new Vector3();
// Start is called before the first frame update
void Start()
{
player = WebXRManager.Instance.gameObject;
cameraGroup = WebXRManager.Instance.GetComponentInChildren<WebXRCamera>();
camera = cameraGroup.transform.GetChild(cameraGroup.transform.childCount - 1);
controller = GetComponent<WebXRController>();
}
// Update is called once per frame
void Update()
{
Move();
}
private void Move()
{
moveVector.Set(0, 0, 0);
// Get input vector from controller
Vector2 axes = controller.GetAxis2D(WebXRController.Axis2DTypes.Thumbstick);
if (axes.magnitude < 0.1f) return;
// Get our initial move vector and normalize it
axes.Normalize();
// If we don't want to fly, this zeroes out any movement that isn't side-to-side
float rotation = Mathf.Atan2(axes.x, axes.y) * Mathf.Rad2Deg;
if (!fly) orientation = Quaternion.Euler(0, camera.rotation.eulerAngles.y + rotation, 0);
// Adjust our vector based on where we're looking
moveVector += orientation * Vector3.forward;
// Scale movement vector
moveVector.x *= scale;
moveVector.y *= scale;
moveVector.z *= scale;
// Move the player
player.transform.Translate(moveVector);
}
}
| 33.357143 | 97 | 0.664347 | [
"MIT"
] | marianydesign/Unity-WebXR-Teleportation-and-SmoothLocomotion | Assets/Scripts/SmoothLocomotion.cs | 1,868 | 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("SumOfOddDivisors")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SumOfOddDivisors")]
[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("31810bf4-597d-4acb-893e-3ce0931900af")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.837838 | 84 | 0.749286 | [
"MIT"
] | SimeonGerginov/Telerik-Academy | 01. C# I/Exams/2016-04-26/SumOfOddDivisors/Properties/AssemblyInfo.cs | 1,403 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Bam.Net.Data.Schema;
using Bam.Net.Data.MsSql;
using System.IO;
using System.CodeDom.Compiler;
using System.Reflection;
using Bam.Net.CoreServices;
namespace Bam.Net.Data.Dynamic
{
public partial class DaoAssemblyGenerator
{
public DaoAssemblyGenerator(SchemaExtractor schemaExtractor, string workspacePath = null)
{
this.SchemaExtractor = schemaExtractor ?? ServiceRegistry.Default.Get<ISchemaExtractor>();
this.ReferenceAssemblies = new Assembly[] { };
this._referenceAssemblyPaths = new List<string>(AdHocCSharpCompiler.DefaultReferenceAssemblies);
this.Workspace = workspacePath ?? ".";
}
}
}
| 29.851852 | 108 | 0.722084 | [
"MIT"
] | BryanApellanes/Bam.Net.Data.Dynamic | _Dynamic/DaoAssemblyGenerator.cs | 808 | C# |
using Sandbox;
using Sandbox.UI;
using Sandbox.UI.Construct;
using System;
using System.Linq;
namespace SWB_Base
{
/// <summary>
/// A horizontal slider. Can be float or whole number.
/// </summary>
public class Slider : Panel
{
public Panel Track { get; protected set; }
public Panel TrackInner { get; protected set; }
public Panel Thumb { get; protected set; }
public Label Name { get; protected set; }
public float Sensitivity { get; protected set; } = 1;
/// <summary>
/// The right side of the slider
/// </summary>
public float MaxValue { get; set; } = 100;
/// <summary>
/// The left side of the slider
/// </summary>
public float MinValue { get; set; } = 0;
/// <summary>
/// If set to 1, value will be rounded to 1's
/// If set to 10, value will be rounded to 10's
/// If set to 0.1, value will be rounded to 0.1's
/// </summary>
public float Step { get; set; } = 1.0f;
public Slider()
{
StyleSheet.Load("/swb_base/editor/ui/components/Slider.scss");
Name = Add.Label(null, "name");
var sliderContainer = Add.Panel("sliderContainer");
Track = sliderContainer.Add.Panel("track");
TrackInner = Track.Add.Panel("inner");
Thumb = sliderContainer.Add.Panel("thumb");
}
protected float _value = float.MaxValue;
/// <summary>
/// The actual value. Setting the value will snap and clamp it.
/// </summary>
public float Value
{
get => _value.Clamp(MinValue, MaxValue);
set
{
var snapped = Step > 0 ? value.SnapToGrid(Step) : value;
snapped = snapped.Clamp(MinValue, MaxValue);
if (_value == snapped) return;
_value = snapped;
CreateEvent("onchange");
CreateValueEvent("value", _value);
UpdateSliderPositions();
}
}
public override void SetProperty(string name, string value)
{
if (name == "min" && float.TryParse(value, out var floatValue))
{
MinValue = floatValue;
UpdateSliderPositions();
return;
}
if (name == "step" && float.TryParse(value, out floatValue))
{
Step = floatValue;
UpdateSliderPositions();
return;
}
if (name == "max" && float.TryParse(value, out floatValue))
{
MaxValue = floatValue;
UpdateSliderPositions();
return;
}
if (name == "value" && float.TryParse(value, out floatValue))
{
Value = floatValue;
return;
}
if (name == "name")
{
Name.Text = value;
Name.Style.Display = DisplayMode.Flex;
return;
}
if (name == "sensitivity" && float.TryParse(value, out floatValue))
{
Sensitivity = floatValue;
}
base.SetProperty(name, value);
}
/// <summary>
/// Convert a screen position to a value. The value is clamped, but not snapped.
/// </summary>
public virtual float ScreenPosToValue(Vector2 pos)
{
var localPos = ScreenPositionToPanelPosition(pos);
var thumbSize = Thumb.Box.Rect.width * 0.5f;
var normalized = MathX.LerpInverse(localPos.x, thumbSize, (Box.Rect.width - thumbSize), true);
var scaled = MathX.LerpTo(MinValue, MaxValue, normalized, true);
return Step > 0 ? scaled.SnapToGrid(Step) : scaled;
}
/// <summary>
/// If we move the mouse while we're being pressed then set the position,
/// but skip transitions.
/// </summary>
protected override void OnMouseMove(MousePanelEvent e)
{
base.OnMouseMove(e);
if (!HasActive) return;
Value = ScreenPosToValue(Mouse.Position);
UpdateSliderPositions();
SkipTransitions();
e.StopPropagation();
}
/// <summary>
/// On mouse press jump to that position
/// </summary>
protected override void OnMouseDown(MousePanelEvent e)
{
base.OnMouseDown(e);
Value = ScreenPosToValue(Mouse.Position);
UpdateSliderPositions();
e.StopPropagation();
}
int positionHash;
/// <summary>
/// Updates the styles for TrackInner and Thumb to position us based on the current value.
/// Note this purposely uses percentages instead of pixels when setting up, this way we don't
/// have to worry about parent size, screen scale etc.
/// </summary>
void UpdateSliderPositions()
{
var hash = HashCode.Combine(Value, MinValue, MaxValue);
if (hash == positionHash) return;
positionHash = hash;
var pos = MathX.LerpInverse(Value, MinValue, MaxValue, true);
TrackInner.Style.Width = Length.Fraction(pos);
Thumb.Style.Left = Length.Fraction(pos);
TrackInner.Style.Dirty();
Thumb.Style.Dirty();
}
}
namespace Construct
{
public static class SliderConstructor
{
public static Slider Slider(this PanelCreator self, float min, float max, float step, string name = "")
{
var control = self.panel.AddChild<Slider>();
control.MinValue = min;
control.MaxValue = max;
control.Step = step;
control.Name.Text = name;
return control;
}
}
}
}
| 30.255 | 115 | 0.520906 | [
"MIT"
] | BullyHunter32/simple-weapon-base | code/swb_base/editor/ui/components/Slider.cs | 6,053 | C# |
// EuropeanOptionFactory.cs
//
// Classes for creating Eurpean Options. This is
// a Factory Method pattern.
//
// (C) Datasim Education BV 2005-2013
using System;
public interface IOptionFactory
{
Option create();
}
public class ConsoleEuropeanOptionFactory: IOptionFactory
{
public Option create()
{
Console.Write( "\n*** Parameters for option object ***\n");
Option opt = new Option();
Console.Write( "Strike: ");
opt.K = Convert.ToDouble(Console.ReadLine());
Console.Write( "Volatility: ");
opt.sig = Convert.ToDouble(Console.ReadLine());
Console.Write( "Interest rate: ");
opt.r = Convert.ToDouble(Console.ReadLine());
Console.Write( "Expiry date: ");
opt.T = Convert.ToDouble(Console.ReadLine());
Console.Write( "1. Call, 2. Put: ");
opt.type = Convert.ToInt32(Console.ReadLine());
return opt;
}
}
| 19.3125 | 63 | 0.624595 | [
"MIT"
] | jdm7dv/financial | windows/CsForFinancialMarkets/CsForFinancialMarkets/BookExamples/Ch9/LatticeMethodsSourceCode/OneFactorBinomial/EuropeanOptionFactory.cs | 927 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Web.Syndication
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
#endif
public partial class SyndicationContent : global::Windows.Web.Syndication.ISyndicationText,global::Windows.Web.Syndication.ISyndicationNode
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public global::System.Uri SourceUri
{
get
{
throw new global::System.NotImplementedException("The member Uri SyndicationContent.SourceUri is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Web.Syndication.SyndicationContent", "Uri SyndicationContent.SourceUri");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public string NodeValue
{
get
{
throw new global::System.NotImplementedException("The member string SyndicationContent.NodeValue is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Web.Syndication.SyndicationContent", "string SyndicationContent.NodeValue");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public global::System.Uri BaseUri
{
get
{
throw new global::System.NotImplementedException("The member Uri SyndicationContent.BaseUri is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Web.Syndication.SyndicationContent", "Uri SyndicationContent.BaseUri");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public string Language
{
get
{
throw new global::System.NotImplementedException("The member string SyndicationContent.Language is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Web.Syndication.SyndicationContent", "string SyndicationContent.Language");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public string NodeName
{
get
{
throw new global::System.NotImplementedException("The member string SyndicationContent.NodeName is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Web.Syndication.SyndicationContent", "string SyndicationContent.NodeName");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public string NodeNamespace
{
get
{
throw new global::System.NotImplementedException("The member string SyndicationContent.NodeNamespace is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Web.Syndication.SyndicationContent", "string SyndicationContent.NodeNamespace");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public global::System.Collections.Generic.IList<global::Windows.Web.Syndication.SyndicationAttribute> AttributeExtensions
{
get
{
throw new global::System.NotImplementedException("The member IList<SyndicationAttribute> SyndicationContent.AttributeExtensions is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public global::System.Collections.Generic.IList<global::Windows.Web.Syndication.ISyndicationNode> ElementExtensions
{
get
{
throw new global::System.NotImplementedException("The member IList<ISyndicationNode> SyndicationContent.ElementExtensions is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public string Text
{
get
{
throw new global::System.NotImplementedException("The member string SyndicationContent.Text is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Web.Syndication.SyndicationContent", "string SyndicationContent.Text");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public string Type
{
get
{
throw new global::System.NotImplementedException("The member string SyndicationContent.Type is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Web.Syndication.SyndicationContent", "string SyndicationContent.Type");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public global::Windows.Data.Xml.Dom.XmlDocument Xml
{
get
{
throw new global::System.NotImplementedException("The member XmlDocument SyndicationContent.Xml is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Web.Syndication.SyndicationContent", "XmlDocument SyndicationContent.Xml");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public SyndicationContent( string text, global::Windows.Web.Syndication.SyndicationTextType type)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Web.Syndication.SyndicationContent", "SyndicationContent.SyndicationContent(string text, SyndicationTextType type)");
}
#endif
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.SyndicationContent(string, Windows.Web.Syndication.SyndicationTextType)
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public SyndicationContent( global::System.Uri sourceUri)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Web.Syndication.SyndicationContent", "SyndicationContent.SyndicationContent(Uri sourceUri)");
}
#endif
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.SyndicationContent(System.Uri)
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public SyndicationContent()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Web.Syndication.SyndicationContent", "SyndicationContent.SyndicationContent()");
}
#endif
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.SyndicationContent()
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.Text.get
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.Text.set
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.Type.get
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.Type.set
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.Xml.get
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.Xml.set
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.NodeName.get
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.NodeName.set
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.NodeNamespace.get
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.NodeNamespace.set
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.NodeValue.get
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.NodeValue.set
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.Language.get
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.Language.set
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.BaseUri.get
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.BaseUri.set
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.AttributeExtensions.get
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.ElementExtensions.get
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public global::Windows.Data.Xml.Dom.XmlDocument GetXmlDocument( global::Windows.Web.Syndication.SyndicationFormat format)
{
throw new global::System.NotImplementedException("The member XmlDocument SyndicationContent.GetXmlDocument(SyndicationFormat format) is not implemented in Uno.");
}
#endif
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.SourceUri.get
// Forced skipping of method Windows.Web.Syndication.SyndicationContent.SourceUri.set
// Processing: Windows.Web.Syndication.ISyndicationText
// Processing: Windows.Web.Syndication.ISyndicationNode
}
}
| 42.151659 | 203 | 0.767933 | [
"Apache-2.0"
] | nv-ksavaria/Uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Web.Syndication/SyndicationContent.cs | 8,894 | C# |
namespace MassTransit.Serialization
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Context;
using Metadata;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class JsonConsumeContext :
DeserializerConsumeContext
{
readonly JsonSerializer _deserializer;
readonly MessageEnvelope _envelope;
readonly JToken _messageToken;
readonly IDictionary<Type, ConsumeContext> _messageTypes;
readonly string[] _supportedTypes;
Guid? _conversationId;
Guid? _correlationId;
Uri _destinationAddress;
Uri _faultAddress;
Headers _headers;
Guid? _initiatorId;
Guid? _messageId;
Guid? _requestId;
Uri _responseAddress;
Uri _sourceAddress;
public JsonConsumeContext(JsonSerializer deserializer, ReceiveContext receiveContext, MessageEnvelope envelope)
: base(receiveContext)
{
if (envelope == null)
throw new ArgumentNullException(nameof(envelope));
_envelope = envelope;
_deserializer = deserializer;
_messageToken = GetMessageToken(envelope.Message);
_supportedTypes = envelope.MessageType.ToArray();
_messageTypes = new Dictionary<Type, ConsumeContext>();
}
public override Guid? MessageId => _messageId ??= ConvertIdToGuid(_envelope.MessageId);
public override Guid? RequestId => _requestId ??= ConvertIdToGuid(_envelope.RequestId);
public override Guid? CorrelationId => _correlationId ??= ConvertIdToGuid(_envelope.CorrelationId);
public override Guid? ConversationId => _conversationId ??= ConvertIdToGuid(_envelope.ConversationId);
public override Guid? InitiatorId => _initiatorId ??= ConvertIdToGuid(_envelope.InitiatorId);
public override DateTime? ExpirationTime => _envelope.ExpirationTime;
public override Uri SourceAddress => _sourceAddress ??= ConvertToUri(_envelope.SourceAddress);
public override Uri DestinationAddress => _destinationAddress ??= ConvertToUri(_envelope.DestinationAddress);
public override Uri ResponseAddress => _responseAddress ??= ConvertToUri(_envelope.ResponseAddress);
public override Uri FaultAddress => _faultAddress ??= ConvertToUri(_envelope.FaultAddress);
public override DateTime? SentTime => _envelope.SentTime;
public override Headers Headers =>
_headers ??= _envelope.Headers != null ? (Headers)new JsonEnvelopeHeaders(_envelope.Headers) : NoMessageHeaders.Instance;
public override HostInfo Host => _envelope.Host;
public override IEnumerable<string> SupportedMessageTypes => _supportedTypes;
public override bool HasMessageType(Type messageType)
{
lock (_messageTypes)
{
if (_messageTypes.TryGetValue(messageType, out var existing))
return existing != null;
}
string typeUrn = MessageUrn.ForTypeString(messageType);
return _supportedTypes.Any(x => typeUrn.Equals(x, StringComparison.OrdinalIgnoreCase));
}
public override bool TryGetMessage<T>(out ConsumeContext<T> message)
{
lock (_messageTypes)
{
if (_messageTypes.TryGetValue(typeof(T), out var existing))
{
message = existing as ConsumeContext<T>;
return message != null;
}
if (typeof(T) == typeof(JToken))
{
_messageTypes[typeof(T)] = message = new MessageConsumeContext<T>(this, _messageToken as T);
return true;
}
string typeUrn = MessageUrn.ForTypeString<T>();
if (_supportedTypes.Any(x => typeUrn.Equals(x, StringComparison.OrdinalIgnoreCase)))
{
object obj;
Type deserializeType = typeof(T);
if (deserializeType.GetTypeInfo().IsInterface && TypeMetadataCache<T>.IsValidMessageType)
deserializeType = TypeMetadataCache<T>.ImplementationType;
using (JsonReader jsonReader = _messageToken.CreateReader())
{
obj = _deserializer.Deserialize(jsonReader, deserializeType);
}
_messageTypes[typeof(T)] = message = new MessageConsumeContext<T>(this, (T)obj);
return true;
}
_messageTypes[typeof(T)] = message = null;
return false;
}
}
static JToken GetMessageToken(object message)
{
var messageToken = message as JToken;
if (messageToken == null || messageToken.Type == JTokenType.Null)
return new JObject();
return messageToken;
}
/// <summary>
/// Converts a string identifier to a Guid, if it is actually a Guid. Can throw a FormatException
/// if things are not right
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
static Guid? ConvertIdToGuid(string id)
{
if (string.IsNullOrWhiteSpace(id))
return default;
if (Guid.TryParse(id, out var messageId))
return messageId;
throw new FormatException("The Id was not a Guid: " + id);
}
/// <summary>
/// Convert the string to a Uri, or return null if it is empty
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
static Uri ConvertToUri(string uri)
{
if (string.IsNullOrWhiteSpace(uri))
return null;
return new Uri(uri);
}
}
}
| 39.423077 | 134 | 0.585366 | [
"ECL-2.0",
"Apache-2.0"
] | CodeNotFoundException/MassTransit | src/MassTransit/Serialization/JsonConsumeContext.cs | 6,150 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Invoices.DataAccess;
namespace Invoices.DataAccess.Sql
{
/// <summary>
/// DAL SQL Server implementation of <see cref="IProductTypeCollDal"/>
/// </summary>
public partial class ProductTypeCollDal : IProductTypeCollDal
{
#region DAL methods
/// <summary>
/// Loads a ProductTypeColl collection from the database.
/// </summary>
/// <returns>A list of <see cref="ProductTypeItemDto"/>.</returns>
public List<ProductTypeItemDto> Fetch()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices"))
{
using (var cmd = new SqlCommand("dbo.GetProductTypeColl", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
var dr = cmd.ExecuteReader();
return LoadCollection(dr);
}
}
}
private List<ProductTypeItemDto> LoadCollection(IDataReader data)
{
var productTypeColl = new List<ProductTypeItemDto>();
using (var dr = new SafeDataReader(data))
{
while (dr.Read())
{
productTypeColl.Add(Fetch(dr));
}
}
return productTypeColl;
}
private ProductTypeItemDto Fetch(SafeDataReader dr)
{
var productTypeItem = new ProductTypeItemDto();
// Value properties
productTypeItem.ProductTypeId = dr.GetInt32("ProductTypeId");
productTypeItem.Name = dr.GetString("Name");
return productTypeItem;
}
#endregion
}
}
| 30.079365 | 91 | 0.546702 | [
"MIT"
] | CslaGenFork/CslaGenFork | trunk/CoverageTest/Invoices-CS-DAL-DTO-INT64/Invoices.DataAccess.Sql/ProductTypeCollDal.Designer.cs | 1,895 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Общие сведения об этой сборке предоставляются следующим набором
// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
// связанные с этой сборкой.
[assembly: AssemblyTitle("ExcFilters")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ExcFilters")]
[assembly: AssemblyCopyright("shuryak © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
// из модели COM задайте для атрибута ComVisible этого типа значение true.
[assembly: ComVisible(false)]
// Следующий GUID представляет идентификатор typelib, если этот проект доступен из модели COM
[assembly: Guid("c9ea32af-6a35-4dee-8342-069a6d7c0d1d")]
// Сведения о версии сборки состоят из указанных ниже четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Номер редакции
//
// Можно задать все значения или принять номера сборки и редакции по умолчанию
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.756757 | 93 | 0.763598 | [
"MIT"
] | shuryak/csharp-learning | Exceptions/Exception filters/ExcFilters/Properties/AssemblyInfo.cs | 2,018 | C# |
// Copyright 2020 Google LLC
//
// 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 Google.Ads.GoogleAds.Interceptors;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.Tests.V8;
using Google.Ads.GoogleAds.V8.Errors;
using Grpc.Core;
using NUnit.Framework;
using System;
using System.Threading.Tasks;
namespace Google.Ads.GoogleAds.Tests.Interceptors
{
/// <summary>
/// Tests for <see cref="UnaryRpcInterceptor"/> class.
/// </summary>
[TestFixture]
[Category("Smoke")]
internal class UnaryRpcInterceptorTests
{
/// <summary>
/// The exception object for testing purposes.
/// </summary>
private static readonly RpcException TEST_EXCEPTION = TestUtils.CreateException(
"Test message", "Test trigger", "request-id");
/// <summary>
/// A test function delegate that raises an exception.
/// </summary>
private static Func<int> throwExceptionFunc = () => { throw TEST_EXCEPTION; };
/// <summary>
/// A test function delegate that returns a result without raising an exception.
/// </summary>
private static Func<int> returnIntFunc = () => { return 42; };
/// <summary>
/// A test action delegate that raises an exception.
/// </summary>
private static Action throwExceptionAction = () => { throw TEST_EXCEPTION; };
/// <summary>
/// A test function delegate that returns without raising an exception.
/// </summary>
private static Action returnAction = () => { return; };
/// <summary>
/// Tests if a task that returns a result without raising exception is intercepted
/// correctly.
/// </summary>
[Test]
public void TestInterceptTaskNoException()
{
Task<int> interceptedTask = UnaryRpcInterceptor.Intercept(Task.Run(returnIntFunc));
Assert.DoesNotThrow(delegate ()
{
interceptedTask.Wait();
});
}
/// <summary>
/// Tests if a task that raises an exception is intercepted correctly.
/// </summary>
[Test]
public void TestInterceptTaskWithException()
{
Task<int> interceptedTask = UnaryRpcInterceptor.Intercept(
Task.Run(throwExceptionFunc));
try
{
interceptedTask.Wait();
}
catch (AggregateException ae)
{
CheckForGoogleAdsException(ae);
}
}
/// <summary>
/// Tests if a function delegate that returns results without raising an exception is
/// intercepted correctly.
/// </summary>
[Test]
public void TestInterceptFuncDelegateNoException()
{
Func<int> interceptedFunc = UnaryRpcInterceptor.Intercept(returnIntFunc);
Assert.DoesNotThrow(delegate ()
{
interceptedFunc();
});
}
/// <summary>
/// Tests if a function delegate that throws an exception is intercepted correctly.
/// </summary>
[Test]
public void TestInterceptFuncDelegateWithException()
{
Func<int> interceptedFunc = UnaryRpcInterceptor.Intercept(throwExceptionFunc);
try
{
interceptedFunc();
}
catch (GoogleAdsException)
{
Assert.Pass("Exception parsed correctly.");
}
catch
{
Assert.Pass("Exception could not be parsed.");
}
}
/// <summary>
/// Tests if an action delegate that raises no exception is intercepted correctly.
/// </summary>
[Test]
public void TestInterceptActionNoException()
{
Action interceptedAction = UnaryRpcInterceptor.Intercept(returnAction);
Assert.DoesNotThrow(delegate ()
{
interceptedAction();
});
}
/// <summary>
/// Tests if an action delegate that raises an exception is intercepted correctly.
/// </summary>
[Test]
public void TestInterceptActionWithException()
{
Action interceptedTask = UnaryRpcInterceptor.Intercept(throwExceptionAction);
try
{
interceptedTask();
}
catch (GoogleAdsException)
{
Assert.Pass("Exception parsed correctly.");
}
catch
{
Assert.Pass("Exception could not be parsed.");
}
}
/// <summary>
/// Tests for <see cref="UnaryRpcInterceptor.ParseRpcException(RpcException)"/>
/// method.
/// </summary>
[Test]
public void TestParseRpcException()
{
Assert.NotNull(UnaryRpcInterceptor.ParseRpcException(TEST_EXCEPTION));
}
/// <summary>
/// Tests for <see cref="UnaryRpcInterceptor.ParseTaskException(RpcException)"/>
/// method.
/// </summary>
[Test]
public void TestParseTaskException()
{
Assert.NotNull(UnaryRpcInterceptor.ParseTaskException(
new AggregateException(TEST_EXCEPTION)));
}
/// <summary>
/// Tests for <see cref="UnaryRpcInterceptor.ExtractRpcException(AggregateException)"/>
/// method.
/// </summary>
[Test]
public void TestExtractRpcException()
{
AggregateException ae = new AggregateException(TEST_EXCEPTION);
RpcException innerException = UnaryRpcInterceptor.ExtractRpcException(ae);
Assert.IsInstanceOf<GoogleAdsBaseException>(innerException);
}
/// <summary>
/// Checks for a <see cref="GoogleAdsException"/> in an <see cref="AggregateException"/>.
/// </summary>
/// <param name="ae">The <see cref="AggregateException"/>.</param>
private static void CheckForGoogleAdsException(AggregateException ae)
{
bool found = false;
foreach (var ex in ae.Flatten().InnerExceptions)
{
if (ex is GoogleAdsException)
{
found = true;
}
}
if (!found)
{
Assert.Fail("Missing exception.");
}
}
}
}
| 33 | 97 | 0.566978 | [
"Apache-2.0"
] | deni-skaraudio/google-ads-dotnet | tests/Interceptors/UnaryRpcInterceptorTests.cs | 7,064 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GUI_ConpleteTask : MonoBehaviour, ICompletedTask
{
[SerializeField]
private UnityEngine.UI.Button Btn_Request;
[SerializeField]
private GUIPrint_TournametsData _PrintData;
[SerializeField]
private RectTransform ExitButton;
public void OnCompletedTask()
{
Btn_Request.interactable = false;
LeanTween.scale(ExitButton, Vector3.one, .2f).setEaseInCirc();
_PrintData.UI_CallPrintData();
}
public void UI_ExitButton()
{
Application.Quit();
}
}
| 25.541667 | 70 | 0.711256 | [
"MIT"
] | idcpstark1992/Lists | Assets/Scripts/GUI_ConpleteTask.cs | 615 | C# |
/*
* LeagueClient
*
* 7.23.209.3517
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Text;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;
namespace LeagueClientApi.Model
{
/// <summary>
/// LolLoginLoginSessionWallet
/// </summary>
[DataContract]
public partial class LolLoginLoginSessionWallet : IEquatable<LolLoginLoginSessionWallet>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="LolLoginLoginSessionWallet" /> class.
/// </summary>
/// <param name="Ip">Ip.</param>
/// <param name="Rp">Rp.</param>
public LolLoginLoginSessionWallet(long? Ip = default(long?), long? Rp = default(long?))
{
this.Ip = Ip;
this.Rp = Rp;
}
/// <summary>
/// Gets or Sets Ip
/// </summary>
[DataMember(Name="ip", EmitDefaultValue=false)]
public long? Ip { get; set; }
/// <summary>
/// Gets or Sets Rp
/// </summary>
[DataMember(Name="rp", EmitDefaultValue=false)]
public long? Rp { 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 LolLoginLoginSessionWallet {\n");
sb.Append(" Ip: ").Append(Ip).Append("\n");
sb.Append(" Rp: ").Append(Rp).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, 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 LolLoginLoginSessionWallet);
}
/// <summary>
/// Returns true if LolLoginLoginSessionWallet instances are equal
/// </summary>
/// <param name="other">Instance of LolLoginLoginSessionWallet to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(LolLoginLoginSessionWallet other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Ip == other.Ip ||
this.Ip != null &&
this.Ip.Equals(other.Ip)
) &&
(
this.Rp == other.Rp ||
this.Rp != null &&
this.Rp.Equals(other.Rp)
);
}
/// <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.Ip != null)
hash = hash * 59 + this.Ip.GetHashCode();
if (this.Rp != null)
hash = hash * 59 + this.Rp.GetHashCode();
return hash;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 31.582734 | 140 | 0.530752 | [
"MIT"
] | wildbook/LeagueClientApi | Model/LolLoginLoginSessionWallet.cs | 4,390 | C# |
namespace ResXManager.Model
{
using System;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using TomsToolbox.Essentials;
/// <summary>
/// A type converter that converts an integer string to a boolean value.
/// </summary>
/// <remarks>
/// 0 means false, any other integer value true.
/// If the string can not be parsed, false.
/// </remarks>
public class JsonSerializerTypeConverter<T> : TypeConverter
where T : class
{
private readonly DataContractJsonSerializer _serializer = new(typeof(T));
/// <summary>
/// Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context.
/// </summary>
/// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param>
/// <param name="sourceType">A <see cref="Type"/> that represents the type you want to convert from.</param>
/// <returns>
/// true if this converter can perform the conversion; otherwise, false.
/// </returns>
public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType)
{
return sourceType == typeof(string);
}
/// <summary>
/// Returns whether this converter can convert the object to the specified type, using the specified context.
/// </summary>
/// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param>
/// <param name="destinationType">A <see cref="Type"/> that represents the type you want to convert to.</param>
/// <returns>
/// true if this converter can perform the conversion; otherwise, false.
/// </returns>
public override bool CanConvertTo(ITypeDescriptorContext? context, Type destinationType)
{
return destinationType == typeof(string);
}
/// <summary>
/// Converts the given object to the type of this converter, using the specified context and culture information.
/// </summary>
/// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param>
/// <param name="culture">The <see cref="CultureInfo"/> to use as the current culture.</param>
/// <param name="value">The <see cref="object"/> to convert.</param>
/// <returns>
/// An <see cref="object"/> that represents the converted value.
/// </returns>
/// <exception cref="NotSupportedException">The conversion cannot be performed. </exception>
public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo culture, object? value)
{
if (value is not string stringValue)
return null;
try
{
if (!stringValue.IsNullOrEmpty())
{
using (var stream = new MemoryStream())
{
var data = Encoding.Default.GetBytes(stringValue);
stream.Write(data, 0, data.Length);
stream.Seek(0, SeekOrigin.Begin);
return _serializer.ReadObject(stream);
}
}
}
catch (SerializationException)
{
}
return default(T);
}
/// <summary>
/// Converts the given value object to the specified type, using the specified context and culture information.
/// </summary>
/// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param>
/// <param name="culture">A <see cref="CultureInfo"/>. If null is passed, the current culture is assumed.</param>
/// <param name="value">The <see cref="object"/> to convert.</param>
/// <param name="destinationType">The <see cref="Type"/> to convert the <paramref name="value"/> parameter to.</param>
/// <returns>
/// An <see cref="object"/> that represents the converted value.
/// </returns>
/// <exception cref="ArgumentNullException">The <paramref name="destinationType"/> parameter is null. </exception>
/// <exception cref="NotSupportedException">The conversion cannot be performed. </exception>
public override object ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object value, Type? destinationType)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.GetType() != typeof(T))
throw new ArgumentException(typeof(T).Name + @" expected", nameof(value));
if (destinationType != typeof(string))
throw new InvalidOperationException(@"Only string conversion is supported.");
using (var stream = new MemoryStream())
{
_serializer.WriteObject(stream, value);
return Encoding.Default.GetString(stream.GetBuffer(), 0, (int)stream.Length);
}
}
}
}
| 45.680672 | 143 | 0.589956 | [
"MIT"
] | GeertvanHorrik/ResXResourceManager | src/ResXManager.Model/JsonSerializerTypeConverter.cs | 5,438 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace System.ComponentModel.DataAnnotations
{
/// <summary>
/// Validation attribute that executes a user-supplied method at runtime, using one of these signatures:
/// <para>
/// public static <see cref="ValidationResult" /> Method(object value) { ... }
/// </para>
/// <para>
/// public static <see cref="ValidationResult" /> Method(object value, <see cref="ValidationContext" /> context) {
/// ... }
/// </para>
/// <para>
/// The value can be strongly typed as type conversion will be attempted.
/// </para>
/// </summary>
/// <remarks>
/// This validation attribute is used to invoke custom logic to perform validation at runtime.
/// Like any other <see cref="ValidationAttribute" />, its <see cref="IsValid(object, ValidationContext)" />
/// method is invoked to perform validation. This implementation simply redirects that call to the method
/// identified by <see cref="Method" /> on a type identified by <see cref="ValidatorType" />
/// <para>
/// The supplied <see cref="ValidatorType" /> cannot be null, and it must be a public type.
/// </para>
/// <para>
/// The named <see cref="Method" /> must be public, static, return <see cref="ValidationResult" /> and take at
/// least one input parameter for the value to be validated. This value parameter may be strongly typed.
/// Type conversion will be attempted if clients pass in a value of a different type.
/// </para>
/// <para>
/// The <see cref="Method" /> may also declare an additional parameter of type <see cref="ValidationContext" />.
/// The <see cref="ValidationContext" /> parameter provides additional context the method may use to determine
/// the context in which it is being used.
/// </para>
/// <para>
/// If the method returns <see cref="ValidationResult" />.<see cref="ValidationResult.Success" />, that indicates
/// the given value is acceptable and validation passed.
/// Returning an instance of <see cref="ValidationResult" /> indicates that the value is not acceptable
/// and validation failed.
/// </para>
/// <para>
/// If the method returns a <see cref="ValidationResult" /> with a <c>null</c>
/// <see cref="ValidationResult.ErrorMessage" />
/// then the normal <see cref="ValidationAttribute.FormatErrorMessage" /> method will be called to compose the
/// error message.
/// </para>
/// </remarks>
[AttributeUsage(
AttributeTargets.Class
| AttributeTargets.Property
| AttributeTargets.Field
| AttributeTargets.Method
| AttributeTargets.Parameter,
AllowMultiple = true
)]
public sealed class CustomValidationAttribute : ValidationAttribute
{
#region Member Fields
private readonly Lazy<string?> _malformedErrorMessage;
private bool _isSingleArgumentMethod;
private string? _lastMessage;
private MethodInfo? _methodInfo;
private Type? _firstParameterType;
private Tuple<string, Type>? _typeId;
#endregion
#region All Constructors
/// <summary>
/// Instantiates a custom validation attribute that will invoke a method in the
/// specified type.
/// </summary>
/// <remarks>
/// An invalid <paramref name="validatorType" /> or <paramref name="method" /> will be cause
/// <see cref="IsValid(object, ValidationContext)" />> to return a <see cref="ValidationResult" />
/// and <see cref="ValidationAttribute.FormatErrorMessage" /> to return a summary error message.
/// </remarks>
/// <param name="validatorType">
/// The type that will contain the method to invoke. It cannot be null. See
/// <see cref="Method" />.
/// </param>
/// <param name="method">The name of the method to invoke in <paramref name="validatorType" />.</param>
public CustomValidationAttribute(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)]
Type validatorType,
string method
) : base(() => SR.CustomValidationAttribute_ValidationError)
{
ValidatorType = validatorType;
Method = method;
_malformedErrorMessage = new Lazy<string?>(CheckAttributeWellFormed);
}
#endregion
#region Properties
/// <summary>
/// Gets the type that contains the validation method identified by <see cref="Method" />.
/// </summary>
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)]
public Type ValidatorType { get; }
/// <summary>
/// Gets a unique identifier for this attribute.
/// </summary>
public override object TypeId
{
get
{
if (_typeId is null)
{
_typeId = new Tuple<string, Type>(Method, ValidatorType);
}
return _typeId;
}
}
/// <summary>
/// Gets the name of the method in <see cref="ValidatorType" /> to invoke to perform validation.
/// </summary>
public string Method { get; }
public override bool RequiresValidationContext
{
get
{
// If attribute is not valid, throw an exception right away to inform the developer
ThrowIfAttributeNotWellFormed();
// We should return true when 2-parameter form of the validation method is used
return !_isSingleArgumentMethod;
}
}
#endregion
/// <summary>
/// Override of validation method. See <see cref="ValidationAttribute.IsValid(object, ValidationContext)" />.
/// </summary>
/// <param name="value">The value to validate.</param>
/// <param name="validationContext">
/// A <see cref="ValidationContext" /> instance that provides
/// context about the validation operation, such as the object and member being validated.
/// </param>
/// <returns>Whatever the <see cref="Method" /> in <see cref="ValidatorType" /> returns.</returns>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception>
protected override ValidationResult? IsValid(
object? value,
ValidationContext validationContext
)
{
// If attribute is not valid, throw an exception right away to inform the developer
ThrowIfAttributeNotWellFormed();
var methodInfo = _methodInfo;
// If the value is not of the correct type and cannot be converted, fail
// to indicate it is not acceptable. The convention is that IsValid is merely a probe,
// and clients are not expecting exceptions.
object? convertedValue;
if (!TryConvertValue(value, out convertedValue))
{
return new ValidationResult(
SR.Format(
SR.CustomValidationAttribute_Type_Conversion_Failed,
(value != null ? value.GetType().ToString() : "null"),
_firstParameterType,
ValidatorType,
Method
)
);
}
// Invoke the method. Catch TargetInvocationException merely to unwrap it.
// Callers don't know Reflection is being used and will not typically see
// the real exception
try
{
// 1-parameter form is ValidationResult Method(object value)
// 2-parameter form is ValidationResult Method(object value, ValidationContext context),
var methodParams = _isSingleArgumentMethod
? new object?[] { convertedValue }
: new[] { convertedValue, validationContext };
var result = (ValidationResult?)methodInfo!.Invoke(null, methodParams);
// We capture the message they provide us only in the event of failure,
// otherwise we use the normal message supplied via the ctor
_lastMessage = null;
if (result != null)
{
_lastMessage = result.ErrorMessage;
}
return result;
}
catch (TargetInvocationException tie)
{
throw tie.InnerException!;
}
}
/// <summary>
/// Override of <see cref="ValidationAttribute.FormatErrorMessage" />
/// </summary>
/// <param name="name">The name to include in the formatted string</param>
/// <returns>A localized string to describe the problem.</returns>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception>
public override string FormatErrorMessage(string name)
{
// If attribute is not valid, throw an exception right away to inform the developer
ThrowIfAttributeNotWellFormed();
if (!string.IsNullOrEmpty(_lastMessage))
{
return string.Format(CultureInfo.CurrentCulture, _lastMessage, name);
}
// If success or they supplied no custom message, use normal base class behavior
return base.FormatErrorMessage(name);
}
/// <summary>
/// Checks whether the current attribute instance itself is valid for use.
/// </summary>
/// <returns>The error message why it is not well-formed, null if it is well-formed.</returns>
private string? CheckAttributeWellFormed() =>
ValidateValidatorTypeParameter() ?? ValidateMethodParameter();
/// <summary>
/// Internal helper to determine whether <see cref="ValidatorType" /> is legal for use.
/// </summary>
/// <returns><c>null</c> or the appropriate error message.</returns>
private string? ValidateValidatorTypeParameter()
{
if (ValidatorType == null)
{
return SR.CustomValidationAttribute_ValidatorType_Required;
}
if (!ValidatorType.IsVisible)
{
return SR.Format(
SR.CustomValidationAttribute_Type_Must_Be_Public,
ValidatorType.Name
);
}
return null;
}
/// <summary>
/// Internal helper to determine whether <see cref="Method" /> is legal for use.
/// </summary>
/// <returns><c>null</c> or the appropriate error message.</returns>
private string? ValidateMethodParameter()
{
if (string.IsNullOrEmpty(Method))
{
return SR.CustomValidationAttribute_Method_Required;
}
// Named method must be public and static
var methodInfo = ValidatorType
.GetMethods(BindingFlags.Public | BindingFlags.Static)
.SingleOrDefault(m => string.Equals(m.Name, Method, StringComparison.Ordinal));
if (methodInfo == null)
{
return SR.Format(
SR.CustomValidationAttribute_Method_Not_Found,
Method,
ValidatorType.Name
);
}
// Method must return a ValidationResult or derived class
if (!typeof(ValidationResult).IsAssignableFrom(methodInfo.ReturnType))
{
return SR.Format(
SR.CustomValidationAttribute_Method_Must_Return_ValidationResult,
Method,
ValidatorType.Name
);
}
ParameterInfo[] parameterInfos = methodInfo.GetParameters();
// Must declare at least one input parameter for the value and it cannot be ByRef
if (parameterInfos.Length == 0 || parameterInfos[0].ParameterType.IsByRef)
{
return SR.Format(
SR.CustomValidationAttribute_Method_Signature,
Method,
ValidatorType.Name
);
}
// We accept 2 forms:
// 1-parameter form is ValidationResult Method(object value)
// 2-parameter form is ValidationResult Method(object value, ValidationContext context),
_isSingleArgumentMethod = (parameterInfos.Length == 1);
if (!_isSingleArgumentMethod)
{
if (
(parameterInfos.Length != 2)
|| (parameterInfos[1].ParameterType != typeof(ValidationContext))
)
{
return SR.Format(
SR.CustomValidationAttribute_Method_Signature,
Method,
ValidatorType.Name
);
}
}
_methodInfo = methodInfo;
_firstParameterType = parameterInfos[0].ParameterType;
return null;
}
/// <summary>
/// Throws InvalidOperationException if the attribute is not valid.
/// </summary>
private void ThrowIfAttributeNotWellFormed()
{
string? errorMessage = _malformedErrorMessage.Value;
if (errorMessage != null)
{
throw new InvalidOperationException(errorMessage);
}
}
/// <summary>
/// Attempts to convert the given value to the type needed to invoke the method for the current
/// CustomValidationAttribute.
/// </summary>
/// <param name="value">The value to check/convert.</param>
/// <param name="convertedValue">If successful, the converted (or copied) value.</param>
/// <returns><c>true</c> if type value was already correct or was successfully converted.</returns>
private bool TryConvertValue(object? value, out object? convertedValue)
{
convertedValue = null;
var expectedValueType = _firstParameterType!;
// Null is permitted for reference types or for Nullable<>'s only
if (value == null)
{
if (
expectedValueType.IsValueType
&& (
!expectedValueType.IsGenericType
|| expectedValueType.GetGenericTypeDefinition() != typeof(Nullable<>)
)
)
{
return false;
}
return true; // convertedValue already null, which is correct for this case
}
// If the type is already legally assignable, we're good
if (expectedValueType.IsInstanceOfType(value))
{
convertedValue = value;
return true;
}
// Value is not the right type -- attempt a convert.
// Any expected exception returns a false
try
{
convertedValue = Convert.ChangeType(
value,
expectedValueType,
CultureInfo.CurrentCulture
);
return true;
}
catch (FormatException)
{
return false;
}
catch (InvalidCastException)
{
return false;
}
catch (NotSupportedException)
{
return false;
}
}
}
}
| 40.570025 | 126 | 0.556928 | [
"MIT"
] | belav/runtime | src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CustomValidationAttribute.cs | 16,512 | C# |
namespace RazorPages.Pages.Internal
{
using Microsoft.AspNetCore.Mvc.RazorPages;
public class TestModel : PageModel
{
public void OnGet()
{
}
}
} | 15.666667 | 46 | 0.601064 | [
"MIT"
] | pirocorp/ASP.NET-Core | 04. RAZOR PAGES/Demo/RazorPages/Pages/Internal/Test.cshtml.cs | 190 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DevWorkshop2018AriaAccess
{
public static class JsonHelper
{
private const string INDENT_STRING = " ";
public static string FormatJson(string str)
{
var indent = 0;
var quoted = false;
var sb = new StringBuilder();
for (var i = 0; i < str.Length; i++)
{
var ch = str[i];
switch (ch)
{
case '{':
case '[':
sb.Append(ch);
if (!quoted)
{
sb.AppendLine();
Enumerable.Range(0, ++indent).ForEach(item => sb.Append(INDENT_STRING));
}
break;
case '}':
case ']':
if (!quoted)
{
sb.AppendLine();
Enumerable.Range(0, --indent).ForEach(item => sb.Append(INDENT_STRING));
}
sb.Append(ch);
break;
case '"':
sb.Append(ch);
bool escaped = false;
var index = i;
while (index > 0 && str[--index] == '\\')
escaped = !escaped;
if (!escaped)
quoted = !quoted;
break;
case ',':
sb.Append(ch);
if (!quoted)
{
sb.AppendLine();
Enumerable.Range(0, indent).ForEach(item => sb.Append(INDENT_STRING));
}
break;
case ':':
sb.Append(ch);
if (!quoted)
sb.Append(" ");
break;
default:
sb.Append(ch);
break;
}
}
return sb.ToString();
}
}
static class Extensions
{
public static void ForEach<T>(this IEnumerable<T> ie, Action<T> action)
{
foreach (var i in ie)
{
action(i);
}
}
}
}
| 31.679012 | 100 | 0.325799 | [
"MIT"
] | VarianAPIs/Varian-Code-Samples | webinars & workshops/Developer Workshop 2018/Aria Access Sample/ARIAAccessSample/JsonHelper.cs | 2,568 | C# |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Linq;
using UnityEngine;
using System.Collections.Generic;
namespace UnityEditor.Sprites
{
// DefaultPackerPolicy will pack rectangles no matter what Sprite mesh type is unless their packing tag contains "[TIGHT]".
internal class DefaultPackerPolicy : IPackerPolicy
{
protected class Entry
{
public Sprite sprite;
public AtlasSettings settings;
public string atlasName;
public SpritePackingMode packingMode;
public int anisoLevel;
}
private const uint kDefaultPaddingPower = 3; // Good for base and two mip levels.
public virtual int GetVersion() { return 1; }
public virtual bool AllowSequentialPacking { get { return false; } }
protected virtual string TagPrefix { get { return "[TIGHT]"; } }
protected virtual bool AllowTightWhenTagged { get { return true; } }
protected virtual bool AllowRotationFlipping { get { return false; } }
public void OnGroupAtlases(BuildTarget target, PackerJob job, int[] textureImporterInstanceIDs)
{
List<Entry> entries = new List<Entry>();
string targetName = "";
if (target != BuildTarget.NoTarget)
{
targetName = BuildPipeline.GetBuildTargetName(target);
}
foreach (int instanceID in textureImporterInstanceIDs)
{
TextureImporter ti = EditorUtility.InstanceIDToObject(instanceID) as TextureImporter;
TextureFormat desiredFormat;
ColorSpace colorSpace;
int compressionQuality;
ti.ReadTextureImportInstructions(target, out desiredFormat, out colorSpace, out compressionQuality);
TextureImporterSettings tis = new TextureImporterSettings();
ti.ReadTextureSettings(tis);
bool hasAlphaSplittingForCompression = (targetName != "" && HasPlatformEnabledAlphaSplittingForCompression(targetName, ti));
Sprite[] sprites = AssetDatabase.LoadAllAssetRepresentationsAtPath(ti.assetPath).Select(x => x as Sprite).Where(x => x != null).ToArray();
foreach (Sprite sprite in sprites)
{
Entry entry = new Entry();
entry.sprite = sprite;
entry.settings.format = desiredFormat;
entry.settings.colorSpace = colorSpace;
// Use Compression Quality for Grouping later only for Compressed Formats. Otherwise leave it Empty.
entry.settings.compressionQuality = UnityEditor.TextureUtil.IsCompressedTextureFormat(desiredFormat) ? compressionQuality : 0;
entry.settings.filterMode = Enum.IsDefined(typeof(FilterMode), ti.filterMode) ? ti.filterMode : FilterMode.Bilinear;
entry.settings.maxWidth = 2048;
entry.settings.maxHeight = 2048;
entry.settings.generateMipMaps = ti.mipmapEnabled;
entry.settings.enableRotation = AllowRotationFlipping;
entry.settings.allowsAlphaSplitting = TextureImporter.IsTextureFormatETC1Compression(desiredFormat) && hasAlphaSplittingForCompression;
if (ti.mipmapEnabled)
entry.settings.paddingPower = kDefaultPaddingPower;
else
entry.settings.paddingPower = (uint)EditorSettings.spritePackerPaddingPower;
entry.atlasName = ParseAtlasName(ti.spritePackingTag);
entry.packingMode = GetPackingMode(ti.spritePackingTag, tis.spriteMeshType);
entry.anisoLevel = ti.anisoLevel;
entries.Add(entry);
}
Resources.UnloadAsset(ti);
}
// First split sprites into groups based on atlas name
var atlasGroups =
from e in entries
group e by e.atlasName;
foreach (var atlasGroup in atlasGroups)
{
int page = 0;
// Then split those groups into smaller groups based on texture settings
var settingsGroups =
from t in atlasGroup
group t by t.settings;
foreach (var settingsGroup in settingsGroups)
{
string atlasName = atlasGroup.Key;
if (settingsGroups.Count() > 1)
atlasName += string.Format(" (Group {0})", page);
AtlasSettings settings = settingsGroup.Key;
settings.anisoLevel = 1;
// Use the highest aniso level from all entries in this atlas
if (settings.generateMipMaps)
foreach (Entry entry in settingsGroup)
if (entry.anisoLevel > settings.anisoLevel)
settings.anisoLevel = entry.anisoLevel;
job.AddAtlas(atlasName, settings);
foreach (Entry entry in settingsGroup)
{
job.AssignToAtlas(atlasName, entry.sprite, entry.packingMode, SpritePackingRotation.None);
}
++page;
}
}
}
protected bool HasPlatformEnabledAlphaSplittingForCompression(string targetName, TextureImporter ti)
{
TextureImporterPlatformSettings platformSettings = ti.GetPlatformTextureSettings(targetName);
return (platformSettings.overridden && platformSettings.allowsAlphaSplitting);
}
protected bool IsTagPrefixed(string packingTag)
{
packingTag = packingTag.Trim();
if (packingTag.Length < TagPrefix.Length)
return false;
return (packingTag.Substring(0, TagPrefix.Length) == TagPrefix);
}
private string ParseAtlasName(string packingTag)
{
string name = packingTag.Trim();
if (IsTagPrefixed(name))
name = name.Substring(TagPrefix.Length).Trim();
return (name.Length == 0) ? "(unnamed)" : name;
}
private SpritePackingMode GetPackingMode(string packingTag, SpriteMeshType meshType)
{
if (meshType == SpriteMeshType.Tight)
if (IsTagPrefixed(packingTag) == AllowTightWhenTagged)
return SpritePackingMode.Tight;
return SpritePackingMode.Rectangle;
}
}
}
| 44.777778 | 155 | 0.590133 | [
"Unlicense"
] | HelloWindows/AccountBook | client/framework/UnityCsReference-master/Editor/Mono/Sprites/DefaultSpritePackerPolicy.cs | 6,851 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using BlogOps.Commands.Blog;
using BlogOps.Commands.Utils;
using CliFx;
using CliFx.Attributes;
using CliFx.Infrastructure;
using JetBrains.Annotations;
using Spectre.Console;
namespace BlogOps.Commands
{
[Command("publish", Description = "Publish a draft.")]
[UsedImplicitly]
public class PublishCommand : ICommand
{
[CommandOption("Overwrite", 'o', Description = "Overwrite file if it exists.")]
public bool Overwrite { get; set; } = false;
public async ValueTask ExecuteAsync(IConsole console)
{
var (draftFileInfo, draftFrontMatter) = await BlogUtils.AskUserToSelectDraft("Which draft do you want to publish?");
var blogPostPath = Path.Combine(BlogSettings.PostsFolder, draftFileInfo.Name);
if (!Overwrite && File.Exists(blogPostPath))
{
await console.Output.WriteLineAsync($"File exists, please use {nameof(Overwrite)} parameter.");
return;
}
var updatedDraftLines = await GetUpdatedDraftFrontMatterLines(draftFileInfo.FullName, draftFrontMatter);
await File.WriteAllLinesAsync(blogPostPath, updatedDraftLines);
File.Delete(draftFileInfo.FullName);
AnsiConsole.Markup($"Published [green]{blogPostPath}[/]");
}
private async Task<string[]> GetUpdatedDraftFrontMatterLines(string fileInfoFullName, BlogFrontMatter draftFrontMatter)
{
var sourceDraftPath = Path.Combine(BlogSettings.DraftsFolder, fileInfoFullName);
var draftContent = await File.ReadAllTextAsync(sourceDraftPath);
var draftContentLines = draftContent.Split(Environment.NewLine);
UpdateDraftFrontMatter(draftContentLines, draftFrontMatter);
return draftContentLines;
}
private static void UpdateDraftFrontMatter(IList<string> contentLines, BlogFrontMatter blogFrontMatter)
{
var now = DateTime.Now;
var slug = blogFrontMatter.Title.ToUrlSlug();
for (var index = 0; index < contentLines.Count; index++)
{
var contentLine = contentLines[index];
if (contentLine.IsPermalinkLine())
{
contentLines[index] = now.ToPermalink(slug);
}
if (contentLine.IsDateLine())
{
contentLines[index] = now.ToDate();
}
if (contentLine.IsDisqusIdentifierLine())
{
contentLines[index] = now.ToDisqusIdentifier();
}
}
}
}
} | 34.875 | 128 | 0.619355 | [
"Unlicense"
] | laurentkempe/BlogOps | Commands/PublishCommand.cs | 2,792 | C# |
#if MXM_PRESENT
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Cinemachine;
namespace WizardsCode.Character.MxM
{
public class UiController : MonoBehaviour
{
[SerializeField, Tooltip("The UI Canvas to control.")]
RectTransform m_UI;
[SerializeField, Tooltip("The Cinemachine virtual camera to use.")]
CinemachineFreeLook m_Cinemachine;
private int m_CharacterIndex;
private List<Transform> m_Characters = new List<Transform>();
private void Start()
{
MxMActorController[] allActors = GameObject.FindObjectsOfType<MxMActorController>();
for (int i = 0; i < allActors.Length; i++)
{
m_Characters.Add(allActors[i].transform);
}
m_Characters.Add(GameObject.FindObjectOfType<CharacterController>().transform);
m_CharacterIndex = m_Characters.Count - 1;
m_Cinemachine.Follow = m_Characters[m_CharacterIndex];
m_Cinemachine.LookAt = m_Characters[m_CharacterIndex];
}
public void Update()
{
if (Input.GetKeyDown(KeyCode.H))
{
m_UI.gameObject.SetActive(!m_UI.gameObject.activeSelf);
}
if (Input.GetKeyDown(KeyCode.N))
{
m_CharacterIndex++;
if (m_CharacterIndex >= m_Characters.Count)
{
m_CharacterIndex = 0;
}
m_Cinemachine.Follow = m_Characters[m_CharacterIndex];
m_Cinemachine.LookAt = m_Characters[m_CharacterIndex];
}
}
}
}
#endif | 32.351852 | 97 | 0.575272 | [
"MIT"
] | TheWizardsCode/Character | Assets/_Character/Character/_Third Party Demos/Motion Matching for Unity/Scripts/UiController.cs | 1,747 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MTGAHelper.Web.UI.Model.Response.Misc
{
public class GetVersionResponse
{
public DateTimeOffset DateTimeUtc { get; set; }
}
}
| 19.615385 | 55 | 0.733333 | [
"MIT"
] | omarjuul/MTGAHelper-Windows-Client | MtgaHelper.Web.Models/Response/Misc/GetVersionResponse.cs | 257 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace QuickDraw
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class InstallingWindow : Window
{
public void OnClosed(object sender, EventArgs args)
{
((App)Application.Current).Shutdown();
}
public InstallingWindow()
{
InitializeComponent();
this.Closed += OnClosed;
}
}
}
| 22.2 | 59 | 0.670528 | [
"MIT"
] | blendermf/QuickDraw | QuickDraw/Installing.xaml.cs | 779 | C# |
using Latios;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;
namespace Dragons
{
public class UpdateCharacterTranslationsSystem : SubSystem
{
protected override void OnUpdate()
{
Entities.ForEach((ref Translation trans, in GridPosition position) =>
{
trans.Value = new float3(position.position.x, trans.Value.y, position.position.y);
}).ScheduleParallel();
}
}
}
| 23.434783 | 98 | 0.656772 | [
"MIT"
] | Dreaming381/LatiosFrameworkMiniDemos | LatiosGridDemo/Assets/_Code/Systems/UpdateCharacterTranslationsSystem.cs | 539 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tab = Microsoft.AnalysisServices.Tabular;
using Newtonsoft.Json;
namespace PBSurgeon
{
/// <summary>
/// A class to read a model and report on various components.
/// It will not update the model
/// </summary>
public static class Reporter
{
static string indent = " ";
static string separatorLine = "================================";
static string parameterQuery = "IsParameterQuery=true";
/// <summary>
/// Must be set before any of the methods are called.
/// </summary>
public static string ConnectionString { get; set; }
/// <summary>
/// Creates the raw TMSL json schema of an existing model.
/// The detailed schema contains too much information.
/// </summary>
/// <returns></returns>
public static string DumpRawSchema()
{
var srv = new Tab.Server();
srv.Connect(ConnectionString);
var model = srv.Databases[0].Model;
return JsonConvert.SerializeObject(model, Formatting.Indented, new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
}
public static Schema ExtractSchema()
{
var srv = new Tab.Server();
srv.Connect(ConnectionString);
var model = srv.Databases[0].Model;
var sch = new PBSurgeon.Schema();
foreach (var t in model.Tables.OrderBy(x => x.Name).ToList())
{
var tab = new PBSurgeon.Table
{
Name = t.Name,
IsHidden = t.IsHidden,
ExcludeFromModelRefresh = t.ExcludeFromModelRefresh,
Description = t.Description
};
foreach (var par in t.Partitions.OrderBy(x => x.Name).ToList())
{
var part = new PBSurgeon.Partition
{
Name = par.Name,
Mode = par.Mode.ToString()
};
if (par.Source is Tab.MPartitionSource mpar)
{
part.Kind = par.SourceType.ToString();
part.Expression = mpar.Expression;
}
tab.Partitions.Add(part);
}
foreach (var c in t.Columns)
{
var fl = new PBSurgeon.Field
{
Name = c.Name,
OrdinalPosition = c.DisplayOrdinal,
DisplayFolder = c.DisplayFolder,
FormatString = c.FormatString,
DataType = c.DataType.ToString(),
Type = c.Type.ToString(),
Description = c.Description,
SortByColumn = c.SortByColumn?.Name
};
if (c is Tab.CalculatedColumn column)
{
fl.FieldType = FieldType.CalculatedColumn;
fl.Expression = column.Expression;
}
else
{
fl.FieldType = FieldType.Column;
if (c is Tab.DataColumn cxd) fl.SourceColumnName = cxd.SourceColumn;
}
tab.Fields.Add(fl);
}
foreach (var m in t.Measures)
{
var fl = new PBSurgeon.Field
{
Name = m.Name,
DisplayFolder = m.DisplayFolder,
FormatString = m.FormatString,
DataType = m.DataType.ToString(),
Type = m.ObjectType.ToString(),
Description = m.Description,
FieldType = FieldType.Measure,
Expression = m.Expression
};
tab.Fields.Add(fl);
}
// Let us reorder the fields alphabetically.
tab.Fields = tab.Fields.OrderBy(x => x.Name).ToList();
sch.Tables.Add(tab);
}
foreach (var p in model.Expressions.OrderBy(x => x.Name).ToList())
{
if (p.Expression.Contains(parameterQuery))
{
var param = new PBSurgeon.Parameter
{
Name = p.Name,
Description = p.Description,
Expression = p.Expression,
Kind = p.Kind.ToString()
};
sch.Parameters.Add(param);
}
}
return sch;
}
/// <summary>
/// Creates a simplified JSON schema for a model
/// </summary>
/// <returns></returns>
public static string DumpSchema()
{
var sch = ExtractSchema();
return JsonConvert.SerializeObject(sch, Formatting.Indented, new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
}
/// <summary>
/// Prints a simplified JSON schema
/// </summary>
/// <returns></returns>
public static void PrintSchema()
{
var level = 0;
var sch = ExtractSchema();
Console.WriteLine("{0}Date: {1:MM/dd/yyyy H:mm:ss}", GetLeftIndent(level), DateTime.Now);
Console.WriteLine("{0}Model: {1}", GetLeftIndent(level), ConnectionString);
Console.WriteLine("{0}Summary", GetLeftIndent(level));
level++;
Console.WriteLine("{0}Parameters: {1}", GetLeftIndent(level), sch.Parameters.Count);
level++;
foreach (var p in sch.Parameters)
{
Console.WriteLine("{0}{1}", GetLeftIndent(level), p.Name);
}
level--;
Console.WriteLine("{0}Tables: {1}", GetLeftIndent(level), sch.Tables.Count);
level++;
foreach (var t in sch.Tables)
{
Console.WriteLine("{0}{1}", GetLeftIndent(level), t.Name);
if (t.Partitions.Count > 0)
{
level++;
Console.WriteLine("{0}This table contains {1} partitions.", GetLeftIndent(level), t.Partitions.Count);
foreach (var part in t.Partitions)
{
Console.WriteLine("{0}Name: {1}", GetLeftIndent(level), part.Name);
Console.WriteLine("{0}Mode: {1}", GetLeftIndent(level), part.Mode);
Console.WriteLine("{0}Kind: {1}", GetLeftIndent(level), part.Kind);
Console.WriteLine("{0}Expression:", GetLeftIndent(level));
Console.WriteLine(AlignExpression(part.Expression, level + 1));
Console.WriteLine();
}
level--;
}
}
level = 0;
Console.WriteLine("{0}Details", GetLeftIndent(level));
level = 1;
Console.WriteLine();
Console.WriteLine("{0}Parameters:", GetLeftIndent(level));
level++;
foreach (var p in sch.Parameters)
{
Console.WriteLine("{0}Name: {1}", GetLeftIndent(level), p.Name);
Console.WriteLine("{0}Description: {1}", GetLeftIndent(level), p.Description);
Console.WriteLine("{0}Kind: {1}", GetLeftIndent(level), p.Kind);
Console.WriteLine("{0}Expression: {1}", GetLeftIndent(level), p.Expression);
Console.WriteLine("{0}{1}", GetLeftIndent(level), separatorLine);
Console.WriteLine();
}
Console.WriteLine();
level = 1;
Console.WriteLine("{0}Tables:", GetLeftIndent(level));
level++;
foreach (var t in sch.Tables)
{
Console.WriteLine("{0}Name: {1}", GetLeftIndent(level), t.Name);
Console.WriteLine("{0}Description: {1}", GetLeftIndent(level), t.Description);
Console.WriteLine("{0}IsHidden: {1}", GetLeftIndent(level), t.IsHidden);
Console.WriteLine("{0}Exclude from model refresh: {1}", GetLeftIndent(level), t.ExcludeFromModelRefresh);
Console.WriteLine("{0}{1}", GetLeftIndent(level), separatorLine);
Console.WriteLine();
}
level = 1;
Console.WriteLine("{0}Columns and measures:", GetLeftIndent(level));
level++;
foreach (var t in sch.Tables)
{
Console.WriteLine("{0}Table: {1}", GetLeftIndent(level), t.Name);
level++;
foreach (var c in t.Fields)
{
Console.WriteLine("{0}{1}", GetLeftIndent(level), c.Name);
level++;
Console.WriteLine("{0}Source column: {1}", GetLeftIndent(level), c.SourceColumnName);
Console.WriteLine("{0}Field type: {1}", GetLeftIndent(level), c.FieldType);
Console.WriteLine("{0}Data type: {1}", GetLeftIndent(level), c.DataType);
Console.WriteLine("{0}Description: {1}", GetLeftIndent(level), c.Description);
Console.WriteLine("{0}Format string: {1}", GetLeftIndent(level), c.FormatString);
Console.WriteLine("{0}Display folder: {1}", GetLeftIndent(level), c.DisplayFolder);
Console.WriteLine("{0}Type: {1}", GetLeftIndent(level), c.Type);
if ((new List<string> { FieldType.CalculatedColumn, FieldType.Measure }).Contains(c.FieldType))
{
Console.WriteLine("{0}Expression:", GetLeftIndent(level));
DumpExpression(level + 1, c.Expression);
}
Console.WriteLine();
level--;
}
level--;
Console.WriteLine("{0}{1}", GetLeftIndent(level), separatorLine);
Console.WriteLine();
}
Console.WriteLine("End report");
}
private static void DumpExpression(int level, string expression)
{
var lines = (expression.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None)).ToList();
foreach (var line in lines)
{
Console.WriteLine("{0}{1}", GetLeftIndent(level), line);
}
}
private static string GetLeftIndent(int level)
{
if (level == 0) return "";
return String.Concat(Enumerable.Repeat(indent, level));
}
private static string AlignExpression(string expression, int level)
{
if (expression == null) return "";
var ret = new StringBuilder("");
var lines = expression.Split(new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
foreach (var line in lines)
{
ret.AppendLine(GetLeftIndent(level) + line);
}
return ret.ToString();
}
}
}
| 42.856089 | 122 | 0.484674 | [
"MIT"
] | jujiro/PBSurgeon | PBSurgeon.Net/PBSurgeon/Reporter.cs | 11,616 | C# |
namespace moe.yo3explorer.azusa.SedgeTree.Boundary
{
partial class Editor
{
/// <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.pictureBox1 = new System.Windows.Forms.PictureBox();
this.button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.label4 = new System.Windows.Forms.Label();
this.textBox3 = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.textBox4 = new System.Windows.Forms.TextBox();
this.button2 = new System.Windows.Forms.Button();
this.label6 = new System.Windows.Forms.Label();
this.textBox5 = new System.Windows.Forms.TextBox();
this.label7 = new System.Windows.Forms.Label();
this.textBox6 = new System.Windows.Forms.TextBox();
this.button3 = new System.Windows.Forms.Button();
this.label8 = new System.Windows.Forms.Label();
this.textBox7 = new System.Windows.Forms.TextBox();
this.button4 = new System.Windows.Forms.Button();
this.label9 = new System.Windows.Forms.Label();
this.textBox8 = new System.Windows.Forms.TextBox();
this.button5 = new System.Windows.Forms.Button();
this.button6 = new System.Windows.Forms.Button();
this.label10 = new System.Windows.Forms.Label();
this.label11 = new System.Windows.Forms.Label();
this.textBox9 = new System.Windows.Forms.TextBox();
this.label12 = new System.Windows.Forms.Label();
this.textBox10 = new System.Windows.Forms.TextBox();
this.button7 = new System.Windows.Forms.Button();
this.textBox11 = new System.Windows.Forms.TextBox();
this.label13 = new System.Windows.Forms.Label();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.button8 = new System.Windows.Forms.Button();
this.button9 = new System.Windows.Forms.Button();
this.label14 = new System.Windows.Forms.Label();
this.textBox12 = new System.Windows.Forms.TextBox();
this.button10 = new System.Windows.Forms.Button();
this.button11 = new System.Windows.Forms.Button();
this.button12 = new System.Windows.Forms.Button();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.checkBox2 = new System.Windows.Forms.CheckBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// pictureBox1
//
this.pictureBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.pictureBox1.Location = new System.Drawing.Point(588, 12);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(167, 167);
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
//
// button1
//
this.button1.Location = new System.Drawing.Point(680, 403);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 1;
this.button1.Text = "Schließen";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(12, 33);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(176, 20);
this.textBox1.TabIndex = 2;
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 17);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(52, 13);
this.label1.TabIndex = 3;
this.label1.Text = "Vorname:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(191, 17);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(62, 13);
this.label2.TabIndex = 4;
this.label2.Text = "Nachname:";
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(194, 33);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(100, 20);
this.textBox2.TabIndex = 5;
this.textBox2.TextChanged += new System.EventHandler(this.textBox2_TextChanged);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(12, 56);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(64, 13);
this.label3.TabIndex = 6;
this.label3.Text = "Geschlecht:";
//
// comboBox1
//
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Items.AddRange(new object[] {
"?",
"W",
"M"});
this.comboBox1.Location = new System.Drawing.Point(15, 72);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(121, 21);
this.comboBox1.TabIndex = 7;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(12, 96);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(76, 13);
this.label4.TabIndex = 8;
this.label4.Text = "Anmerkungen:";
//
// textBox3
//
this.textBox3.Location = new System.Drawing.Point(15, 112);
this.textBox3.Multiline = true;
this.textBox3.Name = "textBox3";
this.textBox3.Size = new System.Drawing.Size(279, 67);
this.textBox3.TabIndex = 9;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(12, 182);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(40, 13);
this.label5.TabIndex = 10;
this.label5.Text = "Mutter:";
this.label5.TextAlign = System.Drawing.ContentAlignment.TopCenter;
//
// textBox4
//
this.textBox4.Location = new System.Drawing.Point(15, 198);
this.textBox4.Name = "textBox4";
this.textBox4.ReadOnly = true;
this.textBox4.Size = new System.Drawing.Size(279, 20);
this.textBox4.TabIndex = 11;
//
// button2
//
this.button2.Location = new System.Drawing.Point(15, 224);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(121, 23);
this.button2.TabIndex = 12;
this.button2.Text = "Mutter auswählen";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(312, 17);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(40, 13);
this.label6.TabIndex = 13;
this.label6.Text = "Kinder:";
//
// textBox5
//
this.textBox5.Location = new System.Drawing.Point(315, 33);
this.textBox5.Multiline = true;
this.textBox5.Name = "textBox5";
this.textBox5.ReadOnly = true;
this.textBox5.Size = new System.Drawing.Size(267, 60);
this.textBox5.TabIndex = 14;
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(17, 250);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(35, 13);
this.label7.TabIndex = 15;
this.label7.Text = "Vater:";
//
// textBox6
//
this.textBox6.Location = new System.Drawing.Point(15, 266);
this.textBox6.Name = "textBox6";
this.textBox6.ReadOnly = true;
this.textBox6.Size = new System.Drawing.Size(279, 20);
this.textBox6.TabIndex = 16;
//
// button3
//
this.button3.Location = new System.Drawing.Point(15, 292);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(121, 23);
this.button3.TabIndex = 17;
this.button3.Text = "Vater auswählen";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(12, 318);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(62, 13);
this.label8.TabIndex = 18;
this.label8.Text = "Ehepartner:";
//
// textBox7
//
this.textBox7.Location = new System.Drawing.Point(15, 334);
this.textBox7.Name = "textBox7";
this.textBox7.ReadOnly = true;
this.textBox7.Size = new System.Drawing.Size(279, 20);
this.textBox7.TabIndex = 19;
//
// button4
//
this.button4.Location = new System.Drawing.Point(15, 387);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(121, 23);
this.button4.TabIndex = 20;
this.button4.Text = "Ehepartner auswählen";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(312, 119);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(68, 13);
this.label9.TabIndex = 21;
this.label9.Text = "Geschwister:";
//
// textBox8
//
this.textBox8.Location = new System.Drawing.Point(315, 135);
this.textBox8.Multiline = true;
this.textBox8.Name = "textBox8";
this.textBox8.ReadOnly = true;
this.textBox8.Size = new System.Drawing.Size(267, 60);
this.textBox8.TabIndex = 22;
//
// button5
//
this.button5.Location = new System.Drawing.Point(315, 201);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(141, 23);
this.button5.TabIndex = 23;
this.button5.Text = "Alle Geschwister entfernen";
this.button5.UseVisualStyleBackColor = true;
this.button5.Click += new System.EventHandler(this.button5_Click);
//
// button6
//
this.button6.Location = new System.Drawing.Point(462, 201);
this.button6.Name = "button6";
this.button6.Size = new System.Drawing.Size(120, 23);
this.button6.TabIndex = 24;
this.button6.Text = "mehr Geschwister";
this.button6.UseVisualStyleBackColor = true;
this.button6.Click += new System.EventHandler(this.button6_Click);
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(17, 413);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(41, 13);
this.label10.TabIndex = 25;
this.label10.Text = "label10";
this.label10.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(312, 228);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(107, 13);
this.label11.TabIndex = 26;
this.label11.Text = "evtl.: Mädchenname:";
//
// textBox9
//
this.textBox9.Location = new System.Drawing.Point(315, 244);
this.textBox9.Name = "textBox9";
this.textBox9.Size = new System.Drawing.Size(267, 20);
this.textBox9.TabIndex = 27;
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(312, 273);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(59, 13);
this.label12.TabIndex = 28;
this.label12.Text = "Geburtsort:";
//
// textBox10
//
this.textBox10.Location = new System.Drawing.Point(315, 289);
this.textBox10.Name = "textBox10";
this.textBox10.Size = new System.Drawing.Size(267, 20);
this.textBox10.TabIndex = 29;
//
// button7
//
this.button7.Location = new System.Drawing.Point(462, 332);
this.button7.Name = "button7";
this.button7.Size = new System.Drawing.Size(120, 23);
this.button7.TabIndex = 30;
this.button7.Text = "Datum eintragen";
this.button7.UseVisualStyleBackColor = true;
this.button7.Click += new System.EventHandler(this.button7_Click);
//
// textBox11
//
this.textBox11.Location = new System.Drawing.Point(315, 334);
this.textBox11.Name = "textBox11";
this.textBox11.ReadOnly = true;
this.textBox11.Size = new System.Drawing.Size(141, 20);
this.textBox11.TabIndex = 31;
//
// label13
//
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(312, 318);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(76, 13);
this.label13.TabIndex = 32;
this.label13.Text = "Geburtsdatum:";
//
// checkBox1
//
this.checkBox1.AutoSize = true;
this.checkBox1.Location = new System.Drawing.Point(15, 360);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(209, 17);
this.checkBox1.TabIndex = 33;
this.checkBox1.Text = "Diese Person war mehrmals verheiratet";
this.checkBox1.UseVisualStyleBackColor = true;
//
// button8
//
this.button8.Location = new System.Drawing.Point(483, 96);
this.button8.Name = "button8";
this.button8.Size = new System.Drawing.Size(99, 23);
this.button8.TabIndex = 34;
this.button8.Text = "Kind hinzufügen";
this.button8.UseVisualStyleBackColor = true;
this.button8.Click += new System.EventHandler(this.button8_Click);
//
// button9
//
this.button9.Location = new System.Drawing.Point(364, 96);
this.button9.Name = "button9";
this.button9.Size = new System.Drawing.Size(113, 23);
this.button9.TabIndex = 35;
this.button9.Text = "Alle Kinder entfernen";
this.button9.UseVisualStyleBackColor = true;
this.button9.Click += new System.EventHandler(this.button9_Click);
//
// label14
//
this.label14.AutoSize = true;
this.label14.Location = new System.Drawing.Point(312, 360);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(93, 13);
this.label14.TabIndex = 36;
this.label14.Text = "evtl. Sterbedatum:";
//
// textBox12
//
this.textBox12.Location = new System.Drawing.Point(315, 376);
this.textBox12.Name = "textBox12";
this.textBox12.ReadOnly = true;
this.textBox12.Size = new System.Drawing.Size(141, 20);
this.textBox12.TabIndex = 38;
//
// button10
//
this.button10.Location = new System.Drawing.Point(462, 374);
this.button10.Name = "button10";
this.button10.Size = new System.Drawing.Size(120, 23);
this.button10.TabIndex = 37;
this.button10.Text = "Datum eintragen";
this.button10.UseVisualStyleBackColor = true;
this.button10.Click += new System.EventHandler(this.button10_Click);
//
// button11
//
this.button11.Location = new System.Drawing.Point(588, 185);
this.button11.Name = "button11";
this.button11.Size = new System.Drawing.Size(167, 23);
this.button11.TabIndex = 39;
this.button11.Text = "Bild anhängen";
this.button11.UseVisualStyleBackColor = true;
this.button11.Click += new System.EventHandler(this.button11_Click);
//
// button12
//
this.button12.Location = new System.Drawing.Point(588, 214);
this.button12.Name = "button12";
this.button12.Size = new System.Drawing.Size(167, 23);
this.button12.TabIndex = 40;
this.button12.Text = "Bild löschen";
this.button12.UseVisualStyleBackColor = true;
this.button12.Click += new System.EventHandler(this.button12_Click);
//
// openFileDialog1
//
this.openFileDialog1.FileName = "openFileDialog1";
this.openFileDialog1.Filter = "Digitalbild|*.jpg;*.png;*.bmp";
//
// checkBox2
//
this.checkBox2.AutoSize = true;
this.checkBox2.Location = new System.Drawing.Point(588, 243);
this.checkBox2.Name = "checkBox2";
this.checkBox2.Size = new System.Drawing.Size(171, 17);
this.checkBox2.TabIndex = 41;
this.checkBox2.Text = "Dieser Datensatz ist konsistent";
this.checkBox2.UseVisualStyleBackColor = true;
//
// Editor
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(775, 438);
this.Controls.Add(this.checkBox2);
this.Controls.Add(this.button12);
this.Controls.Add(this.button11);
this.Controls.Add(this.textBox12);
this.Controls.Add(this.button10);
this.Controls.Add(this.label14);
this.Controls.Add(this.button9);
this.Controls.Add(this.button8);
this.Controls.Add(this.checkBox1);
this.Controls.Add(this.label13);
this.Controls.Add(this.textBox11);
this.Controls.Add(this.button7);
this.Controls.Add(this.textBox10);
this.Controls.Add(this.label12);
this.Controls.Add(this.textBox9);
this.Controls.Add(this.label11);
this.Controls.Add(this.label10);
this.Controls.Add(this.button6);
this.Controls.Add(this.button5);
this.Controls.Add(this.textBox8);
this.Controls.Add(this.label9);
this.Controls.Add(this.button4);
this.Controls.Add(this.textBox7);
this.Controls.Add(this.label8);
this.Controls.Add(this.button3);
this.Controls.Add(this.textBox6);
this.Controls.Add(this.label7);
this.Controls.Add(this.textBox5);
this.Controls.Add(this.label6);
this.Controls.Add(this.button2);
this.Controls.Add(this.textBox4);
this.Controls.Add(this.label5);
this.Controls.Add(this.textBox3);
this.Controls.Add(this.label4);
this.Controls.Add(this.comboBox1);
this.Controls.Add(this.label3);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button1);
this.Controls.Add(this.pictureBox1);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(783, 445);
this.Name = "Editor";
this.Text = "Editor";
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox textBox3;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox textBox4;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.TextBox textBox5;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.TextBox textBox6;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.TextBox textBox7;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.TextBox textBox8;
private System.Windows.Forms.Button button5;
private System.Windows.Forms.Button button6;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.TextBox textBox9;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.TextBox textBox10;
private System.Windows.Forms.Button button7;
private System.Windows.Forms.TextBox textBox11;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.CheckBox checkBox1;
private System.Windows.Forms.Button button8;
private System.Windows.Forms.Button button9;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.TextBox textBox12;
private System.Windows.Forms.Button button10;
private System.Windows.Forms.Button button11;
private System.Windows.Forms.Button button12;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.CheckBox checkBox2;
}
} | 44.755672 | 107 | 0.564048 | [
"BSD-2-Clause"
] | feyris-tan/azusa | AzusaERP.OldStuff/SedgeTree/Boundary/Editor.designer.cs | 25,655 | C# |
using NodaTime;
using NUnit.Framework;
using System.Collections.Generic;
namespace TempoDB.Tests
{
[TestFixture]
class MultiStatusTest
{
static List<Status> statuses1 = new List<Status> { new Status(1, new List<string> { "message" }) };
static List<Status> statuses2 = new List<Status> { new Status(1, new List<string> { "message" }) };
static List<Status> statuses3 = new List<Status> { new Status(100, new List<string> { "message" }) };
[Test]
public void Equality()
{
var ms1 = new MultiStatus(statuses1);
var ms2 = new MultiStatus(statuses2);
Assert.AreEqual(ms1, ms2);
}
[Test]
public void Equality_EmptyStatuses()
{
var ms1 = new MultiStatus(new List<Status>());
var ms2 = new MultiStatus(new List<Status>());
Assert.AreEqual(ms1, ms2);
}
[Test]
public void Inequality()
{
var ms1 = new MultiStatus(statuses1);
var ms2 = new MultiStatus(statuses3);
Assert.AreNotEqual(ms1, ms2);
}
[Test]
public void Inequality_Null()
{
var ms1 = new MultiStatus(statuses1);
Assert.AreNotEqual(ms1, null);
}
}
}
| 27.808511 | 109 | 0.557001 | [
"MIT"
] | tempodb/tempodb-net | TempoDB.Tests/src/MultiStatusTest.cs | 1,307 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.