content
stringlengths
23
1.05M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UsefullAlgorithms.Graph { public class VertexEqualityComparer<T> : IComparer<Vertex<T>>, IEqualityComparer<Vertex<T>> where T : IEquatable<T> { public int Compare(Vertex<T> x, Vertex<T> y) => x.CompareTo(y); public bool Equals(Vertex<T> x, Vertex<T> y) => x.Data.Equals(y.Data); public int GetHashCode(Vertex<T> obj) => obj.GetHashCode(); } }
using System; using System.Collections.Generic; using OpenRasta.Concordia; using OpenRasta.Configuration; using OpenRasta.Configuration.Fluent; using OpenRasta.DI; using OpenRasta.Hosting.InMemory; using OpenRasta.Plugins.Caching; using OpenRasta.Plugins.Caching.Configuration; using OpenRasta.Web; using Shouldly; namespace Tests.Plugins.Caching.contexts { public abstract class caching : IDisposable { protected static DateTimeOffset now = DateTimeOffset.UtcNow; readonly TestConfiguration _configuration = new TestConfiguration(); readonly IDictionary<string, string> _requestHeaders = new Dictionary<string, string>(); InMemoryHost _host; readonly string _method = "GET"; protected object resource; protected IResponse response; protected caching() { _configuration.Uses.Add(() => ResourceSpace.Uses.Caching()); } void IDisposable.Dispose() { _host.Close(); } protected void given_has(Action<IHas> has) { _configuration.Has.Add(() => has(ResourceSpace.Has)); } protected void given_request_header(string header, string value) { _requestHeaders[header] = value; } protected void given_request_header(string header, DateTimeOffset? value) { _requestHeaders[header] = value.Value.ToUniversalTime().ToString("R"); } protected void given_resource<T>(Action<IResourceDefinition<T>> configuration = null, string uri = null, T resource = null) where T : class, new() { Action action = () => { var res = ResourceSpace.Has.ResourcesOfType<T>(); configuration?.Invoke(res); res.AtUri(uri ?? "/" + typeof(T).Name) .HandledBy<ResourceHandler>() .TranscodedBy<NullCodec>(); }; _configuration.Has.Add(action); this.resource = resource ?? new T(); } protected void given_resource<T>(string uri, T resource) where T : class, new() { given_resource(configuration: null, uri: uri, resource: resource); } protected void given_uses(Action<IUses> use) { _configuration.Uses.Add(() => use(ResourceSpace.Uses)); } protected void should_be_date(string input, DateTimeOffset? expected) { DateTimeOffset.Parse(response.Headers["last-modified"]).ToUniversalTime() .ToString("R").ShouldBe(expected.Value.ToUniversalTime().ToString("R")); } protected void when_executing_request(string uri) { _host = new InMemoryHost(_configuration, startup: new StartupProperties() { OpenRasta = { Errors = { HandleAllExceptions = false, HandleCatastrophicExceptions = false }} }); _host.Resolver.AddDependencyInstance(typeof(caching), this, DependencyLifetime.Singleton); var request = new InMemoryRequest { HttpMethod = _method, Uri = new Uri(new Uri("http://localhost"), new Uri(uri, UriKind.RelativeOrAbsolute)) }; foreach (var kv in _requestHeaders) request.Headers.Add(kv); response = _host.ProcessRequest(request); } protected void given_current_time(DateTimeOffset dateTimeOffset) { now = dateTimeOffset; ServerClock.UtcNowDefinition = () => dateTimeOffset; } public class ResourceHandler { readonly caching test; public ResourceHandler(caching test) { this.test = test; } public object Get() { return test.resource; } } } }
using eWAY.Rapid.Enums; using eWAY.Rapid.Models; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace eWAY.Rapid.Tests.IntegrationTests { [TestClass] public class SettlementSearchTests : SdkTestBase { [TestMethod] public void SettlementSearch_ByDate_Test() { var client = CreateRapidApiClient(); //Arrange //Act var settlementSearch = new SettlementSearchRequest() { ReportMode = SettlementSearchMode.Both, SettlementDate = "2016-02-01" }; var settlementResponse = client.SettlementSearch(settlementSearch); //Assert Assert.IsNotNull(settlementResponse); } [TestMethod] public void SettlementSearch_ByDateRange_Test() { var client = CreateRapidApiClient(); //Arrange //Act var settlementSearch = new SettlementSearchRequest() { ReportMode = SettlementSearchMode.Both, StartDate = "2016-02-01", EndDate = "2016-02-08", CardType = CardType.ALL, }; var settlementResponse = client.SettlementSearch(settlementSearch); //Assert Assert.IsNotNull(settlementResponse); Assert.IsTrue(settlementResponse.SettlementTransactions.Length >= 0); Assert.IsTrue(settlementResponse.SettlementSummaries.Length >= 0); } [TestMethod] public void SettlementSearch_WithPage_Test() { var client = CreateRapidApiClient(); //Arrange //Act var settlementSearch = new SettlementSearchRequest() { ReportMode = SettlementSearchMode.TransactionOnly, SettlementDate = "2016-02-01", Page = 1, PageSize = 5 }; var settlementResponse = client.SettlementSearch(settlementSearch); //Assert Assert.IsNotNull(settlementResponse); Assert.IsTrue(settlementResponse.SettlementTransactions.Length < 6); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; [AttributeUsage(AttributeTargets.Field)] public class WellKnownTypeLookupAttribute : Attribute { // // State // public readonly string AssemblyName; public readonly string Namespace; public readonly string Name; // // Constructor Methods // public WellKnownTypeLookupAttribute( string assemblyName , string nameSpace , string name ) { this.AssemblyName = assemblyName; this.Namespace = nameSpace; this.Name = name; } } }
// Amplify Shader Editor - Visual Shader Editing Tool // Copyright (c) Amplify Creations, Lda <info@amplify.pt> namespace AmplifyShaderEditor { [System.Serializable] [NodeAttributes( "Texture 1 Matrix", "Matrix Transform", "Texture 1 Matrix" )] public sealed class Texture1MatrixNode : ConstantShaderVariable { protected override void CommonInit( int uniqueId ) { base.CommonInit( uniqueId ); ChangeOutputProperties( 0, "Out", WirePortDataType.FLOAT4x4 ); m_value = "UNITY_MATRIX_TEXTURE1"; m_drawPreview = false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RimWorld; using HarmonyLib; using Verse; using System.Reflection; namespace DArcaneTechnology.CorePatches { class Patch_CanEquip_Postfix { private static void Postfix(Thing thing, Pawn pawn, ref string cantReason, ref bool __result) { if (__result == true) { if (Base.IsResearchLocked(thing.def, pawn)) { __result = false; cantReason = "DUnknownTechnology".Translate(); } } } } }
namespace MuOnline.Core.Commands { using MuOnline.Core.Commands.Contracts; using MuOnline.Models.Heroes.HeroContracts; using MuOnline.Models.Items.Contracts; using MuOnline.Repositories.Contracts; public class AddItemToHeroCommand : ICommand { private const string successfullMessage = "Successfully added {0} to hero {1}"; private readonly IRepository<IHero> heroRepository; private readonly IRepository<IItem> itemRepository; public AddItemToHeroCommand( IRepository<IHero> heroRepository, IRepository<IItem> itemRepository) { this.heroRepository = heroRepository; this.itemRepository = itemRepository; } public string Execute(string[] inputArgs) { string heroUsername = inputArgs[0]; string itemName = inputArgs[1]; var hero = this.heroRepository.Get(heroUsername); var item = this.itemRepository.Get(itemName); hero.Inventory.AddItem(item); return string.Format(successfullMessage, item.GetType().Name, heroUsername); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class warningMessage : MonoBehaviour { SpriteRenderer sprite; float timer; // Use this for initialization void Start () { sprite = GetComponent<SpriteRenderer>(); } // Update is called once per frame void FixedUpdate () { timer += Time.deltaTime; if (timer > 0.7f) { //sprite.color = Color.Lerp(sprite.color, new Color(255, 255, 255, 1), Time.deltaTime); sprite.color = new Color(255, 255, 255, 0.5f); } else { //sprite.color = Color.Lerp(sprite.color, new Color(255, 255, 255, 1), Time.deltaTime / 2); sprite.color = new Color(255, 255, 255, 1f); } if (timer > 1.1f) { timer = 0; } //sprite.color = new Color(255, 255, 255, 0.5f); } }
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; namespace Microsoft.FeatureFlighting.Api.Controllers { /// <summary> /// Controller to check the health of the system /// </summary> [Route("api/probe")] public class ProbeController : ControllerBase { private readonly IConfiguration _config; /// <summary> /// Constructor /// </summary> public ProbeController(IConfiguration config) { _config = config; } /// <summary> /// Simple Ping controller /// </summary> /// <returns></returns> [HttpGet] [Route("ping")] public IActionResult Ping([FromQuery] string echo = "Pong") { return new OkObjectResult(echo); } } }
using System.Linq; namespace MsSql.Adapter.Collector.Types { public static class Helpers { public static bool IsOperationResult(this ResponseItem item) { if (item.Params.Count != 2) return false; if (!item.Params.Any(x => x.Name == "StatusCode")) return false; if (!item.Params.Any(x => x.Name == "StatusMessage")) return false; return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Defence { interface ICommando : ISpecialisedSoldier { List<Mission> missions { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WebAssemblyInfo { enum Opcode : byte { // control Unreachable = 0x00, Nop = 0x01, Block = 0x02, Loop = 0x03, If = 0x04, Else = 0x05, End = 0x0b, Br = 0x0c, Br_If = 0x0d, Br_Table = 0x0e, Return = 0x0f, Call = 0x10, Call_Indirect = 0x11, // reference Ref_Null = 0xd0, Ref_Is_Null = 0xd1, Ref_Func = 0xd2, // parametric Drop = 0x1a, Select = 0x1b, Select_Vec = 0x1c, // variable Local_Get = 0x20, Local_Set = 0x21, Local_Tee = 0x22, Global_Get = 0x23, Global_Set = 0x24, // table Table_Get = 0x25, Table_Set = 0x26, // memory I32_Load = 0x28, I64_Load = 0x29, F32_Load = 0x2a, F64_Load = 0x2b, I32_Load8_S = 0x2c, I32_Load8_U = 0x2d, I32_Load16_S = 0x2e, I32_Load16_U = 0x2f, I64_Load8_S = 0x30, I64_Load8_U = 0x31, I64_Load16_S = 0x32, I64_Load16_U = 0x33, I64_Load32_S = 0x34, I64_Load32_U = 0x35, I32_Store = 0x36, I64_Store = 0x37, F32_Store = 0x38, F64_Store = 0x39, I32_Store8 = 0x3a, I32_Store16 = 0x3b, I64_Store8 = 0x3c, I64_Store16 = 0x3d, I64_Store32 = 0x3e, Memory_Size = 0x3f, Memory_Grow = 0x40, // numeric I32_Const = 0x41, I64_Const = 0x42, F32_Const = 0x43, F64_Const = 0x44, I32_Eqz = 0x45, I32_Eq = 0x46, I32_Ne = 0x47, I32_Lt_S = 0x48, I32_Lt_U = 0x49, I32_Gt_S = 0x4a, I32_Gt_U = 0x4b, I32_Le_S = 0x4c, I32_Le_U = 0x4d, I32_Ge_S = 0x4e, I32_Ge_U = 0x4f, I64_Eqz = 0x50, I64_Eq = 0x51, I64_Ne = 0x52, I64_Lt_S = 0x53, I64_Lt_U = 0x54, I64_Gt_S = 0x55, I64_Gt_U = 0x56, I64_Le_S = 0x57, I64_Le_U = 0x58, I64_Ge_S = 0x59, I64_Ge_U = 0x5a, F32_Eq = 0x5b, F32_Ne = 0x5c, F32_Lt = 0x5d, F32_Gt = 0x5e, F32_Le = 0x5f, F32_Ge = 0x60, F64_Eq = 0x61, F64_Ne = 0x62, F64_Lt = 0x63, F64_Gt = 0x64, F64_Le = 0x65, F64_Ge = 0x66, I32_Clz = 0x67, I32_Ctz = 0x68, I32_Popcnt = 0x69, I32_Add = 0x6a, I32_Sub = 0x6b, I32_Mul = 0x6c, I32_Div_S = 0x6d, I32_Div_U = 0x6e, I32_Rem_S = 0x6f, I32_Rem_U = 0x70, I32_And = 0x71, I32_Or = 0x72, I32_Xor = 0x73, I32_Shl = 0x74, I32_Shr_S = 0x75, I32_Shr_U = 0x76, I32_Rotl = 0x77, I32_Rotr = 0x78, I64_Clz = 0x79, I64_Ctz = 0x7a, I64_Popcnt = 0x7b, I64_Add = 0x7c, I64_Sub = 0x7d, I64_Mul = 0x7e, I64_Div_S = 0x7f, I64_Div_U = 0x80, I64_Rem_S = 0x81, I64_Rem_U = 0x82, I64_And = 0x83, I64_Or = 0x84, I64_Xor = 0x85, I64_Shl = 0x86, I64_Shr_S = 0x87, I64_Shr_U = 0x88, I64_Rotl = 0x89, I64_Rotr = 0x8a, F32_Abs = 0x8b, F32_Neg = 0x8c, F32_Ceil = 0x8d, F32_Floor = 0x8e, F32_Trunc = 0x8f, F32_Nearest = 0x90, F32_Sqrt = 0x91, F32_Add = 0x92, F32_Sub = 0x93, F32_Mul = 0x94, F32_Div = 0x95, F32_Min = 0x96, F32_Max = 0x97, F32_Copysign = 0x98, F64_Abs = 0x99, F64_Neg = 0x9a, F64_Ceil = 0x9b, F64_Floor = 0x9c, F64_Trunc = 0x9d, F64_Nearest = 0x9e, F64_Sqrt = 0x9f, F64_Add = 0xa0, F64_Sub = 0xa1, F64_Mul = 0xa2, F64_Div = 0xa3, F64_Min = 0xa4, F64_Max = 0xa5, F64_Copysign = 0xa6, I32_Wrap_I64 = 0xa7, I32_Trunc_F32_S = 0xa8, I32_Trunc_F32_U = 0xa9, I32_Trunc_F64_S = 0xaa, I32_Trunc_F64_U = 0xab, I64_Extend_I32_S = 0xac, I64_Extend_I32_U = 0xad, I64_Trunc_F32_S = 0xae, I64_Trunc_F32_U = 0xaf, I64_Trunc_F64_S = 0xb0, I64_Trunc_F64_U = 0xb1, F32_Convert_I32_S = 0xb2, F32_Convert_I32_U = 0xb3, F32_Convert_I64_S = 0xb4, F32_Convert_I64_U = 0xb5, F32_Demote_F64 = 0xb6, F64_Convert_I32_S = 0xb7, F64_Convert_I32_U = 0xb8, F64_Convert_I64_S = 0xb9, F64_Convert_I64_U = 0xba, F64_Promote_F32 = 0xbb, I32_Reinterpret_F32 = 0xbc, I64_Reinterpret_F64 = 0xbd, F32_Reinterpret_I32 = 0xbe, F64_Reinterpret_I64 = 0xbf, I32_Extend8_S = 0xc0, I32_Extend16_S = 0xc1, I64_Extend8_S = 0xc2, I64_Extend16_S = 0xc3, I64_Extend32_S = 0xc4, // special Prefix = 0xfc, } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.AI.Luis; using Microsoft.Bot.Builder.AI.QnA; namespace Microsoft.Bot.Solutions { [ExcludeFromCodeCoverageAttribute] public class CognitiveModelSet { public IRecognizer DispatchService { get; set; } public Dictionary<string, LuisRecognizer> LuisServices { get; set; } = new Dictionary<string, LuisRecognizer>(); [Obsolete("Please update your Virtual Assistant to use the new QnAMakerDialog with Multi Turn and Active Learning support instead. For more information, refer to https://aka.ms/bfvaqnamakerupdate.", false)] public Dictionary<string, QnAMaker> QnAServices { get; set; } = new Dictionary<string, QnAMaker>(); public Dictionary<string, QnAMakerEndpoint> QnAConfiguration { get; set; } = new Dictionary<string, QnAMakerEndpoint>(); } }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Dolittle. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *--------------------------------------------------------------------------------------------*/ using Machine.Specifications; using Moq; using Dolittle.Types.Testing; namespace Dolittle.Resilience.Specs.for_Policies.given { public class defined_default_policy { protected static Policies policies; protected static Mock<IDefineDefaultPolicy> policy_definer; protected static Polly.Policy underlying_policy; Establish context = () => { policy_definer = new Mock<IDefineDefaultPolicy>(); underlying_policy = Polly.Policy.NoOp(); policy_definer.Setup(_ => _.Define()).Returns(underlying_policy); policies = new Policies( new StaticInstancesOf<IDefineDefaultPolicy>(policy_definer.Object), new StaticInstancesOf<IDefineNamedPolicy>(), new StaticInstancesOf<IDefinePolicyForType>() ); }; } }
using System; using System.Collections.Generic; using Newtonsoft.Json; using Comformation.IntrinsicFunctions; namespace Comformation.Config.ConfigRule { /// <summary> /// AWS::Config::ConfigRule Scope /// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configrule-scope.html /// </summary> public class Scope { /// <summary> /// ComplianceResourceId /// /// The ID of the only AWS resource that you want to trigger an evaluation for the rule. If you /// specify a resource ID, you must specify one resource type for ComplianceResourceTypes. /// /// Required: No /// Type: String /// Minimum: 1 /// Maximum: 768 /// Update requires: No interruption /// </summary> [JsonProperty("ComplianceResourceId")] public Union<string, IntrinsicFunction> ComplianceResourceId { get; set; } /// <summary> /// ComplianceResourceTypes /// /// The resource types of only those AWS resources that you want to trigger an evaluation for the /// rule. You can only specify one type if you also specify a resource ID for /// ComplianceResourceId. /// /// Required: No /// Type: List of String /// Maximum: 100 /// Update requires: No interruption /// </summary> [JsonProperty("ComplianceResourceTypes")] public List<Union<string, IntrinsicFunction>> ComplianceResourceTypes { get; set; } /// <summary> /// TagKey /// /// The tag key that is applied to only those AWS resources that you want to trigger an evaluation /// for the rule. /// /// Required: No /// Type: String /// Minimum: 1 /// Maximum: 128 /// Update requires: No interruption /// </summary> [JsonProperty("TagKey")] public Union<string, IntrinsicFunction> TagKey { get; set; } /// <summary> /// TagValue /// /// The tag value applied to only those AWS resources that you want to trigger an evaluation for the /// rule. If you specify a value for TagValue, you must also specify a value for TagKey. /// /// Required: No /// Type: String /// Minimum: 1 /// Maximum: 256 /// Update requires: No interruption /// </summary> [JsonProperty("TagValue")] public Union<string, IntrinsicFunction> TagValue { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ButtonCollision : MonoBehaviour { //Attach to objects that are able to press buttons. void OnCollisionEnter(Collision coll){ ButtonClick script = coll.collider.GetComponent<ButtonClick>(); if(script != null){ script.ButtonAction(); } } }
using Assets.Scripts.Types; namespace Assets.Scripts.Components.Debug.TargetMapper { public class DefaultTargetMapper : IDebugTargetMapper { public DebugImageTarget? Map(string name) { switch (name) { case "CorrectTextTarget": return DebugImageTarget.GermanNoErrors; case "ErrorTextTarget": return DebugImageTarget.GermanErrors; case "GermanCurseWordsTarget": return DebugImageTarget.GermanCurseWords; case "EnglishErrorTarget": return DebugImageTarget.EnglishErrors; case "EnglishCurseWordTarget": return DebugImageTarget.EnglishCurseWords; case "EnglishErrorAndCurseWordsTarget": return DebugImageTarget.EnglishErrorsAndCurseWordsTarget; case "EnglishNoErrorTarget": return DebugImageTarget.EnglishNoErrors; default: return null; } } } }
using System; using System.IO; using System.Text; using Newtonsoft.Json.Linq; namespace OpenBots.Core.ChromeNativeClient { public class ServerCommunication { private readonly Stream _Stream; private readonly UnicodeEncoding _StreamEncoding; public ServerCommunication(Stream stream) { _Stream = stream; _StreamEncoding = new UnicodeEncoding(); } public string ReadMessage() { int length = _Stream.ReadByte()*256; length += _Stream.ReadByte(); byte[] buffer = new byte[length]; _Stream.Read(buffer, 0, length); return _StreamEncoding.GetString(buffer); } public JObject ReadMessageAsJObject() { int length = _Stream.ReadByte()*256; length += _Stream.ReadByte(); byte[] buffer = new byte[length]; _Stream.Read(buffer, 0, length); string msg = _StreamEncoding.GetString(buffer); return JObject.Parse(msg); } public int SendMessage(string outString) { byte[] buffer = _StreamEncoding.GetBytes(outString); int length = buffer.Length; if (length > UInt16.MaxValue) { length = (int) UInt16.MaxValue; } _Stream.WriteByte((byte) (length / 256)); _Stream.WriteByte((byte) (length & 255)); _Stream.Write(buffer, 0, length); _Stream.Flush(); return buffer.Length + 2; } } }
using System; using Microsoft.Owin.Hosting; using System.Threading; namespace MediaCentreServer { class Program { private const int port = 55343; static void Main(string[] args) { // Fire event on Ctrl+C. var quitEvent = new ManualResetEvent(false); Console.CancelKeyPress += (o, e) => { quitEvent.Set(); e.Cancel = true; }; var url = $"http://*:{port}"; using (WebApp.Start<Startup>(url)) { Console.WriteLine($"Listening on port {port}"); // Wait for Ctrl+C (which RunInTray uses to trigger exit). quitEvent.WaitOne(); } } } }
using Microsoft.EntityFrameworkCore; using System.ComponentModel.DataAnnotations; namespace DotNetCoreDemo { public class DBContext : DbContext { public DBContext(DbContextOptions<DBContext> options) : base(options) { } //public DbSet<WebLoggingModel> WebLogging { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<WebLoggingModel>().ToTable<WebLoggingModel>("syslogging"); } } internal class WebLoggingModel { [Key] public int cix { get; set; } } }
using UnityEngine; using System.Collections; public class board : MonoBehaviour { public GameObject gameParent; private game bingoGame; void Start() { bingoGame = gameParent.GetComponent<game> (); } void OnMouseDown() { // Handle someone pressing the board bingoGame.BoardClicked (gameObject.name); } }
// // Copyright (C) 2013 EllieWare // // All rights reserved // // www.EllieWare.com // using System; using System.IO; using System.IO.IsolatedStorage; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; using System.Windows.Forms; namespace EllieWare.Support { public static class WindowPersister { private static string GetSettingsFileName(Assembly assy) { return assy.FullName + ".Settings"; } private static IsolatedStorageFile GetIsolatedStorageFile() { try { return IsolatedStorageFile.GetStore( IsolatedStorageScope.User | IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain, typeof(System.Security.Policy.Url), typeof(System.Security.Policy.Url)); } catch (IsolatedStorageException) { // probably running inside an app domain return IsolatedStorageFile.GetUserStoreForAssembly(); } } public static void Restore(Assembly assy, Form form, params SplitContainer[] splitters) { using (var store = GetIsolatedStorageFile()) { var settingsFileName = GetSettingsFileName(assy); if (!store.FileExists(settingsFileName)) { // probably first time run return; } using (var settings = store.OpenFile(settingsFileName, FileMode.Open)) { var formatter = new BinaryFormatter(); var windowSettings = (WindowSettings.WindowSettings)formatter.Deserialize(settings); windowSettings.Restore(form, splitters); } } } public static void Record(Assembly assy, Form form, params SplitContainer[] splitters) { using (var store = GetIsolatedStorageFile()) { using (var settings = store.OpenFile(GetSettingsFileName(assy), FileMode.OpenOrCreate)) { var windowSettings = new WindowSettings.WindowSettings(); windowSettings.Record(form, splitters); var formatter = new BinaryFormatter(); formatter.Serialize(settings, windowSettings); } } } } }
using UnityEngine; using System; using UnityEngine.EventSystems; public class MouseListener : MonoBehaviour, IPointerUpHandler, IPointerDownHandler { public event Action<PointerEventData> LeftClick; public event Action<PointerEventData> RightClick; public event Action<PointerEventData> LeftClickDraggedUp; public event Action<PointerEventData> LeftClickDraggedDown; public event Action<PointerEventData> RightClickDraggedUp; public event Action<PointerEventData> RightClickDraggedDown; private float lastMousePos; private float firstMousePos; private float targetPos; public void OnPointerDown(PointerEventData eventData) { firstMousePos = eventData.position.y; if (Input.GetMouseButtonDown(0)) { LeftClick?.Invoke(eventData); } if (Input.GetMouseButtonDown(1)) { RightClick?.Invoke(eventData); } } public void OnPointerUp(PointerEventData eventData) { lastMousePos = eventData.position.y; targetPos = lastMousePos - firstMousePos; if (Input.GetMouseButtonUp(0) && targetPos > 0.0f) { LeftClickDraggedUp?.Invoke(eventData); } if (Input.GetMouseButtonUp(0) && targetPos < 0.0f) { LeftClickDraggedDown?.Invoke(eventData); } if (Input.GetMouseButtonUp(1) && targetPos > 0.0f) { RightClickDraggedUp?.Invoke(eventData); } if (Input.GetMouseButtonUp(1) && targetPos < 0.0f) { RightClickDraggedDown?.Invoke(eventData); } } }
using System.Threading.Tasks; using FluentAssertions; using Xunit; using AArray = System.Collections.Generic.List<object>; using AObject = System.Collections.Generic.Dictionary<string, object>; namespace MR.Augmenter { public class AugmenterTest : TestHost { private AugmenterConfiguration _configuration; private Augmenter _fixture; public AugmenterTest() { _configuration = CreateCommonConfiguration(); _fixture = MocksHelper.Augmenter(_configuration); } public class BasicTest : AugmenterTest { [Fact] public async Task Basic() { var model = new TestModel1(); var result = await _fixture.AugmentAsync(model) as AObject; ((string)result["Bar"]).Should().Be($"({model.Id})"); result.Should().NotContainKey(nameof(TestModel1.Some)); } [Fact] public async Task WithLocal() { var model = new TestModel1(); var result = await _fixture.AugmentAsync(model, c => { c.Add("Baz", (_, __) => 2); }) as AObject; result["Bar"].Cast<string>().Should().Be($"({model.Id})"); result["Baz"].Cast<int>().Should().Be(2); result.Should().NotContainKey(nameof(TestModel1.Some)); } [Fact] public async Task Add_WithIgnore_IgnoresAugment() { var model = new TestModel1(); var result = await _fixture.AugmentAsync(model, c => { c.Add("Some", (_, __) => AugmentationValue.Ignore); }) as AObject; result.Should().NotContainKey("Some"); } [Fact] public async Task Remove_WithIgnore_IgnoresAugment() { var model = new TestModel1(); var result = await _fixture.AugmentAsync(model, c => { c.Remove(nameof(TestModel1.Foo), (_, __) => AugmentationValue.Ignore); }) as AObject; result[nameof(TestModel1.Foo)].Cast<string>().Should().Be("foo"); } [Fact] public async Task Enums() { var model = new TestModelWithEnum(); var result = await _fixture.AugmentAsync(model, c => { /* force augment */ }) as AObject; result[nameof(TestModelWithEnum.Some)].Cast<SomeEnum>().Should().Be(SomeEnum.Bar); } [Fact] public async Task WrapperAroundArray() { var wrapper = new AugmenterWrapper<TestModelForWrapping>(new[] { new TestModelForWrapping() { Id = 42, Model = new TestModel1() }, new TestModelForWrapping() { Id = 43, Model = new TestModel1() } }); wrapper.SetTypeConfiguration(c => { c.Add("Foo", (x, state) => $"{x.Id}-foo"); }); var model = new { Models = wrapper }; var result = await _fixture.AugmentAsync(model) as AObject; result["Models"].GetType().Should().Be(typeof(AArray)); var list = result["Models"] as AArray; list.Should().HaveCount(2); list[0].Cast<AObject>()["Foo"].Cast<string>().Should().Be("42-foo"); list[1].Cast<AObject>()["Foo"].Cast<string>().Should().Be("43-foo"); } [Fact] public async Task WrapperAroundArray_Direct() { var wrapper = new AugmenterWrapper<TestModelForWrapping>(new[] { new TestModelForWrapping() { Id = 42, Model = new TestModel1() }, new TestModelForWrapping() { Id = 43, Model = new TestModel1() } }); wrapper.SetTypeConfiguration(c => { c.Add("Foo", (x, state) => $"{x.Id}-foo"); }); var result = await _fixture.AugmentAsync(wrapper) as AArray; result.Should().NotBeNull().And.Subject.Should().HaveCount(2); result[0].Cast<AObject>()["Foo"].Cast<string>().Should().Be("42-foo"); result[1].Cast<AObject>()["Foo"].Cast<string>().Should().Be("43-foo"); } [Fact] public async Task Custom() { var configuration = new AugmenterConfiguration(); configuration.Configure<TestModel1>(c => { c.Custom((x, d) => { d["Opt1"] = Boxed.True; d["Opt2"] = Boxed.False; d["Opt3"] = "something"; d.Remove(nameof(TestModel1.Foo)); }); }); configuration.Build(); var augmenter = MocksHelper.Augmenter(configuration); var model = new TestModel1(); var result = (await augmenter.AugmentAsync(model)).Cast<AObject>(); result["Opt1"].Should().Be(Boxed.True); result["Opt2"].Should().Be(Boxed.False); result["Opt3"].Should().Be("something"); result.Should().NotContainKey(nameof(TestModel1.Foo)); } } public class ThroughInterfaceTest : AugmenterTest { [Fact] public async Task ThroughInterface() { var model = new TestModelD(); var result = await _fixture.AugmentAsync(model) as AObject; result.Should().NotContainKey("Names"); } } public class NestedTest : AugmenterTest { public NestedTest() { _configuration = new AugmenterConfiguration(); _configuration.Configure<TestModel1>(c => { }); _configuration.Configure<TestModelWithNested>(c => { c.Add("Foo", (_, __) => "42"); }); _configuration.Configure<TestModelNested>(c => { c.Add("Foo", (_, __) => "43"); }); _configuration.Configure<TestModelNestedNested>(c => { c.Add("Foo", (_, __) => "44"); }); _configuration.Build(); _fixture = MocksHelper.Augmenter(_configuration); } [Fact] public async Task Basic() { var model = new TestModelWithNested(); var result = await _fixture.AugmentAsync(model) as AObject; result["Foo"].Cast<string>().Should().Be("42"); var nested = result["Nested"].Cast<AObject>(); nested["Foo"].Cast<string>().Should().Be("43"); var nestedNested = nested["Nested"].Cast<AObject>(); nestedNested["Foo"].Cast<string>().Should().Be("44"); } [Fact] public async Task Array() { var model = new { Models = new[] { new TestModelWithNested(), new TestModelWithNested() } }; var result = await _fixture.AugmentAsync(model) as AObject; result["Models"].GetType().Should().Be(typeof(AArray)); result["Models"].Cast<AArray>().Should().HaveCount(2); } [Fact] public async Task HandlesNullComplex() { var model = new TestModelForWrapping() { Id = 42, Model = null }; var result = await _fixture.AugmentAsync(model) as AObject; result["Model"].Should().BeNull(); } [Fact] public async Task Wrapper() { var model = new { Model = new AugmenterWrapper<TestModelForWrapping>( new TestModelForWrapping() { Id = 42, Model = new TestModel1() }) }; var result = await _fixture.AugmentAsync(model) as AObject; result["Model"].Cast<AObject>().Should().HaveCount(3); result["Model"].Cast<AObject>()["Id"].Cast<int>().Should().Be(42); result["Model"].Cast<AObject>()["Model"].Cast<AObject>()["Id"].Cast<int>().Should().Be(42); } [Fact] public async Task ArrayAndWrapper() { var model = new { Models = new[] { new AugmenterWrapper<TestModelForWrapping>( new TestModelForWrapping() { Id = 42, Model = new TestModel1() }), new AugmenterWrapper<TestModelForWrapping>( new TestModelForWrapping() { Id = 43, Model = new TestModel1() }) } }; var result = await _fixture.AugmentAsync(model) as AObject; result["Models"].GetType().Should().Be(typeof(AArray)); var list = result["Models"] as AArray; list.Should().HaveCount(2); list[0].Cast<AObject>()["Id"].Cast<int>().Should().Be(42); list[1].Cast<AObject>()["Id"].Cast<int>().Should().Be(43); } } public class StateTest : AugmenterTest { public StateTest() { _configuration = CreateBuiltConfiguration(); _fixture = MocksHelper.Augmenter(_configuration); } [Fact] public async Task Globally() { var model = new TestModel1(); _configuration = new AugmenterConfiguration(); _configuration.Configure<TestModel1>(c => { c.Add("Bar", (x, state) => { return state["key"]; }); }); _configuration.Build(); _fixture = MocksHelper.Augmenter(_configuration); var result = await _fixture.AugmentAsync(model, addState: state => { state.Add("key", "bar"); }) as AObject; result["Bar"].Cast<string>().Should().Be("bar"); } [Fact] public async Task Locally() { var model = new TestModel1(); var result = await _fixture.AugmentAsync(model, c => { c.Add("Bar", (x, state) => { return state["key"]; }); }, state => { state.Add("key", "bar"); }) as AObject; result["Bar"].Cast<string>().Should().Be("bar"); } [Fact] public async Task Nested() { var model = new TestModelWithNested(); _configuration = new AugmenterConfiguration(); _configuration.Configure<TestModelNested>(c => { c.Add("Foo", (x, state) => { return state["key"]; }); }); _configuration.Build(); _fixture = MocksHelper.Augmenter(_configuration); var result = await _fixture.AugmentAsync(model, addState: state => { state.Add("key", "foo"); }) as AObject; result["Nested"].Cast<AObject>()["Foo"].Cast<string>().Should().Be("foo"); } [Fact] public async Task WithIgnore() { var model = new TestModel1(); var result = await _fixture.AugmentAsync(model, config => { config.Add("Bar", (x, state) => { if ((bool)state["key"]) { return "YES"; } return AugmentationValue.Ignore; }); }, state => { state.Add("key", false); }) as AObject; result.Should().NotContainKey("Bar"); } } public class NestedConfigureTest : AugmenterTest { public NestedConfigureTest() { var configuration = new AugmenterConfiguration(); configuration.Configure<NestedConfigureModels.Model1>(c => { c.Add("Bar", (x, _) => $"({x.Id})"); c.Remove(nameof(NestedConfigureModels.Model1.Ex)); c.ConfigureNested(x => x.Nested1, nc => { nc.SetAddState((m, s1, s2) => { s2["ParentId"] = m.Id; }); nc.SetTypeConfiguration(ntc => { ntc.Add("Some", (x, state) => "some"); }); }); }); configuration.Configure<NestedConfigureModels.Model2>(c => { }); configuration.Configure<NestedConfigureModels.Model3>(c => { c.ConfigureNestedArray(x => x.Nested, nc => { nc.SetAddState((m, s1, s2) => { s2["ParentId"] = m.Id; }); nc.SetTypeConfiguration(ntc => { ntc.Add("Some", (x, state) => "some"); }); }); }); configuration.Configure<NestedConfigureModels.Model4>(c => { c.ConfigureNestedArray(x => x.Nested, nc => { nc.SetAddState((m, s1, s2) => { s2["ParentId"] = m.Id; }); nc.SetTypeConfiguration(ntc => { ntc.Add("Some", (x, state) => "some"); }); }); }); configuration.Configure<NestedConfigureModels.ModelNested>(c => { c.AddIf("ParentId", "ParentId", (m, s) => s["ParentId"]); }); configuration.Build(); _configuration = configuration; _fixture = MocksHelper.Augmenter(_configuration); } [Fact] public async Task Picks_up_nested_state_and_configuration() { var model = new NestedConfigureModels.Model2(); var result = await _fixture.AugmentAsync(model) as AObject; var nested = result["Nested1"].Cast<AObject>(); nested["ParentId"].Cast<int>().Should().Be(model.Id); nested["Some"].Cast<string>().Should().Be("some"); } [Fact] public async Task Other_entities_of_the_same_type_are_not_affected() { var model = new NestedConfigureModels.Model2(); var result = await _fixture.AugmentAsync(model) as AObject; var nested = result["Nested2"].Cast<AObject>(); nested.Should().NotContainKeys("ParentId", "Some"); } [Fact] public async Task Works_with_enumerables() { var model = new NestedConfigureModels.Model3(); var result = await _fixture.AugmentAsync(model) as AObject; var nested = result["Nested"].Cast<AArray>(); foreach (var item in nested) { item.Cast<AObject>()["ParentId"].Should().Be(model.Id); item.Cast<AObject>()["Some"].Should().Be("some"); } } [Fact] public async Task Works_with_arrays() { var model = new NestedConfigureModels.Model4(); var result = await _fixture.AugmentAsync(model) as AObject; var nested = result["Nested"].Cast<AArray>(); foreach (var item in nested) { item.Cast<AObject>()["ParentId"].Should().Be(model.Id); item.Cast<AObject>()["Some"].Should().Be("some"); } } } } }
namespace SampleApp { partial class MainForm { /// <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.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.simpleExample1 = new SampleApp.SimpleExample(); this.tabPage3 = new System.Windows.Forms.TabPage(); this.advancedExample1 = new SampleApp.AdvancedExample(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.folderBrowser1 = new SampleApp.FolderBrowser(); this.tabPage4 = new System.Windows.Forms.TabPage(); this.performanceTest1 = new SampleApp.PerformanceTest(); this.tabPage5 = new System.Windows.Forms.TabPage(); this.hiddenColumn1 = new SampleApp.ColumnHandling(); this.tabPage6 = new System.Windows.Forms.TabPage(); this.backgroundExpand1 = new SampleApp.BackgroundExpand(); this.tabPage7 = new System.Windows.Forms.TabPage(); this.dataTableTreeExample1 = new SampleApp.DataTableTreeExample(); this.tabControl1.SuspendLayout(); this.tabPage2.SuspendLayout(); this.tabPage3.SuspendLayout(); this.tabPage1.SuspendLayout(); this.tabPage4.SuspendLayout(); this.tabPage5.SuspendLayout(); this.tabPage6.SuspendLayout(); this.tabPage7.SuspendLayout(); this.SuspendLayout(); // // tabControl1 // this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Controls.Add(this.tabPage3); this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage4); this.tabControl1.Controls.Add(this.tabPage5); this.tabControl1.Controls.Add(this.tabPage6); this.tabControl1.Controls.Add(this.tabPage7); this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControl1.Location = new System.Drawing.Point(0, 0); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(834, 589); this.tabControl1.TabIndex = 0; // // tabPage2 // this.tabPage2.Controls.Add(this.simpleExample1); this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Padding = new System.Windows.Forms.Padding(3); this.tabPage2.Size = new System.Drawing.Size(826, 563); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Simple Example"; this.tabPage2.UseVisualStyleBackColor = true; // // simpleExample1 // this.simpleExample1.Dock = System.Windows.Forms.DockStyle.Fill; this.simpleExample1.Location = new System.Drawing.Point(3, 3); this.simpleExample1.Name = "simpleExample1"; this.simpleExample1.Size = new System.Drawing.Size(820, 557); this.simpleExample1.TabIndex = 0; // // tabPage3 // this.tabPage3.Controls.Add(this.advancedExample1); this.tabPage3.Location = new System.Drawing.Point(4, 22); this.tabPage3.Name = "tabPage3"; this.tabPage3.Padding = new System.Windows.Forms.Padding(3); this.tabPage3.Size = new System.Drawing.Size(826, 563); this.tabPage3.TabIndex = 2; this.tabPage3.Text = "Advanced Example"; this.tabPage3.UseVisualStyleBackColor = true; // // advancedExample1 // this.advancedExample1.Dock = System.Windows.Forms.DockStyle.Fill; this.advancedExample1.Location = new System.Drawing.Point(3, 3); this.advancedExample1.Name = "advancedExample1"; this.advancedExample1.Size = new System.Drawing.Size(820, 557); this.advancedExample1.TabIndex = 0; // // tabPage1 // this.tabPage1.Controls.Add(this.folderBrowser1); this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(3); this.tabPage1.Size = new System.Drawing.Size(826, 563); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Folder Browser"; this.tabPage1.UseVisualStyleBackColor = true; // // folderBrowser1 // this.folderBrowser1.Dock = System.Windows.Forms.DockStyle.Fill; this.folderBrowser1.Location = new System.Drawing.Point(3, 3); this.folderBrowser1.Name = "folderBrowser1"; this.folderBrowser1.Size = new System.Drawing.Size(820, 557); this.folderBrowser1.TabIndex = 0; // // tabPage4 // this.tabPage4.Controls.Add(this.performanceTest1); this.tabPage4.Location = new System.Drawing.Point(4, 22); this.tabPage4.Name = "tabPage4"; this.tabPage4.Padding = new System.Windows.Forms.Padding(3); this.tabPage4.Size = new System.Drawing.Size(826, 563); this.tabPage4.TabIndex = 3; this.tabPage4.Text = "Performance Test"; this.tabPage4.UseVisualStyleBackColor = true; // // performanceTest1 // this.performanceTest1.Dock = System.Windows.Forms.DockStyle.Fill; this.performanceTest1.Location = new System.Drawing.Point(3, 3); this.performanceTest1.Name = "performanceTest1"; this.performanceTest1.Size = new System.Drawing.Size(820, 557); this.performanceTest1.TabIndex = 0; // // tabPage5 // this.tabPage5.Controls.Add(this.hiddenColumn1); this.tabPage5.Location = new System.Drawing.Point(4, 22); this.tabPage5.Name = "tabPage5"; this.tabPage5.Size = new System.Drawing.Size(826, 563); this.tabPage5.TabIndex = 4; this.tabPage5.Text = "Column Handling"; this.tabPage5.UseVisualStyleBackColor = true; // // hiddenColumn1 // this.hiddenColumn1.Dock = System.Windows.Forms.DockStyle.Fill; this.hiddenColumn1.Location = new System.Drawing.Point(0, 0); this.hiddenColumn1.Name = "hiddenColumn1"; this.hiddenColumn1.Size = new System.Drawing.Size(826, 563); this.hiddenColumn1.TabIndex = 0; // // tabPage6 // this.tabPage6.Controls.Add(this.backgroundExpand1); this.tabPage6.Location = new System.Drawing.Point(4, 22); this.tabPage6.Name = "tabPage6"; this.tabPage6.Padding = new System.Windows.Forms.Padding(3); this.tabPage6.Size = new System.Drawing.Size(826, 563); this.tabPage6.TabIndex = 5; this.tabPage6.Text = "Background Expanding"; this.tabPage6.UseVisualStyleBackColor = true; // // backgroundExpand1 // this.backgroundExpand1.Dock = System.Windows.Forms.DockStyle.Fill; this.backgroundExpand1.Location = new System.Drawing.Point(3, 3); this.backgroundExpand1.Name = "backgroundExpand1"; this.backgroundExpand1.Size = new System.Drawing.Size(820, 557); this.backgroundExpand1.TabIndex = 0; // // tabPage7 // this.tabPage7.Controls.Add(this.dataTableTreeExample1); this.tabPage7.Location = new System.Drawing.Point(4, 22); this.tabPage7.Name = "tabPage7"; this.tabPage7.Padding = new System.Windows.Forms.Padding(3); this.tabPage7.Size = new System.Drawing.Size(826, 563); this.tabPage7.TabIndex = 6; this.tabPage7.Text = "DataTableModel"; this.tabPage7.UseVisualStyleBackColor = true; // // dataTableTreeExample1 // this.dataTableTreeExample1.Dock = System.Windows.Forms.DockStyle.Fill; this.dataTableTreeExample1.Location = new System.Drawing.Point(3, 3); this.dataTableTreeExample1.Name = "dataTableTreeExample1"; this.dataTableTreeExample1.Size = new System.Drawing.Size(820, 557); this.dataTableTreeExample1.TabIndex = 0; // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(834, 589); this.Controls.Add(this.tabControl1); this.Name = "MainForm"; this.Text = "Sample Application"; this.tabControl1.ResumeLayout(false); this.tabPage2.ResumeLayout(false); this.tabPage3.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.tabPage4.ResumeLayout(false); this.tabPage5.ResumeLayout(false); this.tabPage6.ResumeLayout(false); this.tabPage7.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.TabPage tabPage2; private FolderBrowser folderBrowser1; private SimpleExample simpleExample1; private System.Windows.Forms.TabPage tabPage3; private AdvancedExample advancedExample1; private System.Windows.Forms.TabPage tabPage4; private PerformanceTest performanceTest1; private System.Windows.Forms.TabPage tabPage5; private ColumnHandling hiddenColumn1; private System.Windows.Forms.TabPage tabPage6; private BackgroundExpand backgroundExpand1; private System.Windows.Forms.TabPage tabPage7; private DataTableTreeExample dataTableTreeExample1; } }
#nullable enable using System.ComponentModel; using System.Windows.Forms; using BizHawk.Client.Common; using BizHawk.Common.StringExtensions; using BizHawk.WinForms.Controls; namespace BizHawk.Client.EmuHawk { public class FeedbackBindControl : UserControl { private readonly Container _components = new(); /// <summary>'+'-delimited e.g. <c>"Mono"</c>, <c>"Left"</c>, <c>"Left+Right"</c></summary> public string BoundChannels { get; private set; } public string BoundGamepadPrefix { get; private set; } public float Prescale { get; private set; } public readonly string VChannelName; public FeedbackBindControl(string vChannel, FeedbackBind existingBind, IHostInputAdapter hostInputAdapter) { BoundChannels = existingBind.Channels ?? string.Empty; BoundGamepadPrefix = existingBind.GamepadPrefix ?? string.Empty; Prescale = existingBind.IsZeroed ? 1.0f : existingBind.Prescale; VChannelName = vChannel; SzTextBoxEx txtBoundPrefix = new() { ReadOnly = true, Size = new(19, 19) }; ComboBox cbBoundChannel = new() { Enabled = false, Size = new(112, 24) }; void UpdateDropdownAndLabel(string newPrefix) { txtBoundPrefix.Text = newPrefix; var wasSelected = (string) cbBoundChannel.SelectedItem; cbBoundChannel.Enabled = false; cbBoundChannel.SelectedIndex = -1; cbBoundChannel.Items.Clear(); if (hostInputAdapter.GetHapticsChannels().TryGetValue(newPrefix, out var channels) && channels.Count != 0) { var hasLeft = false; var hasRight = false; foreach (var hostChannel in channels) { cbBoundChannel.Items.Add(hostChannel); if (hostChannel == "Left") hasLeft = true; else if (hostChannel == "Right") hasRight = true; } if (hasLeft && hasRight) cbBoundChannel.Items.Add("Left+Right"); cbBoundChannel.SelectedItem = wasSelected; cbBoundChannel.Enabled = true; } else if (!string.IsNullOrEmpty(newPrefix)) { cbBoundChannel.Items.Add("(none available)"); cbBoundChannel.SelectedIndex = 0; } } UpdateDropdownAndLabel(BoundGamepadPrefix); cbBoundChannel.SelectedIndexChanged += (changedSender, _) => BoundChannels = (string?) ((ComboBox) changedSender).SelectedItem ?? string.Empty; SingleRowFLP flpBindReadout = new() { Controls = { txtBoundPrefix, cbBoundChannel, new LabelEx { Text = vChannel } } }; Timer timer = new(_components); SzButtonEx btnBind = new() { Size = new(75, 23), Text = "Bind!" }; void UpdateListeningState(bool newState) { if (newState) { Input.Instance.StartListeningForAxisEvents(); timer.Start(); btnBind.Text = "Cancel!"; } else { timer.Stop(); Input.Instance.StopListeningForAxisEvents(); btnBind.Text = "Bind!"; } } var isListening = false; timer.Tick += (_, _) => { var bindValue = Input.Instance.GetNextAxisEvent(); if (bindValue == null) return; UpdateListeningState(isListening = false); UpdateDropdownAndLabel(BoundGamepadPrefix = bindValue.SubstringBefore(' ') + ' '); }; btnBind.Click += (_, _) => UpdateListeningState(isListening = !isListening); SzButtonEx btnUnbind = new() { Size = new(75, 23), Text = "Unbind!" }; btnUnbind.Click += (_, _) => UpdateDropdownAndLabel(BoundGamepadPrefix = string.Empty); LocSingleColumnFLP flpButtons = new() { Controls = { btnBind, btnUnbind } }; LabelEx lblPrescale = new() { Margin = new(0, 0, 0, 24) }; TransparentTrackBar tbPrescale = new() { Maximum = 20, Size = new(96, 45), TickFrequency = 5 }; tbPrescale.ValueChanged += (changedSender, _) => { Prescale = ((TrackBar) changedSender).Value / 10.0f; lblPrescale.Text = $"Pre-scaled by: {Prescale:F1}x"; }; tbPrescale.Value = (int) (Prescale * 10.0f); LocSzSingleRowFLP flpPrescale = new() { Controls = { lblPrescale, tbPrescale }, Size = new(200, 32) }; SuspendLayout(); AutoScaleDimensions = new(6.0f, 13.0f); AutoScaleMode = AutoScaleMode.Font; Size = new(378, 99); Controls.Add(new SingleColumnFLP { Controls = { flpBindReadout, new SingleRowFLP { Controls = { flpButtons, flpPrescale } } } }); ResumeLayout(); } protected override void Dispose(bool disposing) { if (disposing) _components.Dispose(); base.Dispose(disposing); } } }
using System; using System.Runtime.InteropServices; using System.ComponentModel.DataAnnotations; namespace LeaderboardAPI.Interfaces { public class LeaderboardRowDTO { public Guid ClientId {get; set;} [Required] // TODO: Add an id validator public short LeaderboardId {get; set;} [Required] [Range(1, long.MaxValue, ErrorMessage = "Invalid rating supplied")] public long Rating {get; set;} } }
namespace Auction.Web.ViewModels.Item.Admin { public class ItemManagementViewModel { public string Id { get; set; } public string Name { get; set; } public string Picture { get; set; } public string HighestBid { get; set; } public string BidderId { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using ServiceStack.IO; namespace ServiceStack.VirtualPath { public abstract class AbstractVirtualDirectoryBase : IVirtualDirectory { protected IVirtualPathProvider VirtualPathProvider; public IVirtualDirectory ParentDirectory { get; set; } public IVirtualDirectory Directory => this; public abstract DateTime LastModified { get; } public virtual string VirtualPath => GetVirtualPathToRoot(); public virtual string RealPath => GetRealPathToRoot(); public virtual bool IsDirectory => true; public virtual bool IsRoot => ParentDirectory == null; public abstract IEnumerable<IVirtualFile> Files { get; } public abstract IEnumerable<IVirtualDirectory> Directories { get; } public abstract string Name { get; } protected AbstractVirtualDirectoryBase(IVirtualPathProvider owningProvider) : this(owningProvider, null) {} protected AbstractVirtualDirectoryBase(IVirtualPathProvider owningProvider, IVirtualDirectory parentDirectory) { this.VirtualPathProvider = owningProvider ?? throw new ArgumentNullException(nameof(owningProvider)); this.ParentDirectory = parentDirectory; } public virtual IVirtualFile GetFile(string virtualPath) { var tokens = virtualPath.TokenizeVirtualPath(VirtualPathProvider); return GetFile(tokens); } public virtual IVirtualDirectory GetDirectory(string virtualPath) { var tokens = virtualPath.TokenizeVirtualPath(VirtualPathProvider); return GetDirectory(tokens); } public virtual IVirtualFile GetFile(Stack<string> virtualPath) { if (virtualPath.Count == 0) return null; var pathToken = virtualPath.Pop(); if (virtualPath.Count == 0) return GetFileFromBackingDirectoryOrDefault(pathToken); var virtDir = GetDirectoryFromBackingDirectoryOrDefault(pathToken); return virtDir?.GetFile(virtualPath); } public virtual IVirtualDirectory GetDirectory(Stack<string> virtualPath) { if (virtualPath.Count == 0) return null; var pathToken = virtualPath.Pop(); var virtDir = GetDirectoryFromBackingDirectoryOrDefault(pathToken); if (virtDir == null) return null; return virtualPath.Count == 0 ? virtDir : virtDir.GetDirectory(virtualPath); } public virtual IEnumerable<IVirtualFile> GetAllMatchingFiles(string globPattern, int maxDepth = Int32.MaxValue) { if (maxDepth == 0) yield break; foreach (var f in GetMatchingFilesInDir(globPattern)) yield return f; foreach (var childDir in Directories) { var matchingFilesInChildDir = childDir.GetAllMatchingFiles(globPattern, maxDepth - 1); foreach (var f in matchingFilesInChildDir) yield return f; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } protected virtual string GetVirtualPathToRoot() { if (IsRoot) return null; return GetPathToRoot(VirtualPathProvider.VirtualPathSeparator, p => p.VirtualPath); } protected virtual string GetRealPathToRoot() { return GetPathToRoot(VirtualPathProvider.RealPathSeparator, p => p.RealPath); } protected virtual string GetPathToRoot(string separator, Func<IVirtualDirectory, string> pathSel) { var parentPath = ParentDirectory != null ? pathSel(ParentDirectory) : string.Empty; if (parentPath == separator) parentPath = string.Empty; return parentPath == null ? Name : string.Concat(parentPath, separator, Name); } public override bool Equals(object obj) { if (!(obj is AbstractVirtualDirectoryBase other)) return false; return other.VirtualPath == this.VirtualPath; } public override int GetHashCode() { return VirtualPath.GetHashCode(); } public override string ToString() { return $"{RealPath} -> {VirtualPath}"; } public abstract IEnumerator<IVirtualNode> GetEnumerator(); protected abstract IVirtualFile GetFileFromBackingDirectoryOrDefault(string fileName); protected abstract IEnumerable<IVirtualFile> GetMatchingFilesInDir(string globPattern); protected abstract IVirtualDirectory GetDirectoryFromBackingDirectoryOrDefault(string directoryName); } }
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; namespace Tbd.WebApi.Shared.Extensions { public static class ApiVersioningMiddlewareExtensions { public static void AddApiVersioningEx(this IServiceCollection services) { services.AddApiVersioning(options => { options.ReportApiVersions = true; options.AssumeDefaultVersionWhenUnspecified = true; options.DefaultApiVersion = new ApiVersion(1, 0); }); } } }
using Util.Ui.Builders; using Util.Ui.Configs; namespace Util.Ui.Material.Grids.Builders { /// <summary> /// Mat网格列生成器 /// </summary> public class GridColumnBuilder : TagBuilder { /// <summary> /// 初始化网格列生成器 /// </summary> public GridColumnBuilder() : base( "mat-grid-tile" ) { } /// <summary> /// 添加合并列 /// </summary> /// <param name="config">配置</param> /// <param name="name">属性名</param> public void AddColspan( IConfig config,string name) { AddAttribute( "colspan", config.GetValue( name ) ); } } }
using ArtifactAPI.MatchHistory.Enums; using System; using System.Globalization; using System.Windows.Data; using System.Windows.Media; namespace ArtifactAPI.MatchHistory.Converters { public class OutcomeToColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Outcome outcome = (Outcome)value; switch (outcome) { case Outcome.Unknown: return Brushes.Blue; case Outcome.Loss: return Brushes.DarkRed; case Outcome.Victory: return Brushes.DarkGreen; default: { Logger.OutputError($"Unable to Convert outcome to color - Unknown Outcome number '{value}'"); throw new NotImplementedException("Implement case"); } } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
using System; using System.IO; namespace U4DosRandomizer { public class SpoilerLog { private StreamWriter spoilerWriter; private bool enabled; public SpoilerLog(StreamWriter spoilerWriter, bool enabled) { this.spoilerWriter = spoilerWriter; this.enabled = enabled; } internal void WriteFlags(Flags flags) { //throw new NotImplementedException(); } internal void Add(SpoilerCategory category, string v) { if (enabled) { spoilerWriter.WriteLine(v); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2 { /// <summary> /// Contains config about global context /// </summary> public class Smb2ClientGlobalConfig { /// <summary> /// A Boolean that, if set, indicates that this node requires that messages MUST be signed /// if the message is sent with a user security context that is neither anonymous nor guest. /// If not set, this node does not require that any messages be signed, but MAY still choose /// to do so if the other node requires it /// </summary> public bool RequireMessageSigning { get { return true; } } public TimeSpan Timeout { get { return TimeSpan.FromSeconds(10); } } public bool ImplementedV2002 { get { return true; } } public bool ImplementedV21 { get { return true; } } public bool MaySignRequest { get { return false; } } public bool MayReuseConnection { get { return false; } } } }
using JsonPathway.Internal; using System.Collections.Generic; using System.Text.Json; using Xunit; namespace JsonPathway.Tests.Internal { public class JsonElementComparerTests { [Fact] public void SameNumbers_ReturnsTrue() { JsonElement n1 = JsonElementFactory.CreateNumber(1.123); JsonElement n2 = JsonElementFactory.CreateNumber(1.123); bool result = JsonElementEqualityComparer.Default.Equals(n1, n2); Assert.True(result); } [Fact] public void DifferentNumbers_ReturnsFalse() { JsonElement n1 = JsonElementFactory.CreateNumber(1.123); JsonElement n2 = JsonElementFactory.CreateNumber(1.121); bool result = JsonElementEqualityComparer.Default.Equals(n1, n2); Assert.False(result); } [Fact] public void SameStrings_ReturnsTrue() { JsonElement n1 = JsonElementFactory.CreateString("abc"); JsonElement n2 = JsonElementFactory.CreateString("abc"); bool result = JsonElementEqualityComparer.Default.Equals(n1, n2); Assert.True(result); } [Fact] public void DifferentStrings_ReturnsFalse() { JsonElement n1 = JsonElementFactory.CreateString("a"); JsonElement n2 = JsonElementFactory.CreateString(" a"); bool result = JsonElementEqualityComparer.Default.Equals(n1, n2); Assert.False(result); } [Fact] public void SameArrays_ReturnsTrue() { JsonElement n1 = JsonElementFactory.CreateArray(new List<object> { 1, "abc", false }); JsonElement n2 = JsonElementFactory.CreateArray(new List<object> { 1, "abc", false }); bool result = JsonElementEqualityComparer.Default.Equals(n1, n2); Assert.True(result); } [Fact] public void DifferentArrays_ReturnsFalse() { JsonElement n1 = JsonElementFactory.CreateArray(new List<object> { 1, "abc", false }); JsonElement n2 = JsonElementFactory.CreateArray(new List<object> { 1, "abc", 3 }); bool result = JsonElementEqualityComparer.Default.Equals(n1, n2); Assert.False(result); } [Fact] public void DifferentTypes_ReturnsFalse() { JsonElement n1 = JsonElementFactory.CreateBool(true); JsonElement n2 = JsonElementFactory.CreateArray(new List<object> { 1, "abc", 3 }); bool result = JsonElementEqualityComparer.Default.Equals(n1, n2); Assert.False(result); } [Fact] public void SameObjects_ReturnsTrue() { JsonElement n1 = JsonDocument.Parse("{ \"a\": 3 }").RootElement; JsonElement n2 = JsonDocument.Parse("{ \"a\": 3 }").RootElement; bool result = JsonElementEqualityComparer.Default.Equals(n1, n2); Assert.True(result); } [Fact] public void DifferentObjects_ReturnsTrue() { JsonElement n1 = JsonDocument.Parse("{ \"a\": 3 }").RootElement; JsonElement n2 = JsonDocument.Parse("{ \"a\": 1 }").RootElement; bool result = JsonElementEqualityComparer.Default.Equals(n1, n2); Assert.False(result); } [Fact] public void SameBools_ReturnsTrue() { JsonElement n1 = JsonElementFactory.CreateBool(true); JsonElement n2 = JsonElementFactory.CreateBool(true); bool result = JsonElementEqualityComparer.Default.Equals(n1, n2); Assert.True(result); } [Fact] public void DifferentBools_ReturnsTrue() { JsonElement n1 = JsonElementFactory.CreateBool(true); JsonElement n2 = JsonElementFactory.CreateBool(false); bool result = JsonElementEqualityComparer.Default.Equals(n1, n2); Assert.False(result); } } }
namespace DotLToExcel.POCOS { public class Station { public string Name { get; set; } public string Description { get; set; } public int StationNumber { get; set; } public string MeterName { get; set; } public string MeterNumber { get; set; } public string Group { get; set; } public string Dataset { get; set; } public string Message { get; set; } public string Templatename { get; set; } public string UpstreamStation { get; set; } public string DownStreamStation { get; set; } public string StationType { get; set; } public string SchematicDisplayName { get; set; } public string Address1 { get; set; } public string Address2 { get; set; } public string City { get; set; } public string State { get; set; } public string Zip { get; set; } public string Phone1 { get; set; } public string Phone2 { get; set; } public string Fax { get; set; } public string MilePost { get; set; } public string Location { get; set; } public string Description2 { get; set; } public string Comment { get; set; } public string Custom1 { get; set; } public string Custom2 { get; set; } public string Custom3 { get; set; } public string Custom4 { get; set; } public string Custom5 { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Media; using System.ComponentModel; using System.Windows.Markup; using Microsoft.Research.DynamicDataDisplay.Common.Auxiliary; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; namespace Microsoft.Research.DynamicDataDisplay.Common.Palettes { public class ColorStep { public Color Color { get; set; } } [ContentProperty("ColorSteps_XAML")] public sealed class LinearPalette : IPalette, ISupportInitialize { private double[] points; private ObservableCollection<Color> colors = new ObservableCollection<Color>(); public ObservableCollection<Color> ColorSteps { get { return colors; } } private List<ColorStep> colorSteps_XAML = new List<ColorStep>(); [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [EditorBrowsable(EditorBrowsableState.Never)] public List<ColorStep> ColorSteps_XAML { get { return colorSteps_XAML; } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private void RaiseChanged() { Changed.Raise(this); } public event EventHandler Changed; public LinearPalette() { } public LinearPalette(params Color[] colors) { if (colors == null) throw new ArgumentNullException("colors"); if (colors.Length < 2) throw new ArgumentException(Properties.Resources.PaletteTooFewColors); this.colors = new ObservableCollection<Color>(colors); FillPoints(colors.Length); } private void FillPoints(int size) { points = new double[size]; for (int i = 0; i < size; i++) { points[i] = i / (double)(size - 1); } } private bool increaseBrightness = true; [DefaultValue(true)] public bool IncreaseBrightness { get { return increaseBrightness; } set { increaseBrightness = value; } } public Color GetColor(double t) { Verify.AssertIsFinite(t); Verify.IsTrue(0 <= t && t <= 1); if (t <= 0) return colors[0]; else if (t >= 1) return colors[colors.Count - 1]; else { int i = 0; while (points[i] < t) i++; double alpha = (points[i] - t) / (points[i] - points[i - 1]); Verify.IsTrue(0 <= alpha && alpha <= 1); Color c0 = colors[i - 1]; Color c1 = colors[i]; Color res = Color.FromRgb( (byte)(c0.R * alpha + c1.R * (1 - alpha)), (byte)(c0.G * alpha + c1.G * (1 - alpha)), (byte)(c0.B * alpha + c1.B * (1 - alpha))); // Increasing saturation and brightness if (increaseBrightness) { HsbColor hsb = res.ToHsbColor(); //hsb.Saturation = 0.5 * (1 + hsb.Saturation); hsb.Brightness = 0.5 * (1 + hsb.Brightness); return hsb.ToArgb(); } else { return res; } } } #region ISupportInitialize Members bool beganInit = false; public void BeginInit() { beganInit = true; } public void EndInit() { if (beganInit) { colors = new ObservableCollection<Color>(colorSteps_XAML.Select(step => step.Color)); FillPoints(colors.Count); } } #endregion } }
/* The MIT License (MIT) Copyright (c) 2018 Helix Toolkit contributors */ using System.Collections.Generic; #if !NETFX_CORE namespace HelixToolkit.Wpf.SharpDX #else namespace HelixToolkit.UWP #endif { /// <summary> /// /// </summary> public struct DefaultRenderTechniqueNames { /// <summary> /// /// </summary> public const string Blinn = "RenderBlinn"; /// <summary> /// /// </summary> public const string Diffuse = "RenderDiffuse"; /// <summary> /// /// </summary> public const string Colors = "RenderColors"; /// <summary> /// /// </summary> public const string Positions = "RenderPositions"; /// <summary> /// /// </summary> public const string Normals = "RenderNormals"; /// <summary> /// /// </summary> public const string PerturbedNormals = "RenderPerturbedNormals"; /// <summary> /// /// </summary> public const string Tangents = "RenderTangents"; /// <summary> /// /// </summary> public const string TexCoords = "RenderTexCoords"; /// <summary> /// /// </summary> public const string Lines = "RenderLines"; /// <summary> /// /// </summary> public const string Points = "RenderPoints"; /// <summary> /// /// </summary> public const string CubeMap = "RenderCubeMap"; /// <summary> /// /// </summary> public const string BillboardText = "RenderBillboard"; /// <summary> /// /// </summary> public const string BillboardInstancing = "RenderBillboardInstancing"; /// <summary> /// /// </summary> public const string InstancingBlinn = "RenderInstancingBlinn"; /// <summary> /// /// </summary> public const string BoneSkinBlinn = "RenderBoneSkinBlinn"; /// <summary> /// /// </summary> public const string ParticleStorm = "ParticleStorm"; /// <summary> /// /// </summary> public const string CrossSection = "RenderCrossSectionBlinn"; /// <summary> /// /// </summary> public const string ViewCube = "RenderViewCube"; /// <summary> /// /// </summary> public const string Skybox = "Skybox"; /// <summary> /// /// </summary> public const string PostEffectMeshBorderHighlight = "PostEffectMeshBorderHighlight"; /// <summary> /// The post effect mesh x ray /// </summary> public const string PostEffectMeshXRay = "PostEffectMeshXRay"; /// <summary> /// /// </summary> public const string PostEffectMeshOutlineBlur = "PostEffectMeshOutlineBlur"; /// <summary> /// /// </summary> public const string PostEffectBloom = "PostEffectBloom"; #if !NETFX_CORE /// <summary> /// /// </summary> public const string ScreenDuplication = "ScreenDup"; #endif } /// <summary> /// /// </summary> public struct DefaultPassNames { /// <summary> /// /// </summary> public const string Default = "Default"; /// <summary> /// /// </summary> public const string MeshTriTessellation = "MeshTriTessellation"; /// <summary> /// /// </summary> public const string MeshQuadTessellation = "MeshQuadTessellation"; /// <summary> /// /// </summary> public const string MeshOutline = "RenderMeshOutline"; /// <summary> /// /// </summary> public const string EffectBlurVertical = "EffectBlurVertical"; /// <summary> /// /// </summary> public const string EffectBlurHorizontal = "EffectBlurHorizontal"; /// <summary> /// /// </summary> public const string EffectOutlineP1 = "RenderMeshOutlineP1"; /// <summary> /// /// </summary> public const string EffectMeshXRayP1 = "EffectMeshXRayP1"; /// <summary> /// /// </summary> public const string EffectMeshXRayP2 = "EffectMeshXRayP2"; /// <summary> /// /// </summary> public const string ShadowPass = "RenderShadow"; /// <summary> /// /// </summary> public const string Backface = "RenderBackface"; /// <summary> /// /// </summary> public const string ScreenQuad = "ScreenQuad"; /// <summary> /// /// </summary> public const string ScreenQuadCopy = "ScreenQuadCopy"; /// <summary> /// The wireframe /// </summary> public const string Wireframe = "Wireframe"; /// <summary> /// The depth prepass /// </summary> public const string DepthPrepass = "DepthPrepass"; } /// <summary> /// /// </summary> public struct DefaultParticlePassNames { /// <summary> /// The insert /// </summary> public const string Insert = "InsertParticle";//For compute shader /// <summary> /// The update /// </summary> public const string Update = "UpdateParticle";//For compute shader /// <summary> /// The default /// </summary> public const string Default = "Default";//For rendering } //public struct TessellationRenderTechniqueNames //{ // public const string PNTriangles = "RenderPNTriangs"; // public const string PNQuads = "RenderPNQuads"; //} /// <summary> /// /// </summary> public struct DeferredRenderTechniqueNames { /// <summary> /// The deferred /// </summary> public const string Deferred = "RenderDeferred"; /// <summary> /// The g buffer /// </summary> public const string GBuffer = "RenderGBuffer"; /// <summary> /// The deferred lighting /// </summary> public const string DeferredLighting = "RenderDeferredLighting"; /// <summary> /// The screen space /// </summary> public const string ScreenSpace = "RenderScreenSpace"; } }
/* * Written by James Leahy. (c) 2017 DeFunc Art. * https://github.com/defuncart/ */ using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using UnityEngine; /// <summary>Part of the DeFuncArt.Serialization namespace.</summary> namespace DeFuncArt.Serialization { /// <summary>A Binary Serializer which serializes and deserializes classes into binary format.</summary> public class BinarySerializer { /// <summary>Load an instance of the class T from file.</summary> /// <param name="filename">Filename of the file to load.</param> /// <typeparam name="T">The object type to be loaded.</typeparam> /// <returns>A loaded instance of the class T.</returns> public static T Load<T>(string filename) where T: class { string path = PathForFilename(filename); if(BinarySerializer.PathExists(path)) { try { using(Stream stream = File.OpenRead(path)) { BinaryFormatter formatter = new BinaryFormatter(); return formatter.Deserialize(stream) as T; } } catch(Exception e) { Debug.LogWarning(e.Message); } } return default(T); } /// <summary>Save an instance of the class T to file.</summary> /// <param name="filename">Filename of file to save.</param> /// <param name="data">The class object to save.</param> /// <typeparam name="T">The object type to be saved.</typeparam> public static void Save<T>(string filename, T data) where T: class { string path = PathForFilename(filename); using(Stream stream = File.OpenWrite(path)) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, data); } } /// <summary>Determine whether a file exists at a given filepath.</summary> /// <param name="filepath">Filepath of the file.</param> /// <returns>True if the file exists, otherwise file.</returns> private static bool PathExists(string filepath) { return File.Exists(filepath); } /// <summary>Determine if a File with a given filename exists.</summary> /// <param name="filename">Filename of the file.</param> /// <returns>Bool if the file exists.</returns> public static bool FileExists(string filename) { return PathExists(PathForFilename(filename)); } /// <summary>Delete a File with a given filename.</summary> /// <param name="filename">Filename of the file.</param> public static void DeleteFile(string filename) { string filepath = PathForFilename(filename); if(PathExists(filepath)) { File.Delete(filepath); } } /// <summary>Determine the correct filepath for a filename. In UNITY_EDITOR this is in the project's root /// folder, on mobile it is in the persistent data folder while standalone is the data folder.</summary> /// <param name="filename">Filename of the file.</param> /// <returns>The filepath for a given file on the current device.</returns> private static string PathForFilename(string filename) { string path = filename; //for editor #if UNITY_STANDALONE path = Path.Combine(Application.dataPath, filename); #elif UNITY_IOS || UNITY_ANDROID path = Path.Combine(Application.persistentDataPath, filename); #endif return path; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnerBexiga : MonoBehaviour { [SerializeField] private GameObject bexiga; public Transform bexigaSpawnTransform; public void SpawnBexiga(){ bexiga.gameObject.SetActive(true); } }
using MediatR; namespace Miru.Domain; public interface IEnqueuedEvent { INotification GetJob(); }
using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; using MVCCoreStarterKit.Areas.Identity.Model; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace MVCCoreStarterKit.Areas.Identity { public class ApplicationUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<IzendaUser> { #region CTOR public ApplicationUserClaimsPrincipalFactory(ApplicationUserManager userManager, IOptions<IdentityOptions> options) : base(userManager, options) { } #endregion #region Methods protected override async Task<ClaimsIdentity> GenerateClaimsAsync(IzendaUser user) { var identity = await base.GenerateClaimsAsync(user); var tenant = user.Tenant; if (user.Tenant != null) { identity.AddClaims(new[] { new Claim("tenantName",tenant.Name), new Claim("tenantId",tenant.Id.ToString()), }); } var role = await UserManager.GetRolesAsync(user); identity.AddClaim(new Claim(ClaimsIdentity.DefaultRoleClaimType, role.FirstOrDefault())); return identity; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; namespace CoreSchematic { public abstract class Component { public static readonly Component Resistor = new BasicComponent("R", false); public static readonly Component UnipolarCapacitor = new BasicComponent("C", false); public static readonly Component Inductivity = new BasicComponent("L", false); private readonly List<Function> functions = new List<Function>(); protected Component(string name) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException(nameof(name)); this.Name = name; } protected Function AddFunction(string name) { var p = new Function(this, name); this.functions.Add(p); return p; } public Function GetFunction(string name) => this.functions.SingleOrDefault(p => p.Name == name); public IReadOnlyList<Function> Functions => this.functions; public string Name { get; } public override string ToString() => this.Name; } }
// ------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本: 12.0.0.0 // // 对此文件的更改可能会导致不正确的行为。此外,如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> // ------------------------------------------------------------------------------ namespace T4ProjectGenerator { using System.Linq; using System.Text; using System.Collections.Generic; using System; /// <summary> /// Class to produce the template output /// </summary> #line 1 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "12.0.0.0")] public partial class ContextTemplate : Base { #line hidden /// <summary> /// Create the template output /// </summary> public override string TransformText() { this.Write("using System;\r\nusing System.Data;\r\nusing System.Data.SqlClient;\r\nusing "); #line 9 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(Config.CommonNamespace)); #line default #line hidden this.Write(";\r\n\r\nnamespace "); #line 11 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(Config.ContextNamespace)); #line default #line hidden this.Write("\r\n{\r\n public partial class "); #line 13 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(Config.ContextClassPrefix)); #line default #line hidden this.Write("Context : DbProviderFactory\r\n {\r\n private Lazy<IDbContextComponent> _Co" + "ntext;\r\n\r\n protected override IDbContextComponent Context\r\n {\r\n " + " get { return _Context.Value; }\r\n }\r\n\r\n public "); #line 22 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(Config.ContextClassPrefix)); #line default #line hidden this.Write("Context()\r\n : base()\r\n {\r\n _Context = new Lazy<IDbCo" + "ntextComponent>(() => new "); #line 25 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(Config.ContextClassPrefix)); #line default #line hidden this.Write("ContextWrapper());\r\n"); #line 26 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" foreach(DataSchema item in _ColumnList) { #line default #line hidden this.Write(" _Client"); #line 31 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(item.TableName)); #line default #line hidden this.Write(" = new Lazy<"); #line 31 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(item.TableName)); #line default #line hidden #line 31 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(Config.ServiceClassSuffix)); #line default #line hidden this.Write(">(() => new "); #line 31 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(item.TableName)); #line default #line hidden #line 31 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(Config.ServiceClassSuffix)); #line default #line hidden this.Write("(Context));\r\n"); #line 32 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" } #line default #line hidden this.Write(" }\r\n\r\n"); #line 38 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" foreach(DataSchema item in _ColumnList) { #line default #line hidden this.Write(" private Lazy<"); #line 43 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(item.TableName)); #line default #line hidden #line 43 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(Config.ServiceClassSuffix)); #line default #line hidden this.Write("> _Client"); #line 43 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(item.TableName)); #line default #line hidden this.Write(" = null;\r\n /// <summary>\r\n /// "); #line 45 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(item.TableDescription)); #line default #line hidden this.Write("\r\n /// </summary>\r\n public "); #line 47 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(item.TableName)); #line default #line hidden #line 47 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(Config.ServiceClassSuffix)); #line default #line hidden this.Write(" Client"); #line 47 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(item.TableName)); #line default #line hidden this.Write("\r\n {\r\n get { return _Client"); #line 49 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(item.TableName)); #line default #line hidden this.Write(".Value; }\r\n }\r\n\r\n"); #line 52 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" } #line default #line hidden this.Write(" }\r\n\r\n internal class "); #line 58 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(Config.ContextClassPrefix)); #line default #line hidden this.Write("ContextWrapper : IDbContextComponent\r\n {\r\n public IDbConnection Connect" + "ion { get; set; }\r\n\r\n public IDbTransaction Transaction { get; set; }\r\n\r\n" + " public "); #line 64 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(Config.ContextClassPrefix)); #line default #line hidden this.Write("ContextWrapper()\r\n {\r\n this.Connection = new SqlConnection(Conf" + "igManager.GetValue(\""); #line 66 "E:\zy\T4\T4\T4ProjectGenerator\T4ProjectGenerator\Template\BLL\ContextTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(Config.ContextConnectionStringKey)); #line default #line hidden this.Write(@""")); if (this.Connection.State != ConnectionState.Open) { this.Connection.Open(); } } public void Dispose() { if (this.Transaction != null) { this.Transaction.Dispose(); this.Transaction = null; } if (this.Connection != null) { this.Connection.Close(); this.Connection.Dispose(); this.Connection = null; } } } }"); return this.GenerationEnvironment.ToString(); } } #line default #line hidden }
//Saltarelle // Inheritance is fully supported, including the possibility to override members. using System; 
using System.Text;
 public class Base { public virtual string Method() { return "Base.Method"; } public virtual string Property { get { return "Base.Property"; } } } public class Derived1 : Base { public override string Method() { return "Derived1.Method"; } public override string Property { get { return "Derived1.Property"; } } } public class Derived2 : Base { public new string Method() { return "Derived2.Method"; } public new string Property { get { return "Derived2.Property"; } } } public class Driver { public static void Main() { Derived1 d1 = new Derived1(); Derived2 d2 = new Derived2(); Base b2 = d2; var sb = new StringBuilder(); sb.AppendLine("d1.Method() = " + d1.Method()); sb.AppendLine("d1.Property = " + d1.Property); sb.AppendLine("d2.Method() = " + d2.Method()); sb.AppendLine("d2.Property = " + d2.Property); sb.AppendLine("b2.Method() = " + b2.Method()); sb.AppendLine("b2.Property = " + b2.Property); Console.WriteLine(sb.ToString()); } }
// 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 Xunit; namespace System.Drawing.Tests { public class BufferedGraphicsTests { [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.GdiplusIsAvailable)] public void Dispose_TempMultipleTimes_Success() { using (var context = new BufferedGraphicsContext()) using (var image = new Bitmap(3, 3)) using (Graphics targetGraphics = Graphics.FromImage(image)) { BufferedGraphics graphics = context.Allocate(targetGraphics, Rectangle.Empty); Assert.NotNull(graphics.Graphics); graphics.Dispose(); Assert.Null(graphics.Graphics); graphics.Dispose(); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.GdiplusIsAvailable)] public void Dispose_ActualMultipleTimes_Success() { using (var context = new BufferedGraphicsContext()) using (var image = new Bitmap(3, 3)) using (Graphics targetGraphics = Graphics.FromImage(image)) { BufferedGraphics graphics = context.Allocate(targetGraphics, new Rectangle(0, 0, context.MaximumBuffer.Width + 1, context.MaximumBuffer.Height + 1)); Assert.NotNull(graphics.Graphics); graphics.Dispose(); Assert.Null(graphics.Graphics); graphics.Dispose(); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.GdiplusIsAvailable)] public void Render_ParameterlessWithTargetGraphics_Success() { Color color = Color.FromArgb(255, 0, 0, 0); using (var context = new BufferedGraphicsContext()) using (var image = new Bitmap(3, 3)) using (Graphics graphics = Graphics.FromImage(image)) using (var brush = new SolidBrush(Color.Red)) { graphics.FillRectangle(brush, new Rectangle(0, 0, 3, 3)); using (BufferedGraphics bufferedGraphics = context.Allocate(graphics, new Rectangle(0, 0, 3, 3))) { bufferedGraphics.Render(); Helpers.VerifyBitmap(image, new Color[][] { new Color[] { color, color, color }, new Color[] { color, color, color }, new Color[] { color, color, color } }); } } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.GdiplusIsAvailable)] public void Render_ParameterlessWithNullTargetGraphics_Success() { Color color = Color.FromArgb(255, 0, 0, 0); using (var context = new BufferedGraphicsContext()) using (var image = new Bitmap(3, 3)) using (Graphics graphics = Graphics.FromImage(image)) using (var brush = new SolidBrush(Color.Red)) { graphics.FillRectangle(brush, new Rectangle(0, 0, 3, 3)); try { IntPtr hdc = graphics.GetHdc(); using (BufferedGraphics bufferedGraphics = context.Allocate(hdc, new Rectangle(0, 0, 3, 3))) { bufferedGraphics.Render(); } } finally { graphics.ReleaseHdc(); } } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.GdiplusIsAvailable)] public void Render_TargetGraphics_Success() { Color color = Color.FromArgb(255, 0, 0, 0); using (var context = new BufferedGraphicsContext()) using (var originalImage = new Bitmap(3, 3)) using (var targetImage = new Bitmap(3, 3)) using (Graphics originalGraphics = Graphics.FromImage(originalImage)) using (Graphics targetGraphics = Graphics.FromImage(targetImage)) using (var brush = new SolidBrush(Color.Red)) { originalGraphics.FillRectangle(brush, new Rectangle(0, 0, 3, 3)); using (BufferedGraphics graphics = context.Allocate(originalGraphics, new Rectangle(0, 0, 3, 3))) { graphics.Render(targetGraphics); Helpers.VerifyBitmap(targetImage, new Color[][] { new Color[] { color, color, color }, new Color[] { color, color, color }, new Color[] { color, color, color } }); } } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.GdiplusIsAvailable)] public void Render_NullGraphics_Nop() { using (var context = new BufferedGraphicsContext()) using (BufferedGraphics graphics = context.Allocate(null, Rectangle.Empty)) { graphics.Render(null); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.GdiplusIsAvailable)] public void Render_InvalidTargetDC_Nop() { using (var context = new BufferedGraphicsContext()) using (BufferedGraphics graphics = context.Allocate(null, Rectangle.Empty)) { graphics.Render(IntPtr.Zero); graphics.Render((IntPtr)(-1)); } } } }
using System; using System.Collections.Generic; using System.Text; using SqlAccessor; using NUnit.Framework; namespace FoundationTester { [TestFixture()] public class StringExtensionTester { [Test()] public void Split() { StringExtension str; string[] ret; str = new StringExtension("This is an \"example.\".Cool!"); ret = str.Split(".", "\""); Assert.AreEqual(new string[] { "This is an \"example.\"", "Cool!"}, ret); str = new StringExtension(""); ret = str.Split(",", "\""); Assert.AreEqual(new string[0], ret); str = new StringExtension("AAA,BBB,CCC"); ret = str.Split(",", "\""); Assert.AreEqual(new string[] { "AAA", "BBB", "CCC"}, ret); str = new StringExtension("\'AAA , BBB , CCC\'"); ret = str.Split(",", "\'"); Assert.AreEqual(new string[] { "\'AAA , BBB , CCC\'"}, ret); str = new StringExtension("AAA,BBB,CCC,"); ret = str.Split(",", "\""); Assert.AreEqual(new string[] { "AAA", "BBB", "CCC"}, ret); str = new StringExtension("AAA,BBB,CCC,,,"); ret = str.Split(",", "\""); Assert.AreEqual(new string[] { "AAA", "BBB", "CCC"}, ret); str = new StringExtension("\'AAA , BBB , CCC"); ret = str.Split(",", "\'"); Assert.AreEqual(new string[] { "\'AAA , BBB , CCC"}, ret); str = new StringExtension("\'AAA , BBB , CCC"); ret = str.Split(",", "\'"); Assert.AreEqual(new string[] { "\'AAA , BBB , CCC"}, ret); str = new StringExtension("STRYMD = 4220320 AND DANTAI = \'00\' AND SYOZOK = \'001001001000010001\'"); ret = str.Split(" AND ", "\'"); Assert.AreEqual(new string[] { "STRYMD = 4220320", "DANTAI = \'00\'", "SYOZOK = \'001001001000010001\'"}, ret); str = new StringExtension("STRYMD = 4220320 AND DANTAI = \'00\' AND SYOZOK = \'001001001000010001\' "); ret = str.Split(" AND ", "\'"); Assert.AreEqual(new string[] { "STRYMD = 4220320", "DANTAI = \'00\'", "SYOZOK = \'001001001000010001\' "}, ret); str = new StringExtension("STRYMD = 4220320 AND DANTAI = qqq00qqq AND SYOZOK = qqq001001001000010001qqq "); ret = str.Split(" AND ", "qqq"); Assert.AreEqual(new string[] { "STRYMD = 4220320", "DANTAI = qqq00qqq", "SYOZOK = qqq001001001000010001qqq "}, ret); } [Test()] public void IsInComment() { StringExtension str; str = new StringExtension("0123qqq7890123qqq7890123qqq7890"); Assert.IsFalse(str.IsInComment(0, "qqq")); str = new StringExtension("0123qqq7890123qqq7890123qqq7890"); Assert.IsFalse(str.IsInComment(3, "qqq")); str = new StringExtension("0123qqq7890123qqq7890123qqq7890"); Assert.IsTrue(str.IsInComment(4, "qqq")); str = new StringExtension("0123qqq7890123qqq7890123qqq7890"); Assert.IsTrue(str.IsInComment(6, "qqq")); str = new StringExtension("0123qqq7890123qqq7890123qqq7890"); Assert.IsTrue(str.IsInComment(10, "qqq")); str = new StringExtension("0123qqq7890123qqq7890123qqq7890"); Assert.IsTrue(str.IsInComment(14, "qqq")); str = new StringExtension("0123qqq7890123qqq7890123qqq7890"); Assert.IsTrue(str.IsInComment(16, "qqq")); str = new StringExtension("0123qqq7890123qqq7890123qqq7890"); Assert.IsFalse(str.IsInComment(20, "qqq")); str = new StringExtension("0123qqq7890123qqq7890123qqq7890"); Assert.IsTrue(str.IsInComment(27, "qqq")); str = new StringExtension("0123qqq7890123qqq7890123qqq7890"); Assert.IsTrue(str.IsInComment(30, "qqq")); } [Test()] public void IsInComment2() { StringExtension str; str = new StringExtension("0123qqq7890123ppp7890123qqq7890"); Assert.IsFalse(str.IsInComment(0, "qqq", "ppp")); str = new StringExtension("0123qqq7890123ppp7890123qqq7890"); Assert.IsFalse(str.IsInComment(3, "qqq", "ppp")); str = new StringExtension("0123qqq7890123ppp7890123qqq7890"); Assert.IsTrue(str.IsInComment(4, "qqq", "ppp")); str = new StringExtension("0123qqq7890123ppp7890123qqq7890"); Assert.IsTrue(str.IsInComment(6, "qqq", "ppp")); str = new StringExtension("0123qqq7890123ppp7890123qqq7890"); Assert.IsTrue(str.IsInComment(10, "qqq", "ppp")); str = new StringExtension("0123qqq7890123ppp7890123qqq7890"); Assert.IsTrue(str.IsInComment(14, "qqq", "ppp")); str = new StringExtension("0123qqq7890123ppp7890123qqq7890"); Assert.IsTrue(str.IsInComment(16, "qqq", "ppp")); str = new StringExtension("0123qqq7890123ppp7890123qqq7890"); Assert.IsFalse(str.IsInComment(20, "qqq", "ppp")); str = new StringExtension("0123qqq7890123ppp7890123qqq7890"); Assert.IsTrue(str.IsInComment(27, "qqq", "ppp")); str = new StringExtension("0123qqq7890123ppp7890123qqq7890"); Assert.IsTrue(str.IsInComment(30, "qqq", "ppp")); str = new StringExtension("0123qqq7890123qqq7ppp123ppp7890"); Assert.IsTrue(str.IsInComment(7, "qqq", "ppp")); str = new StringExtension("0123qqq7890123qqq7ppp123ppp7890"); Assert.IsTrue(str.IsInComment(17, "qqq", "ppp")); str = new StringExtension("0123qqq7890123qqq7ppp123ppp7890"); Assert.IsFalse(str.IsInComment(30, "qqq", "ppp")); str = new StringExtension("0123ppp7890123ppp7qqq123qqq7890"); Assert.IsFalse(str.IsInComment(17, "qqq", "ppp")); str = new StringExtension("0123456/*90123456789012*/567890"); Assert.IsTrue(str.IsInComment(15, "/*", "*/")); str = new StringExtension("0123456/*901*/456789012*/567890"); Assert.IsFalse(str.IsInComment(15, "/*", "*/")); } } }
using HotAndCold.Application.Messages; using System; namespace HotAndCold.Contract { public record RoomCreated(Guid Id, string RoomName) : IEvent<Guid>; }
/* * Created by SharpDevelop. * User: Dan * Date: 26/07/2009 * Time: 11:34 PM * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Drawing; using System.Collections.Generic; namespace thor { public class TexturePackageWAD : TexturePackage { HLLibTransaction transaction; public TexturePackageWAD(string packagelocation) : base(packagelocation) { transaction = new HLLibTransaction(packagelocation); } public override void loadTextures() { try { foreach (TextureObject tex in transaction.WadGetAll(this)) { textures.Add(tex); } /*foreach (TextureObject tex in HLLibFunctions.getAllTexturesFromWad(fileName)) { textures.Add(tex); } foreach (string name in HLLibFunctions.getAllTextureNamesFromWad(fileName)) { TextureObject tex = new TextureObject(name, fileName); textures.Add(tex); }*/ } catch (HLLibException e) { System.Windows.Forms.MessageBox.Show("Texture Error: " + e.Message); } } public override Bitmap getTexture(string name) { return transaction.WadGet(name); } public override void getTextureDimensions(string name, out int w, out int h) { transaction.WadGetSize(name, out w, out h); } public override void Dispose() { transaction.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Navigation; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; namespace ChameleonLib.View { public partial class PrivacyPolicyPage : PhoneApplicationPage { public PrivacyPolicyPage() { InitializeComponent(); } protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) { base.OnBackKeyPress(e); if (PrivacyPolicy.CanGoBack) { PrivacyPolicy.GoBack(); e.Cancel = true; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public interface IBehaviorState { public void StateHandle(); }
using JetBrains.Annotations; using Microsoft.Extensions.Configuration; using RestEase; using RestEase.Authentication.Azure; using RestEase.Authentication.Azure.Authentication; using RestEase.Authentication.Azure.Http; using RestEase.Authentication.Azure.Interfaces; using RestEase.Authentication.Azure.Options; using RestEase.Authentication.Azure.RetryPolicies; using RestEase.HttpClientFactory; using Stef.Validation; // ReSharper disable once CheckNamespace namespace Microsoft.Extensions.DependencyInjection; [PublicAPI] public static class ServiceCollectionExtensions { public static IServiceCollection UseWithAzureAuthenticatedRestEaseClient<T>( this IServiceCollection services, IConfigurationSection section, Action<RestClient>? configureRestClient = null) where T : class { Guard.NotNull(services); Guard.NotNull(section); var options = new AzureAuthenticatedRestEaseOptions<T>(); section.Bind(options); return services.UseWithAzureAuthenticatedRestEaseClient(options, configureRestClient); } public static IServiceCollection UseWithAzureAuthenticatedRestEaseClient<T>( this IServiceCollection services, Action<AzureAuthenticatedRestEaseOptions<T>> configureAction, Action<RestClient>? configureRestClient = null) where T : class { Guard.NotNull(services); Guard.NotNull(configureAction); var options = new AzureAuthenticatedRestEaseOptions<T>(); configureAction(options); return services.UseWithAzureAuthenticatedRestEaseClient(options, configureRestClient); } public static IServiceCollection UseWithAzureAuthenticatedRestEaseClient<T>( this IServiceCollection services, AzureAuthenticatedRestEaseOptions<T> options, Action<RestClient>? configureRestClient = null) where T : class { Guard.NotNull(services); Guard.NotNull(options); if (string.IsNullOrEmpty(options.HttpClientName)) { options.HttpClientName = typeof(T).FullName; } if (string.IsNullOrEmpty(options.AccessTokenCacheKeyPrefix)) { options.AccessTokenCacheKeyPrefix = typeof(T).FullName; } // Azure services services.AddSingleton<ITokenCredentialFactory<T>, TokenCredentialFactory<T>>(); services.AddSingleton<IAccessTokenService<T>, AccessTokenService<T>>(); // HttpClient and RestEase services services .AddTransient<AuthenticationHttpMessageHandler<T>>() .AddTransient<CustomHttpClientHandler<T>>() .AddHttpClient(options.HttpClientName, httpClient => { httpClient.BaseAddress = options.BaseAddress; httpClient.Timeout = TimeSpan.FromSeconds(options.TimeoutInSeconds); }) .ConfigurePrimaryHttpMessageHandler<CustomHttpClientHandler<T>>() .AddHttpMessageHandler<AuthenticationHttpMessageHandler<T>>() .AddPolicyHandler((serviceProvider, _) => HttpClientRetryPolicies.GetPolicy<T>(serviceProvider)) .UseWithRestEaseClient<T>(config => { configureRestClient?.Invoke(config); }); services.AddOptionsWithDataAnnotationValidation(options); services.AddMemoryCache(); return services; } }
using System; namespace WebSgn.Users { public interface IWebSgnUserManager { } }
namespace DwC_A.Meta { internal class CoreFileMetaData : AbstractFileMetaData, IFileMetaData { private readonly CoreFileType coreFileType; public CoreFileMetaData(CoreFileType coreFileType): base(coreFileType) { this.coreFileType = coreFileType ?? new CoreFileType(); Fields = new FieldMetaData(this.coreFileType?.Id, this.coreFileType?.Field); } public IdFieldType Id { get { return coreFileType.Id; } } public IFieldMetaData Fields { get; } } }
using System; using System.Collections.Generic; using System.Text; using Windows.UI.Xaml; using Windows.UI.Xaml.Media; namespace Uno.UI.Samples.Converters { public class FromBoolToBrushConverter : FromBoolToObjectConverter<Brush> { } }
using System; using System.Runtime.InteropServices; using NuiEngine.NuiControl.Window32.Enum; namespace NuiEngine.NuiControl.Window32.Struct { [StructLayout(LayoutKind.Sequential)] internal struct TRACKMOUSEEVENT { internal uint cbSize; internal TRACKMOUSEEVENT_FLAGS dwFlags; internal IntPtr hwndTrack; internal uint dwHoverTime; } }
using InfluxDB.Client.Core.Test; using InfluxDB.Client.Linq; using InfluxDB.Client.Linq.Internal; using NUnit.Framework; namespace Client.Linq.Test { [TestFixture] public class QueryAggregatorTest : AbstractTest { private QueryAggregator _aggregator; [SetUp] public void CreateAggregator() { _aggregator = new QueryAggregator(); } [Test] public void Range() { var ranges = new[] { ( "p1", RangeExpressionType.GreaterThanOrEqual, "p2", RangeExpressionType.LessThan, "start_shifted = int(v: time(v: p1))\n" + "stop_shifted = int(v: time(v: p2))\n\n", "range(start: time(v: start_shifted), stop: time(v: stop_shifted))" ), ( "p1", RangeExpressionType.GreaterThan, "p2", RangeExpressionType.LessThan, "start_shifted = int(v: time(v: p1)) + 1\n" + "stop_shifted = int(v: time(v: p2))\n\n", "range(start: time(v: start_shifted), stop: time(v: stop_shifted))" ), ( "p1", RangeExpressionType.GreaterThan, "p2", RangeExpressionType.LessThanOrEqual, "start_shifted = int(v: time(v: p1)) + 1\n" + "stop_shifted = int(v: time(v: p2)) + 1\n\n", "range(start: time(v: start_shifted), stop: time(v: stop_shifted))" ), ( "p1", RangeExpressionType.Equal, "p2", RangeExpressionType.Equal, "start_shifted = int(v: time(v: p1))\n" + "stop_shifted = int(v: time(v: p2)) + 1\n\n", "range(start: time(v: start_shifted), stop: time(v: stop_shifted))" ), ( "p1", RangeExpressionType.GreaterThan, null, RangeExpressionType.Equal, "start_shifted = int(v: time(v: p1)) + 1\n\n", "range(start: time(v: start_shifted))" ), }; foreach (var (startAssignment, startExpression, stopAssignment, stopExpression, shift, range) in ranges) { _aggregator.AddBucket("p1"); _aggregator.AddRangeStart(startAssignment, startExpression); _aggregator.AddRangeStop(stopAssignment, stopExpression); var expected = shift + "from(bucket: p1) " + $"|> {range} " + "|> pivot(rowKey:[\"_time\"], columnKey: [\"_field\"], valueColumn: \"_value\") " + "|> drop(columns: [\"_start\", \"_stop\", \"_measurement\"])"; var settings = new QueryableOptimizerSettings(); Assert.AreEqual(expected, _aggregator.BuildFluxQuery(settings), $"Expected Range: {range}, Shift: {shift}"); } } } }
using System.Collections.Generic; using System.Web.Mvc; using Umbraco.Web.Models; using umbraco.cms.businesslogic.macro; using umbraco.interfaces; using System.Linq; namespace Umbraco.Web.Macros { /// <summary> /// Controller to render macro content for Parital View Macros /// </summary> internal class PartialViewMacroController : Controller { private readonly UmbracoContext _umbracoContext; private readonly MacroModel _macro; private readonly INode _currentPage; public PartialViewMacroController(UmbracoContext umbracoContext, MacroModel macro, INode currentPage) { _umbracoContext = umbracoContext; _macro = macro; _currentPage = currentPage; } /// <summary> /// Child action to render a macro /// </summary> /// <returns></returns> [ChildActionOnly] public PartialViewResult Index() { var model = new PartialViewMacroModel( _currentPage.ConvertFromNode(), _macro.Id, _macro.Alias, _macro.Name, _macro.Properties.ToDictionary(x => x.Key, x => (object)x.Value)); return PartialView(_macro.ScriptName, model); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using NuGetGallery; namespace NuGet.Services { public class InMemoryCloudBlobContainer : ICloudBlobContainer { private readonly object _lock = new object(); public SortedDictionary<string, InMemoryCloudBlob> Blobs { get; } = new SortedDictionary<string, InMemoryCloudBlob>(); public Task CreateAsync(BlobContainerPermissions permissions) { throw new NotImplementedException(); } public Task CreateIfNotExistAsync(BlobContainerPermissions permissions) { throw new NotImplementedException(); } public Task<bool> DeleteIfExistsAsync() { throw new NotImplementedException(); } public Task<bool> ExistsAsync(BlobRequestOptions options = null, OperationContext operationContext = null) { throw new NotImplementedException(); } public ISimpleCloudBlob GetBlobReference(string blobAddressUri) { lock (_lock) { InMemoryCloudBlob blob; if (!Blobs.TryGetValue(blobAddressUri, out blob)) { blob = new InMemoryCloudBlob(); Blobs[blobAddressUri] = blob; } return blob; } } public Task<ISimpleBlobResultSegment> ListBlobsSegmentedAsync( string prefix, bool useFlatBlobListing, BlobListingDetails blobListingDetails, int? maxResults, BlobContinuationToken blobContinuationToken, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task SetPermissionsAsync(BlobContainerPermissions permissions) { throw new NotImplementedException(); } } }
using Microsoft.Xna.Framework; using StardewModdingAPI; using StardewValley; using StardewValley.Tools; namespace TheLion.AwesomeTools { /// <summary>Manages control between each tool.</summary> public class EffectsManager { private readonly AxeEffect _axe; private readonly PickaxeEffect _pickaxe; private readonly float _multiplier; /// <summary>Construct an instance.</summary> /// <param name="config">The overal mod settings.</param> /// <param name="modRegistry">Metadata about loaded mods.</param> public EffectsManager(ToolConfig config, IModRegistry modRegistry) { _axe = new AxeEffect(config.AxeConfig, modRegistry); _pickaxe = new PickaxeEffect(config.PickaxeConfig, modRegistry); _multiplier = config.StaminaCostMultiplier; } /// <summary>Do awesome shit with your tools.</summary> public void DoShockwave(Vector2 actionTile, Tool tool, GameLocation location, Farmer who) { switch (tool) { case Axe: if (_axe.Config.EnableAxeCharging) { _axe.SpreadToolEffect(tool, actionTile, _axe.Config.RadiusAtEachPowerLevel, _multiplier, location, who); } break; case Pickaxe: if (_pickaxe.Config.EnablePickaxeCharging) { _pickaxe.SpreadToolEffect(tool, actionTile, _pickaxe.Config.RadiusAtEachPowerLevel, _multiplier, location, who); } break; } } } }
using Improbable.Gdk.CodeGeneration.CodeWriter; using Improbable.Gdk.CodeGeneration.Model.Details; using NLog; namespace Improbable.Gdk.CodeGenerator { public static class ViewStorageGenerator { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); public static CodeWriter Generate(UnityComponentDetails componentDetails) { return CodeWriter.Populate(cgw => { cgw.UsingDirectives( "System", "System.Collections.Generic", "Improbable.Gdk.Core", "Improbable.Worker.CInterop" ); cgw.Namespace(componentDetails.Namespace, ns => { ns.Type($"public partial class {componentDetails.Name}", partial => { Logger.Trace($"Generating {componentDetails.Namespace}.{componentDetails.Name}.{componentDetails.Name}ViewStorage class."); partial.Type($"public class {componentDetails.Name}ViewStorage : IViewStorage, IViewComponentStorage<Snapshot>, IViewComponentUpdater<Update>", vs => { vs.Line(@" private readonly Dictionary<long, Authority> authorityStates = new Dictionary<long, Authority>(); private readonly Dictionary<long, Snapshot> componentData = new Dictionary<long, Snapshot>(); public Type GetSnapshotType() { return typeof(Snapshot); } public Type GetUpdateType() { return typeof(Update); } public uint GetComponentId() { return ComponentId; } public bool HasComponent(long entityId) { return componentData.ContainsKey(entityId); } public Snapshot GetComponent(long entityId) { if (!componentData.TryGetValue(entityId, out var component)) { throw new ArgumentException($""Entity with Entity ID {entityId} does not have component {typeof(Snapshot)} in the view.""); } return component; } public Authority GetAuthority(long entityId) { if (!authorityStates.TryGetValue(entityId, out var authority)) { throw new ArgumentException($""Entity with Entity ID {entityId} does not have component {typeof(Snapshot)} in the view.""); } return authority; } public void ApplyDiff(ViewDiff viewDiff) { var storage = viewDiff.GetComponentDiffStorage(ComponentId); foreach (var entity in storage.GetComponentsAdded()) { authorityStates[entity.Id] = Authority.NotAuthoritative; componentData[entity.Id] = new Snapshot(); } foreach (var entity in storage.GetComponentsRemoved()) { authorityStates.Remove(entity.Id); componentData.Remove(entity.Id); } var updates = ((IDiffUpdateStorage<Update>) storage).GetUpdates(); for (var i = 0; i < updates.Count; i++) { ref readonly var update = ref updates[i]; ApplyUpdate(update.EntityId.Id, in update.Update); } var authorityChanges = ((IDiffAuthorityStorage) storage).GetAuthorityChanges(); for (var i = 0; i < authorityChanges.Count; i++) { var authorityChange = authorityChanges[i]; authorityStates[authorityChange.EntityId.Id] = authorityChange.Authority; } } "); vs.Method("public void ApplyUpdate(long entityId, in Update update)", m => { m.Line(@" if (!componentData.TryGetValue(entityId, out var data)) { return; } "); foreach (var field in componentDetails.FieldDetails) { var fieldName = field.PascalCaseName; m.Line($@" if (update.{fieldName}.HasValue) {{ data.{fieldName} = update.{fieldName}.Value; }} "); } m.Line("componentData[entityId] = data;"); }); }); }); }); }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Drawing; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.TrustUI; using System.Globalization; // For localization of string conversion using System.Security.Cryptography.X509Certificates; using System.Security.RightsManagement; using System.Security; namespace MS.Internal.Documents { internal sealed class RightsManagementResourceHelper { #region Constructors //------------------------------------------------------ // Constructors //------------------------------------------------------ /// <summary> /// The constructor /// </summary> private RightsManagementResourceHelper() { } #endregion Constructors #region Internal Methods //------------------------------------------------------ // Internal Methods //------------------------------------------------------ /// <summary> /// GetDocumentLevelResources. /// </summary> internal static DocumentStatusResources GetDocumentLevelResources(RightsManagementStatus status) { DocumentStatusResources docStatusResources = new DocumentStatusResources(); // Set appropriate Text and ToolTip values. switch (status) { case (RightsManagementStatus.Protected): docStatusResources.Text = SR.Get(SRID.RMProtected); docStatusResources.ToolTip = SR.Get(SRID.RMAppliedToolTip); break; default: // RightsManagementStatus.Unknown or RightsManagementStatus.Unprotected docStatusResources.Text = String.Empty; docStatusResources.ToolTip = SR.Get(SRID.RMDefaultToolTip); break; } docStatusResources.Image = GetDrawingBrushFromStatus(status); return docStatusResources; } /// <summary> /// GetCredentialManagementResources. /// </summary> /// <param name="user">The user object from which to get resources</param> internal static string GetCredentialManagementResources(RightsManagementUser user) { string accountName = null; if (user == null) { throw new ArgumentNullException("user"); } switch (user.AuthenticationType) { case (AuthenticationType.Windows): accountName = String.Format( CultureInfo.CurrentCulture, SR.Get(SRID.RMCredManagementWindowsAccount), user.Name); break; case (AuthenticationType.Passport): accountName = String.Format( CultureInfo.CurrentCulture, SR.Get(SRID.RMCredManagementPassportAccount), user.Name); break; default: accountName = String.Format( CultureInfo.CurrentCulture, SR.Get(SRID.RMCredManagementUnknownAccount), user.Name); break; } return accountName; } #endregion Internal Methods #region Private Methods //-------------------------------------------------------------------------- // Private Methods //-------------------------------------------------------------------------- /// <summary> /// Get the DrawingBrush icon for the status. /// </summary> /// <param name="status">Requested status</param> /// <returns>A DrawingBrush on success (valid status, DrawingBrush found), null otherwise.</returns> private static DrawingBrush GetDrawingBrushFromStatus(RightsManagementStatus status) { if (_brushResources == null) { // Get the entire list of RightsManagementStatus values. Array statusList = Enum.GetValues(typeof(RightsManagementStatus)); // Construct the array to hold brush references. _brushResources = new DrawingBrush[statusList.Length]; // To find the DrawingBrushes in the theme resources we need a FrameworkElement. // TextBlock was used as it appears to have a very small footprint, and won't // take long to construct. The actual FrameworkElement doesn't matter as long // as we have an instance to one _frameworkElement = new TextBlock(); } if ((_brushResources != null) && (_frameworkElement != null)) { int index = (int)status; // If there is no cached value of the requested DrawingBrush, then find // it in the Resources. if (_brushResources[index] == null) { // Determine resource name. string resourceName = "PUIRMStatus" + Enum.GetName(typeof(RightsManagementStatus), status) + "BrushKey"; // Acquire reference to the brush. object resource = _frameworkElement.FindResource( new ComponentResourceKey(typeof(PresentationUIStyleResources), resourceName)); // Set cache value for the brush. _brushResources[index] = resource as DrawingBrush; } return _brushResources[index]; } return null; } #endregion Private Methods private static DrawingBrush[] _brushResources; // To cache DrawingBrushes. private static FrameworkElement _frameworkElement; // Used to search resources. } }
namespace Autossential.Activities.Design.Designers { // Interaction logic for ContainerDesigner.xaml public partial class ContainerDesigner { public ContainerDesigner() { InitializeComponent(); } } }
// <copyright file="Guild.cs" company="https://gitlab.com/edrochenski/juvo"> // Licensed under the MIT License. See LICENSE in the project root for license information. // </copyright> namespace JuvoProcess.Net.Discord.Model { using System.Collections.Generic; using Newtonsoft.Json; /// <summary> /// Represents a Guild object/resource. A collection of users and /// channels often referred to as "servers" in the UI. /// </summary> /// <remarks> /// <see href="https://discordapp.com/developers/docs/resources/guild">More info</see>. /// </remarks> public class Guild { /// <summary> /// Gets or sets the AFK channel ID. /// </summary> [JsonProperty(PropertyName = "afk_channel_id")] public string AfkChannelId { get; set; } = string.Empty; /// <summary> /// Gets or sets the AFK timeout in seconds. /// </summary> [JsonProperty(PropertyName = "afk_timeout")] public int AfkTimeout { get; set; } /// <summary> /// Gets or sets the application ID. /// </summary> [JsonProperty(PropertyName = "application_id")] public string ApplicationId { get; set; } = string.Empty; /// <summary> /// Gets or sets the default message notification level. /// </summary> [JsonProperty(PropertyName = "default_message_notifications")] public MessageNotificationLevel DefaultMessageNotifications { get; set; } /// <summary> /// Gets or sets ID of the embeddable channel. /// </summary> [JsonProperty(PropertyName = "embed_channel_id")] public string EmbedChannelId { get; set; } = string.Empty; /// <summary> /// Gets or sets if the guild is embeddable (i.e. widget). /// </summary> [JsonProperty(PropertyName = "embed_enabled")] public bool? EmbedEnabled { get; set; } /// <summary> /// Gets or sets the custom guild emojis. /// </summary> public IEnumerable<Emoji>? Emojis { get; set; } /// <summary> /// Gets or sets the explicit content filter level. /// </summary> [JsonProperty(PropertyName = "explicit_content_filter")] public ExplicitContentFilterLevel ExplicitContentFilter { get; set; } /// <summary> /// Gets or sets the enabled guild features. /// </summary> public IEnumerable<string>? Features { get; set; } /// <summary> /// Gets or sets the icon hash. /// </summary> public string Icon { get; set; } = string.Empty; /// <summary> /// Gets or sets the ID. /// </summary> public string Id { get; set; } = string.Empty; /// <summary> /// Gets or sets the MFA level. /// </summary> [JsonProperty(PropertyName = "mfa_level")] public MfaLevel MfaLevel { get; set; } /// <summary> /// Gets or sets the name. /// </summary> /// <remarks>Limited to 2-100 characters.</remarks> public string Name { get; set; } = string.Empty; /// <summary> /// Gets or sets if the current user is the owner. /// </summary> /// <remarks> /// Have not seen this in the logs, possibly deprecated. /// </remarks> public bool? Owner { get; set; } /// <summary> /// Gets or sets the owner's ID. /// </summary> public string OwnerId { get; set; } = string.Empty; /// <summary> /// Gets or sets the total permissions for the user (not including channel overrides.) /// </summary> public int? Permissions { get; set; } /// <summary> /// Gets or sets the voice region ID. /// </summary> public string Region { get; set; } = string.Empty; /// <summary> /// Gets or sets the roles in the guild. /// </summary> public IEnumerable<Role>? Roles { get; set; } /// <summary> /// Gets or sets the splash hash. /// </summary> /// <remarks> /// Discord uses IDs/hashes to render images to the client. /// </remarks> public string Splash { get; set; } = string.Empty; /// <summary> /// Gets or sets the system channel ID. /// </summary> [JsonProperty(PropertyName = "system_channel_id")] public string SystemChannelId { get; set; } = string.Empty; /// <summary> /// Gets or sets the verification level. /// </summary> [JsonProperty(PropertyName = "verification_level")] public VerificationLevel VerificationLevel { get; set; } /// <summary> /// Gets or sets the widget channel ID. /// </summary> [JsonProperty(PropertyName = "widget_channel_id")] public string WidgetChannelId { get; set; } = string.Empty; /// <summary> /// Gets or sets a value indicating whether the widget is enabled. /// </summary> [JsonProperty(PropertyName = "widget_enabled")] public bool? WidgetEnabled { get; set; } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.Build.Logging.Query.Result; namespace Microsoft.Build.Logging.Query.Ast { public sealed class PathNode<TParent> : ConstraintNode<TParent, string>, IEquatable<PathNode<TParent>> where TParent : class, IQueryResult, IResultWithPath { public PathNode(string value) : base(value) { } public override bool Equals(object obj) { return Equals(obj as PathNode<TParent>); } public bool Equals([AllowNull] PathNode<TParent> other) { return base.Equals(other); } public override int GetHashCode() { return base.GetHashCode(); } public override IEnumerable<TParent> Filter(IEnumerable<TParent> components) { return components .Where(component => component.Path == Value); } } }
using MoonSharp.Interpreter; using MoonSharp.Interpreter.Loaders; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Poke1Bot.Scripting { internal class CustomScriptLoader : ScriptLoaderBase { //HashSet used, so that dulplicate entries are filtered by default private HashSet<string> _baseDirs = new HashSet<string>(); private string poke1SystemVar = "lua_path"; public CustomScriptLoader(string scriptDir) { //for readability added every string by hand //1. relative path | script dir is root then _baseDirs.Add(scriptDir); //2. absolute path | if given an exact location on disk e.g.: C:\ultrascript.lua _baseDirs.Add(""); //3. lua_path | using system variables as root keys if (Environment.GetEnvironmentVariable(poke1SystemVar) != null) { string luaPaths = Environment.GetEnvironmentVariable(poke1SystemVar); foreach (var lua_path in luaPaths.Split(';')) _baseDirs.Add(lua_path); } } public override object LoadFile(string relPath, Table globalContext) { return File.ReadAllText(getPath(relPath)); } public override bool ScriptFileExists(string relPath) { return getPath(relPath) != null; } /// <summary> /// Returns an absolute path if every combination of baseDirs + relative return only one existing file. /// </summary> /// <param name="relPath"> /// The reference one uses to import another lua script. Relative in terms of script path, lua /// path or it is an absolute path itself. /// </param> /// <returns>The file path if unique or null, if multiple files are accessible via the relPath param.</returns> public string getPath(string relPath) { //return path, only if a single match exists: //base directories are unique, but constructed directories could reference multiple files e.g.: //1. opening ...workspace\ultrascript.lua makes rel_path = "ultrascript.lua" //2. lua_path = "C:\" //==> reference could either point to workspace\ultrascript.lua or C:\ultrascript.lua try { //building paths HashSet<string> dirs = new HashSet<string>(); foreach (var baseDir in _baseDirs) dirs.Add(buildPath(baseDir, relPath)); //check uniqueness | added as function for future enrichment. //if path would point to a dir: hasOneMatch = e => Directory.Exists(e); Func<string, bool> hasOneMatch = e => File.Exists(e); return dirs.Single(hasOneMatch); } //Single() throws exception if zero or multiple matches exist catch (InvalidOperationException ex) { #if DEBUG Console.WriteLine(ex.Message); #endif Console.WriteLine(ex.Message); return null; } } /// <summary> /// Generates the file path, while making some lua reference/interpreter specific changes. /// </summary> /// <param name="baseDir">The root path, eiter script dir, absolut or lua path.</param> /// <param name="relPath"> /// The reference one uses to import another lua script. Relative in terms of script path, lua /// path or it is an absolute path itself. /// </param> /// <returns>Either combined path of baseDir and relPath or "" if exception occurs.</returns> private string buildPath(string baseDir, string relPath) { try { string relPathMod = getCleanPath(relPath); string combine = Path.Combine(baseDir, relPathMod); return Path.GetFullPath(combine); } catch (Exception ex) { #if DEBUG Console.WriteLine(ex.Message); #endif Console.WriteLine(ex.Message); //has to return "" for dirs.Single() to work, don't return null return ""; } } /// <summary> /// Searches for differences between lua and Windows specific referening and makes it so that /// relPath can be used with Path.Combine() function. /// </summary> /// <param name="relPath"> /// The reference one uses to import another lua script. Relative in terms of script path, lua /// path or it is an absolute path itself. /// </param> ///<attention>Probably more cases, that need handeling.</attention> private string getCleanPath(string relPath) { return relPath.Replace("//", ".."); } } }
public enum SowingPattern // TypeDefIndex: 7348 { // Fields public int value__; // 0x0 public const SowingPattern None = 0; public const SowingPattern Way1 = 1; public const SowingPattern Way2 = 2; public const SowingPattern Way3 = 3; public const SowingPattern Way4 = 4; public const SowingPattern Way5 = 5; }
using System; public enum GameGenreEnum { FirstPersonShooter, MOBA, RPG, BoardGames, }
using System; using MediatR; namespace HorCup.Players.Commands.EditPlayer { public record EditPlayerCommand( Guid Id, string Nickname) : IRequest<Unit>; }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using SharpCompress.Archive; namespace ArchiveManager { public partial class FileArchiveExplorer : UserControl { #region LIST_ITEMS_WIDTH_ARRANGER private int ConvPercent(int percentage, int total) { return ((percentage * total) / 100) ; } private void SetListItemsSizeByPercent(int p_name, int p_size, int p_type) { int lst_w = this.lstExplorer.Size.Width; this.columnHeaderName.Width = this.ConvPercent(p_name, lst_w); this.columnHeaderSize.Width = this.ConvPercent(p_size, lst_w); this.columnHeaderType.Width = this.ConvPercent(p_type, lst_w); } #endregion #region Class : List Item Info public class ListItemInfo { private bool is_dir, is_file, is_arc_entry = false; private string name, type, source = null; private long siz = 0; private string siz_str = null; public string Source { get { return this.source; } } public string Name { get { return this.name; } } public long Size { get { return this.siz; } } public string strSize { get { return this.siz_str; } } public string Type { get { return this.type; } } public bool IsDirectory { get { return this.is_dir; } } public bool IsFile { get { return this.is_file; } } public bool IsArchiveEntry { get { return this.is_arc_entry; } } public ListItemInfo(string _source, string _name,long _siz,string _type,bool dir,bool file, bool arc) { this.Assign(_source, _name, _siz, _type, dir, file, arc); } public ListItemInfo(FileInfo f) { string type = Path.GetExtension(f.FullName); if (type == null) type = "<NONE>"; this.Assign(f.FullName, f.Name, f.Length, type, false, true, false); } public ListItemInfo(DirectoryInfo d) { this.Assign(d.FullName, d.Name, 0, "Directory", true, false, false); } private void Assign(string _source, string _name, long _siz, string _type, bool dir, bool file, bool arc) { this.source = _source; this.name = _name; this.siz = _siz; this.siz_str = dir ? "Directory" : Helper.SizeToString(_siz); this.type = _type; this.is_dir = dir; this.is_file = file; this.is_arc_entry = arc; } } #endregion public FileArchiveExplorer() { InitializeComponent(); } public bool ShowTreeView { get; set; } [Browsable(false)] public bool HasArchiveEntries { get { foreach(ListViewItem itm in this.lstExplorer.Items) { ListItemInfo item_info = itm.Tag as ListItemInfo; if (item_info != null && item_info.IsArchiveEntry) return true; } return false; } } [Browsable(false)] public int SelectedIndex { get { var indinces = this.lstExplorer.SelectedIndices; return (indinces != null && indinces.Count > 0) ? indinces[0] : -1; } } [Browsable(false)] public int Count { get { return this.lstExplorer.Items.Count; } } private int AddToList(ListItemInfo info) { if(info != null) { var itm = this.lstExplorer.Items.Add(info.Name); itm.SubItems.Add(info.strSize); itm.SubItems.Add(info.Type); itm.Tag = info; if (this.ShowTreeView) this.UpdateTreeView(); return itm.Index; } return -1; } private void UpdateTreeView() { this.treeExplorer.Nodes.Clear(); foreach (ListViewItem lstitem in this.lstExplorer.Items) { var info = lstitem.Tag as ListItemInfo; if(info != null) { foreach(TreeNode tnode in this.treeExplorer.Nodes) { if (tnode.Text == info.Name && tnode.Tag == info) continue; } if (info.IsFile) { var node = this.treeExplorer.Nodes.Add(info.Name); node.Tag = info; } else if (info.IsDirectory) { var snode = Helper.PopulateNode(new DirectoryInfo(info.Source)); snode.Tag = info; this.treeExplorer.Nodes.Add(snode); } } } } public int AddFile(FileInfo file) { if(file != null && file.Exists) { return this.AddToList(new ListItemInfo(file)); } return -1; } public int AddDirectory(DirectoryInfo dir) { if(dir != null && dir.Exists) { return this.AddToList(new ListItemInfo(dir)); } return -1; } public void AddAllFromDirectory(DirectoryInfo d) { if(d != null && d.Exists) { //var mydir = d.Parent; var files = d.GetFiles(); if(files != null) { foreach(var f in files) { this.AddFile(f); } } var dirs = d.GetDirectories(); if(dirs != null) { foreach(var sub_dir in dirs) { this.AddDirectory(sub_dir); } } } } public bool AddArchive(string archive_path) { if(archive_path != null && File.Exists(archive_path)) { try { using (var arc = ArchiveFactory.Open(archive_path)) { if(arc.Entries != null) { foreach(var entry in arc.Entries) { var itm_info = new ListItemInfo( archive_path, entry.FilePath, entry.Size, entry.IsDirectory ? "Archive/Directory" : "Archive/File", entry.IsDirectory, !entry.IsDirectory, true); this.AddToList(itm_info); } } } return true; } catch (Exception) { return false; } } return false; } public void RemoveAt(int index) { this.lstExplorer.Items.RemoveAt(index); this.UpdateTreeView(); } public void Clear() { this.lstExplorer.Items.Clear(); this.UpdateTreeView(); } public ListItemInfo GetListItem(int index) { return (this.lstExplorer.Items[index].Tag as ListItemInfo); } public ListItemInfo[] GetAllListItems() { List<ListItemInfo> myitminfo = new List<ListItemInfo>(); foreach(ListViewItem itm in this.lstExplorer.Items) { myitminfo.Add(itm.Tag as ListItemInfo); } return myitminfo.Count > 0 ? myitminfo.ToArray() : null; } private void FileArchiveExplorer_Load(object sender, EventArgs e) { if(this.ShowTreeView == false) { this.treeExplorer.Visible = false; this.lstExplorer.Dock = DockStyle.Fill; } this.SetListItemsSizeByPercent(69, 15, 15); } } }
using System; using MvvmCross.ViewModels; using Toggl.Multivac; namespace Toggl.Foundation.MvvmCross.ViewModels { [Preserve(AllMembers = true)] public sealed class SelectableBeginningOfWeekViewModel : MvxNotifyPropertyChanged { public BeginningOfWeek BeginningOfWeek { get; } public bool Selected { get; set; } public SelectableBeginningOfWeekViewModel(BeginningOfWeek beginningOfWeek, bool selected) { BeginningOfWeek = beginningOfWeek; Selected = selected; } } }
using System.Collections.Generic; namespace GRA.Domain.Model { public class StoredReportSet { public ICollection<StoredReport> Reports { get; set; } } }
using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace QarnotSDK { internal class HardwareConstraintsJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(HardwareConstraint) || objectType.IsSubclassOf(typeof(HardwareConstraint)); } public override bool CanWrite => false; public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer) { serializer.Serialize(writer, value); } public override Object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { try { var jo = JObject.Load(reader); var discriminatorField = jo.Value<string>(nameof(HardwareConstraint.Discriminator).ToLower()) ?? jo.Value<string>(nameof(HardwareConstraint.Discriminator)); switch (discriminatorField) { case HardwareConstraintDiscriminators.MinimumCoreHardwareConstraint: return jo.ToObject<MinimumCoreHardware>(); case HardwareConstraintDiscriminators.MaximumCoreHardwareConstraint: return jo.ToObject<MaximumCoreHardware>(); case HardwareConstraintDiscriminators.MinimumRamCoreRatioHardwareConstraint: return jo.ToObject<MinimumRamCoreRatioHardware>(); case HardwareConstraintDiscriminators.MaximumRamCoreRatioHardwareConstraint: return jo.ToObject<MaximumRamCoreRatioHardware>(); case HardwareConstraintDiscriminators.SpecificHardwareConstraint: return jo.ToObject<SpecificHardware>(); case HardwareConstraintDiscriminators.MinimumRamHardwareConstraint: return jo.ToObject<MinimumRamHardware>(); case HardwareConstraintDiscriminators.MaximumRamHardwareConstraint: return jo.ToObject<MaximumRamHardware>(); case HardwareConstraintDiscriminators.GpuHardwareConstraint: return jo.ToObject<GpuHardware>(); default: return default; }; } catch (Exception ex) { Console.WriteLine($"Failed to deserialize Hardware constraints: {ex.Message}", ex); } return default; } } }
using System; using UnityEngine; namespace Game.Slots { using Field; [CreateAssetMenuAttribute(menuName="Game/Slot/SetRunning")] public class SetRunning : Utility.Slot { [SerializeField] private bool isRunning; public override void Run(GameObject gameObject) { Judge.IsRunning = this.isRunning; } } }
using System.IO; namespace QQMessageManager { public class MHTCacher { public const string DefaultDir = "cache"; public static readonly MHTCacher Default; static MHTCacher() { Default = new MHTCacher(DefaultDir); } public MHTCacher(string dir) { CacheDir = dir; if (! Directory.Exists(CacheDir)) Directory.CreateDirectory(CacheDir); } public string CacheDir { get; private set; } public void Clear() { Directory.Delete(CacheDir, true); Directory.CreateDirectory(CacheDir); } public string GetCacheFile(MHTAsset asset, bool force = false) { string fn = Path.Combine(CacheDir, asset.Hash); if (false == File.Exists(fn) || force) { using (FileStream file = File.Open(fn, FileMode.Create, FileAccess.Write)) file.Write(asset.Bytes, 0, asset.Bytes.Length); } return fn; } public void CopyTo(MHTAsset asset, string dest, bool overwrite = false) { string src = GetCacheFile(asset); if (overwrite == false && File.Exists(dest)) return; File.Copy(src, dest, overwrite); } } }
using LocalParks.Core.Domain; using LocalParks.Core.Domain.Shop; using System.Threading.Tasks; namespace LocalParks.Services.Reports { public interface IReportsDataService { Task<Order[]> GetAllOrders(); Task<ParkEvent[]> GetAllParkEvents(); Task<Park[]> GetAllParks(); Task<SportsClub[]> GetAllSportsClubs(); Task<Supervisor[]> GetAllSupervisors(); Task<Product[]> GetAllProducts(); Task<int> SportCount(); Task<string> SportName(int pos); } }
namespace JexusManager.Main.Features { public class ListViewColumnNumericSorter : ListViewColumnTextSorter { protected override ComparerResult InnerCompare(string a, string b) { // Null parsing. if ((a == null) && (b == null)) return ComparerResult.Equals; if ((a == null) && (b != null)) return ComparerResult.LessThan; if ((a != null) && (b == null)) return ComparerResult.GreaterThan; float singleA; float singleB; // True And True. if (float.TryParse(a, out singleA) && float.TryParse(b, out singleB)) return (ComparerResult) singleA.CompareTo(singleB); if (float.TryParse(a, out singleA) && !float.TryParse(b, out singleB)) return ComparerResult.GreaterThan; if (!float.TryParse(a, out singleA) && float.TryParse(b, out singleB)) return ComparerResult.LessThan; return (ComparerResult) a.CompareTo(b); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Serialization; namespace Lpp.Dns.DTO.Enums { [DataContract] public enum QueryComposerCriteriaTypes { [EnumMember] Paragraph = 0, [EnumMember] Event = 1, [EnumMember, Description("Index Event")] IndexEvent = 2 } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Controls; using ComponentArt.Win.DataVisualization.Charting; using ComponentArt.Win.DataVisualization.Common; using ComponentArt.Win.DataVisualization; namespace EpiDashboard.Gadgets.Charting { //public enum BarSpacing //{ // Default, // None, // Small, // Medium, // Large //} public interface IChartSettings { bool UseRefValues { get; set; } bool ShowAnnotationsY2 { get; set; } bool ShowDefaultGridLines { get; set; } Palette Palette { get; set; } LineKind LineKindY2 { get; set; } LineDashStyle LineDashStyleY2 { get; set; } string Y2AxisLabel { get; set; } string Y2AxisLegendTitle { get; set; } string YAxisLabel { get; set; } string XAxisLabel { get; set; } double Y2LineThickness { get; set; } XAxisLabelType XAxisLabelType { get; set; } int XAxisLabelRotation { get; set; } string ChartTitle { get; set; } string ChartStrataTitle { get; set; } string ChartSubTitle { get; set; } bool ShowLegend { get; set; } bool ShowLegendBorder { get; set; } bool ShowLegendVarNames { get; set; } double LegendFontSize { get; set; } int ChartWidth { get; set; } int ChartHeight { get; set; } string YAxisFormattingString { get; set; } string Y2AxisFormattingString { get; set; } ComponentArt.Win.DataVisualization.Charting.Dock LegendDock { get; set; } } public class AreaChartSettings : IChartSettings { public bool ShowSeriesLine { get; set; } public bool UseRefValues { get; set; } public bool ShowAnnotationsY2 { get; set; } public bool ShowDefaultGridLines { get; set; } public CompositionKind Composition { get; set; } public Palette Palette { get; set; } public LineKind AreaType { get; set; } public LineKind LineKindY2 { get; set; } public LineDashStyle LineDashStyleY2 { get; set; } public string Y2AxisLabel { get; set; } public string Y2AxisLegendTitle { get; set; } public int TransparencyTop { get; set; } public int TransparencyBottom { get; set; } public string YAxisLabel { get; set; } public string XAxisLabel { get; set; } public double Y2LineThickness { get; set; } public XAxisLabelType XAxisLabelType { get; set; } public int XAxisLabelRotation { get; set; } public string ChartTitle { get; set; } public string ChartStrataTitle { get; set; } public string ChartSubTitle { get; set; } public bool ShowLegend { get; set; } public bool ShowLegendBorder { get; set; } public bool ShowLegendVarNames { get; set; } public double LegendFontSize { get; set; } public int ChartWidth { get; set; } public int ChartHeight { get; set; } public string YAxisFormattingString { get; set; } public string Y2AxisFormattingString { get; set; } public ComponentArt.Win.DataVisualization.Charting.Dock LegendDock { get; set; } } public class LineChartSettings : IChartSettings { public bool UseRefValues { get; set; } public bool ShowAnnotations { get; set; } public bool ShowAnnotationsY2 { get; set; } public bool ShowDefaultGridLines { get; set; } public Palette Palette { get; set; } public LineKind LineKind { get; set; } public LineKind LineKindY2 { get; set; } public LineDashStyle LineDashStyleY2 { get; set; } public string Y2AxisLabel { get; set; } public string Y2AxisLegendTitle { get; set; } public string YAxisLabel { get; set; } public string XAxisLabel { get; set; } public double LineThickness { get; set; } public double Y2LineThickness { get; set; } public XAxisLabelType XAxisLabelType { get; set; } public int XAxisLabelRotation { get; set; } public string ChartTitle { get; set; } public string ChartStrataTitle { get; set; } public string ChartSubTitle { get; set; } public bool ShowLegend { get; set; } public bool ShowLegendBorder { get; set; } public bool ShowLegendVarNames { get; set; } public double LegendFontSize { get; set; } public int ChartWidth { get; set; } public int ChartHeight { get; set; } public string YAxisFormattingString { get; set; } public string Y2AxisFormattingString { get; set; } public ComponentArt.Win.DataVisualization.Charting.Dock LegendDock { get; set; } } public class ColumnChartSettings : IChartSettings { public bool UseDiffColors { get; set; } public bool UseRefValues { get; set; } public bool ShowAnnotations { get; set; } public bool ShowAnnotationsY2 { get; set; } public bool ShowDefaultGridLines { get; set; } public CompositionKind Composition { get; set; } public Orientation Orientation { get; set; } public BarSpacing BarSpacing { get; set; } public Palette Palette { get; set; } public BarKind BarKind { get; set; } public LineKind LineKindY2 { get; set; } public LineDashStyle LineDashStyleY2 { get; set; } public string Y2AxisLabel { get; set; } public string Y2AxisLegendTitle { get; set; } public string YAxisLabel { get; set; } public string XAxisLabel { get; set; } public double Y2LineThickness { get; set; } public XAxisLabelType XAxisLabelType { get; set; } public int XAxisLabelRotation { get; set; } public string ChartTitle { get; set; } public string ChartStrataTitle { get; set; } public string ChartSubTitle { get; set; } public bool ShowLegend { get; set; } public bool ShowLegendBorder { get; set; } public bool ShowLegendVarNames { get; set; } public double LegendFontSize { get; set; } public int ChartWidth { get; set; } public int ChartHeight { get; set; } public string YAxisFormattingString { get; set; } public string Y2AxisFormattingString { get; set; } public ComponentArt.Win.DataVisualization.Charting.Dock LegendDock { get; set; } } public class HistogramChartSettings : IChartSettings { public bool UseRefValues { get; set; } public bool ShowAnnotations { get; set; } public bool ShowAnnotationsY2 { get; set; } public bool ShowDefaultGridLines { get; set; } public Palette Palette { get; set; } public BarKind BarKind { get; set; } public LineKind LineKindY2 { get; set; } public LineDashStyle LineDashStyleY2 { get; set; } public BarSpacing BarSpacing { get; set; } public int Step { get; set; } public DateType DateType { get; set; } public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; } public string Y2AxisLabel { get; set; } public string Y2AxisLegendTitle { get; set; } public string YAxisLabel { get; set; } public string XAxisLabel { get; set; } public double Y2LineThickness { get; set; } public XAxisLabelType XAxisLabelType { get; set; } public int XAxisLabelRotation { get; set; } public string ChartTitle { get; set; } public string ChartStrataTitle { get; set; } public string ChartSubTitle { get; set; } public bool ShowLegend { get; set; } public bool ShowLegendBorder { get; set; } public bool ShowLegendVarNames { get; set; } public double LegendFontSize { get; set; } public int ChartWidth { get; set; } public int ChartHeight { get; set; } public string YAxisFormattingString { get; set; } public string Y2AxisFormattingString { get; set; } public ComponentArt.Win.DataVisualization.Charting.Dock LegendDock { get; set; } } public enum DateType { Minute, Hour, Day, Month, Year } public class PieChartSettings : IChartSettings { public bool UseRefValues { get; set; } public bool ShowAnnotations { get; set; } public bool ShowAnnotationsY2 { get; set; } public bool ShowDefaultGridLines { get; set; } public bool ShowAnnotationLabel { get; set; } public bool ShowAnnotationValue { get; set; } public bool ShowAnnotationPercent { get; set; } public Palette Palette { get; set; } public LineKind LineKindY2 { get; set; } public LineDashStyle LineDashStyleY2 { get; set; } public string Y2AxisLabel { get; set; } public string Y2AxisLegendTitle { get; set; } public double Y2LineThickness { get; set; } public string YAxisLabel { get; set; } public string XAxisLabel { get; set; } public XAxisLabelType XAxisLabelType { get; set; } public int XAxisLabelRotation { get; set; } public string ChartTitle { get; set; } public string ChartStrataTitle { get; set; } public string ChartSubTitle { get; set; } public bool ShowLegend { get; set; } public bool ShowLegendBorder { get; set; } public bool ShowLegendVarNames { get; set; } public double LegendFontSize { get; set; } public PieChartKind PieChartKind { get; set; } public int ChartWidth { get; set; } public int ChartHeight { get; set; } public double AnnotationPercent { get; set; } public string YAxisFormattingString { get; set; } public string Y2AxisFormattingString { get; set; } public ComponentArt.Win.DataVisualization.Charting.Dock LegendDock { get; set; } } }
using System; using System.Diagnostics; using System.Xml; using XmlCompare.Model; namespace XmlCompare.Presenter { class ReportPresenter : IReportPresenter { public ReportPresenter() { } public event Action OnReportSaveError; public void OnMakeReportClick(ICompare Compare) { if (string.IsNullOrEmpty(Compare.LeftFileName) || string.IsNullOrEmpty(Compare.RightFileName)) { if (OnReportSaveError != null) OnReportSaveError(); return; } using (var writer = XmlWriter.Create("Report.html")) { writer.WriteStartElement("html"); writer.WriteStartElement("head"); writer.WriteStartElement("title"); writer.WriteString("Differences"); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteStartElement("body"); writer.Write("List of differences of the file " + Compare.RightFileName + " relative to the file " + Compare.LeftFileName, "h2"); writer.WriteEndElement(); writer.WriteEndElement(); Process.Start("Report.html"); } } } }
using System.Drawing; using System.Drawing.Imaging; using System.IO; using Microsoft.Xna.Framework.Graphics; namespace SpriteToolBox { class TextureSprite { public Texture2D Texture { get; set; } public int XCenter { get; set; } public int YCenter { get; set; } public TextureSprite(Texture2D texture) { Texture = texture; CalculateCenter(); } public TextureSprite(GraphicsDevice graphics, Bitmap bitmap) { Texture = TextureSprite.GetTexture(graphics, bitmap); CalculateCenter(); } private void CalculateCenter() { XCenter = Texture.Width / 2 + 1; YCenter = Texture.Height / 2 + 1; if (Texture.Width % 2 == 1) XCenter -= 1; if (Texture.Height % 2 == 1) YCenter -= 1; } public static Texture2D GetTexture(GraphicsDevice graphics, Bitmap bitmap) { Texture2D tex = null; using (MemoryStream s = new MemoryStream()) { bitmap.Save(s, ImageFormat.Png); s.Seek(0, SeekOrigin.Begin); tex = Texture2D.FromStream(graphics, s); } return tex; } } }
using System.Threading; using System.Threading.Tasks; using LiteGuard; using Mileage.Server.Contracts.Commands; using Mileage.Server.Contracts.Commands.Users; using Mileage.Shared.Entities; using Mileage.Shared.Entities.Users; using Mileage.Shared.Extensions; using Mileage.Shared.Results; using Raven.Client; namespace Mileage.Server.Infrastructure.Commands.Users { public class GetCurrentUserCommandHandler : ICommandHandler<GetCurrentUserCommand, User> { private readonly IAsyncDocumentSession _documentSession; public GetCurrentUserCommandHandler(IAsyncDocumentSession documentSession) { Guard.AgainstNullArgument("documentSession", documentSession); this._documentSession = documentSession; } public async Task<Result<User>> Execute(GetCurrentUserCommand command, ICommandScope scope) { string currentUserId = Thread.CurrentPrincipal.Identity.Name; var currentUser = await this._documentSession.LoadAsync<User>(currentUserId).WithCurrentCulture(); return Result.AsSuccess(currentUser); } } }
using System; using System.Linq; using System.Net.Http; using Fathcore.Infrastructures; using Fathcore.Infrastructures.Abstractions; using Fathcore.Tests.Fakes; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace Fathcore.Tests { public class CoreEngineTests { private IServiceCollection Collection { get; } = new ServiceCollection(); [Fact] public void Should_Register_Service_Dependency() { Collection.AddSingleton(typeof(ITransientService), typeof(TransientService)); var engine = new CoreEngine(Collection); engine.ConfigureServices(); using (var serviceScope = engine.ServiceProvider.CreateScope()) { var requiredService = serviceScope.ServiceProvider.GetService<ITransientService>(); Assert.NotNull(requiredService); } } [Fact] public void Should_Resolve_Service_Dependency() { Collection.AddSingleton(typeof(ITransientService), typeof(TransientService)); var engine = new CoreEngine(Collection); engine.ConfigureServices(); var requiredService = engine.Resolve<ITransientService>(); Assert.NotNull(requiredService); } [Fact] public void Should_Not_Resolve_Service_Dependency() { var engine = new CoreEngine(Collection); engine.ConfigureServices(); Assert.Throws<InvalidOperationException>(() => engine.Resolve<ITransientService>()); } [Fact] public void Should_Resolve_All_Service_Dependency() { Collection.AddSingleton(typeof(ITransientService), typeof(TransientService)); Collection.AddSingleton(typeof(ITransientService), typeof(TransientService1)); var engine = new CoreEngine(Collection); engine.ConfigureServices(); var requiredService = engine.ResolveAll<ITransientService>(); Assert.Equal(2, requiredService.Count()); } [Fact] public void Should_Resolve_Unregistered_Service_Dependency() { var engine = new CoreEngine(Collection); engine.ConfigureServices(); var requiredService = engine.ResolveUnregistered(typeof(UnregisteredService)); Assert.NotNull(requiredService); } [Fact] public void Engine_Http_Client_Is_Singleton() { var engine = new CoreEngine(); HttpClient httpClient = engine.HttpClient; Assert.Equal(httpClient, Singleton<HttpClient>.Instance); Assert.Equal(httpClient, BaseSingleton.AllSingletons[typeof(HttpClient)]); } } }
namespace HealthCare020.Core.Request { public class MedicinskiTehnicarUpsertDto : RadnikUpsertDto { } }
using System; using System.Threading.Tasks; using Microsoft.Owin; using OwinFramework.InterfacesV1.Middleware; using OwinFramework.Pages.Core.Debug; using OwinFramework.Pages.Core.Enums; using OwinFramework.Pages.Core.Interfaces; using OwinFramework.Pages.Core.Interfaces.Builder; using OwinFramework.Pages.Core.Interfaces.Runtime; namespace OwinFramework.Pages.Restful.Runtime { /// <summary> /// Base implementation of IComponent. Inheriting from this olass will insulate you /// from any future additions to the IComponent interface /// </summary> public class Service : IService, IDebuggable { public ElementType ElementType { get { return ElementType.Service; } } public string Name { get; set; } public IPackage Package { get; set; } public string RequiredPermission { get; set; } public bool AllowAnonymous { get; set; } public Func<IOwinContext, bool> AuthenticationFunc { get { return null; } } string IRunable.CacheCategory { get; set; } CachePriority IRunable.CachePriority { get; set; } public Service(IServiceDependenciesFactory serviceDependenciesFactory) { } public void Initialize() { } public Task Run(IOwinContext context, Action<IOwinContext, Func<string>> trace) { throw new NotImplementedException(); } T IDebuggable.GetDebugInfo<T>(int parentDepth, int childDepth) { return new DebugService() as T; } } }
using Microsoft.Extensions.DependencyInjection; namespace DotNetCloud.RequestMonitoring.Core.DependencyInjection { public interface IRequestMetricsBuilder { /// <summary> /// Gets the application service collection. /// </summary> IServiceCollection Services { get; } public IServiceCollection Build(); } }
interface IMonth<T> { } interface IJanuary : IMonth<int> { } //No error interface IFebruary<T> : IMonth<int> { } //No error interface IMarch<T> : IMonth<T> { } //No error //interface IApril<T> : IMonth<T, U> {} //Error
using System.Collections.Generic; using System.Threading.Tasks; namespace PokemonCardTraderBot.Database.Generic { public interface IGenericAsyncRepository<TObject, in TObjectId> where TObject : class { Task<IEnumerable<TObject>> GetAllAsync(); Task<TObject> GetByIdAsync(TObjectId id); Task<IEnumerable<TObject>> GetByIdsAsync(IEnumerable<TObjectId> ids); Task<TObject> SaveAsync(TObject obj); Task<IEnumerable<TObject>> SaveAsync(IReadOnlyList<TObject> objs); Task DeleteByIdAsync(TObjectId id); Task DeleteByIdsAsync(IEnumerable<TObjectId> ids); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.ContainerService.Fluent.ContainerService.Update { using Microsoft.Azure.Management.ContainerService.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Update; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions; /// <summary> /// The stage of the container service update allowing to enable or disable diagnostics. /// </summary> public interface IWithDiagnostics { /// <summary> /// Enables diagnostics. /// </summary> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.ContainerService.Update.IUpdate WithDiagnostics(); /// <summary> /// Disables diagnostics. /// </summary> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.ContainerService.Update.IUpdate WithoutDiagnostics(); } /// <summary> /// The template for an update operation, containing all the settings that /// can be modified. /// </summary> public interface IUpdate : Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Update.IUpdateWithTags<Microsoft.Azure.Management.ContainerService.Fluent.ContainerService.Update.IUpdate>, Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.IAppliable<Microsoft.Azure.Management.ContainerService.Fluent.IContainerService>, Microsoft.Azure.Management.ContainerService.Fluent.ContainerService.Update.IWithUpdateAgentPoolCount, Microsoft.Azure.Management.ContainerService.Fluent.ContainerService.Update.IWithDiagnostics { } /// <summary> /// The stage of the container service update allowing to specify the number of agents in the specified pool. /// </summary> public interface IWithUpdateAgentPoolCount { /// <summary> /// Updates the agent pool virtual machine count. /// </summary> /// <param name="agentCount">The number of agents (virtual machines) to host docker containers.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.ContainerService.Fluent.ContainerService.Update.IUpdate WithAgentVirtualMachineCount(int agentCount); } }
@model SocialStream.Models.StreamModel @{ ViewBag.Title = "Stream"; } <section class="jumbotron"> <h1>Stream</h1> <p class="lead">Here's an example of how it works (sometimes)</p> </section> @for (int i = 0; i < 10; i++) { <section class="row"> <section class="col-md-6"> <img src="@Model.FacebookPictures[i].Url" class="image"/> </section> <section class="col-md-6"> <h2>@Model.TwitterTweets[i].TweetAuthor</h2> <p>@Model.TwitterTweets[i].Tweet</p> </section> </section> }
using System; using System.Collections.Generic; using System.Threading.Tasks; using ordering.Domain; namespace ordering.Persistence.Impl { public class OrdersRepository : IOrdersRepository { private static readonly Random _random = new Random(); public async Task<IEnumerable<Order>> GetClientOrders(Guid clientId) { var numberOfOrders = _random.Next(0, 4); var orders = new List<Order>(numberOfOrders); for (var i = 0; i < numberOfOrders; i++) { var orderId = Guid.NewGuid(); var order = await CreateMockOrder(clientId, orderId); orders.Add(order); } return orders; } public async Task<Order> GetOrder(Guid orderId) { var clientId = Guid.NewGuid(); return await CreateMockOrder(clientId, orderId); } private static Task<Order> CreateMockOrder(Guid clientId, Guid orderId) { var createdAt = DateTimeOffset.UtcNow; return Task.FromResult(new Order { Id = orderId, ClientId = clientId, Created = createdAt, Modified = createdAt, State = OrderStates.Created }); } } }
using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class InputValidator : MonoBehaviour { public string expected; public string id; Text textUI; static Dictionary<string, Text> publicValues = new Dictionary<string, Text>(); private bool isValid; public static int ValidTextUICount { get; private set; } public static int TextUICount { get; private set; } void Start() { textUI = GetComponent<InputField>().textComponent; if (!string.IsNullOrEmpty(id)) publicValues[id] = textUI; isValid = textUI.text == expected; if (isValid) ValidTextUICount++; TextUICount++; } public void OnEditChanged() { //print(textUI.text + (textUI.text == expected ? " == " : " != ") + expected); var isValidForNow = textUI.text == expected; if (isValidForNow == isValid) return; // no changes ValidTextUICount += isValidForNow ? 1 : -1; isValid = isValidForNow; print(ValidTextUICount); print(AllTextAreValid); if (ValidTextUICount == TextUICount && AllTextAreValid != null) AllTextAreValid(ValidTextUICount); } public static Text GetTextUIById(string id) { Text value; publicValues.TryGetValue(id, out value); return value; } public static event System.Action<int> AllTextAreValid; }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using System; public class PersonIcon : MonoBehaviour, IPointerClickHandler { public Sprite aliveSprite; public Sprite deadSprite; public Sprite recentlyDeadSprite; private PersonCardState _state; public PersonCardState state { get { return _state; } set { _state = value; var sprite = value.dead ? deadSprite : aliveSprite; icon.sprite = sprite; } } public Image icon { get { return GetComponentInChildren<Image>(); } } void IPointerClickHandler.OnPointerClick(PointerEventData eventData) { FindObjectOfType<GameUI>().ShowPersonInfo(this.state); } public void JustBecameDead() { StartCoroutine(RunJustBecameDead()); } IEnumerator RunJustBecameDead() { this.icon.sprite = recentlyDeadSprite; yield return new WaitForSeconds(1.0f); this.icon.sprite = deadSprite; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; class Program { #region Type Declarations class Player { public int Left; public int Top; } class Bullet { public int Left; public int Top; public int Frame; } class Explosion { public int Left; public int Top; public int Frame; } class UFO { public int Frame; public int Left; public int Top; public int Health; } static class Ascii { #region Ascii Renders public static string[] bulletRenders = new string[] { " ", // 0 "-", // 1 "~", // 2 "█", // 3 }; public static readonly string[] helicopterRenders = new string[] { // 0 @" " + '\n' + @" " + '\n' + @" ", // 1 @" ~~~~~+~~~~~" + '\n' + @"'\===<[_]L) " + '\n' + @" -'-`- ", // 2 @" -----+-----" + '\n' + @"*\===<[_]L) " + '\n' + @" -'-`- ", }; public static string[] ufoRenders = new string[] { // 0 @" __O__ " + '\n' + @"-=<_‗_‗_>=-", // 1 @" _!_ " + '\n' + @" /_O_\ " + '\n' + @"-==<_‗_‗_>==-", // 2 @" _/\_ " + '\n' + @" /_OO_\ " + '\n' + @"() () ()", // 3 @" _!_!_ " + '\n' + @"|_o-o_|" + '\n' + @" ^^^^^ ", // 4 @" _!_ " + '\n' + @"(_o_)" + '\n' + @" ^^^ ", }; public static readonly string[] explosionRenders = new string[] { // 0 @" " + '\n' + @" █████ " + '\n' + @" █████ " + '\n' + @" █████ " + '\n' + @" ", // 1 @" " + '\n' + @" " + '\n' + @" * " + '\n' + @" " + '\n' + @" ", // 2 @" " + '\n' + @" * " + '\n' + @" *#* " + '\n' + @" * " + '\n' + @" ", // 3 @" " + '\n' + @" *#* " + '\n' + @" *#*#* " + '\n' + @" *#* " + '\n' + @" ", // 4 @" * " + '\n' + @" *#*#* " + '\n' + @" *#* *#* " + '\n' + @" *#*#* " + '\n' + @" * ", // 5 @" *#* " + '\n' + @" *#* *#* " + '\n' + @" *#* *#* " + '\n' + @" *#* *#* " + '\n' + @" *#* ", // 6 @" * * " + '\n' + @" ** ** " + '\n' + @"** **" + '\n' + @" ** ** " + '\n' + @" * * ", // 7 @" * * " + '\n' + @" * * " + '\n' + @"* *" + '\n' + @" * * " + '\n' + @" * * ", }; #endregion } #endregion static readonly int height = Console.WindowHeight; static readonly int width = Console.WindowWidth; static readonly TimeSpan threadSleepTimeSpan = TimeSpan.FromMilliseconds(10); static readonly TimeSpan helicopterTimeSpan = TimeSpan.FromMilliseconds(70); static readonly TimeSpan ufoMovementTimeSpan = TimeSpan.FromMilliseconds(100); static readonly TimeSpan enemySpawnTimeSpan = TimeSpan.FromSeconds(1.75); static readonly Player player = new Player { Left = 2, Top = height / 2, }; static readonly List<UFO> ufos = new List<UFO>(); static readonly List<Bullet> bullets = new List<Bullet>(); static readonly List<Explosion> explosions = new List<Explosion>(); static readonly Stopwatch stopwatchGame = new Stopwatch(); static readonly Stopwatch stopwatchUFOSpawn = new Stopwatch(); static readonly Stopwatch stopwatchHelicopter = new Stopwatch(); static readonly Stopwatch stopwatchUFO = new Stopwatch(); static readonly Random random = new Random(); static int score = 0; static bool bulletFrame; static bool helicopterRender; static void Main() { Console.Clear(); Console.WindowWidth = 100; Console.WindowHeight = 30; Console.CursorVisible = false; stopwatchGame.Restart(); stopwatchUFOSpawn.Restart(); stopwatchHelicopter.Restart(); stopwatchUFO.Restart(); while (true) { #region Window Resize if (height != Console.WindowHeight || width != Console.WindowWidth) { Console.Clear(); Console.Write("Console window resized. Helicopter closed."); return; } #endregion #region Update UFOs if (stopwatchUFOSpawn.Elapsed > enemySpawnTimeSpan) { ufos.Add(new UFO { Health = 4, Frame = random.Next(5), Top = random.Next(height - 3), Left = width, }); stopwatchUFOSpawn.Restart(); } if (stopwatchUFO.Elapsed > ufoMovementTimeSpan) { foreach (UFO ufo in ufos) { if (ufo.Left < width) { Console.SetCursorPosition(ufo.Left, ufo.Top); Erase(Ascii.ufoRenders[ufo.Frame]); } ufo.Left--; if (ufo.Left <= 0) { Console.Clear(); Console.Write("Game Over. Score: " + score + "."); return; } } stopwatchUFO.Restart(); } #endregion #region Update Player bool playerRenderRequired = false; if (Console.KeyAvailable) { switch (Console.ReadKey(true).Key) { case ConsoleKey.UpArrow: Console.SetCursorPosition(player.Left, player.Top); Render(Ascii.helicopterRenders[default], true); player.Top = Math.Max(player.Top - 1, 0); playerRenderRequired = true; break; case ConsoleKey.DownArrow: Console.SetCursorPosition(player.Left, player.Top); Render(Ascii.helicopterRenders[default], true); player.Top = Math.Min(player.Top + 1, height - 3); playerRenderRequired = true; break; case ConsoleKey.RightArrow: bullets.Add(new Bullet { Left = player.Left + 11, Top = player.Top + 1, Frame = (bulletFrame = !bulletFrame) ? 1 : 2, }); break; case ConsoleKey.Escape: Console.Clear(); Console.Write("Helicopter was closed."); return; } } while (Console.KeyAvailable) { Console.ReadKey(true); } #endregion #region Update Bullets HashSet<Bullet> bulletRemovals = new HashSet<Bullet>(); foreach (Bullet bullet in bullets) { Console.SetCursorPosition(bullet.Left, bullet.Top); Console.Write(Ascii.bulletRenders[default]); bullet.Left++; if (bullet.Left >= width || bullet.Frame is 3) { bulletRemovals.Add(bullet); } HashSet<UFO> ufoRemovals = new HashSet<UFO>(); foreach (UFO ufo in ufos) { if (ufo.Left <= bullet.Left && ufo.Top <= bullet.Top && CollisionCheck( (Ascii.bulletRenders[bullet.Frame], bullet.Left, bullet.Top), (Ascii.ufoRenders[ufo.Frame], ufo.Left, ufo.Top))) { bullet.Frame = 3; ufo.Health--; if (ufo.Health <= 0) { score += 100; Console.SetCursorPosition(ufo.Left, ufo.Top); Erase(Ascii.ufoRenders[ufo.Frame]); ufoRemovals.Add(ufo); explosions.Add(new Explosion { Left = bullet.Left - 5, Top = Math.Max(bullet.Top - 2, 0), }); } } } ufos.RemoveAll(ufoRemovals.Contains); } bullets.RemoveAll(bulletRemovals.Contains); #endregion #region Update & Render Explosions HashSet<Explosion> explosionRemovals = new HashSet<Explosion>(); foreach (Explosion explosion in explosions) { if (explosion.Frame > 0) { Console.SetCursorPosition(explosion.Left, explosion.Top); Erase(Ascii.explosionRenders[explosion.Frame - 1]); } if (explosion.Frame < Ascii.explosionRenders.Length) { Console.SetCursorPosition(explosion.Left, explosion.Top); Render(Ascii.explosionRenders[explosion.Frame]); } explosion.Frame++; if (explosion.Frame > Ascii.explosionRenders.Length) { explosionRemovals.Add(explosion); } } explosions.RemoveAll(explosionRemovals.Contains); #endregion #region Render Player if (stopwatchHelicopter.Elapsed > helicopterTimeSpan) { helicopterRender = !helicopterRender; stopwatchHelicopter.Restart(); playerRenderRequired = true; } if (playerRenderRequired) { Console.SetCursorPosition(player.Left, player.Top); Render(Ascii.helicopterRenders[helicopterRender ? 1 : 2]); } #endregion #region Render UFOs foreach (UFO ufo in ufos) { if (ufo.Left < width) { Console.SetCursorPosition(ufo.Left, ufo.Top); Render(Ascii.ufoRenders[ufo.Frame]); } } #endregion #region Render Bullets foreach (Bullet bullet in bullets) { Console.SetCursorPosition(bullet.Left, bullet.Top); Render(Ascii.bulletRenders[bullet.Frame]); } #endregion Thread.Sleep(threadSleepTimeSpan); } } static void Render(string @string, bool renderSpace = false) { int x = Console.CursorLeft; int y = Console.CursorTop; foreach (char c in @string) if (c is '\n') Console.SetCursorPosition(x, ++y); else if (Console.CursorLeft < width - 1 && (!(c is ' ') || renderSpace)) Console.Write(c); else if (Console.CursorLeft < width - 1 && Console.CursorTop < height - 1) Console.SetCursorPosition(Console.CursorLeft + 1, Console.CursorTop); } static void Erase(string @string) { int x = Console.CursorLeft; int y = Console.CursorTop; foreach (char c in @string) if (c is '\n') Console.SetCursorPosition(x, ++y); else if (Console.CursorLeft < width - 1 && !(c is ' ')) Console.Write(' '); else if (Console.CursorLeft < width - 1 && Console.CursorTop < height - 1) Console.SetCursorPosition(Console.CursorLeft + 1, Console.CursorTop); } static bool CollisionCheck((string String, int Left, int Top) A, (string String, int Left, int Top) B) { char[,] buffer = new char[width, height]; int left = A.Left; int top = A.Top; foreach (char c in A.String) { if (c is '\n') { left = A.Left; top++; } else if (left < width && top < height && c != ' ') { buffer[left++, top] = c; } } left = B.Left; top = B.Top; foreach (char c in B.String) { if (c is '\n') { left = A.Left; top++; } else if (left < width && top < height && c != ' ') { if (buffer[left, top] != default) { return true; } buffer[left++, top] = c; } } return false; } }
using System; using System.Threading; namespace Dissonance.Engine.IO { internal readonly struct ContinuationScheduler { public readonly Asset Asset; internal ContinuationScheduler(Asset asset) { Asset = asset; } public void OnCompleted(Action continuation) { // Make the action only runnable once continuation = MakeOnlyRunnableOnce(continuation); Assets.AssetTransferQueue.Enqueue(continuation); Asset.Continuation = continuation; } public static Action MakeOnlyRunnableOnce(Action action) => () => Interlocked.Exchange(ref action, null)?.Invoke(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sdl.Community.GroupShareKit.Models.Response.TranslationMemory { public class CommentDefinition { /// <summary> /// Gets or sets the id /// </summary> public int Id { get; set; } /// <summary> /// Gets or sets the text /// </summary> public string Text { get; set; } /// <summary> /// Gets or sets author /// </summary> public string Author { get; set; } /// <summary> /// Gets or sets the date /// </summary> public DateTime? Date { get; set; } /// <summary> /// Gets or sets comment severity /// </summary> public string CommentSeverity { get; set; } /// <summary> /// Gets or sets metadata /// </summary> public Metadata Metadata { get; set; } } }
// Copyright © John Gietzen. All Rights Reserved. This source is subject to the MIT license. Please see license.md for more information. namespace Pegasus.Expressions { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; /// <summary> /// Represents a parse rule. /// </summary> [DebuggerDisplay("Rule {Identifier.Name}")] public class Rule { /// <summary> /// Initializes a new instance of the <see cref="Rule"/> class. /// </summary> /// <param name="identifier">The identifier that represents the <see cref="Rule"/>.</param> /// <param name="expression">The expression that this <see cref="Rule"/> represents.</param> /// <param name="flags" >The flags to be set on this <see cref="Rule"/>.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "flags", Justification = "The usage of 'flags' here is intentional and desired.")] public Rule(Identifier identifier, Expression expression, IEnumerable<Identifier> flags) { this.Identifier = identifier ?? throw new ArgumentNullException(nameof(identifier)); this.Expression = expression ?? throw new ArgumentNullException(nameof(expression)); this.Flags = (flags ?? Enumerable.Empty<Identifier>()).ToList().AsReadOnly(); } /// <summary> /// Gets the expression that this <see cref="Rule"/> represents. /// </summary> public Expression Expression { get; } /// <summary> /// Gets the flags that have been set on this <see cref="Rule"/>. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags", Justification = "The usage of 'Flags' here is intentional and desired.")] public IList<Identifier> Flags { get; } /// <summary> /// Gets the name of this <see cref="Rule"/>. /// </summary> public Identifier Identifier { get; } } }
using System.Numerics; using ImGuiNET; using Newtonsoft.Json; namespace XIVLauncher.Core.Style; /// <summary> /// Version one of the Dalamud style model. /// </summary> public class StyleModelV1 : StyleModel { /// <summary> /// Initializes a new instance of the <see cref="StyleModelV1"/> class. /// </summary> private StyleModelV1() { this.Colors = new Dictionary<string, Vector4>(); this.Name = "Unknown"; } /// <summary> /// Gets the standard Dalamud look. /// </summary> public static StyleModelV1 DalamudStandard => new() { Name = "Dalamud Standard", Alpha = 1, WindowPadding = new Vector2(8, 8), WindowRounding = 4, WindowBorderSize = 0, WindowTitleAlign = new Vector2(0, 0.5f), WindowMenuButtonPosition = ImGuiDir.Right, ChildRounding = 0, ChildBorderSize = 1, PopupRounding = 0, PopupBorderSize = 0, FramePadding = new Vector2(4, 3), //FrameRounding = 4, FrameRounding = 0, FrameBorderSize = 0, ItemSpacing = new Vector2(8, 4), ItemInnerSpacing = new Vector2(4, 4), CellPadding = new Vector2(4, 2), TouchExtraPadding = new Vector2(0, 0), IndentSpacing = 21, ScrollbarSize = 16, ScrollbarRounding = 9, GrabMinSize = 13, GrabRounding = 3, LogSliderDeadzone = 4, TabRounding = 1, TabBorderSize = 0, ButtonTextAlign = new Vector2(0.5f, 0.5f), SelectableTextAlign = new Vector2(0, 0), DisplaySafeAreaPadding = new Vector2(3, 3), Colors = new Dictionary<string, Vector4> { { "Text", new Vector4(1, 1, 1, 1) }, { "TextDisabled", new Vector4(0.5f, 0.5f, 0.5f, 1) }, { "WindowBg", new Vector4(0.06f, 0.06f, 0.06f, 0.93f) }, { "ChildBg", new Vector4(0, 0, 0, 0) }, { "PopupBg", new Vector4(0.08f, 0.08f, 0.08f, 0.94f) }, { "Border", new Vector4(0.43f, 0.43f, 0.5f, 0.5f) }, { "BorderShadow", new Vector4(0, 0, 0, 0) }, { "FrameBg", new Vector4(0.29f, 0.29f, 0.29f, 0.54f) }, { "FrameBgHovered", new Vector4(0.54f, 0.54f, 0.54f, 0.4f) }, { "FrameBgActive", new Vector4(0.64f, 0.64f, 0.64f, 0.67f) }, { "TitleBg", new Vector4(0.022624433f, 0.022624206f, 0.022624206f, 0.85067874f) }, { "TitleBgActive", new Vector4(0.38914025f, 0.10917056f, 0.10917056f, 0.8280543f) }, { "TitleBgCollapsed", new Vector4(0, 0, 0, 0.51f) }, { "MenuBarBg", new Vector4(0.14f, 0.14f, 0.14f, 1) }, { "ScrollbarBg", new Vector4(0, 0, 0, 0) }, { "ScrollbarGrab", new Vector4(0.31f, 0.31f, 0.31f, 1) }, { "ScrollbarGrabHovered", new Vector4(0.41f, 0.41f, 0.41f, 1) }, { "ScrollbarGrabActive", new Vector4(0.51f, 0.51f, 0.51f, 1) }, { "CheckMark", new Vector4(0.86f, 0.86f, 0.86f, 1) }, { "SliderGrab", new Vector4(0.54f, 0.54f, 0.54f, 1) }, { "SliderGrabActive", new Vector4(0.67f, 0.67f, 0.67f, 1) }, { "Button", new Vector4(0.71f, 0.71f, 0.71f, 0.4f) }, { "ButtonHovered", ImGuiColors.BlueShade3 }, { "ButtonActive", ImGuiColors.Blue }, { "Header", new Vector4(0.59f, 0.59f, 0.59f, 0.31f) }, { "HeaderHovered", new Vector4(0.5f, 0.5f, 0.5f, 0.8f) }, { "HeaderActive", new Vector4(0.6f, 0.6f, 0.6f, 1) }, { "Separator", new Vector4(0.43f, 0.43f, 0.5f, 0.5f) }, { "SeparatorHovered", new Vector4(0.3647059f, 0.078431375f, 0.078431375f, 0.78280544f) }, { "SeparatorActive", new Vector4(0.3647059f, 0.078431375f, 0.078431375f, 0.94509804f) }, { "ResizeGrip", new Vector4(0.79f, 0.79f, 0.79f, 0.25f) }, { "ResizeGripHovered", new Vector4(0.78f, 0.78f, 0.78f, 0.67f) }, { "ResizeGripActive", new Vector4(0.3647059f, 0.078431375f, 0.078431375f, 0.94509804f) }, { "Tab", new Vector4(0.23f, 0.23f, 0.23f, 0.86f) }, { "TabHovered", ImGuiColors.BlueShade3 }, { "TabActive", ImGuiColors.Blue }, { "TabUnfocused", new Vector4(0.068f, 0.10199998f, 0.14800003f, 0.9724f) }, { "TabUnfocusedActive", ImGuiColors.Blue }, { "DockingPreview", new Vector4(0.26f, 0.59f, 0.98f, 0.7f) }, { "DockingEmptyBg", new Vector4(0.2f, 0.2f, 0.2f, 1) }, { "PlotLines", new Vector4(0.61f, 0.61f, 0.61f, 1) }, { "PlotLinesHovered", new Vector4(1, 0.43f, 0.35f, 1) }, { "PlotHistogram", new Vector4(0.9f, 0.7f, 0, 1) }, { "PlotHistogramHovered", new Vector4(1, 0.6f, 0, 1) }, { "TableHeaderBg", new Vector4(0.19f, 0.19f, 0.2f, 1) }, { "TableBorderStrong", new Vector4(0.31f, 0.31f, 0.35f, 1) }, { "TableBorderLight", new Vector4(0.23f, 0.23f, 0.25f, 1) }, { "TableRowBg", new Vector4(0, 0, 0, 0) }, { "TableRowBgAlt", new Vector4(1, 1, 1, 0.06f) }, { "TextSelectedBg", new Vector4(0.26f, 0.59f, 0.98f, 0.35f) }, { "DragDropTarget", new Vector4(1, 1, 0, 0.9f) }, { "NavHighlight", new Vector4(0.26f, 0.59f, 0.98f, 1) }, { "NavWindowingHighlight", new Vector4(1, 1, 1, 0.7f) }, { "NavWindowingDimBg", new Vector4(0.8f, 0.8f, 0.8f, 0.2f) }, { "ModalWindowDimBg", new Vector4(0.8f, 0.8f, 0.8f, 0.35f) }, }, }; /// <summary> /// Gets the standard Dalamud look. /// </summary> public static StyleModelV1 DalamudClassic => new() { Name = "Dalamud Classic", Alpha = 1, WindowPadding = new Vector2(8, 8), WindowRounding = 4, WindowBorderSize = 0, WindowTitleAlign = new Vector2(0, 0.5f), WindowMenuButtonPosition = ImGuiDir.Right, ChildRounding = 0, ChildBorderSize = 1, PopupRounding = 0, PopupBorderSize = 0, FramePadding = new Vector2(4, 3), FrameRounding = 4, FrameBorderSize = 0, ItemSpacing = new Vector2(8, 4), ItemInnerSpacing = new Vector2(4, 4), CellPadding = new Vector2(4, 2), TouchExtraPadding = new Vector2(0, 0), IndentSpacing = 21, ScrollbarSize = 16, ScrollbarRounding = 9, GrabMinSize = 10, GrabRounding = 3, LogSliderDeadzone = 4, TabRounding = 4, TabBorderSize = 0, ButtonTextAlign = new Vector2(0.5f, 0.5f), SelectableTextAlign = new Vector2(0, 0), DisplaySafeAreaPadding = new Vector2(3, 3), Colors = new Dictionary<string, Vector4> { { "Text", new Vector4(1f, 1f, 1f, 1f) }, { "TextDisabled", new Vector4(0.5f, 0.5f, 0.5f, 1f) }, { "WindowBg", new Vector4(0.06f, 0.06f, 0.06f, 0.87f) }, { "ChildBg", new Vector4(0f, 0f, 0f, 0f) }, { "PopupBg", new Vector4(0.08f, 0.08f, 0.08f, 0.94f) }, { "Border", new Vector4(0.43f, 0.43f, 0.5f, 0.5f) }, { "BorderShadow", new Vector4(0f, 0f, 0f, 0f) }, { "FrameBg", new Vector4(0.29f, 0.29f, 0.29f, 0.54f) }, { "FrameBgHovered", new Vector4(0.54f, 0.54f, 0.54f, 0.4f) }, { "FrameBgActive", new Vector4(0.64f, 0.64f, 0.64f, 0.67f) }, { "TitleBg", new Vector4(0.04f, 0.04f, 0.04f, 1f) }, { "TitleBgActive", new Vector4(0.29f, 0.29f, 0.29f, 1f) }, { "TitleBgCollapsed", new Vector4(0f, 0f, 0f, 0.51f) }, { "MenuBarBg", new Vector4(0.14f, 0.14f, 0.14f, 1f) }, { "ScrollbarBg", new Vector4(0f, 0f, 0f, 0f) }, { "ScrollbarGrab", new Vector4(0.31f, 0.31f, 0.31f, 1f) }, { "ScrollbarGrabHovered", new Vector4(0.41f, 0.41f, 0.41f, 1f) }, { "ScrollbarGrabActive", new Vector4(0.51f, 0.51f, 0.51f, 1f) }, { "CheckMark", new Vector4(0.86f, 0.86f, 0.86f, 1f) }, { "SliderGrab", new Vector4(0.54f, 0.54f, 0.54f, 1f) }, { "SliderGrabActive", new Vector4(0.67f, 0.67f, 0.67f, 1f) }, { "Button", new Vector4(0.71f, 0.71f, 0.71f, 0.4f) }, { "ButtonHovered", new Vector4(0.47f, 0.47f, 0.47f, 1f) }, { "ButtonActive", new Vector4(0.74f, 0.74f, 0.74f, 1f) }, { "Header", new Vector4(0.59f, 0.59f, 0.59f, 0.31f) }, { "HeaderHovered", new Vector4(0.5f, 0.5f, 0.5f, 0.8f) }, { "HeaderActive", new Vector4(0.6f, 0.6f, 0.6f, 1f) }, { "Separator", new Vector4(0.43f, 0.43f, 0.5f, 0.5f) }, { "SeparatorHovered", new Vector4(0.1f, 0.4f, 0.75f, 0.78f) }, { "SeparatorActive", new Vector4(0.1f, 0.4f, 0.75f, 1f) }, { "ResizeGrip", new Vector4(0.79f, 0.79f, 0.79f, 0.25f) }, { "ResizeGripHovered", new Vector4(0.78f, 0.78f, 0.78f, 0.67f) }, { "ResizeGripActive", new Vector4(0.88f, 0.88f, 0.88f, 0.95f) }, { "Tab", new Vector4(0.23f, 0.23f, 0.23f, 0.86f) }, { "TabHovered", new Vector4(0.71f, 0.71f, 0.71f, 0.8f) }, { "TabActive", new Vector4(0.36f, 0.36f, 0.36f, 1f) }, { "TabUnfocused", new Vector4(0.068f, 0.10199998f, 0.14800003f, 0.9724f) }, { "TabUnfocusedActive", new Vector4(0.13599998f, 0.26199996f, 0.424f, 1f) }, { "DockingPreview", new Vector4(0.26f, 0.59f, 0.98f, 0.7f) }, { "DockingEmptyBg", new Vector4(0.2f, 0.2f, 0.2f, 1f) }, { "PlotLines", new Vector4(0.61f, 0.61f, 0.61f, 1f) }, { "PlotLinesHovered", new Vector4(1f, 0.43f, 0.35f, 1f) }, { "PlotHistogram", new Vector4(0.9f, 0.7f, 0f, 1f) }, { "PlotHistogramHovered", new Vector4(1f, 0.6f, 0f, 1f) }, { "TableHeaderBg", new Vector4(0.19f, 0.19f, 0.2f, 1f) }, { "TableBorderStrong", new Vector4(0.31f, 0.31f, 0.35f, 1f) }, { "TableBorderLight", new Vector4(0.23f, 0.23f, 0.25f, 1f) }, { "TableRowBg", new Vector4(0f, 0f, 0f, 0f) }, { "TableRowBgAlt", new Vector4(1f, 1f, 1f, 0.06f) }, { "TextSelectedBg", new Vector4(0.26f, 0.59f, 0.98f, 0.35f) }, { "DragDropTarget", new Vector4(1f, 1f, 0f, 0.9f) }, { "NavHighlight", new Vector4(0.26f, 0.59f, 0.98f, 1f) }, { "NavWindowingHighlight", new Vector4(1f, 1f, 1f, 0.7f) }, { "NavWindowingDimBg", new Vector4(0.8f, 0.8f, 0.8f, 0.2f) }, { "ModalWindowDimBg", new Vector4(0.8f, 0.8f, 0.8f, 0.35f) }, }, }; /// <summary> /// Gets the version prefix for this version. /// </summary> public static string SerializedPrefix => "DS1"; #pragma warning disable SA1600 [JsonProperty("a")] public float Alpha { get; set; } [JsonProperty("b")] public Vector2 WindowPadding { get; set; } [JsonProperty("c")] public float WindowRounding { get; set; } [JsonProperty("d")] public float WindowBorderSize { get; set; } [JsonProperty("e")] public Vector2 WindowTitleAlign { get; set; } [JsonProperty("f")] public ImGuiDir WindowMenuButtonPosition { get; set; } [JsonProperty("g")] public float ChildRounding { get; set; } [JsonProperty("h")] public float ChildBorderSize { get; set; } [JsonProperty("i")] public float PopupRounding { get; set; } [JsonProperty("ab")] public float PopupBorderSize { get; set; } [JsonProperty("j")] public Vector2 FramePadding { get; set; } [JsonProperty("k")] public float FrameRounding { get; set; } [JsonProperty("l")] public float FrameBorderSize { get; set; } [JsonProperty("m")] public Vector2 ItemSpacing { get; set; } [JsonProperty("n")] public Vector2 ItemInnerSpacing { get; set; } [JsonProperty("o")] public Vector2 CellPadding { get; set; } [JsonProperty("p")] public Vector2 TouchExtraPadding { get; set; } [JsonProperty("q")] public float IndentSpacing { get; set; } [JsonProperty("r")] public float ScrollbarSize { get; set; } [JsonProperty("s")] public float ScrollbarRounding { get; set; } [JsonProperty("t")] public float GrabMinSize { get; set; } [JsonProperty("u")] public float GrabRounding { get; set; } [JsonProperty("v")] public float LogSliderDeadzone { get; set; } [JsonProperty("w")] public float TabRounding { get; set; } [JsonProperty("x")] public float TabBorderSize { get; set; } [JsonProperty("y")] public Vector2 ButtonTextAlign { get; set; } [JsonProperty("z")] public Vector2 SelectableTextAlign { get; set; } [JsonProperty("aa")] public Vector2 DisplaySafeAreaPadding { get; set; } #pragma warning restore SA1600 /// <summary> /// Gets or sets a dictionary mapping ImGui color names to colors. /// </summary> [JsonProperty("col")] public Dictionary<string, Vector4> Colors { get; set; } /// <summary> /// Get a <see cref="StyleModel"/> instance via ImGui. /// </summary> /// <returns>The newly created <see cref="StyleModel"/> instance.</returns> public static StyleModelV1 Get() { var model = new StyleModelV1(); var style = ImGui.GetStyle(); model.Alpha = style.Alpha; model.WindowPadding = style.WindowPadding; model.WindowRounding = style.WindowRounding; model.WindowBorderSize = style.WindowBorderSize; model.WindowTitleAlign = style.WindowTitleAlign; model.WindowMenuButtonPosition = style.WindowMenuButtonPosition; model.ChildRounding = style.ChildRounding; model.ChildBorderSize = style.ChildBorderSize; model.PopupRounding = style.PopupRounding; model.PopupBorderSize = style.PopupBorderSize; model.FramePadding = style.FramePadding; model.FrameRounding = style.FrameRounding; model.FrameBorderSize = style.FrameBorderSize; model.ItemSpacing = style.ItemSpacing; model.ItemInnerSpacing = style.ItemInnerSpacing; model.CellPadding = style.CellPadding; model.TouchExtraPadding = style.TouchExtraPadding; model.IndentSpacing = style.IndentSpacing; model.ScrollbarSize = style.ScrollbarSize; model.ScrollbarRounding = style.ScrollbarRounding; model.GrabMinSize = style.GrabMinSize; model.GrabRounding = style.GrabRounding; model.LogSliderDeadzone = style.LogSliderDeadzone; model.TabRounding = style.TabRounding; model.TabBorderSize = style.TabBorderSize; model.ButtonTextAlign = style.ButtonTextAlign; model.SelectableTextAlign = style.SelectableTextAlign; model.DisplaySafeAreaPadding = style.DisplaySafeAreaPadding; model.Colors = new Dictionary<string, Vector4>(); foreach (var imGuiCol in Enum.GetValues<ImGuiCol>()) { if (imGuiCol == ImGuiCol.COUNT) { continue; } model.Colors[imGuiCol.ToString()] = style.Colors[(int)imGuiCol]; } return model; } /// <summary> /// Apply this StyleModel via ImGui. /// </summary> public override void Apply() { var style = ImGui.GetStyle(); style.Alpha = this.Alpha; style.WindowPadding = this.WindowPadding; style.WindowRounding = this.WindowRounding; style.WindowBorderSize = this.WindowBorderSize; style.WindowTitleAlign = this.WindowTitleAlign; style.WindowMenuButtonPosition = this.WindowMenuButtonPosition; style.ChildRounding = this.ChildRounding; style.ChildBorderSize = this.ChildBorderSize; style.PopupRounding = this.PopupRounding; style.PopupBorderSize = this.PopupBorderSize; style.FramePadding = this.FramePadding; style.FrameRounding = this.FrameRounding; style.FrameBorderSize = this.FrameBorderSize; style.ItemSpacing = this.ItemSpacing; style.ItemInnerSpacing = this.ItemInnerSpacing; style.CellPadding = this.CellPadding; style.TouchExtraPadding = this.TouchExtraPadding; style.IndentSpacing = this.IndentSpacing; style.ScrollbarSize = this.ScrollbarSize; style.ScrollbarRounding = this.ScrollbarRounding; style.GrabMinSize = this.GrabMinSize; style.GrabRounding = this.GrabRounding; style.LogSliderDeadzone = this.LogSliderDeadzone; style.TabRounding = this.TabRounding; style.TabBorderSize = this.TabBorderSize; style.ButtonTextAlign = this.ButtonTextAlign; style.SelectableTextAlign = this.SelectableTextAlign; style.DisplaySafeAreaPadding = this.DisplaySafeAreaPadding; foreach (var imGuiCol in Enum.GetValues<ImGuiCol>()) { if (imGuiCol == ImGuiCol.COUNT) { continue; } style.Colors[(int)imGuiCol] = this.Colors[imGuiCol.ToString()]; } } /// <inheritdoc/> public override void Push() { throw new NotImplementedException(); } /// <inheritdoc/> public override void Pop() { throw new NotImplementedException(); } }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using SGP.Domain.Entities; using SGP.Domain.Repositories; using SGP.Domain.ValueObjects; using SGP.Infrastructure.Context; using SGP.Infrastructure.Repositories.Common; namespace SGP.Infrastructure.Repositories { public class UsuarioRepository : EfRepository<Usuario>, IUsuarioRepository { public UsuarioRepository(SgpContext context) : base(context) { } public override async Task<Usuario> GetByIdAsync(Guid id) => await DbSet .Include(u => u.Tokens.OrderByDescending(t => t.ExpiraEm)) .FirstOrDefaultAsync(u => u.Id == id); public async Task<Usuario> ObterPorEmailAsync(Email email) => await DbSet .Include(u => u.Tokens.OrderByDescending(t => t.ExpiraEm)) .FirstOrDefaultAsync(u => u.Email.Address == email.Address); public async Task<Usuario> ObterPorTokenAtualizacaoAsync(string tokenAtualizacao) => await DbSet .Include(u => u.Tokens.Where(t => t.Atualizacao == tokenAtualizacao)) .FirstOrDefaultAsync(u => u.Tokens.Any(t => t.Atualizacao == tokenAtualizacao)); public async Task<bool> VerificarSeEmailExisteAsync(Email email) => await DbSet.AsNoTracking().AnyAsync(u => u.Email.Address == email.Address); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class NumberSpawner : MonoBehaviour { //public TextMesh textNumber; public int minNumber = 1; public int maxNumber = 5; //public Color ringColor = Color.red; public static NumberSpawner Instance; //public SpriteRenderer[] ringSprites; public int CurrentNumber { get; private set; } // Start is called before the first frame update void Start() { if (Instance != null) { Destroy(gameObject); } else { Instance = this; } //StartCoroutine(SetRandomNumber(.5f)); } public IEnumerator SetRandomNumber(float delay) { //textNumber.text = ""; //foreach (var ring in ringSprites) // ring.color = Color.white; yield return new WaitForSeconds(delay); GenerateNewNumber(); } public int GenerateNewNumber() { CurrentNumber = Random.Range(minNumber, maxNumber); Debug.Log("currentNumber" + CurrentNumber); //textNumber.text = CurrentNumber.ToString(); // visual //foreach (var ring in ringSprites) // ring.color = Color.white; //ringSprites[CurrentNumber - 1].color = ringColor; return CurrentNumber; } }