content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Immeuble")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Immeuble")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d25fca98-b8fb-4031-b0b7-2568971f0a24")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.540541
84
0.743701
[ "Unlicense" ]
MWFK/Bungalow_Reservation_Management
Immeuble/Properties/AssemblyInfo.cs
1,392
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Resources; using System.Runtime.InteropServices; using System.Windows.Forms; using MUNIA.Controllers; using SharpLib.Hid; using SharpLib.Win32; namespace MuniaInput { public partial class MainForm : Form { MuniaController _activeController; public delegate void OnHidEventDelegate(object aSender, Event aHidEvent); public MainForm() { InitializeComponent(); comboBox1.Items.AddRange(MuniaController.ListDevices().ToArray()); } private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e) { Register(comboBox1.SelectedItem as MuniaController); } private void Register(MuniaController c) { _activeController = c; c.Activate(); c.StateUpdated += ControllerStateUpdated; } private void ControllerStateUpdated(object sender, EventArgs args) { if (InvokeRequired) Invoke((Action<object, EventArgs>)ControllerStateUpdated, sender, args); else { textBox1.AppendText("Buttons: "); textBox1.AppendText(string.Join("", _activeController.GetState().Buttons.Select(x => x ? "Y" : "N"))); textBox1.AppendText("\r\nAxes:"); textBox1.AppendText(string.Join(" ", _activeController.GetState().Axes)); textBox1.AppendText("\r\n"); } } } }
32.765957
118
0.63961
[ "MIT" ]
mathgeek008/MUNIA-splits
MUNIA-win/MuniaInput/MainForm.cs
1,542
C#
using UnityEngine.Rendering; namespace UnityEditor.Rendering { class ShaderGeneratorMenu { [MenuItem("Edit/Render Pipeline/Generate Shader Includes", priority = CoreUtils.editMenuPriority1)] static void GenerateShaderIncludes() { CSharpToHLSL.GenerateAll(); AssetDatabase.Refresh(); } } }
24.8
108
0.63172
[ "MIT" ]
AlePPisa/GameJamPractice1
Cellular/Library/PackageCache/com.unity.render-pipelines.core@8.2.0/Editor/ShaderGenerator/ShaderGeneratorMenu.cs
372
C#
using System.Collections.Generic; using Content.Server.Cuffs.Components; using Content.Server.Hands.Components; using Content.Shared.Hands.Components; using Content.Shared.Inventory; using Content.Shared.Inventory.Events; using Content.Shared.Strip.Components; using Content.Shared.Verbs; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; namespace Content.Server.Strip { public sealed class StrippableSystem : EntitySystem { [Dependency] private readonly InventorySystem _inventorySystem = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<StrippableComponent, GetVerbsEvent<Verb>>(AddStripVerb); SubscribeLocalEvent<StrippableComponent, DidEquipEvent>(OnDidEquip); SubscribeLocalEvent<StrippableComponent, DidUnequipEvent>(OnDidUnequip); SubscribeLocalEvent<StrippableComponent, ComponentInit>(OnCompInit); } private void OnCompInit(EntityUid uid, StrippableComponent component, ComponentInit args) { SendUpdate(uid, component); } private void OnDidUnequip(EntityUid uid, StrippableComponent component, DidUnequipEvent args) { SendUpdate(uid, component); } private void OnDidEquip(EntityUid uid, StrippableComponent component, DidEquipEvent args) { SendUpdate(uid, component); } public void SendUpdate(EntityUid uid, StrippableComponent? strippableComponent = null) { if (!Resolve(uid, ref strippableComponent, false) || strippableComponent.UserInterface == null) { return; } var cuffs = new Dictionary<EntityUid, string>(); var inventory = new Dictionary<(string ID, string Name), string>(); var hands = new Dictionary<string, string>(); if (TryComp(uid, out CuffableComponent? cuffed)) { foreach (var entity in cuffed.StoredEntities) { var name = Name(entity); cuffs.Add(entity, name); } } if (_inventorySystem.TryGetSlots(uid, out var slots)) { foreach (var slot in slots) { var name = "None"; if (_inventorySystem.TryGetSlotEntity(uid, slot.Name, out var item)) name = Name(item.Value); inventory[(slot.Name, slot.DisplayName)] = name; } } if (TryComp(uid, out HandsComponent? handsComp)) { foreach (var hand in handsComp.Hands.Values) { if (hand.HeldEntity == null || HasComp<HandVirtualItemComponent>(hand.HeldEntity)) { hands[hand.Name] = "None"; continue; } hands[hand.Name] = Name(hand.HeldEntity.Value); } } strippableComponent.UserInterface.SetState(new StrippingBoundUserInterfaceState(inventory, hands, cuffs)); } private void AddStripVerb(EntityUid uid, StrippableComponent component, GetVerbsEvent<Verb> args) { if (args.Hands == null || !args.CanAccess || !args.CanInteract || args.Target == args.User) return; if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) return; Verb verb = new(); verb.Text = Loc.GetString("strip-verb-get-data-text"); verb.IconTexture = "/Textures/Interface/VerbIcons/outfit.svg.192dpi.png"; verb.Act = () => component.OpenUserInterface(actor.PlayerSession); args.Verbs.Add(verb); } } }
36.009091
118
0.590507
[ "MIT" ]
Alainx277/space-station-14
Content.Server/Strip/StrippableSystem.cs
3,961
C#
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Bugtracker.Domain { public class Audit { [Key] public int Id { get; set; } public string Property { get; set; } public string OldValue { get; set; } public string NewValue { get; set; } public DateTime Date { get; set; } public Ticket Ticket { get; set; } [ForeignKey(nameof(Ticket))] public Guid TicketId { get; set; } } }
20.653846
51
0.614525
[ "MIT" ]
AliEsenli/Bugtracker
Bugtracker/Domain/Audit.cs
539
C#
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace NetFabric.Hyperlinq { public static partial class ValueReadOnlyCollectionExtensions { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Any<TEnumerable, TEnumerator, TSource>(this TEnumerable source) where TEnumerable : IValueReadOnlyCollection<TSource, TEnumerator> where TEnumerator : struct, IEnumerator<TSource> => source.Count is not 0; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Any<TEnumerable, TEnumerator, TSource>(this TEnumerable source, Func<TSource, bool> predicate) where TEnumerable : IValueReadOnlyCollection<TSource, TEnumerator> where TEnumerator : struct, IEnumerator<TSource> => Any<TEnumerable, TEnumerator, TSource, FunctionWrapper<TSource, bool>>(source, new FunctionWrapper<TSource, bool>(predicate)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Any<TEnumerable, TEnumerator, TSource, TPredicate>(this TEnumerable source, TPredicate predicate = default) where TEnumerable : IValueReadOnlyCollection<TSource, TEnumerator> where TEnumerator : struct, IEnumerator<TSource> where TPredicate : struct, IFunction<TSource, bool> => source.Count is not 0 && ValueEnumerableExtensions.Any<TEnumerable, TEnumerator, TSource, TPredicate>(source, predicate); } }
49.612903
141
0.723667
[ "MIT" ]
Ashrafnet/NetFabric.Hyperlinq
NetFabric.Hyperlinq.SourceGenerator.UnitTests/TestData/Source/Any.ValueReadOnlyCollection.cs
1,538
C#
// WARNING // // This file has been generated automatically by Xamarin Studio from the outlets and // actions declared in your storyboard file. // Manual changes to this file will not be maintained. // using Foundation; using System; using System.CodeDom.Compiler; using UIKit; namespace $safeprojectname$ { [Register ("MainViewController")] partial class MainViewController { [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UILabel ClockText { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UITextField DialogNavText { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIButton IncrementButton { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIButton NavigateButton { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIButton SendMessageButton { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIButton ShowDialogButton { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UILabel WelcomeText { get; set; } void ReleaseDesignerOutlets () { if (ClockText != null) { ClockText.Dispose (); ClockText = null; } if (DialogNavText != null) { DialogNavText.Dispose (); DialogNavText = null; } if (IncrementButton != null) { IncrementButton.Dispose (); IncrementButton = null; } if (NavigateButton != null) { NavigateButton.Dispose (); NavigateButton = null; } if (SendMessageButton != null) { SendMessageButton.Dispose (); SendMessageButton = null; } if (ShowDialogButton != null) { ShowDialogButton.Dispose (); ShowDialogButton = null; } if (WelcomeText != null) { WelcomeText.Dispose (); WelcomeText = null; } } } }
22.384615
84
0.654639
[ "MIT" ]
sunthx/mvvmlight
Templates/CSharp/ProjectTemplates/VS2012/Mvvm.iPhone/MainViewController.designer.cs
1,746
C#
using Mirror; namespace SS3D.Engine.Tiles { /** * Handles making requests on behalf of the player to the TileManager * TODO: This isn't particularly ideal. Need more discussion over alternatives, particularly * networked interactions. * Especially given the power this gives the client to call arbitrary code. */ public class PlayerTileManagerClient : NetworkBehaviour { public void Awake() { tileManager = FindObjectOfType<TileManager>(); } // Note: If getting rid of this class, this code should probably somehow be moved into // the NetworkManager's SpawnPlayer public override void OnStartLocalPlayer() { if(!isServer) CmdRequestServerSendTilesToClient(); } public void CreateTile(TileObject tile, TileDefinition definition) { var pos = tileManager.GetIndexAt(tile.transform.position); CmdCreateTile(pos.x, pos.y, definition); } public void UpdateTile(TileObject tile, TileDefinition definition) { var pos = tileManager.GetIndexAt(tile.transform.position); CmdUpdateTile(pos.x, pos.y, definition); } public void DestroyTile(TileObject tile) { var pos = tileManager.GetIndexAt(tile.transform.position); CmdDestroyTile(pos.x, pos.y); } [Command] private void CmdCreateTile(int x, int y, TileDefinition definition) => tileManager.CreateTile(x, y, definition); [Command] private void CmdUpdateTile(int x, int y, TileDefinition definition) => tileManager.UpdateTile(x, y, definition); [Command] private void CmdDestroyTile(int x, int y) => tileManager.DestroyTile(x, y); // Purposefully stupid name to encourage me to update this. [Command] private void CmdRequestServerSendTilesToClient() { tileManager.SendTilesToClient(connectionToClient); } TileManager tileManager; } }
33.725806
120
0.634146
[ "MIT" ]
Jdeedler/SS3D
Assets/Engine/Tile/PlayerTileManagerClient.cs
2,091
C#
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Security.MicrosoftAccount; using Microsoft.AspNet.Security.OAuth; using MusicStore.Mocks.Common; using System; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace MusicStore.Mocks.MicrosoftAccount { /// <summary> /// Summary description for MicrosoftAccountNotifications /// </summary> internal class MicrosoftAccountNotifications { internal static async Task OnAuthenticated(MicrosoftAccountAuthenticatedContext context) { if (context.Identity != null) { Helpers.ThrowIfConditionFailed(() => context.AccessToken == "ValidAccessToken", "Access token is not valid"); Helpers.ThrowIfConditionFailed(() => context.RefreshToken == "ValidRefreshToken", "Refresh token is not valid"); Helpers.ThrowIfConditionFailed(() => context.FirstName == "AspnetvnextTest", "Email is not valid"); Helpers.ThrowIfConditionFailed(() => context.LastName == "AspnetvnextTest", "Email is not valid"); Helpers.ThrowIfConditionFailed(() => context.Id == "fccf9a24999f4f4f", "Id is not valid"); Helpers.ThrowIfConditionFailed(() => context.Name == "AspnetvnextTest AspnetvnextTest", "Name is not valid"); Helpers.ThrowIfConditionFailed(() => context.ExpiresIn.Value == TimeSpan.FromSeconds(3600), "ExpiresIn is not valid"); Helpers.ThrowIfConditionFailed(() => context.User != null, "User object is not valid"); Helpers.ThrowIfConditionFailed(() => context.Id == context.User.SelectToken("id").ToString(), "User id is not valid"); context.Identity.AddClaim(new Claim("ManageStore", "false")); } await Task.FromResult(0); } internal static async Task OnReturnEndpoint(OAuthReturnEndpointContext context) { if (context.Identity != null && context.SignInAsAuthenticationType == IdentityOptions.ExternalCookieAuthenticationType) { //This way we will know all notifications were fired. var manageStoreClaim = context.Identity.Claims.Where(c => c.Type == "ManageStore" && c.Value == "false").FirstOrDefault(); if (manageStoreClaim != null) { context.Identity.RemoveClaim(manageStoreClaim); context.Identity.AddClaim(new Claim("ManageStore", "Allowed")); } } await Task.FromResult(0); } internal static void OnApplyRedirect(OAuthApplyRedirectContext context) { context.Response.Redirect(context.RedirectUri + "&custom_redirect_uri=custom"); } } }
49.052632
138
0.643777
[ "Apache-2.0" ]
troyhunt/MusicStore
src/MusicStore/Mocks/MicrosoftAccount/MicrosoftAccountNotifications.cs
2,798
C#
using JuanMartin.Kernel.Messaging; using NUnit.Framework; namespace JuanMartin.Kernel.Test.Adapters { [TestFixture] public class AdapterMySqlTests { [Test] public static void MessageRequestReplyTest() { AdapterMySqlMock adapter = new AdapterMySqlMock(); Message request = new Message("Command", System.Data.CommandType.StoredProcedure.ToString()); request.AddData("uspAdapterTest"); request.AddSender("MysqlTest", typeof(AdapterMySqlTests).ToString()); adapter.Send(request); IRecordSet reply = (IRecordSet)adapter.Receive(); Assert.AreNotEqual(reply.Data.Annotations.Count, 0); Assert.AreEqual(reply.Data.GetAnnotationByValue(1).GetAnnotation("id").Value, 1); } } }
31.222222
106
0.633452
[ "MIT" ]
jmbotero/JuanMartin.Kernel.Test
JuanMartin.Kernel.Test/Adapters/AdapterMySqlTests.cs
845
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; using DNTFrameworkCore.Validation; using DNTFrameworkCore.Validation.Interception; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; using Shouldly; namespace DNTFrameworkCore.Tests.Validation { [TestFixture] public class MethodInvocationValidatorTests { [Test] public void Should_Has_Failures_When_Validate_With_Parameter_Implement_IModelValidator() { var invocationValidator = BuildMethodInvocationValidator(options => { }); var failures = invocationValidator.Validate( typeof(TestType).GetMethod(nameof(TestType.PublicMethodValidableObjectParameter)), new object[] {new TestParameter()}).ToList(); failures.ShouldNotBeEmpty(); failures.Any(result => result.MemberName == "TestMember" && result.Message == nameof(IModelValidator)); } [Test] public void Should_Has_Failures_When_Validate_With_Parameter_Implement_IValidatableObject() { var invocationValidator = BuildMethodInvocationValidator(options => { }); var failures = invocationValidator.Validate( typeof(TestType).GetMethod(nameof(TestType.PublicMethodValidableObjectParameter)), new object[] {new TestParameter()}).ToList(); failures.ShouldNotBeEmpty(); failures.Any(result => result.MemberName == "TestMember" && result.Message == nameof(IValidatableObject)); } [Test] public void Should_Has_Failures_When_Method_With_Multiple_Parameters() { var invocationValidator = BuildMethodInvocationValidator(options => { }); var failures = invocationValidator.Validate( typeof(TestType).GetMethod(nameof(TestType.PublicMethodWithMultipleParameter)), new object[] {new TestParameter(), new TestParameter2()}).ToList(); failures.ShouldNotBeEmpty(); failures.Any(result => result.MemberName == nameof(TestParameter.Property1)); failures.Any(result => result.MemberName == nameof(TestParameter2.Property2)); } [Test] public void Should_Has_Failures_When_Method_With_EnableValidation_Is_In_Type_With_SkipValidation() { var invocationValidator = BuildMethodInvocationValidator(options => { }); var failures = invocationValidator.Validate( typeof(SkipValidationTestType).GetMethod(nameof(SkipValidationTestType.PublicMethod)), new[] {new TestParameter()}).ToList(); failures.ShouldNotBeEmpty(); failures.Any(result => result.MemberName == nameof(TestParameter.Property1)); } [Test] public void Should_Not_Has_Failures_When_Method_Has_SkipValidation() { var invocationValidator = BuildMethodInvocationValidator(options => { }); var failures = invocationValidator.Validate( typeof(TestType).GetMethod(nameof(TestType.SkipValidationPublicMethod)), new[] {new TestParameter()}); failures.ShouldBeEmpty(); } [Test] public void Should_Not_Has_Failures_When_Method_Is_Not_Public() { var invocationValidator = BuildMethodInvocationValidator(options => { }); var failures = invocationValidator.Validate( typeof(TestType).GetMethod(nameof(TestType.InternalMethod), BindingFlags.NonPublic | BindingFlags.Instance), new[] {new TestParameter()}); failures.ShouldBeEmpty(); } [Test] public void Should_Not_Has_Failures_When_Method_Parameters_Empty() { var invocationValidator = BuildMethodInvocationValidator(options => { }); var failures = invocationValidator.Validate(typeof(TestType).GetMethod(nameof(TestType.PublicMethod)), Enumerable.Empty<object>().ToArray()); failures.ShouldBeEmpty(); } private static MethodInvocationValidator BuildMethodInvocationValidator(Action<ValidationOptions> options) { var services = new ServiceCollection(); services.AddTransient<IModelValidator<TestParameter>, TestParameterValidator>(); services.AddDNTFrameworkCore() .AddModelValidation(options); var helper = services.BuildServiceProvider().GetRequiredService<MethodInvocationValidator>(); return helper; } public class TestParameter : IValidatableObject { [Required] public string Property1 { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield return new ValidationResult(nameof(IValidatableObject), new[] {"TestMember"}); } } public class TestParameterValidator : ModelValidator<TestParameter> { public override IEnumerable<ValidationFailure> Validate(TestParameter model) { yield return new ValidationFailure("TestMember", nameof(IModelValidator)); } } public class TestParameter2 { [Required] public string Property2 { get; set; } } public class TestType { public void PublicMethod() { } public void PublicMethodWithMultipleParameter(TestParameter parameter1, TestParameter2 parameter2) { } public void PublicMethodValidableObjectParameter(TestParameter parameter) { } public void PublicMethodModelValidatorParameter(TestParameter parameter) { } internal void InternalMethod(TestParameter parameter) { } [SkipValidation] public void SkipValidationPublicMethod(TestParameter parameter) { } } [SkipValidation] public class SkipValidationTestType { [EnableValidation] public void PublicMethod(TestParameter parameter) { } } } }
38.22093
118
0.621083
[ "Apache-2.0" ]
hueifeng/DNTFrameworkCore
test/DNTFrameworkCore.Tests/Validation/MethodInvocationValidatorTests.cs
6,574
C#
using LoggerBot.Storage.State; using LoggerBot.Utilities.Interfaces; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Core.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using LoggerBot.Utilities; namespace LoggerBot.Actions { public class HelloAction : ILoggerBotAction { public static Regex Trigger { get; } = new Regex("hello|" + "hi".CreateGenericRegexPattern(), RegexOptions.IgnoreCase | RegexOptions.Compiled); public async Task Do(LoggerBotContext context) { ////await context.SendActivity("Hello! (From HelloAction)"); var response = ""; foreach (var category in context.LogCategories) { response += category.Name + "\n"; } await context.SendActivity(response); } } }
27.939394
151
0.669197
[ "MIT" ]
jotrick/logger_bot_dotnet
LoggerBot/LoggerBot/Actions/HelloAction.cs
924
C#
using ExternalProject.Net3_1.UnitTestMocks.Sample.NamespaceTests; using Xunit; namespace ExternalProject.Net3_1.UnitTestMocks.xUnit.Sample.NamespaceTests { [SlowFox.InjectMocks(typeof(ReferenceDependencyViaFullType))] public partial class ReferenceDependencyViaFullTypeTests { [Fact] public void Create_ObjectsExist() { ReferenceDependencyViaFullType model = Create(); Assert.NotNull(model); Assert.NotNull(_userReader); } [Fact] public void Mock_CanMock() { _userReader.Setup(p => p.GetName()).Returns("Jamie"); var name = Create().GetName(); Assert.Equal("Jamie", name); _userReader.Verify(p => p.GetName(), Moq.Times.Once); } } }
27.62069
74
0.625468
[ "Apache-2.0" ]
Bungalow64/SlowFox
tests/ExternalProject.Net3_1.UnitTestMocks.xUnit.Sample.Tests/NamespaceTests/ReferenceDependencyViaFullTypeTests.cs
801
C#
namespace ChoETL { #region NameSpaces using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Linq; #endregion /// <summary>Collection implemented with the properties of a binary heap.</summary> public class ChoBinaryHeap : ICollection, ICloneable { #region Member Variables /// <summary>The underlying array for the heap (ArrayList gives us resizing capability).</summary> private ArrayList _list; #endregion #region Construction /// <summary>Initialize the heap with another heap.</summary> /// <param name="heap">The heap on which to perform a shallow-copy.</param> public ChoBinaryHeap(ChoBinaryHeap heap) { // Clone the list (the only state we have) _list = (ArrayList)heap._list.Clone(); } /// <summary>Initialize the heap.</summary> /// <param name="capacity">The initial size of the heap.</param> public ChoBinaryHeap(int capacity) { _list = new ArrayList(capacity); } /// <summary>Initialize the heap.</summary> public ChoBinaryHeap() { _list = new ArrayList(); } #endregion #region Methods /// <summary>Empties the heap.</summary> public virtual void Clear() { _list.Clear(); } /// <summary>Performs a shallow-copy of the heap.</summary> /// <returns>A shallow-copy of the heap.</returns> public virtual ChoBinaryHeap Clone() { return new ChoBinaryHeap(this); } /// <summary>Determines whether an object is in the heap.</summary> /// <param name="value">The object for which we want to search.</param> /// <returns>Whether the object is in the heap.</returns> public virtual bool Contains(object value) { foreach (ChoBinaryHeapEntry entry in _list) { if (entry.Value == value) return true; } return false; } /// <summary>Adds an item to the heap.</summary> /// <param name="key">The key for this entry.</param> /// <param name="value">The value for this entry.</param> public virtual void Insert(IComparable key, object value) { // Create the entry based on the provided key and value ChoBinaryHeapEntry entry = new ChoBinaryHeapEntry(key, value); // Add the item to the list, making sure to keep track of where it was added. int pos = _list.Add(entry); // don't actually need it inserted yet, but want to make sure there's enough space for it // If it was added at the beginning, i.e. this is the only item, we're done. if (pos == 0) return; // Otherwise, perform log(n) operations, walking up the tree, swapping // where necessary based on key values while (pos > 0) { // Get the next position to check int nextPos = pos / 2; // Extract the entry at the next position ChoBinaryHeapEntry toCheck = (ChoBinaryHeapEntry)_list[nextPos]; // Compare that entry to our new one. If our entry has a larger key, move it up. // Otherwise, we're done. if (entry.CompareTo(toCheck) > 0) { _list[pos] = toCheck; pos = nextPos; } else break; } // Make sure we put this entry back in, just in case _list[pos] = entry; } /// <summary>Removes the entry at the top of the heap.</summary> /// <returns>The removed entry.</returns> public virtual object Remove() { // Get the first item and save it for later (this is what will be returned). if (_list.Count == 0) throw new InvalidOperationException("Cannot remove an item from the heap as it is empty."); object toReturn = ((ChoBinaryHeapEntry)_list[0]).Value; // Remove the first item _list.RemoveAt(0); // See if we can stop now (if there's only one item or we're empty, we're done) if (_list.Count > 1) { // Move the last element to the beginning _list.Insert(0, _list[_list.Count - 1]); _list.RemoveAt(_list.Count - 1); // Start reheapify int current = 0, possibleSwap = 0; // Keep going until the tree is a heap while (true) { // Get the positions of the node's children int leftChildPos = 2 * current + 1; int rightChildPos = leftChildPos + 1; // Should we swap with the left child? if (leftChildPos < _list.Count) { // Get the two entries to compare (node and its left child) ChoBinaryHeapEntry entry1 = (ChoBinaryHeapEntry)_list[current]; ChoBinaryHeapEntry entry2 = (ChoBinaryHeapEntry)_list[leftChildPos]; // If the child has a higher key than the parent, set that as a possible swap if (entry2.CompareTo(entry1) > 0) possibleSwap = leftChildPos; } else break; // if can't swap this, we're done // Should we swap with the right child? Note that now we check with the possible swap // position (which might be current and might be left child). if (rightChildPos < _list.Count) { // Get the two entries to compare (node and its left child) ChoBinaryHeapEntry entry1 = (ChoBinaryHeapEntry)_list[possibleSwap]; ChoBinaryHeapEntry entry2 = (ChoBinaryHeapEntry)_list[rightChildPos]; // If the child has a higher key than the parent, set that as a possible swap if (entry2.CompareTo(entry1) > 0) possibleSwap = rightChildPos; } // Now swap current and possible swap if necessary if (current != possibleSwap) { object temp = _list[current]; _list[current] = _list[possibleSwap]; _list[possibleSwap] = temp; } else break; // if nothing to swap, we're done // Update current to the location of the swap current = possibleSwap; } } // Return the item from the heap return toReturn; } public object[] ToArray() { List<object> array = new List<object>(); foreach (ChoBinaryHeapEntry entry in _list) array.Add(entry.Value); return array.ToArray(); } public object[] ToArray(Type type) { List<object> array = new List<object>(); foreach (ChoBinaryHeapEntry entry in _list) array.Add(entry.Value); return array.ToArray(); } #endregion #region Implementation of ICloneable /// <summary>Performs a shallow-copy of the heap.</summary> /// <returns>A shallow-copy of the heap.</returns> object ICloneable.Clone() { return Clone(); } #endregion #region Implementation of ICollection /// <summary>Copies the entire heap to a compatible one-dimensional array, starting at the given index.</summary> /// <param name="array">The array to which the heap should be copied.</param> /// <param name="index">The starting index.</param> public virtual void CopyTo(System.Array array, int index) { _list.CopyTo(array, index); } /// <summary>Gets a value indicating whether this heap is synchronized.</summary> public virtual bool IsSynchronized { get { return false; } } /// <summary>Gets the number of objects stored in the heap.</summary> public virtual int Count { get { return _list.Count; } } /// <summary>Gets an object which can be locked in order to synchronize this class.</summary> public object SyncRoot { get { return this; } } #endregion #region Implementation of IEnumerable /// <summary>Gets an enumerator for the heap.</summary> /// <returns>An enumerator for all elements of the heap.</returns> public virtual IEnumerator GetEnumerator() { return new ChoBinaryHeapEnumerator(_list.GetEnumerator()); } /// <summary>Enumerator for entries in the heap.</summary> public class ChoBinaryHeapEnumerator : IEnumerator { #region Member Variables /// <summary>The enumerator of the array list containing ChoBinaryHeapEntry objects.</summary> private IEnumerator _enumerator; #endregion #region Construction /// <summary>Initialize the enumerator</summary> /// <param name="enumerator">The array list enumerator.</param> internal ChoBinaryHeapEnumerator(IEnumerator enumerator) { _enumerator = enumerator; } #endregion #region Implementation of IEnumerator /// <summary>Resets the enumerator.</summary> public void Reset() { _enumerator.Reset(); } /// <summary>Moves to the next item in the list.</summary> /// <returns>Whether there are more items in the list.</returns> public bool MoveNext() { return _enumerator.MoveNext(); } /// <summary>Gets the current object in the list.</summary> public object Current { get { // Returns the value from the entry if it exists; otherwise, null. ChoBinaryHeapEntry entry = _enumerator.Current as ChoBinaryHeapEntry; return entry != null ? entry.Value : null; } } #endregion } #endregion #region Synchronization /// <summary>Ensures that heap is wrapped in a synchronous wrapper.</summary> /// <param name="heap">The heap to be wrapped.</param> /// <returns>A synchronized wrapper for the heap.</returns> public static ChoBinaryHeap Synchronize(ChoBinaryHeap heap) { // Create a synchronization wrapper around the heap and return it. if (heap is ChoSyncBinaryHeap) return heap; return new ChoSyncBinaryHeap(heap); } #endregion /// <summary>Represents an entry in a binary heap.</summary> private class ChoBinaryHeapEntry : IComparable, ICloneable { #region Member Variables /// <summary>The key for this entry.</summary> private IComparable _key; /// <summary>The value for this entry.</summary> private object _value; #endregion #region Construction /// <summary>Initializes an entry to be used in a binary heap.</summary> /// <param name="key">The key for this entry.</param> /// <param name="value">The value for this entry.</param> public ChoBinaryHeapEntry(IComparable key, object value) { _key = key; _value = value; } #endregion #region Properties /// <summary>Gets the key for this entry.</summary> public IComparable Key { get { return _key; } set { _key = value; } } /// <summary>Gets the value for this entry.</summary> public object Value { get { return _value; } set { _value = value; } } #endregion #region Implementation of IComparable /// <summary>Compares the current instance with another object of the same type.</summary> /// <param name="entry">An object to compare with this instance.</param> /// <returns> /// Less than 0 if this instance is less than the argument, /// 0 if the instances are equal, /// Greater than 0 if this instance is greater than the argument. /// </returns> public int CompareTo(ChoBinaryHeapEntry entry) { // Make sure we have valid arguments. if (entry == null) throw new ArgumentNullException("entry", "Cannot compare to a null value."); // Compare the keys return _key.CompareTo(entry.Key); } /// <summary>Compares the current instance with another object of the same type.</summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns> /// Less than 0 if this instance is less than the argument, /// 0 if the instances are equal, /// Greater than 0 if this instance is greater than the argument. /// </returns> int IComparable.CompareTo(object obj) { // Make sure we have valid arguments, then compare. if (!(obj is ChoBinaryHeapEntry)) throw new ArgumentException("Object is not a ChoBinaryHeapEntry", "obj"); return CompareTo((ChoBinaryHeapEntry)obj); } #endregion #region Implementation of ICloneable /// <summary>Shallow-copy of the object.</summary> /// <returns>A shallow-copy of the object.</returns> public ChoBinaryHeapEntry Clone() { return new ChoBinaryHeapEntry(_key, _value); } /// <summary>Shallow-copy of the object.</summary> /// <returns>A shallow-copy of the object.</returns> object ICloneable.Clone() { return Clone(); } #endregion } /// <summary>A synchronized ChoBinaryHeap.</summary> public class ChoSyncBinaryHeap : ChoBinaryHeap { #region Member Variables /// <summary>The heap to synchronize.</summary> private ChoBinaryHeap _heap; #endregion #region Construction /// <summary>Initialize the synchronized heap.</summary> /// <param name="heap">The heap to synchronize.</param> internal ChoSyncBinaryHeap(ChoBinaryHeap heap) { _heap = heap; } #endregion #region Methods /// <summary>Performs a shallow-copy of the heap.</summary> /// <returns>A shallow-copy of the heap.</returns> public override ChoBinaryHeap Clone() { lock (_heap.SyncRoot) return _heap.Clone(); } /// <summary>Empties the heap.</summary> public override void Clear() { lock (_heap.SyncRoot) _heap.Clear(); } /// <summary>Determines whether an object is in the heap.</summary> /// <param name="value">The object for which we want to search.</param> /// <returns>Whether the object is in the heap.</returns> public override bool Contains(object value) { lock (_heap.SyncRoot) return _heap.Contains(value); } /// <summary>Adds an item to the heap.</summary> /// <param name="key">The key for this entry.</param> /// <param name="value">The value for this entry.</param> public override void Insert(IComparable key, object value) { lock (_heap.SyncRoot) _heap.Insert(key, value); } /// <summary>Removes the entry at the top of the heap.</summary> /// <returns>The removed entry.</returns> public override object Remove() { lock (_heap.SyncRoot) return _heap.Remove(); } /// <summary>Copies the entire heap to a compatible one-dimensional array, starting at the given index.</summary> /// <param name="array">The array to which the heap should be copied.</param> /// <param name="index">The starting index.</param> public override void CopyTo(System.Array array, int index) { lock (_heap.SyncRoot) _heap.CopyTo(array, index); } /// <summary>Gets a value indicating whether this heap is synchronized.</summary> public override bool IsSynchronized { get { return true; } } /// <summary>Gets the number of objects stored in the heap.</summary> public override int Count { get { lock (_heap.SyncRoot) return _heap.Count; } } /// <summary>Gets an enumerator for the heap.</summary> /// <returns>An enumerator for all elements of the heap.</returns> public override IEnumerator GetEnumerator() { lock (_heap.SyncRoot) return _heap.GetEnumerator(); } #endregion } } }
41.170561
129
0.554168
[ "MIT" ]
Cinchoo/ChoETL
src/ChoETL/Common/ChoBinaryHeap.cs
17,621
C#
namespace CovidSafe.Entities.Validation { /// <summary> /// <see cref="RequestValidationResult"/> issue type enumeration /// </summary> public enum RequestValidationIssue { InputEmpty, InputInvalid, InputNull } }
20.153846
68
0.622137
[ "MIT" ]
ContactAssistApp/server
CovidSafe/CovidSafe.Entities/Validation/RequestValidationIssue.cs
264
C#
namespace Omemo.Classes.Keys { public class ECPrivKeyModel: ECKeyModel { //--------------------------------------------------------Attributes:-----------------------------------------------------------------\\ #region --Attributes-- #endregion //--------------------------------------------------------Constructor:----------------------------------------------------------------\\ #region --Constructors-- public ECPrivKeyModel() { } public ECPrivKeyModel(byte[] pubKey) : base(pubKey) { } #endregion //--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\ #region --Set-, Get- Methods-- #endregion //--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\ #region --Misc Methods (Public)-- /// <summary> /// Creates a copy of the object, not including <see cref="id"/>. /// </summary> public new ECPrivKeyModel Clone() { return new ECPrivKeyModel(key); } #endregion #region --Misc Methods (Private)-- #endregion #region --Misc Methods (Protected)-- #endregion //--------------------------------------------------------Events:---------------------------------------------------------------------\\ #region --Events-- #endregion } }
30.96
144
0.312661
[ "MPL-2.0" ]
LibreHacker/UWPX-Client
Omemo/Classes/Keys/ECPrivKeyModel.cs
1,550
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using EA; using System.Windows.Forms; namespace EA_Neo4j_SafetyAnalysis_AddIn { internal class SocketConnection { private TcpClient clientSocket; private NetworkStream ns; private bool received = false; private string currentneo4jpath; private Thread runningSocketConnection = new Thread(t => { }); private SetQueue nextNeo4jUpdate = new SetQueue(); private static readonly HashSet<string> fmstereotypeset = new HashSet<string>() { "FT", "FTInstance", "CFT", "CFTInstance", "IESELogicalComponent", "IESELogicalComponentInstance", "IESELogicalInport", "IESELogicalInportInstance", "IESELogicalOutport", "IESELogicalOutportInstance", "FTAND", "FTOR", "FTM/N", "FTXOR", "FTBasicEvent", "FTNOT", "InputFailureMode", "OutputFailureMode" }; private static readonly HashSet<string> fmtaggedvaluestereotypes = new HashSet<string>() { "FTM/N", "FTBasicEvent", "InputFailureMode" }; private static readonly HashSet<string> fmconnectorstereotypeset = new HashSet<string>() { "ComponentFailureModelTrace", "FailurePropagation", "PortFailureModeTrace", "Logical Information Flow" }; private static readonly string mainSeparator = ",M,"; private static readonly string singleSeparator = ",S,"; private static readonly string partSeparator = ",P,"; private static readonly string tgSeparator = ",T,"; private static readonly int maxStringLength = 4096; private readonly object masterLock = new object(); internal SocketConnection(bool fullupdate) { currentneo4jpath = Main.settings.Neo4jPath; new Thread( t => { while (runningSocketConnection.IsAlive) { Thread.Sleep(10); } lock (masterLock) { runningSocketConnection = new Thread( rt => { startConnection(fullupdate); }); runningSocketConnection.Start(); } }).Start(); } private void startJava(IPAddress ip, int port) { string javapath = Utility.getJavaInstallationPath(); if (javapath != null) { Process cmd = new Process(); cmd.StartInfo.FileName = "cmd.exe"; cmd.StartInfo.RedirectStandardInput = true; cmd.StartInfo.RedirectStandardOutput = true; cmd.StartInfo.CreateNoWindow = true; cmd.StartInfo.UseShellExecute = false; cmd.Start(); cmd.StandardInput.WriteLine("cd " + javapath + @"\bin\"); Utility.Logger(@"java -jar " + @"""" + Utility.Location + "SocketNeo4jPrototype.jar" + @"""" + " " + ip.ToString() + " " + port.ToString() + " " + @"""" + Utility.Location.Replace(@"\", "/") + @""""); cmd.StandardInput.WriteLine(@"java -jar " + @"""" + Utility.Location + "SocketNeo4jPrototype.jar" + @"""" + " " + ip.ToString() + " " + port.ToString() + " " + @"""" + Utility.Location.Replace(@"\", "/") + @""""); cmd.StandardInput.Flush(); cmd.StandardInput.Close(); } } private void startConnection(bool fullupdate) { IPHostEntry hostEntry; hostEntry = Dns.GetHostEntry(Dns.GetHostName()); if (hostEntry.AddressList.Length > 0) { var ip = hostEntry.AddressList[0]; int port = Utility.getAvailableTcpPort(); TcpListener server = new TcpListener(ip, port); server.Start(); startJava(ip, port); Stopwatch timer = new Stopwatch(); timer.Start(); while (timer.ElapsedMilliseconds < 10000 && clientSocket == null) { if (server.Pending()) { clientSocket = server.AcceptTcpClient(); ns = clientSocket.GetStream(); } else { Thread.Sleep(10); } } timer.Reset(); if (clientSocket == null) { ErrorWindow error = new ErrorWindow("Error: Connection timed out!", "ConnectionError"); error.ShowDialog(); } else { string msg = startCommand("start neo4j path") + Main.settings.Neo4jPath.Replace(@"\", "/"); sendData(msg); waitForACK(); if (fullupdate) { startFullUpdate(); } } } else { ErrorWindow error = new ErrorWindow("Error: No IP Address found!", "ConnectionError"); error.ShowDialog(); } } internal void setDeveloperMode(bool value) { new Thread( t => { while (runningSocketConnection.IsAlive) { Thread.Sleep(10); } lock (masterLock) { runningSocketConnection = new Thread( rt => { sendData(startCommand("set developer mode") + value.ToString()); waitForACK(); }); runningSocketConnection.Start(); } }).Start(); } internal void changeNeo4jPath() { new Thread( t => { while (runningSocketConnection.IsAlive) { Thread.Sleep(10); } lock (masterLock) { runningSocketConnection = new Thread( rt => { update(); string msg = startCommand("change neo4j path"); sendData(msg); waitForACK(); new Microsoft.VisualBasic.Devices.Computer().FileSystem.CopyDirectory(currentneo4jpath, Main.settings.Neo4jPath); string msg2 = startCommand("start neo4j path") + Main.settings.Neo4jPath.Replace(@"\", "/"); sendData(msg2); waitForACK(); }); runningSocketConnection.Start(); } }).Start(); } private void startReader() { try { if (ns.DataAvailable) { byte[] buff = new byte[128]; ns.Read(buff, 0, 128); String responseString = System.Text.Encoding.UTF8.GetString(buff); if (responseString.Contains("received")) { received = true; } } } catch (IOException e) { ErrorWindow error = new ErrorWindow("Error: Connection Lost (IOException)!", "ConnectionError", e); error.ShowDialog(); } catch (SocketException se) { ErrorWindow error = new ErrorWindow("Error: Connection Lost (SocketException)!", "ConnectionError", se); error.ShowDialog(); } } private void waitForACK() { while (!received) { startReader(); Thread.Sleep(10); } received = false; } private void sendData(string data) { try { byte[] senddata = System.Text.Encoding.UTF8.GetBytes(data); ns.Write(senddata, 0, senddata.Length); } catch (IOException e) { ErrorWindow error = new ErrorWindow("Error: Connection Lost (IOException)!", "ConnectionError", e); error.ShowDialog(); } catch (SocketException se) { ErrorWindow error = new ErrorWindow("Error: Connection Lost (SocketException)!", "ConnectionError", se); error.ShowDialog(); } } internal void closeJava() { new Thread( t => { while (runningSocketConnection.IsAlive) { Thread.Sleep(10); } lock (masterLock) { runningSocketConnection = new Thread( rt => { update(); sendData(startCommand("exit")); }); runningSocketConnection.Start(); } }).Start(); } internal void performFullAnalysis() { new Thread( t => { while (runningSocketConnection.IsAlive) { Thread.Sleep(10); } lock (masterLock) { runningSocketConnection = new Thread( rt => { sendData(startCommand("analyze and store results")); waitForACK(); }); runningSocketConnection.Start(); } }).Start(); } internal void openAnalysisWindow() { new Thread( t => { while (runningSocketConnection.IsAlive) { Thread.Sleep(10); } lock (masterLock) { runningSocketConnection = new Thread( rt => { update(); sendData(startCommand("open analysis window")); waitForACK(); }); runningSocketConnection.Start(); } }).Start(); } internal void outsideUpdate() { new Thread( t => { while (runningSocketConnection.IsAlive) { Thread.Sleep(10); } lock (masterLock) { runningSocketConnection = new Thread( rt => { update(); }); runningSocketConnection.Start(); } }).Start(); } private void update() { if (Main.settings.LastUpdate.Equals("never")) { startFullUpdate(); nextNeo4jUpdate.clear(); } while (!nextNeo4jUpdate.isEmpty()) { string start = startCommand("update"); StringBuilder elem = new StringBuilder(); int number = 0; int nextlength = 0; while ((elem.Length + nextlength + mainSeparator.Length) < (maxStringLength - start.Length - 1) && !nextNeo4jUpdate.isEmpty()) { elem.Append(mainSeparator + nextNeo4jUpdate.dequeue()); if (!nextNeo4jUpdate.isEmpty()) { nextlength = nextNeo4jUpdate.peek().Length; } number++; } string message = start + number + elem.ToString(); if (message.Length < maxStringLength) { sendData(message); waitForACK(); } else { ErrorWindow error = new ErrorWindow("Error: Message is too long!", "UpdateError"); error.ShowDialog(); } } Main.settings.LastUpdate = Utility.getCurrentDateTime(); if (Main.settings.ContinuousAnalysis) { performFullAnalysis(); } if (!Main.settings.ContinuousUpdate) { DialogResult result1 = MessageBox.Show("Update Complete!", "Neo4j Safety Analysis", MessageBoxButtons.OK); } } private void startFullUpdate() { Queue<string> connectorstoadd = new Queue<string>(); Queue<string> elementstoadd = new Queue<string>(); ; Thread prepareUpdate = new Thread( t => { EA.Collection elementlist = Main.repository.GetElementSet("SELECT el.Object_ID FROM t_object AS el WHERE el.Stereotype IN (\"FT\", \"FTInstance\", \"CFT\", \"CFTInstance\", \"IESELogicalComponent\", \"IESELogicalComponentInstance\", \"IESELogicalInport\", \"IESELogicalInportInstance\", \"IESELogicalOutport\", \"IESELogicalOutportInstance\", \"FTAND\", \"FTOR\", \"FTM/N\", \"FTXOR\", \"FTBasicEvent\", \"FTNOT\", \"InputFailureMode\", \"OutputFailureMode\")", 2); var fmelements = elementlist; foreach (EA.Element fmelement in fmelements) { foreach (EA.Connector con in fmelement.Connectors) { if (fmconnectorstereotypeset.Contains(con.Stereotype) && con.ClientID.Equals(fmelement.ElementID)) { connectorstoadd.Enqueue(getConnectorString(con)); } } if (fmelement.ParentID != 0) { connectorstoadd.Enqueue(getChildConnectorString(fmelement)); } if (fmelement.ClassifierID != 0) { connectorstoadd.Enqueue(getInstanceConnectorString(fmelement)); } elementstoadd.Enqueue(getElementString(fmelement)); } }); prepareUpdate.Start(); sendData(startCommand("start full update")); waitForACK(); while (prepareUpdate.IsAlive) { Thread.Sleep(10); } string start = startCommand("add elements"); while (elementstoadd.Count > 0) { StringBuilder elem = new StringBuilder(); int nextlength = 0; while ((elem.Length + nextlength + mainSeparator.Length) < (maxStringLength - start.Length) && elementstoadd.Count > 0) { elem.Append(mainSeparator + elementstoadd.Dequeue()); if (elementstoadd.Count > 0) { nextlength = elementstoadd.Peek().Length; } } string message = start + elem.ToString(); if (message.Length < maxStringLength) { sendData(message); waitForACK(); } else { ErrorWindow error = new ErrorWindow("Error: Message is too long!", "UpdateError"); error.ShowDialog(); } } string startcon = startCommand("add connectors"); while (connectorstoadd.Count > 0) { StringBuilder cons = new StringBuilder(); int nextlength = 0; while ((cons.Length + nextlength + mainSeparator.Length) < (maxStringLength - startcon.Length) && connectorstoadd.Count > 0) { cons.Append(mainSeparator + connectorstoadd.Dequeue()); if (connectorstoadd.Count > 0) { nextlength = connectorstoadd.Peek().Length; } } string message = startcon + cons.ToString(); if (message.Length < maxStringLength) { sendData(message); waitForACK(); } else { ErrorWindow error = new ErrorWindow("Error: Message is too long!", "UpdateError"); error.ShowDialog(); } } sendData(startCommand("end full update")); waitForACK(); Main.settings.LastUpdate = Utility.getCurrentDateTime(); if (Main.settings.ContinuousAnalysis) { performFullAnalysis(); } } internal void addElement(EA.Element element) { if (fmstereotypeset.Contains(element.Stereotype)) { new Thread( t => { while (runningSocketConnection.IsAlive) { Thread.Sleep(10); } lock (masterLock) { runningSocketConnection = new Thread( rt => { nextNeo4jUpdate.enqueue(startSingleCommand("add single element") + getElementString(element)); foreach (EA.Connector con in element.Connectors) { ErrorWindow error = new ErrorWindow("Error: Connectors were added with a new Element!", "EAError"); error.ShowDialog(); if (fmconnectorstereotypeset.Contains(con.Stereotype) && con.ClientID.Equals(element.ElementID)) { nextNeo4jUpdate.enqueue(startSingleCommand("add single connector") + getConnectorString(con)); } } if (element.ParentID != 0) { nextNeo4jUpdate.enqueue(startSingleCommand("add single connector") + getChildConnectorString(element)); } if (element.ClassifierID != 0) { nextNeo4jUpdate.enqueue(startSingleCommand("add single connector") + getInstanceConnectorString(element)); } if (Main.settings.ContinuousUpdate) { update(); } }); runningSocketConnection.Start(); } }).Start(); } } internal void deleteElement(Element element) { if (fmstereotypeset.Contains(element.Stereotype)) { new Thread( t => { while (runningSocketConnection.IsAlive) { Thread.Sleep(10); } lock (masterLock) { runningSocketConnection = new Thread( rt => { nextNeo4jUpdate.enqueue(startSingleCommand("delete single element") + getElementString(element)); if (Main.settings.ContinuousUpdate) { update(); } }); runningSocketConnection.Start(); } }).Start(); } } internal void updateElement(Element element) { if (fmstereotypeset.Contains(element.Stereotype)) { new Thread( t => { while (runningSocketConnection.IsAlive) { Thread.Sleep(10); } lock (masterLock) { runningSocketConnection = new Thread( rt => { nextNeo4jUpdate.enqueue(startSingleCommand("update single element") + getElementString(element)); if (Main.settings.ContinuousUpdate) { update(); } }); runningSocketConnection.Start(); } }).Start(); } } internal void addConnector(Connector connector) { if (fmconnectorstereotypeset.Contains(connector.Stereotype)) { new Thread( t => { while (runningSocketConnection.IsAlive) { Thread.Sleep(10); } lock (masterLock) { runningSocketConnection = new Thread( rt => { nextNeo4jUpdate.enqueue(startSingleCommand("add single connector") + getConnectorString(connector)); if (Main.settings.ContinuousUpdate) { update(); } }); runningSocketConnection.Start(); } }).Start(); } } internal void deleteConnector(Connector connector) { if (fmconnectorstereotypeset.Contains(connector.Stereotype)) { new Thread( t => { while (runningSocketConnection.IsAlive) { Thread.Sleep(10); } lock (masterLock) { runningSocketConnection = new Thread( rt => { nextNeo4jUpdate.enqueue(startSingleCommand("delete single connector") + getConnectorString(connector)); if (Main.settings.ContinuousUpdate) { update(); } }); runningSocketConnection.Start(); } }).Start(); } } internal void updateConnector(Connector connector) { if (fmconnectorstereotypeset.Contains(connector.Stereotype)) { new Thread( t => { while (runningSocketConnection.IsAlive) { Thread.Sleep(10); } lock (masterLock) { runningSocketConnection = new Thread( rt => { nextNeo4jUpdate.enqueue(startSingleCommand("update single connector") + getConnectorString(connector)); if (Main.settings.ContinuousUpdate) { update(); } }); runningSocketConnection.Start(); } }).Start(); } } private string getElementString(EA.Element element) { StringBuilder elementString = new StringBuilder(); elementString.Append(element.ElementID + partSeparator + element.Name + partSeparator + element.Stereotype + partSeparator + element.ClassifierID); if (fmtaggedvaluestereotypes.Contains(element.Stereotype)) { EA.TaggedValue tg = element.TaggedValues.GetByName("cValue"); if (tg == null) { tg = element.TaggedValues.GetByName("m"); if (tg != null) { elementString.Append(partSeparator + "MOONNumber" + tgSeparator + tg.Value); } } else { elementString.Append(partSeparator + "Basic Failure Probability" + tgSeparator + tg.Value); } } return elementString.ToString(); } private string getConnectorString(EA.Connector connector) { return connector.ConnectorID + partSeparator + connector.Stereotype + partSeparator + connector.ClientID + partSeparator + connector.SupplierID; } private string getChildConnectorString(EA.Element element) { return element.ElementID + partSeparator + "Is_Child_Of" + partSeparator + element.ElementID + partSeparator + element.ParentID; } private string getInstanceConnectorString(EA.Element element) { return element.ElementID + partSeparator + "Is_Instance_Of" + partSeparator + element.ElementID + partSeparator + element.ClassifierID; } private string startCommand(string command) { return command + mainSeparator; } private string startSingleCommand(string command) { return command + singleSeparator; } } }
38.90701
489
0.4301
[ "Apache-2.0" ]
FairPlayer4/BachelorThesis
EA Extension and Prototype/Project1/SocketConnection.cs
27,198
C#
using ContinuationToken.Formatting; using ContinuationToken.Reflection; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace ContinuationToken.Providers { internal class TokenBuilder<T> : ITokenBuilder<T>, ITokenOptions<T> where T : class { private readonly List<ISortedProperty<T>> _properties = new(); private Func<ITokenOptions<T>, IQueryContinuationToken<T>> _factory = options => new BookmarkToken<T>(options); public ISortedProperty<T> Properties => _properties.First(); public ParameterExpression Input { get; } = Expression.Parameter(typeof(T), "x"); public ITokenFormatter Formatter { get; private set; } = new Base64TokenFormatter(new JsonTokenFormatter()); public ComparisonProviderFactory ComparisonProviders { get; private set; } = new ComparisonProviderFactory(); private ITokenBuilder<T> Sort<TProp>(Expression<Func<T, TProp>> property, bool descending) { if (property is null) throw new ArgumentNullException(nameof(property)); var prop = new SortedProperty<T, TProp>( Unify(property), ComparisonProviders.GetProvider(typeof(TProp)), descending: descending, first: _properties.Count == 0); _properties.LastOrDefault()?.Append(prop); _properties.Add(prop); return this; } public ITokenBuilder<T> Ascending<TProp>(Expression<Func<T, TProp>> property) => Sort(property, descending: false); public ITokenBuilder<T> Descending<TProp>(Expression<Func<T, TProp>> property) => Sort(property, descending: true); public ITokenBuilder<T> UseFactory(Func<ITokenOptions<T>, IQueryContinuationToken<T>> factory) { _factory = factory ?? throw new ArgumentNullException(nameof(factory)); return this; } public ITokenBuilder<T> UseFormatter(ITokenFormatter formatter) { Formatter = formatter ?? throw new ArgumentNullException(nameof(formatter)); return this; } public ITokenBuilder<T> UseComparer(Type type, IComparisonProvider provider) { ComparisonProviders.Register(type, provider); return this; } public IQueryContinuationToken<T> Build() { if (_properties.Count == 0) throw new InvalidOperationException("One or more sorted properties must be configured for a continuation token."); return _factory(this); } public override string ToString() { return string.Join(", ", _properties); } private Expression<Func<T, TProp>> Unify<TProp>(Expression<Func<T, TProp>> property) { return Expression.Lambda<Func<T, TProp>>( ParameterUnification.Replace(property.Body, property.Parameters.Single(), Input), Input); } } }
36.141176
130
0.633464
[ "MIT" ]
mpetito/continuation-token
src/ContinuationToken/Providers/TokenBuilder.cs
3,074
C#
// ----------------------------------------------------------------------- // <copyright file="IRawEndpoint.cs" company="PlayFab Inc"> // Copyright 2015 PlayFab Inc. // Copyright 2020 G-Research Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // ----------------------------------------------------------------------- using System.Threading; using System.Threading.Tasks; namespace Consul { /// <summary> /// The interface for the Raw API Endpoints /// </summary> public interface IRawEndpoint { Task<QueryResult<dynamic>> Query(string endpoint, QueryOptions q, CancellationToken ct = default(CancellationToken)); Task<WriteResult<dynamic>> Write(string endpoint, object obj, WriteOptions q, CancellationToken ct = default(CancellationToken)); } }
39.970588
137
0.631347
[ "Apache-2.0" ]
BnMcG/consuldotnet
Consul/Interfaces/IRawEndpoint.cs
1,359
C#
//----------------------------------------------------------------------- // <copyright file="AsyncContext.cs" company="Akka.NET Project"> // Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Nito.AsyncEx.Synchronous; namespace Nito.AsyncEx { /// <summary> /// Provides a context for asynchronous operations. This class is threadsafe. /// </summary> /// <remarks> /// <para><see cref="Execute()"/> may only be called once. After <see cref="Execute()"/> returns, the async context should be disposed.</para> /// </remarks> [DebuggerDisplay("Id = {Id}, OperationCount = {_outstandingOperations}")] [DebuggerTypeProxy(typeof(DebugView))] public sealed partial class AsyncContext : IDisposable { /// <summary> /// The queue holding the actions to run. /// </summary> private readonly TaskQueue _queue; /// <summary> /// The <see cref="SynchronizationContext"/> for this <see cref="AsyncContext"/>. /// </summary> private readonly AsyncContextSynchronizationContext _synchronizationContext; /// <summary> /// The <see cref="TaskScheduler"/> for this <see cref="AsyncContext"/>. /// </summary> private readonly AsyncContextTaskScheduler _taskScheduler; /// <summary> /// The <see cref="TaskFactory"/> for this <see cref="AsyncContext"/>. /// </summary> private readonly TaskFactory _taskFactory; /// <summary> /// The number of outstanding operations, including actions in the queue. /// </summary> private int _outstandingOperations; /// <summary> /// Initializes a new instance of the <see cref="AsyncContext"/> class. This is an advanced operation; most people should use one of the static <c>Run</c> methods instead. /// </summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public AsyncContext() { _queue = new TaskQueue(); _synchronizationContext = new AsyncContextSynchronizationContext(this); _taskScheduler = new AsyncContextTaskScheduler(this); _taskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.HideScheduler, TaskContinuationOptions.HideScheduler, _taskScheduler); } /// <summary> /// Gets a semi-unique identifier for this asynchronous context. This is the same identifier as the context's <see cref="TaskScheduler"/>. /// </summary> public int Id => _taskScheduler.Id; /// <summary> /// Increments the outstanding asynchronous operation count. /// </summary> private void OperationStarted() { var newCount = Interlocked.Increment(ref _outstandingOperations); } /// <summary> /// Decrements the outstanding asynchronous operation count. /// </summary> private void OperationCompleted() { var newCount = Interlocked.Decrement(ref _outstandingOperations); if (newCount == 0) _queue.CompleteAdding(); } /// <summary> /// Queues a task for execution by <see cref="Execute"/>. If all tasks have been completed and the outstanding asynchronous operation count is zero, then this method has undefined behavior. /// </summary> /// <param name="task">The task to queue. May not be <c>null</c>.</param> /// <param name="propagateExceptions">A value indicating whether exceptions on this task should be propagated out of the main loop.</param> private void Enqueue(Task task, bool propagateExceptions) { OperationStarted(); task.ContinueWith(_ => OperationCompleted(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, _taskScheduler); _queue.TryAdd(task, propagateExceptions); // If we fail to add to the queue, just drop the Task. This is the same behavior as the TaskScheduler.FromCurrentSynchronizationContext(WinFormsSynchronizationContext). } /// <summary> /// Disposes all resources used by this class. This method should NOT be called while <see cref="Execute"/> is executing. /// </summary> public void Dispose() { _queue.Dispose(); } /// <summary> /// Executes all queued actions. This method returns when all tasks have been completed and the outstanding asynchronous operation count is zero. This method will unwrap and propagate errors from tasks that are supposed to propagate errors. /// </summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public void Execute() { using (new SynchronizationContextSwitcher(_synchronizationContext)) { var tasks = _queue.GetConsumingEnumerable(); foreach (var task in tasks) { _taskScheduler.DoTryExecuteTask(task.Item1); // Propagate exception if necessary. if (task.Item2) task.Item1.WaitAndUnwrapException(); } } } /// <summary> /// Queues a task for execution, and begins executing all tasks in the queue. This method returns when all tasks have been completed and the outstanding asynchronous operation count is zero. This method will unwrap and propagate errors from the task. /// </summary> /// <param name="action">The action to execute. May not be <c>null</c>.</param> public static void Run(Action action) { if (action == null) throw new ArgumentNullException(nameof(action)); using (var context = new AsyncContext()) { var task = context._taskFactory.StartNew(action); context.Execute(); task.WaitAndUnwrapException(); } } /// <summary> /// Queues a task for execution, and begins executing all tasks in the queue. This method returns when all tasks have been completed and the outstanding asynchronous operation count is zero. Returns the result of the task. This method will unwrap and propagate errors from the task. /// </summary> /// <typeparam name="TResult">The result type of the task.</typeparam> /// <param name="action">The action to execute. May not be <c>null</c>.</param> public static TResult Run<TResult>(Func<TResult> action) { if (action == null) throw new ArgumentNullException(nameof(action)); using (var context = new AsyncContext()) { var task = context._taskFactory.StartNew(action); context.Execute(); return task.WaitAndUnwrapException(); } } /// <summary> /// Queues a task for execution, and begins executing all tasks in the queue. This method returns when all tasks have been completed and the outstanding asynchronous operation count is zero. This method will unwrap and propagate errors from the task proxy. /// </summary> /// <param name="action">The action to execute. May not be <c>null</c>.</param> public static void Run(Func<Task> action) { if (action == null) throw new ArgumentNullException(nameof(action)); // ReSharper disable AccessToDisposedClosure using (var context = new AsyncContext()) { context.OperationStarted(); var task = context._taskFactory.StartNew(action).ContinueWith(t => { context.OperationCompleted(); t.WaitAndUnwrapException(); }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, context._taskScheduler); context.Execute(); task.WaitAndUnwrapException(); } // ReSharper restore AccessToDisposedClosure } /// <summary> /// Queues a task for execution, and begins executing all tasks in the queue. This method returns when all tasks have been completed and the outstanding asynchronous operation count is zero. Returns the result of the task proxy. This method will unwrap and propagate errors from the task proxy. /// </summary> /// <typeparam name="TResult">The result type of the task.</typeparam> /// <param name="action">The action to execute. May not be <c>null</c>.</param> public static TResult Run<TResult>(Func<Task<TResult>> action) { if (action == null) throw new ArgumentNullException(nameof(action)); // ReSharper disable AccessToDisposedClosure using (var context = new AsyncContext()) { context.OperationStarted(); var task = context._taskFactory.StartNew(action).ContinueWith(t => { context.OperationCompleted(); return t.WaitAndUnwrapException(); }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, context._taskScheduler); context.Execute(); return task.WaitAndUnwrapException().Result; } // ReSharper restore AccessToDisposedClosure } /// <summary> /// Gets the current <see cref="AsyncContext"/> for this thread, or <c>null</c> if this thread is not currently running in an <see cref="AsyncContext"/>. /// </summary> public static AsyncContext Current { get { var syncContext = SynchronizationContext.Current as AsyncContextSynchronizationContext; if (syncContext == null) { return null; } return syncContext.Context; } } /// <summary> /// Gets the <see cref="SynchronizationContext"/> for this <see cref="AsyncContext"/>. From inside <see cref="Execute"/>, this value is always equal to <see cref="System.Threading.SynchronizationContext.Current"/>. /// </summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public SynchronizationContext SynchronizationContext => _synchronizationContext; /// <summary> /// Gets the <see cref="TaskScheduler"/> for this <see cref="AsyncContext"/>. From inside <see cref="Execute"/>, this value is always equal to <see cref="TaskScheduler.Current"/>. /// </summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public TaskScheduler Scheduler => _taskScheduler; /// <summary> /// Gets the <see cref="TaskFactory"/> for this <see cref="AsyncContext"/>. Note that this factory has the <see cref="TaskCreationOptions.HideScheduler"/> option set. Be careful with async delegates; you may need to call <see cref="M:System.Threading.SynchronizationContext.OperationStarted"/> and <see cref="M:System.Threading.SynchronizationContext.OperationCompleted"/> to prevent early termination of this <see cref="AsyncContext"/>. /// </summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public TaskFactory Factory => _taskFactory; [DebuggerNonUserCode] internal sealed class DebugView { private readonly AsyncContext _context; public DebugView(AsyncContext context) { _context = context; } public TaskScheduler TaskScheduler => _context._taskScheduler; } } }
47.072797
445
0.617207
[ "Apache-2.0" ]
Bogdan-Rotund/akka.net
src/core/Akka.Tests.Shared.Internals/AsyncContext/AsyncContext.cs
12,288
C#
using Microsoft.Maui.Controls.Internals; using Microsoft.Maui.Controls.Xaml; using Microsoft.Maui.Controls; namespace Maui.Controls.Sample.Pages.SwipeViewGalleries { [Preserve(AllMembers = true)] [XamlCompilation(XamlCompilationOptions.Skip)] public partial class SwipeListViewGallery : ContentPage { public SwipeListViewGallery() { InitializeComponent(); BindingContext = new SwipeViewGalleryViewModel(); MessagingCenter.Subscribe<SwipeViewGalleryViewModel>(this, "favourite", sender => { DisplayAlert("SwipeView", "Favourite", "Ok"); }); MessagingCenter.Subscribe<SwipeViewGalleryViewModel>(this, "delete", sender => { DisplayAlert("SwipeView", "Delete", "Ok"); }); } async void OnSwipeListViewItemTapped(object sender, ItemTappedEventArgs args) { await DisplayAlert("OnSwipeListViewItemTapped", "You have tapped a ListView item", "Ok"); } } }
35.24
136
0.763905
[ "MIT" ]
Mu-L/maui
src/Controls/samples/Controls.Sample/Pages/Controls/SwipeViewGalleries/SwipeListViewGallery.xaml.cs
883
C#
using Hevadea.Entities.Components; using Hevadea.Framework; using Hevadea.Framework.Graphic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Hevadea.Entities { public class Flower : Entity { public int Variant { get; set; } = 0; private static Sprite[] _sprites; public Flower() { SortingOffset = -16; Variant = Rise.Rnd.Next(0, 3); if (_sprites == null) { _sprites = new Sprite[3]; for (var i = 0; i < 3; i++) _sprites[i] = new Sprite(Resources.TileEntities, new Point(6, i)); } AddComponent(new ComponentBreakable()); AddComponent(new ComponentFlammable()); } public override void OnDraw(SpriteBatch spriteBatch, GameTime gameTime) { _sprites[Variant].Draw(spriteBatch, new Vector2(X - 8, Y - 8), Color.White); } } }
28.264706
110
0.579605
[ "MIT" ]
maker-dev/hevadea
Game/Entities/Flower.cs
963
C#
using System; using System.IO; using System.Linq; using NFluent; using NLog; using NLog.Config; using NLog.Targets; using NUnit.Framework; namespace evtx.Test { public class TestMain { [Test] public void vss14Sec() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Debug; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var sysLog = @"D:\Temp\KAPE\vss012\Windows\system32\winevt\logs\Microsoft-Windows-DeviceManagement-Enterprise-Diagnostics-Provider%4Operational.evtx"; var total = 0; var total2 = 0; using (var fs = new FileStream(sysLog, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) { //l.Info($"Record #: {eventRecord.RecordNumber}"); if (eventRecord.EventId == 4000) { l.Info( $"Record #: {eventRecord.RecordNumber} {eventRecord.Channel} {eventRecord.Computer} {eventRecord.TimeCreated} {eventRecord.PayloadData1} {eventRecord.PayloadData2}"); } // eventRecord.ConvertPayloadToXml(); total += 1; } foreach (var esEventIdMetric in es.EventIdMetrics.OrderBy(t => t.Key)) { total2 += esEventIdMetric.Value; l.Info($"{esEventIdMetric.Key}: {esEventIdMetric.Value:N0}"); } l.Info($"Total from here: {total:N0}"); l.Info($"Total2 from here: {total2:N0}"); l.Info($"Event log details: {es}"); l.Info($"Event log error count: {es.ErrorRecords.Count:N0}"); Check.That(es.ErrorRecords.Count).IsEqualTo(0); } } [Test] public void vss15Sec() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Debug; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var sysLog = @"D:\Temp\KAPE\vss015\Windows\system32\winevt\logs\Security.evtx"; var total = 0; var total2 = 0; using (var fs = new FileStream(sysLog, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) { //l.Info($"Record #: {eventRecord.RecordNumber}"); if (eventRecord.EventId == 4000) { l.Info( $"Record #: {eventRecord.RecordNumber} {eventRecord.Channel} {eventRecord.Computer} {eventRecord.TimeCreated} {eventRecord.PayloadData1} {eventRecord.PayloadData2}"); } // eventRecord.ConvertPayloadToXml(); total += 1; } foreach (var esEventIdMetric in es.EventIdMetrics.OrderBy(t => t.Key)) { total2 += esEventIdMetric.Value; l.Info($"{esEventIdMetric.Key}: {esEventIdMetric.Value:N0}"); } l.Info($"Total from here: {total:N0}"); l.Info($"Total2 from here: {total2:N0}"); l.Info($"Event log details: {es}"); l.Info($"Event log error count: {es.ErrorRecords.Count:N0}"); Check.That(es.ErrorRecords.Count).IsEqualTo(2); } } [Test] public void MapTest1() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Debug; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); //var sysLog = @"D:\SynologyDrive\EventLogs\HP_Spec\System.evtx"; EventLog.LoadMaps(@"D:\Code\evtx\evtx\Maps"); Check.That(EventLog.EventLogMaps.Count).IsStrictlyGreaterThan(0); } [Test] public void SystemLog() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Debug; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var sysLog = @"D:\SynologyDrive\EventLogs\HP_Spec\System.evtx"; var total = 0; var total2 = 0; using (var fs = new FileStream(sysLog, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) { //l.Info($"Record #: {eventRecord.RecordNumber}"); if (eventRecord.EventId == 4000) { l.Info( $"Record #: {eventRecord.RecordNumber} {eventRecord.Channel} {eventRecord.Computer} {eventRecord.TimeCreated} {eventRecord.PayloadData1} {eventRecord.PayloadData2}"); } // eventRecord.ConvertPayloadToXml(); total += 1; } foreach (var esEventIdMetric in es.EventIdMetrics.OrderBy(t => t.Key)) { total2 += esEventIdMetric.Value; l.Info($"{esEventIdMetric.Key}: {esEventIdMetric.Value:N0}"); } l.Info($"Total from here: {total:N0}"); l.Info($"Total2 from here: {total2:N0}"); l.Info($"Event log details: {es}"); l.Info($"Event log error count: {es.ErrorRecords.Count:N0}"); Check.That(es.ErrorRecords.Count).IsEqualTo(0); } } [Test] public void SecurityLog() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Debug; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var sysLog = @"D:\SynologyDrive\EventLogs\HP_Spec\Security.evtx"; var total = 0; var total2 = 0; using (var fs = new FileStream(sysLog, FileMode.Open, FileAccess.Read)) { EventLog.LoadMaps(@"D:\Code\evtx\evtx\Maps"); var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // l.Info($"Record: {eventRecord}"); { // eventRecord.ConvertPayloadToXml(); } foreach (var esEventIdMetric in es.EventIdMetrics.OrderBy(t => t.Key)) { total2 += esEventIdMetric.Value; l.Info($"{esEventIdMetric.Key}: {esEventIdMetric.Value:N0}"); } l.Info($"Total from here: {total:N0}"); l.Info($"Total2 from here: {total2:N0}"); l.Info($"Event log details: {es}"); l.Info($"Event log error count: {es.ErrorRecords.Count:N0}"); Check.That(es.ErrorRecords.Count).IsEqualTo(0); } l.Info($"Total: {total}"); } [Test] public void DirTestEZW1() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Info; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var files = Directory.GetFiles(@"D:\SynologyDrive\EventLogs\EZW_Home\1").ToList(); foreach (var file in files) { l.Info($"--------------------------{file}--------------------------"); using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // l.Info($"Record: {eventRecord}"); { eventRecord.ConvertPayloadToXml(); } } } var total = 0; l.Info($"Total: {total}"); } [Test] public void DirTestEZW2() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Info; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var files = Directory.GetFiles(@"D:\SynologyDrive\EventLogs\EZW_Home\2").ToList(); foreach (var file in files) { l.Info($"--------------------------{file}--------------------------"); using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // l.Info($"Record: {eventRecord}"); { eventRecord.ConvertPayloadToXml(); } } } var total = 0; l.Info($"Total: {total}"); } [Test] public void DirTestEZW3() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Info; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var files = Directory.GetFiles(@"D:\SynologyDrive\EventLogs\EZW_Home\3").ToList(); foreach (var file in files) { l.Info($"--------------------------{file}--------------------------"); using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // l.Info($"Record: {eventRecord}"); { eventRecord.ConvertPayloadToXml(); } } } var total = 0; l.Info($"Total: {total}"); } [Test] public void DirTestOther1() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Debug; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var files = Directory.GetFiles(@"D:\SynologyDrive\EventLogs\othertests\1").ToList(); foreach (var file in files) { l.Info($"--------------------------{file}--------------------------"); using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // l.Info($"Record: {eventRecord}"); { eventRecord.ConvertPayloadToXml(); } } l.Info(file); } var total = 0; l.Info($"Total: {total}"); } [Test] public void DirTestOther2() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Debug; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var files = Directory.GetFiles(@"D:\SynologyDrive\EventLogs\othertests\2").ToList(); foreach (var file in files) { l.Info($"--------------------------{file}--------------------------"); using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // l.Info($"Record: {eventRecord}"); { eventRecord.ConvertPayloadToXml(); } } l.Info(file); } var total = 0; l.Info($"Total: {total}"); } [Test] public void DirTestOther3() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Debug; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var files = Directory.GetFiles(@"D:\SynologyDrive\EventLogs\othertests\3").ToList(); foreach (var file in files) { l.Info($"--------------------------{file}--------------------------"); using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // l.Info($"Record: {eventRecord}"); { eventRecord.ConvertPayloadToXml(); } } l.Info(file); } var total = 0; l.Info($"Total: {total}"); } [Test] public void DirTestDefConFS1() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Debug; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var files = Directory.GetFiles(@"D:\SynologyDrive\EventLogs\DefConFS\1").ToList(); foreach (var file in files) { l.Info($"--------------------------{file}--------------------------"); using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // l.Info($"Record: {eventRecord}"); { eventRecord.ConvertPayloadToXml(); } } } var total = 0; l.Info($"Total: {total}"); } [Test] public void DirTestDefConFS2() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Debug; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var files = Directory.GetFiles(@"D:\SynologyDrive\EventLogs\DefConFS\2").ToList(); foreach (var file in files) { l.Info($"--------------------------{file}--------------------------"); using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // l.Info($"Record: {eventRecord}"); { eventRecord.ConvertPayloadToXml(); } } } var total = 0; l.Info($"Total: {total}"); } [Test] public void DirTestDefConFS3() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Debug; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var files = Directory.GetFiles(@"D:\SynologyDrive\EventLogs\DefConFS\3").ToList(); foreach (var file in files) { l.Info($"--------------------------{file}--------------------------"); using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // l.Info($"Record: {eventRecord}"); { eventRecord.ConvertPayloadToXml(); } } } var total = 0; l.Info($"Total: {total}"); } [Test] public void DirTestFury1() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Info; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var files = Directory.GetFiles(@"D:\SynologyDrive\EventLogs\Fury\1").ToList(); foreach (var file in files) { l.Info($"--------------------------{file}--------------------------"); using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // l.Info($"Record: {eventRecord}"); { eventRecord.ConvertPayloadToXml(); } } } var total = 0; l.Info($"Total: {total}"); } [Test] public void DirTestFury2() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Info; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var files = Directory.GetFiles(@"D:\SynologyDrive\EventLogs\Fury\2").ToList(); foreach (var file in files) { l.Info($"--------------------------{file}--------------------------"); using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // l.Info($"Record: {eventRecord}"); { eventRecord.ConvertPayloadToXml(); } } } var total = 0; l.Info($"Total: {total}"); } [Test] public void DirTestFury3() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Info; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var files = Directory.GetFiles(@"D:\SynologyDrive\EventLogs\Fury\3").ToList(); foreach (var file in files) { l.Info($"--------------------------{file}--------------------------"); using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // l.Info($"Record: {eventRecord}"); { eventRecord.ConvertPayloadToXml(); } } } var total = 0; l.Info($"Total: {total}"); } [Test] public void DirTestFury4() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Info; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var files = Directory.GetFiles(@"D:\SynologyDrive\EventLogs\Fury\4").ToList(); foreach (var file in files) { l.Info($"--------------------------{file}--------------------------"); using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // l.Info($"Record: {eventRecord}"); { eventRecord.ConvertPayloadToXml(); } } } var total = 0; l.Info($"Total: {total}"); } [Test] public void DirTestToFix() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Debug; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); // var sourceDir = @"D:\SynologyDrive\EventLogs\To Fix\Damaged"; var sourceDir = @"D:\SynologyDrive\EventLogs\To Fix"; var files = Directory.GetFiles(sourceDir, "*.evtx").ToList(); // var files = Directory.GetFiles(@"D:\SynologyDrive\EventLogs\To Fix\Template OK","*.evtx").ToList(); l.Info($"{sourceDir}"); var total = 0; var total2 = 0; foreach (var file in files) { l.Info( $"\r\n\r\n\r\n-------------------------- file {Path.GetFileName(file)}--------------------------"); using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { try { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // try { // l.Info( eventRecord); //l.Info(eventRecord.ConvertPayloadToXml()); //eventRecord.ConvertPayloadToXml(); } // catch (Exception e) // { // l.Error($"Record: {eventRecord} failed to parse: {e.Message} {e.StackTrace}"); // } foreach (var esEventIdMetric in es.EventIdMetrics.OrderBy(t => t.Key)) { total2 += esEventIdMetric.Value; l.Info($"{esEventIdMetric.Key}: {esEventIdMetric.Value:N0}"); } l.Info($"Total from here: {total:N0}"); l.Info($"Total2 from here: {total2:N0}"); l.Info($"Event log details: {es}"); l.Info($"Event log error count: {es.ErrorRecords.Count:N0}"); Check.That(es.ErrorRecords.Count).IsEqualTo(0); } catch (Exception e) { l.Error($"FILE : {file} failed to parse: {e.Message} {e.StackTrace}"); } } } } [Test] public void DirTestRomanoff1() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Info; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var files = Directory.GetFiles(@"D:\SynologyDrive\EventLogs\Romanoff\1").ToList(); foreach (var file in files) { l.Info($"--------------------------{file}--------------------------"); using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // l.Info($"Record: {eventRecord}"); { eventRecord.ConvertPayloadToXml(); } } } var total = 0; l.Info($"Total: {total}"); } [Test] public void DirTestRomanoff2() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Info; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var files = Directory.GetFiles(@"D:\SynologyDrive\EventLogs\Romanoff\2").ToList(); foreach (var file in files) { l.Info($"--------------------------{file}--------------------------"); using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // l.Info($"Record: {eventRecord}"); { eventRecord.ConvertPayloadToXml(); } } } var total = 0; l.Info($"Total: {total}"); } [Test] public void ApplicationLog() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Debug; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var sysLog = @"D:\SynologyDrive\EventLogs\HP_Spec\Application.evtx"; var total = 0; using (var fs = new FileStream(sysLog, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // l.Info($"Record: {eventRecord}"); { eventRecord.ConvertPayloadToXml(); } } l.Info($"Total: {total}"); } [Test] public void sixty8k() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Trace; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var sysLog = @"D:\SynologyDrive\EventLogs\DefConFS\Microsoft-Windows-TerminalServices-RemoteConnectionManager%4Admin.evtx"; var total = 0; using (var fs = new FileStream(sysLog, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // l.Info($"Record: {eventRecord}"); { eventRecord.ConvertPayloadToXml(); } } l.Info($"Total: {total}"); } } }
30.691614
195
0.471781
[ "MIT" ]
denmilu/evtx.parser
evtx.Test/TestMain.cs
34,039
C#
using System.Collections.Generic; #nullable disable namespace Project1.DataAccess.Entities { public partial class Product { public Product() { Carts = new HashSet<Cart>(); OrderProducts = new HashSet<OrderProduct>(); StoreInventories = new HashSet<StoreInventory>(); } public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public string ProductImage { get; set; } public virtual ICollection<Cart> Carts { get; set; } public virtual ICollection<OrderProduct> OrderProducts { get; set; } public virtual ICollection<StoreInventory> StoreInventories { get; set; } } }
28.423077
81
0.619756
[ "MIT" ]
2011-nov02-net/ryan-project1
Project1/Project1.DataAccess/Entities/Product.cs
741
C#
using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Ridics.Authentication.Core.Models; using Ridics.Authentication.Core.Models.Enum; namespace Ridics.Authentication.Core.MessageSenders { public abstract class SmsSenderBase : IMessageSender { public Task SendMessageAsync(UserModel user, string subject, string message) { var phoneNumber = user.UserContacts.Single(x => x.Type == ContactTypeEnumModel.Phone).Value; return SendSmsAsync(phoneNumber, message); } public abstract Task SendSmsAsync(string phoneNumber, string message); public MessageSenderType MessageSenderType => MessageSenderType.SMS; } public class NullSmsSender : SmsSenderBase { private readonly ILogger<NullSmsSender> m_logger; public NullSmsSender(ILogger<NullSmsSender> logger) { m_logger = logger; } public override Task SendSmsAsync(string phoneNumber, string message) { if (m_logger.IsEnabled(LogLevel.Warning)) m_logger.LogWarning($"Can't send SMS to {phoneNumber} because NullSmsSender is configured instead of working one."); return Task.CompletedTask; } } }
32.74359
132
0.689115
[ "BSD-3-Clause" ]
RIDICS/Authentication
Solution/Ridics.Authentication.Core/MessageSenders/SmsSender.cs
1,279
C#
using System; using System.Threading.Tasks; namespace AteraAPI.V3.Interfaces { /// <summary> /// Common functionality for a read-create endpoint. /// </summary> /// <typeparam name="TInterface"></typeparam> public interface IReadCreateApiEndpoint<TInterface> : IReadOnlyApiEndpoint<TInterface> where TInterface : class { /// <summary> /// Creates the item and returns the ID on success. /// </summary> /// <param name="item">The item to create.</param> /// <returns></returns> int Create(TInterface item); /// <summary> /// Creates the item and returns the ID on success. /// </summary> /// <param name="item">The item to create.</param> /// <returns></returns> Task<int> CreateAsync(TInterface item); /// <summary> /// Creates an item using the provided initialization method and returns the newly created item with the ID set on success.. /// </summary> /// <param name="init">The method used to initialize the new item.</param> /// <returns></returns> TInterface Create(Action<TInterface> init); /// <summary> /// Creates an item using the provided initialization method and returns the newly created item with the ID set on success.. /// </summary> /// <param name="init">The method used to initialize the new item.</param> /// <returns></returns> Task<TInterface> CreateAsync(Action<TInterface> init); /// <summary> /// Creates a new item instance that can be added to this collection. /// </summary> /// <returns></returns> TInterface NewItem(); } }
31.895833
126
0.679948
[ "MIT" ]
barkerest/atera_api_v3
AteraAPI.V3/Interfaces/IReadCreateApiEndpoint.cs
1,533
C#
#pragma warning disable CA1303 // 请不要将文本作为本地化参数传递 using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using dotnetCampus.Cli.Core; namespace dotnetCampus.Cli.Parsers { internal abstract class RuntimeCommandLineOptionParser<T> : ICommandLineOptionParser<T>, IRawCommandLineOptionParser<T> { protected RuntimeCommandLineOptionParser(string? verb) { Verb = verb; } public string? Verb { get; } public abstract void SetValue(IReadOnlyList<string> values); public abstract void SetValue(char shortName, bool value); public abstract void SetValue(char shortName, string value); public abstract void SetValue(char shortName, IReadOnlyList<string> values); public abstract void SetValue(string longName, bool value); public abstract void SetValue(string longName, string value); public abstract void SetValue(string longName, IReadOnlyList<string> values); public abstract void SetValue(char shortName, SingleOptimizedStrings? values); public abstract void SetValue(string longName, SingleOptimizedStrings? values); public abstract T Commit(); internal static RuntimeCommandLineOptionParser<T> Create() { var verb = typeof(T).IsDefined(typeof(VerbAttribute)) ? typeof(T).GetCustomAttribute<VerbAttribute>()!.VerbName : null; var properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public) .Where(x => x.IsDefined(typeof(OptionAttribute)) || x.IsDefined(typeof(ValueAttribute))) .ToList(); if (properties.Count == 0) { throw new NotSupportedException($"类型 {typeof(T).FullName} 中没有发现任何可以作为命令行参数的可见属性。"); } // 目前仅支持所有属性可写,或者所有属性不可写。不处理中间态。 // 所以暂时的判定: // 1. 所有的属性都有 public set,视为可变类型,支持; // 2. 所有属性都只有 public get 方法,视为不可变类型,支持; // 3. 其他任何情况都不支持,包括属性中有 private set,或者部分有 public set 部分没有 set 等。 var isImmutable = properties.All(x => !x.CanWrite); var allCanWrite = properties.All(x => x.CanWrite && x.SetMethod!.IsPublic); if (allCanWrite || isImmutable) { return isImmutable ? new ImmutableRuntimeOptionParser<T>(verb, properties) : (RuntimeCommandLineOptionParser<T>)new RuntimeOptionParser<T>(verb, properties); } throw new NotSupportedException(@"运行时命令行解析器仅支持两种类型的命令行参数类型: 1. 全部属性都只有 public get 的(public string Property { get; }); 2. 全部属性都可以 public get set 的(public string Property { get; set; })"); } } }
43.046875
123
0.646824
[ "MIT" ]
dotnet-campus/dotnetCampus.CommandLine
src/dotnetCampus.CommandLine/Parsers/RuntimeCommandLineOptionParser.cs
3,137
C#
using Vintagestory.API.Client; namespace Toggly.Handlers { class MouseToggleHandler { private bool _isMouseActive; private bool _isMouseToggled; private readonly ICoreClientAPI _clientApi; private readonly TogglyConfig _config; public MouseToggleHandler(ICoreClientAPI clientApi, TogglyConfig config) { _clientApi = clientApi; _config = config; } public void Activate() { _clientApi.Event.KeyDown += EventOnKeyDown; _clientApi.Event.MouseDown += EventOnMouseDown; _clientApi.Event.MouseUp += EventOnMouseUp; _clientApi.Input.RegisterHotKey("toggleMouse", "Toggly Toggle Mouse", GlKeys.Tilde); _clientApi.Input.HotKeys["toggleMouse"].Handler += OnToggleMouseHotKey; } private bool OnToggleMouseHotKey(KeyCombination keyCombination) { _isMouseToggled = !_isMouseToggled; return true; } private void EventOnMouseUp(MouseEvent e) { if (_isMouseToggled && IsValidMouseButton(e)) { e.Handled = true; _isMouseActive = true; } } private void EventOnMouseDown(MouseEvent e) { if (_isMouseActive && _config.DeactivateWhenMouseClick && IsValidMouseButton(e)) { StopMouseActivation(); } } private void EventOnKeyDown(KeyEvent e) { if (_config.AbortKeycodes.Contains(e.KeyCode)) { StopMouseActivation(); } } private bool IsValidMouseButton(MouseEvent e) { return _config.ValidMouseButtons.Contains((int)e.Button); } private void StopMouseActivation() { _isMouseToggled = false; _isMouseActive = false; } } }
27.957143
96
0.572816
[ "MIT" ]
p3t3rix/VsToggly
src/Handlers/MouseToggleHandler.cs
1,959
C#
using System.Drawing; using Emgu.CV; using Emgu.CV.CvEnum; using Emgu.CV.Structure; namespace GameBot.Core.Quantizers { public class MorphologyQuantizer : Quantizer { private readonly Mat _kernel; public MorphologyQuantizer(IConfig config) : base(config) { _kernel = CvInvoke.GetStructuringElement(ElementShape.Rectangle, new Size(7, 7), new Point(-1, -1)); } public override Mat Quantize(Mat image) { var dst = base.Quantize(image); CvInvoke.MorphologyEx(dst, dst, MorphOp.Open, _kernel, new Point(-1, -1), 1, BorderType.Constant, new MCvScalar(0)); return dst; } } }
25.592593
128
0.629522
[ "MIT" ]
winkula/gamebot
GameBot.Core/Quantizers/MorphologyQuantizer.cs
693
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Lclb.Cllb.Interfaces { using Microsoft.Rest; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for Accounts. /// </summary> public static partial class AccountsExtensions { /// <summary> /// Get entities from accounts /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static MicrosoftDynamicsCRMaccountCollection Get(this IAccounts operations, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.GetAsync(top, skip, search, filter, count, orderby, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get entities from accounts /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMaccountCollection> GetAsync(this IAccounts operations, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(top, skip, search, filter, count, orderby, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get entities from accounts /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<MicrosoftDynamicsCRMaccountCollection> GetWithHttpMessages(this IAccounts operations, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null) { return operations.GetWithHttpMessagesAsync(top, skip, search, filter, count, orderby, select, expand, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Add new entity to accounts /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// New entity /// </param> /// <param name='prefer'> /// Required in order for the service to return a JSON representation of the /// object. /// </param> public static MicrosoftDynamicsCRMaccount Create(this IAccounts operations, MicrosoftDynamicsCRMaccount body, string prefer = "return=representation") { return operations.CreateAsync(body, prefer).GetAwaiter().GetResult(); } /// <summary> /// Add new entity to accounts /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// New entity /// </param> /// <param name='prefer'> /// Required in order for the service to return a JSON representation of the /// object. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMaccount> CreateAsync(this IAccounts operations, MicrosoftDynamicsCRMaccount body, string prefer = "return=representation", CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(body, prefer, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Add new entity to accounts /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// New entity /// </param> /// <param name='prefer'> /// Required in order for the service to return a JSON representation of the /// object. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<MicrosoftDynamicsCRMaccount> CreateWithHttpMessages(this IAccounts operations, MicrosoftDynamicsCRMaccount body, string prefer = "return=representation", Dictionary<string, List<string>> customHeaders = null) { return operations.CreateWithHttpMessagesAsync(body, prefer, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Get entity from accounts by key /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountid'> /// key: accountid of account /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static MicrosoftDynamicsCRMaccount GetByKey(this IAccounts operations, string accountid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.GetByKeyAsync(accountid, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get entity from accounts by key /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountid'> /// key: accountid of account /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMaccount> GetByKeyAsync(this IAccounts operations, string accountid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetByKeyWithHttpMessagesAsync(accountid, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get entity from accounts by key /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountid'> /// key: accountid of account /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<MicrosoftDynamicsCRMaccount> GetByKeyWithHttpMessages(this IAccounts operations, string accountid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null) { return operations.GetByKeyWithHttpMessagesAsync(accountid, select, expand, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Update entity in accounts /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountid'> /// key: accountid of account /// </param> /// <param name='body'> /// New property values /// </param> public static void Update(this IAccounts operations, string accountid, MicrosoftDynamicsCRMaccount body) { operations.UpdateAsync(accountid, body).GetAwaiter().GetResult(); } /// <summary> /// Update entity in accounts /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountid'> /// key: accountid of account /// </param> /// <param name='body'> /// New property values /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateAsync(this IAccounts operations, string accountid, MicrosoftDynamicsCRMaccount body, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.UpdateWithHttpMessagesAsync(accountid, body, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Update entity in accounts /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountid'> /// key: accountid of account /// </param> /// <param name='body'> /// New property values /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse UpdateWithHttpMessages(this IAccounts operations, string accountid, MicrosoftDynamicsCRMaccount body, Dictionary<string, List<string>> customHeaders = null) { return operations.UpdateWithHttpMessagesAsync(accountid, body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Delete entity from accounts /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountid'> /// key: accountid of account /// </param> /// <param name='ifMatch'> /// ETag /// </param> public static void Delete(this IAccounts operations, string accountid, string ifMatch = default(string)) { operations.DeleteAsync(accountid, ifMatch).GetAwaiter().GetResult(); } /// <summary> /// Delete entity from accounts /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountid'> /// key: accountid of account /// </param> /// <param name='ifMatch'> /// ETag /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IAccounts operations, string accountid, string ifMatch = default(string), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(accountid, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Delete entity from accounts /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountid'> /// key: accountid of account /// </param> /// <param name='ifMatch'> /// ETag /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse DeleteWithHttpMessages(this IAccounts operations, string accountid, string ifMatch = default(string), Dictionary<string, List<string>> customHeaders = null) { return operations.DeleteWithHttpMessagesAsync(accountid, ifMatch, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } } }
45.195652
479
0.536255
[ "Apache-2.0" ]
brianorwhatever/jag-lcrb-carla-public
cllc-interfaces/Dynamics-Autorest/AccountsExtensions.cs
16,632
C#
#region License // Copyright (c) 2019 smart-me AG https://www.smart-me.com/ // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #endregion namespace SmartMeApiClient.Enumerations { public enum MeterSubType { /// <summary> /// Unknown meter sub type /// </summary> MeterSubTypeUnknown = 0, /// <summary> /// A Cold / Cold Water Meter /// </summary> MeterSubTypeCold = 1, /// <summary> /// A Heat / Hot Water Meter /// </summary> MeterSubTypeHeat = 2, /// <summary> /// A E-Charging Station /// </summary> MeterSubTypeChargingStation = 3, /// <summary> /// A Electricity meter /// </summary> MeterSubTypeElectricity = 4, /// <summary> /// A Water meter /// </summary> MeterSubTypeWater = 5, /// <summary> /// A Gas meter /// </summary> MeterSubTypeGas = 6, /// <summary> /// A Electricity / Heat meter /// </summary> MeterSubTypeElectricityHeat = 7, /// <summary> /// A Temperature meter /// </summary> MeterSubTypeTemperature = 8, /// <summary> /// A Virtual battery /// </summary> MeterSubTypeVirtualBattery = 9, } }
30.512821
81
0.617647
[ "MIT" ]
eCarUp/smartme-api-client-library-dotnet
Src/SmartMeApiClient/Enumerations/MeterSubType.cs
2,382
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data.SQLite; using System.Linq; using System.Linq.Expressions; using System.Reflection; using log4net; using Languages.Interfaces; using StockExchangeGame.Database.Extensions; using StockExchangeGame.Database.Models; namespace StockExchangeGame.Database.Generic { // ReSharper disable once UnusedMember.Global public class NamesController : IEntityController<Names> { private readonly SQLiteConnection _connection; private readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ILanguage _currentLanguage; public NamesController(SQLiteConnection connection) { _connection = connection; } public void SetCurrentLanguage(ILanguage language) { _currentLanguage = language; _log.Info(string.Format(_currentLanguage.GetWord("LanguageSet"), "Names", language.Identifier)); } public ILanguage GetCurrentLanguage() { return _currentLanguage; } public int CreateTable() { int result; var sql = GetCreateTableSQL(); _connection.Open(); using (var command = new SQLiteCommand(sql, _connection)) { result = command.ExecuteNonQuery(); } _log.Info(string.Format(_currentLanguage.GetWord("TableCreated"), "Names", result)); _connection.Close(); return result; } public List<Names> Get() { var list = new List<Names>(); var sql = "SELECT * FROM Names"; _connection.Open(); using (var command = new SQLiteCommand(sql, _connection)) { using (var reader = command.ExecuteReader()) { while (reader.Read()) { var names = GetNamesFromReader(reader); list.Add(names); } } } _log.Info(string.Format(_currentLanguage.GetWord("ExecutedGet"), "Names", string.Join("; ", list))); _connection.Close(); return list; } public Names Get(long id) { Names name = null; var sql = "SELECT * FROM Names WHERE Id = @Id"; _connection.Open(); using (var command = new SQLiteCommand(sql, _connection)) { PrepareCommandSelect(command, id); using (var reader = command.ExecuteReader()) { while (reader.Read()) name = GetNamesFromReader(reader); } } _log.Info(string.Format(_currentLanguage.GetWord("ExecutedGetSingle"), "Names", name)); _connection.Close(); return name; } public ObservableCollection<Names> Get<TValue>(Expression<Func<Names, bool>> predicate = null, Expression<Func<Names, TValue>> orderBy = null) { if (predicate == null && orderBy == null) return GetNoPredicateNoOrderBy(); if (predicate != null && orderBy == null) return GetPredicateOnly(predicate); return predicate == null ? GetOrderByOnly(orderBy) : GetPredicateAndOrderBy(predicate, orderBy); } private ObservableCollection<Names> GetNoPredicateNoOrderBy() { var result = Get().ToCollection(); _log.Info(string.Format(_currentLanguage.GetWord("ExecutedGetPredicateOrderBy"), "Names", null, null, string.Join(";", result))); return result; } private ObservableCollection<Names> GetPredicateOnly(Expression<Func<Names, bool>> predicate = null) { // ReSharper disable once AssignNullToNotNullAttribute var result = GetQueryable().Where(predicate).ToCollection(); _log.Info(string.Format(_currentLanguage.GetWord("ExecutedGetPredicateOrderBy"), "Names", predicate, null, string.Join(";", result))); return result; } private ObservableCollection<Names> GetOrderByOnly<TValue>(Expression<Func<Names, TValue>> orderBy = null) { // ReSharper disable once AssignNullToNotNullAttribute var result = GetQueryable().OrderBy(orderBy).ToCollection(); _log.Info(string.Format(_currentLanguage.GetWord("ExecutedGetPredicateOrderBy"), "Names", null, orderBy, string.Join(";", result))); return result; } private ObservableCollection<Names> GetPredicateAndOrderBy<TValue>( Expression<Func<Names, bool>> predicate = null, Expression<Func<Names, TValue>> orderBy = null) { // ReSharper disable AssignNullToNotNullAttribute var result = GetQueryable().Where(predicate).OrderBy(orderBy).ToCollection(); _log.Info(string.Format(_currentLanguage.GetWord("ExecutedGetPredicateOrderBy"), "Names", predicate, orderBy, string.Join(";", result))); return result; } public Names Get(Expression<Func<Names, bool>> predicate) { var result = GetQueryable().Where(predicate).FirstOrDefault(); _log.Info(string.Format(_currentLanguage.GetWord("ExecutedGetSinglePredicate"), "Names", predicate, string.Join(";", result))); return result; } public int Insert(Names entity) { int result; _connection.Open(); using (var command = new SQLiteCommand(_connection)) { PrepareCommandInsert(command, entity); result = command.ExecuteNonQuery(); } _log.Info(string.Format(_currentLanguage.GetWord("ExecutedInsert"), "Names", entity, result)); _connection.Close(); return result; } public int Update(Names entity) { int result; _connection.Open(); using (var command = new SQLiteCommand(_connection)) { PrepareCommandUpdate(command, entity); result = command.ExecuteNonQuery(); } _log.Info(string.Format(_currentLanguage.GetWord("ExecutedUpdate"), "Names", entity, result)); _connection.Close(); return result; } public int Delete(Names entity) { int result; _connection.Open(); using (var command = new SQLiteCommand(_connection)) { PrepareDeleteCommand(command, entity); result = command.ExecuteNonQuery(); } _log.Info(string.Format(_currentLanguage.GetWord("ExecutedDelete"), "Names", entity, result)); _connection.Close(); return result; } public int Count(Expression<Func<Names, bool>> predicate = null) { return predicate == null ? CountNoPredicate() : CountPredicate(predicate); } private int CountNoPredicate() { var count = 0; const string sql = "SELECT COUNT(Id) FROM Names"; _connection.Open(); using (var command = new SQLiteCommand(sql, _connection)) { using (var reader = command.ExecuteReader()) { while (reader != null && reader.Read()) count = Convert.ToInt32(reader[0].ToString()); } } _log.Info(string.Format(_currentLanguage.GetWord("ExecutedCount"), "Names", null, count)); _connection.Close(); return count; } private int CountPredicate(Expression<Func<Names, bool>> predicate = null) { // ReSharper disable once AssignNullToNotNullAttribute var count = GetQueryable().Where(predicate).Count(); _log.Info(string.Format(_currentLanguage.GetWord("ExecutedCount"), "Names", predicate, count)); return count; } private string GetCreateTableSQL() { return "CREATE TABLE IF NOT EXISTS Names (" + "Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE," + "Name TEXT NOT NULL," + "CreatedAt TEXT NOT NULL," + "Deleted BOOLEAN NOT NULL," + "ModifiedAt TEXT NOT NULL)"; } private void PrepareCommandSelect(SQLiteCommand command, long id) { command.Prepare(); command.Parameters.AddWithValue("@Id", id); } private Names GetNamesFromReader(SQLiteDataReader reader) { return new Names { Id = Convert.ToInt64(reader["Id"].ToString()), Name = reader["Name"].ToString(), CreatedAt = Convert.ToDateTime(reader["CreatedAt"].ToString()), Deleted = Convert.ToBoolean(reader["Deleted"].ToString()), ModifiedAt = Convert.ToDateTime(reader["ModifiedAt"].ToString()) }; } private void PrepareCommandInsert(SQLiteCommand command, Names names) { command.CommandText = "INSERT INTO Names (Id, Name, CreatedAt, Deleted, ModifiedAt) " + "VALUES (@Id, @Name, @CreatedAt, @Deleted, @ModifiedAt)"; command.Prepare(); AddParametersUpdateInsert(command, names); } private void AddParametersUpdateInsert(SQLiteCommand command, Names names) { command.Parameters.AddWithValue("@Id", names.Id); command.Parameters.AddWithValue("@Name", names.Name); command.Parameters.AddWithValue("@CreatedAt", names.CreatedAt.ToString("yyyy-MM-dd HH:mm:ss.fff")); command.Parameters.AddWithValue("@Deleted", names.Deleted); command.Parameters.AddWithValue("@ModifiedAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); } private void PrepareCommandUpdate(SQLiteCommand command, Names names) { command.CommandText = "UPDATE Names SET Name = @Name, CreatedAt = @CreatedAt, Deleted = @Deleted, " + "ModifiedAt = @ModifiedAt WHERE Id = @Id"; command.Prepare(); AddParametersUpdateInsert(command, names); } private void PrepareDeleteCommand(SQLiteCommand command, Names names) { command.CommandText = "UPDATE Names SET Deleted = true, ModifiedAt = @ModifiedAt WHERE Id = @Id"; command.Prepare(); command.Parameters.AddWithValue("@Id", names.Id); command.Parameters.AddWithValue("@ModifiedAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); } private IQueryable<Names> GetQueryable() { return Get().AsQueryable(); } public void Truncate() { const string sql = "DELETE FROM Names"; _connection.Open(); using (var command = new SQLiteCommand(sql, _connection)) { command.ExecuteNonQuery(); } _log.Info(string.Format(_currentLanguage.GetWord("ExecutedTruncate"), "Names")); _connection.Close(); } } }
38.706667
118
0.569239
[ "MIT" ]
SeppPenner/StockExchangeGame
src/StockExchangeGame/Database/Generic/NamesController.cs
11,614
C#
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System.Collections.Generic; using System.Management.Automation.Language; namespace Microsoft.PowerShell.EditorServices { /// <summary> /// The vistor used to find the dont sourced files in an AST /// </summary> internal class FindDotSourcedVisitor : AstVisitor { /// <summary> /// A hash set of the dot sourced files (because we don't want duplicates) /// </summary> public HashSet<string> DotSourcedFiles { get; private set; } public FindDotSourcedVisitor() { this.DotSourcedFiles = new HashSet<string>(); } /// <summary> /// Checks to see if the command invocation is a dot /// in order to find a dot sourced file /// </summary> /// <param name="commandAst">A CommandAst object in the script's AST</param> /// <returns>A decision to stop searching if the right commandAst was found, /// or a decision to continue if it wasn't found</returns> public override AstVisitAction VisitCommand(CommandAst commandAst) { if (commandAst.InvocationOperator.Equals(TokenKind.Dot) && commandAst.CommandElements[0] is StringConstantExpressionAst) { // Strip any quote characters off of the string string fileName = commandAst.CommandElements[0].Extent.Text.Trim('\'', '"'); DotSourcedFiles.Add(fileName); } return base.VisitCommand(commandAst); } } }
35.914894
101
0.626777
[ "MIT" ]
ant-druha/PowerShellEditorServices
src/PowerShellEditorServices/Language/FindDotSourcedVisitor.cs
1,690
C#
using System; using System.Globalization; using System.Linq; using System.Reflection; namespace CompetitionWebsite.WebApi.Areas.HelpPage.ModelDescriptions { internal static class ModelNameHelper { // Modify this to provide custom model name mapping. public static string GetModelName(Type type) { ModelNameAttribute modelNameAttribute = type.GetCustomAttribute<ModelNameAttribute>(); if (modelNameAttribute != null && !String.IsNullOrEmpty(modelNameAttribute.Name)) { return modelNameAttribute.Name; } string modelName = type.Name; if (type.IsGenericType) { // Format the generic type name to something like: GenericOfAgurment1AndArgument2 Type genericType = type.GetGenericTypeDefinition(); Type[] genericArguments = type.GetGenericArguments(); string genericTypeName = genericType.Name; // Trim the generic parameter counts from the name genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); string[] argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray(); modelName = String.Format(CultureInfo.InvariantCulture, "{0}Of{1}", genericTypeName, String.Join("And", argumentTypeNames)); } return modelName; } } }
40.388889
140
0.638927
[ "MIT" ]
TimPiers/Competition-Website
CompetitionWebsite/CompetitionWebsite.WebApi/Areas/HelpPage/ModelDescriptions/ModelNameHelper.cs
1,454
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace WpfUtilV1.Mvvm { [DataContract] public class BindableBase : INotifyPropertyChanged, IDisposable { private BindableBase Source { get; set; } public BindableBase() : this(null) { } public BindableBase(BindableBase source) { Source = source; if (Source != null) { Source.PropertyChanged += OnPropertyChanged; } } /// <summary> /// プロパティの変更を通知するためのマルチキャスト イベント。 /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// プロパティが既に目的の値と一致しているかどうかを確認します。必要な場合のみ、 /// プロパティを設定し、リスナーに通知します。 /// </summary> /// <typeparam name="T">プロパティの型。</typeparam> /// <param name="storage">get アクセス操作子と set アクセス操作子両方を使用したプロパティへの参照。</param> /// <param name="value">プロパティに必要な値。</param> /// <param name="propertyName">リスナーに通知するために使用するプロパティの名前。 /// この値は省略可能で、 /// CallerMemberName をサポートするコンパイラから呼び出す場合に自動的に指定できます。</param> /// <returns>値が変更された場合は true、既存の値が目的の値に一致した場合は /// false です。</returns> protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null) { if (object.Equals(storage, value)) return false; storage = value; this.OnPropertyChanged(propertyName); return true; } /// <summary> /// プロパティ値が変更されたことをリスナーに通知します。 /// </summary> /// <param name="propertyName">リスナーに通知するために使用するプロパティの名前。 /// この値は省略可能で、 /// <see cref="CallerMemberNameAttribute"/> をサポートするコンパイラから呼び出す場合に自動的に指定できます。</param> protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { var eventHandler = this.PropertyChanged; if (eventHandler != null) { eventHandler(this, new PropertyChangedEventArgs(propertyName)); } } protected virtual void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { } #region IDisposable Support private bool disposedValue = false; // 重複する呼び出しを検出するには private static List<string> DisposedArrays = new List<string>(); protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { //var disposables = this.GetType().GetProperties() // .Where(p => Attribute.GetCustomAttribute(p, typeof(ExclusionAttribute)) == null) // .Select(p => p.GetValue(this, null)) // .Where(o => o != null && !this.Equals(o)) // .OfType<BindableBase>() // .Where(b => !DisposedArrays.Contains(b.Guid)) // .ToArray(); //DisposedArrays.Add(this.Guid); // Disposeするプロパティを取得 var disposables = this.GetType().GetProperties() .Where(p => Attribute.GetCustomAttribute(p, typeof(ExclusionAttribute)) == null) .Select(p => p.GetValue(this, null)) .OfType<BindableBase>() .Where(o => o != null && !this.Equals(o)); foreach (var d in disposables) { try { if (!d.disposedValue) { d.Dispose(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } // TODO: マネージ状態を破棄します (マネージ オブジェクト)。 OnDisposing(); } disposedValue = true; // TODO: アンマネージ リソース (アンマネージ オブジェクト) を解放し、下のファイナライザーをオーバーライドします。 // TODO: 大きなフィールドを null に設定します。 OnDisposed(); } } // TODO: 上の Dispose(bool disposing) にアンマネージ リソースを解放するコードが含まれる場合にのみ、ファイナライザーをオーバーライドします。 // ~BindableBase() { // // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。 // Dispose(false); // } // このコードは、破棄可能なパターンを正しく実装できるように追加されました。 public void Dispose() { // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。 Dispose(true); // TODO: 上のファイナライザーがオーバーライドされる場合は、次の行のコメントを解除してください。 // GC.SuppressFinalize(this); } /// <summary> /// Disposeによりマネージ状態を破棄します。 /// </summary> protected virtual void OnDisposing() { } /// <summary> /// Disposeによりアンマネージリソースを開放します。 /// </summary> protected virtual void OnDisposed() { if (Source != null) { Source.PropertyChanged -= OnPropertyChanged; } Source = null; } /// <summary> /// GUID /// </summary> private string Guid { get; set; } = System.Guid.NewGuid().ToString(); #endregion } }
31.758427
108
0.512117
[ "MIT" ]
twinbird827/WpfUtilV1
Mvvm/BindableBase.cs
7,029
C#
// ****************************************************************** // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THE CODE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH // THE CODE OR THE USE OR OTHER DEALINGS IN THE CODE. // ****************************************************************** using System; namespace Microsoft.Toolkit.Uwp.UI.Controls { /// <summary> /// Event args for a value changing event /// </summary> public class RangeChangedEventArgs : EventArgs { /// <summary> /// Gets the old value. /// </summary> public double OldValue { get; private set; } /// <summary> /// Gets the new value. /// </summary> public double NewValue { get; private set; } /// <summary> /// Gets the range property that triggered the event /// </summary> public RangeSelectorProperty ChangedRangeProperty { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="RangeChangedEventArgs"/> class. /// </summary> /// <param name="oldValue">The old value</param> /// <param name="newValue">The new value</param> /// <param name="changedRangeProperty">The changed range property</param> public RangeChangedEventArgs(double oldValue, double newValue, RangeSelectorProperty changedRangeProperty) { OldValue = oldValue; NewValue = newValue; ChangedRangeProperty = changedRangeProperty; } } /// <summary> /// Enumeration used to determine what value triggered ValueChanged event on the /// RangeSelector /// </summary> public enum RangeSelectorProperty { /// <summary> /// Minimum value was changed /// </summary> MinimumValue, /// <summary> /// Maximum value was changed /// </summary> MaximumValue } }
34.794118
114
0.589603
[ "MIT" ]
Mimetis/UWPCommunityToolkit
Microsoft.Toolkit.Uwp.UI.Controls/RangeSelector/RangeChangedEventArgs.cs
2,372
C#
//----------------------------------------------------------------------------- // Copyright : (c) Chris Moore, 2020 // License : MIT //----------------------------------------------------------------------------- namespace Z0 { using System; using System.Runtime.CompilerServices; using static Root; /// <summary> /// Defines an untyped identified expression, identifier := expression /// </summary> public readonly struct FormulaExpr : IFormulaExpr { /// <summary> /// The identifier /// </summary> public string Name {get;} /// <summary> /// The identified expression /// </summary> public IExpr Encoding {get;} [MethodImpl(Inline)] public FormulaExpr(string name, IExpr encoding) { Name = name; Encoding = encoding; } public string Format() => $"{Name} := {Encoding.Format()}"; } }
26.324324
79
0.450719
[ "BSD-3-Clause" ]
0xCM/z0
src/logix/src/core/models/FormulaExpr.cs
974
C#
using System.Collections.Generic; using FluentAssertions; using Wellcome.Dds.AssetDomainRepositories.Mets.Model; using Wellcome.Dds.IIIFBuilding; using Xunit; namespace Wellcome.Dds.AssetDomainRepositories.Tests.Mets { public class MetsMetadataTests { [Theory] [InlineData("22mn 49s", 1369)] [InlineData("1mn 41s", 101)] [InlineData("9mn 46s", 586)] public void TestDurationParsing(string input, int expected) { PremisMetadata.ParseDuration(input).Should().Be(expected); } } }
27.85
70
0.682226
[ "MIT" ]
wellcomecollection/iiif-builder
src/Wellcome.Dds/Wellcome.Dds.AssetDomainRepositories.Tests/Mets/MetsMetadataTests.cs
557
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Identity; namespace MidnightLizard.Web.Identity.Models.ManageViewModels { public class ExternalLoginsViewModel { public IList<UserLoginInfo> CurrentLogins { get; set; } public IList<AuthenticationScheme> OtherLogins { get; set; } public bool ShowRemoveButton { get; set; } public string StatusMessage { get; set; } } }
25.47619
68
0.736449
[ "MIT" ]
Midnight-Lizard/Identity
app/Models/ManageViewModels/ExternalLoginsViewModel.cs
537
C#
using ReactiveUI.Winforms.Samples.Core.Routing.ViewModels; using System.Windows.Forms; namespace ReactiveUI.Winforms.Samples.Core.Routing.Views { public partial class HomeView : UserControl, IViewFor<HomeViewModel> { public HomeView() { InitializeComponent(); this.WhenActivated(d => { d(this.OneWayBind(ViewModel, vm => vm.ViewTitle, v => v.lViewTitle.Text)); }); } public HomeViewModel ViewModel { get; set; } object IViewFor.ViewModel { get => ViewModel; set => ViewModel = (HomeViewModel)value; } } }
25.576923
90
0.578947
[ "MIT" ]
lxman/ReactiveUI.Winforms.Samples
ReactiveUI.Winforms.Samples.Core.Routing/Views/HomeView.cs
667
C#
using System; using System.Runtime.Serialization; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace Lemonade.entity { /// <summary> /// Used for any entity that will not attack the player; Quest givers, characters, etc... /// </summary> class Npc : Entity { public string dialogueKey = "<default>"; public Npc() { } public override void Initialize() { } public override void Update() { } public override void Draw(SpriteBatch batch) { } } }
19.857143
93
0.592806
[ "MIT" ]
BlueTRaven/Lemonade
entity/Npc.cs
697
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace WebApiFileUpload.API { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
24.5
99
0.591837
[ "MIT" ]
chsakell/webapi-fileupload
WebApiFileUpload.API/App_Start/RouteConfig.cs
590
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.AspNetCore.Mvc.Routing; namespace VersioningWebSite { public class VersionPutAttribute : VersionRoute, IActionHttpMethodProvider { public VersionPutAttribute(string template) : base(template) { } public VersionPutAttribute(string template, string versionRange) : base(template, versionRange) { } private readonly IEnumerable<string> _httpMethods = new[] { "PUT" }; public IEnumerable<string> HttpMethods { get { return _httpMethods; } } } }
26.774194
111
0.627711
[ "Apache-2.0" ]
Elfocrash/Mvc
test/WebSites/VersioningWebSite/VersionPutAttribute.cs
830
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using RegulatedNoise.Enums_and_Utility_Classes; public partial class FilterTest : Form { private Bitmap _TestBitmap; private Rectangle _MagnifierPosition; private bool _MousebuttonIsDown = false; public FilterTest() { InitializeComponent(); } public int CutoffLevel { get; set; } public Bitmap TestBitmap { get { return _TestBitmap; } set { _TestBitmap = value; } } private void FilterTest_Load(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; this.DialogResult = System.Windows.Forms.DialogResult.None; nudCutoffValue.Value = CutoffLevel; pbPicture.Image = RNGraphics.PreprocessScreenshot(_TestBitmap, 1, (int)(nudCutoffValue.Value)); pbPicture.Size = pbPicture.Image.Size; Cursor = Cursors.Default; } private void cmdCloseOnly_Click(object sender, EventArgs e) { this.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.Close(); } private void cmdSaveClose_Click(object sender, EventArgs e) { this.DialogResult = System.Windows.Forms.DialogResult.OK; this.Close(); } private void FilterTest_Shown(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; _MagnifierPosition = new Rectangle((paPicturePanel.Width / 2) - 25, (paPicturePanel.Height / 2) - 17, 50, 31); setMagnifier(); Cursor = Cursors.Default; } private void setMagnifier() { if (pb_calibratorMagnifier.Image != null) pb_calibratorMagnifier.Image.Dispose(); if (_MagnifierPosition.Width>0 && _MagnifierPosition.Height > 0) pb_calibratorMagnifier.Image = RNGraphics.Crop((Bitmap)(pbPicture.Image), _MagnifierPosition); } private void FilterTest_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e) { Cursor = Cursors.WaitCursor; if (this.DialogResult == System.Windows.Forms.DialogResult.None) { this.DialogResult = System.Windows.Forms.DialogResult.Cancel; } CutoffLevel = (int)(nudCutoffValue.Value); Cursor = Cursors.Default; } private void nudCutoffValue_ValueChanged(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; pbPicture.Image = RNGraphics.PreprocessScreenshot(_TestBitmap, 1, (int)(nudCutoffValue.Value)); setMagnifier(); Cursor = Cursors.Default; } private void pbPicture_Click(object sender, MouseEventArgs e) { Cursor = Cursors.WaitCursor; _MagnifierPosition = new Rectangle(e.X - 25, e.Y - 17, 50, 31); setMagnifier(); Cursor = Cursors.Default; } private void pbSampleTooHigh_Click(object sender, EventArgs e) { //pb_calibratorMagnifier.Image.Save(@"C:\temp\SampleTooHigh.png"); } private void pbSampleTooLow_Click(object sender, EventArgs e) { //pb_calibratorMagnifier.Image.Save(@"C:\temp\SampleTooLow.png"); } private void pbPicture_MouseMove(object sender, MouseEventArgs e) { if (_MousebuttonIsDown) { _MagnifierPosition = new Rectangle(e.X - 25, e.Y - 17, 50, 31); setMagnifier(); } } private void pbPicture_MouseUp(object sender, MouseEventArgs e) { _MousebuttonIsDown = false; } private void pbPicture_MouseDown(object sender, MouseEventArgs e) { _MousebuttonIsDown = true; } }
27.264286
119
0.648153
[ "MIT" ]
zericco/Elite-Insight
sources/RegulatedNoise/Ocr/Calibration/FilterTest.cs
3,819
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; // Base class for things that contain entities and other groups of entities //Notes // * Searches its immediate children to fill a dict for entities and a dict // for other entity containers // * The base class doesn't automatically do this as you have to specify what the // string key in the dicts will be public class EntityContainer : Selectable { //protected members protected Dictionary<string, List<Entity>> mGroupMap = new Dictionary<string, List<Entity>>(); protected Dictionary<string, List<EntityContainer>> mContainerMap = new Dictionary<string, List<EntityContainer>>(); //------------------------------------------------------------------------------------------------- // unity methods //------------------------------------------------------------------------------------------------- public override void Awake() { base.Awake(); } public override void Update() { base.Update(); removeDeadEntities(); } //------------------------------------------------------------------------------------------------- // public methods //------------------------------------------------------------------------------------------------- public virtual void addEntity(string group_name, Entity ent) { /*if ( !mGroupMap.ContainsKey(group_name) ) { List<Entity> lempty = new List<Entity>(); mGroupMap.Add(group_name, lempty); }*/ newGroup(group_name); mGroupMap[group_name].Add(ent); } public void addContainer(string cont_name, EntityContainer cent) { if (!mContainerMap.ContainsKey(cont_name)) { List<EntityContainer> lempty = new List<EntityContainer>(); mContainerMap.Add(cont_name, lempty); } mContainerMap[cont_name].Add(cent); } public void clearGroup(string gname) { //clears the group but doesnt remove it from the map if (mGroupMap.ContainsKey(gname)) { mGroupMap[gname].Clear(); } } public List<Entity> getGroup(string gname) { if (mGroupMap.ContainsKey(gname)) { return mGroupMap[gname]; } else return new List<Entity>(); } public void removeContainer(string cname, EntityContainer ec) { //removes ec from container map group named cname if ec is in that group bool contains_ec = false; if (mContainerMap.ContainsKey(cname)) { foreach (EntityContainer lec in mContainerMap[cname]) { if (lec == ec) { contains_ec = true; break; } } if (contains_ec) { mContainerMap[cname].Remove(ec); } } } public void removeEntity(string gname, Entity ent) { //removes ent from group named gname if ent is in that group bool contains_ent = false; if ( mGroupMap.ContainsKey(gname) ) { foreach (Entity lent in mGroupMap[gname]) { if (lent == ent) { contains_ent = true; break; } } if (contains_ent) { mGroupMap[gname].Remove(ent); } } } //------------------------------------------------------------------------------------------------- // protected methods //------------------------------------------------------------------------------------------------- protected void newContainerGroup(string cname) { if (!mContainerMap.ContainsKey(cname)) { List<EntityContainer> lempty = new List<EntityContainer>(); mContainerMap.Add(cname, lempty); } } protected void newGroup(string gname) { if (!mGroupMap.ContainsKey(gname)) { List<Entity> lempty = new List<Entity>(); mGroupMap.Add(gname, lempty); } } //------------------------------------------------------------------------------------------------- // private methods //------------------------------------------------------------------------------------------------- private void removeDeadEntities() { Dictionary<string, List<Entity>> gm = new Dictionary<string, List<Entity>>(); foreach (KeyValuePair<string, List<Entity>> pair in mGroupMap) { List<Entity> elist = new List<Entity>(pair.Value); foreach (Entity ent in pair.Value) { if (!ent) elist.Remove(ent); } gm[pair.Key] = elist; } mGroupMap = gm; } }
31.606452
120
0.46438
[ "MIT" ]
kevinkraft/RTS_4
Assets/Containers/EntityContainer.cs
4,901
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the directconnect-2012-10-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.DirectConnect.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DirectConnect.Model.Internal.MarshallTransformations { /// <summary> /// RouteFilterPrefix Marshaller /// </summary> public class RouteFilterPrefixMarshaller : IRequestMarshaller<RouteFilterPrefix, JsonMarshallerContext> { public void Marshall(RouteFilterPrefix requestObject, JsonMarshallerContext context) { if(requestObject.IsSetCidr()) { context.Writer.WritePropertyName("cidr"); context.Writer.Write(requestObject.Cidr); } } public readonly static RouteFilterPrefixMarshaller Instance = new RouteFilterPrefixMarshaller(); } }
32.660377
111
0.723859
[ "Apache-2.0" ]
ermshiperete/aws-sdk-net
AWSSDK_DotNet35/Amazon.DirectConnect/Model/Internal/MarshallTransformations/RouteFilterPrefixMarshaller.cs
1,731
C#
namespace PPWCode.Kit.Tasks.Server.NTServiceHost { partial class ProjectInstaller { /// <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 Component 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.serviceProcessInstaller = new System.ServiceProcess.ServiceProcessInstaller(); this.serviceInstaller = new System.ServiceProcess.ServiceInstaller(); // // serviceProcessInstaller // this.serviceProcessInstaller.Password = null; this.serviceProcessInstaller.Username = null; // // serviceInstaller // this.serviceInstaller.Description = "PPWCode Kit Tasks Services"; this.serviceInstaller.DisplayName = "PPWCode Kit Tasks API I"; this.serviceInstaller.ServiceName = "PPWCode.Kit.Tasks.API_I"; this.serviceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic; // // ProjectInstaller // this.Installers.AddRange(new System.Configuration.Install.Installer[] { this.serviceProcessInstaller, this.serviceInstaller}); } #endregion private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller; private System.ServiceProcess.ServiceInstaller serviceInstaller; } }
37.152542
108
0.586223
[ "Apache-2.0" ]
jandockx/ppwcode
dotnet/Kit/Tasks.NTServiceHost/I/2.n/2.0.0/src/Server.NTServiceHost/ProjectInstaller.Designer.cs
2,194
C#
// Copyright (c) Binshop and Contributors. All rights reserved. // Licensed under the MIT License namespace Binshop.DTOs.ApplePay { public class MerchantSessionResponose { public long EpochTimestamp { get; set; } public long ExpiresAt { get; set; } public string MerchantSessionIdentifier { get; set; } public string Nonce { get; set; } public string MerchantIdentifier { get; set; } public string DomainName { get; set; } public string DisplayName { get; set; } public string Signature { get; set; } } }
23.56
63
0.643463
[ "MIT" ]
Binshop/apple-pay-demo
src/ApplicationCore/DTOs/ApplePay/MerchantSessionResponose.cs
589
C#
namespace ErpDataFactory { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class I_BeiJingGoods { public int Id { get; set; } [StringLength(255)] public string I_ProductId { get; set; } [StringLength(255)] public string I_Category { get; set; } [StringLength(255)] public string I_Brand { get; set; } [StringLength(500)] public string I_ProductName { get; set; } public decimal? I_SalePrice { get; set; } } }
24.035714
55
0.637444
[ "Unlicense" ]
heiazuo/mockOrders
model/I_BeiJingGoods.cs
673
C#
/* * Author: Imagos Softworks 2015 * www.imagossoftworks.com */ using UnityEngine; using System.Collections; namespace EventSystem { /// <summary> /// Base class for Event Triggers. Extend this class to add /// a new condition for an event sequence to be performed. /// </summary> [AddComponentMenu("Events/Triggers/Trigger Base")] public class EventTrigger : MonoBehaviour { public event System.EventHandler Triggered; /// <summary> /// Allows you to manually check if the conditions of this trigger have been met. /// Triggers that require this call are 'passive' triggers. /// </summary> /// <returns><c>true</c>, if conditions are met, <c>false</c> otherwise.</returns> public virtual bool ConditionsMet(){ return true; } /// <summary> /// This function is to be called by sub classes when conditions are /// met. Calling this function makes this an 'active' trigger. /// </summary> protected void OnTrigger(){ if(Triggered != null){ Triggered(this, new System.EventArgs()); } } } }
26.769231
84
0.688697
[ "MIT" ]
PicklesIIDX/EventSystem
eventsystem/Assets/Event System/Triggers/EventTrigger.cs
1,046
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\IEntityReferenceRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; /// <summary> /// The interface ITeamsTemplateReferenceRequestBuilder. /// </summary> public partial interface ITeamsTemplateReferenceRequestBuilder : IBaseRequestBuilder { /// <summary> /// Builds the request. /// </summary> /// <returns>The built request.</returns> ITeamsTemplateReferenceRequest Request(); /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> ITeamsTemplateReferenceRequest Request(IEnumerable<Option> options); } }
37.176471
153
0.587816
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/ITeamsTemplateReferenceRequestBuilder.cs
1,264
C#
using SF.Sys.Entities; namespace SF.Common.UserGroups.Front { /// <summary> /// 成员查询参数 /// </summary> public class MemberQueryArgument : QueryArgument { /// <summary> /// 组ID /// </summary> public long? GroupId { get; set; } /// <summary> /// 用户ID /// </summary> public long? OwnerId { get; set; } } }
16.3
49
0.595092
[ "Apache-2.0" ]
etechi/ServiceFramework
Projects/Server/Common/SF.Common.UserGroups/Front/MemberQueryArgument.cs
346
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20200301.Outputs { [OutputType] public sealed class CustomDnsConfigPropertiesFormatResponse { /// <summary> /// Fqdn that resolves to private endpoint ip address. /// </summary> public readonly string? Fqdn; /// <summary> /// A list of private ip addresses of the private endpoint. /// </summary> public readonly ImmutableArray<string> IpAddresses; [OutputConstructor] private CustomDnsConfigPropertiesFormatResponse( string? fqdn, ImmutableArray<string> ipAddresses) { Fqdn = fqdn; IpAddresses = ipAddresses; } } }
28.222222
81
0.647638
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Network/V20200301/Outputs/CustomDnsConfigPropertiesFormatResponse.cs
1,016
C#
using FlaUI.Core.AutomationElements.Infrastructure; using FlaUI.Core.Conditions; using FlaUI.Core.Definitions; using OpenRPA.Input; using OpenRPA.Interfaces; using OpenRPA.Interfaces.Selector; using System; using System.Activities; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Controls; namespace OpenRPA.IE { class Plugin : ObservableObject, IRecordPlugin { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "IDE1006")] public static treeelement[] _GetRootElements(Selector anchor) { var browser = Browser.GetBrowser(true); if (browser == null) { Log.Warning("Failed locating an Internet Explore instance"); return new treeelement[] { }; } if(anchor != null) { if (!(anchor is IESelector ieselector)) { ieselector = new IESelector(anchor.ToString()); } var elements = IESelector.GetElementsWithuiSelector(ieselector, null, 5); var result = new List<treeelement>(); foreach (var _ele in elements) { var e = new IETreeElement(null, true, _ele); result.Add(e); } return result.ToArray(); } else { var e = new IETreeElement(null, true, new IEElement(browser, browser.Document.documentElement)); return new treeelement[] { e }; } } public treeelement[] GetRootElements(Selector anchor) { return Plugin._GetRootElements(anchor); } public Interfaces.Selector.Selector GetSelector(Selector anchor, Interfaces.Selector.treeelement item) { var ieitem = item as IETreeElement; IESelector ieanchor = anchor as IESelector; if (ieanchor == null && anchor != null) { ieanchor = new IESelector(anchor.ToString()); } return new IESelector(ieitem.IEElement.Browser, ieitem.IEElement.RawElement, ieanchor, true, 0, 0); } public event Action<IRecordPlugin, IRecordEvent> OnUserAction; public event Action<IRecordPlugin, IRecordEvent> OnMouseMove { add { } remove { } } public string Name { get => "IE"; } public string Status => ""; private Views.RecordPluginView view; public System.Windows.Controls.UserControl editor { get { if (view == null) { view = new Views.RecordPluginView(); } return view; } } public void Start() { OpenRPA.Input.InputDriver.Instance.CallNext = false; InputDriver.Instance.OnMouseUp += OnMouseUp; } public void Stop() { OpenRPA.Input.InputDriver.Instance.CallNext = true; InputDriver.Instance.OnMouseUp -= OnMouseUp; } private void ParseMouseUp(InputEventArgs e) { try { // if(string.IsNullOrEmpty(Thread.CurrentThread.Name)) Thread.CurrentThread.Name = "IE.Plugin.OnMouseUP"; Log.Debug(string.Format("IE.Recording::OnMouseUp::begin")); var re = new RecordEvent { Button = e.Button }; var a = new GetElement { DisplayName = (e.Element.Name).Replace(Environment.NewLine, "").Trim() }; var p = System.Diagnostics.Process.GetProcessById(e.Element.ProcessId); if (p.ProcessName != "iexplore" && p.ProcessName != "iexplore.exe") return; var browser = new Browser(); var htmlelement = browser.ElementFromPoint(e.X, e.Y); if (htmlelement == null) { return; } var sw = new System.Diagnostics.Stopwatch(); sw.Start(); IESelector sel = null; // sel = new IESelector(e.Element.rawElement, null, true); GenericTools.RunUI(() => { sel = new IESelector(browser, htmlelement, null, false, e.X, e.Y); }); if (sel == null) return; if (sel.Count < 2) return; a.Selector = sel.ToString(); a.Image = sel.Last().Element.ImageString(); re.UIElement = e.Element; re.Element = new IEElement(browser, htmlelement); re.Selector = sel; re.X = e.X; re.Y = e.Y; Log.Debug(e.Element.SupportInput + " / " + e.Element.ControlType); re.a = new GetElementResult(a); //if (htmlelement.tagName.ToLower() == "input" && htmlelement.tagName.ToLower() == "select") if (htmlelement.tagName.ToLower() == "input") { MSHTML.IHTMLInputElement inputelement = (MSHTML.IHTMLInputElement)htmlelement; re.SupportInput = (inputelement.type.ToLower() == "text" || inputelement.type.ToLower() == "password"); } re.SupportSelect = false; Log.Debug(string.Format("IE.Recording::OnMouseUp::end {0:mm\\:ss\\.fff}", sw.Elapsed)); OnUserAction?.Invoke(this, re); } catch (Exception ex) { Log.Error(ex.ToString()); } } private void OnMouseUp(InputEventArgs e) { var thread = new Thread(new ThreadStart(() => { ParseMouseUp(e); })); thread.IsBackground = true; thread.Start(); } public bool ParseUserAction(ref IRecordEvent e) { if (e.UIElement == null) return false; if (e.UIElement.ProcessId < 1) return false; var p = System.Diagnostics.Process.GetProcessById(e.UIElement.ProcessId); if(p.ProcessName!="iexplore" && p.ProcessName != "iexplore.exe") return false; var browser = new Browser(); var htmlelement = browser.ElementFromPoint(e.X, e.Y); if (htmlelement == null) { return false; } var selector = new IESelector(browser, htmlelement, null, true, e.X, e.Y); e.Selector = selector; e.Element = new IEElement(browser, htmlelement); var a = new GetElement { DisplayName = (htmlelement.id + "-" + htmlelement.tagName + "-" + htmlelement.className).Replace(Environment.NewLine, "").Trim() }; a.Selector = selector.ToString(); var last = selector.Last() as IESelectorItem; a.Image = last.Element.ImageString(); var tagName = htmlelement.tagName; if (string.IsNullOrEmpty(tagName)) tagName = ""; tagName = tagName.ToLower(); e.a = new GetElementResult(a); //if (tagName == "input") //{ // // MSHTML.IHTMLInputElement inputelement = (MSHTML.IHTMLInputElement)htmlelement; // e.SupportInput = (last.type.ToLower() == "text" || last.type.ToLower() == "password"); //} // if (htmlelement.tagName.ToLower() == "input" && htmlelement.tagName.ToLower() == "select") if (htmlelement.tagName.ToLower() == "input") { MSHTML.IHTMLInputElement inputelement = (MSHTML.IHTMLInputElement)htmlelement; e.SupportInput = (inputelement.type.ToLower() == "text" || inputelement.type.ToLower() == "password"); } e.SupportSelect = htmlelement.tagName.ToLower() == "select"; return true; } public void Initialize(IOpenRPAClient client) { _ = PluginConfig.enable_xpath_support; } public IElement[] GetElementsWithSelector(Selector selector, IElement fromElement = null, int maxresults = 1) { if (!(selector is IESelector ieselector)) { ieselector = new IESelector(selector.ToString()); } var result = IESelector.GetElementsWithuiSelector(ieselector, fromElement, maxresults); return result; } public IElement LaunchBySelector(Selector selector, bool CheckRunning, TimeSpan timeout) { if (selector == null || selector.Count == 0) return null; var f = selector.First(); var p = f.Properties.Where(x => x.Name == "url").FirstOrDefault(); if (p == null) return null; var url = p.Value; if (string.IsNullOrEmpty(url)) return null; GenericTools.RunUI(() => { var browser = Browser.GetBrowser(true, url); var doc = browser.Document; if (url != doc.url) doc.url = url; browser.Show(); var sw = new System.Diagnostics.Stopwatch(); sw.Start(); while (sw.Elapsed < timeout) { try { Log.Debug("pending complete, readyState: " + doc.readyState); Thread.Sleep(100); if (doc.readyState != "complete" && doc.readyState != "interactive") break; } catch (Exception) { } } }); var wbs = new SHDocVw.ShellWindows().Cast<SHDocVw.WebBrowser>().ToList(); foreach (var w in wbs) { try { var doc = (w.Document as MSHTML.HTMLDocument); if (doc != null) { var wBrowser = w as SHDocVw.WebBrowser; var automation = Interfaces.AutomationUtil.getAutomation(); var _ele = automation.FromHandle(new IntPtr(wBrowser.HWND)); if(_ele != null) { var ui = new UIElement(_ele); var window = ui.GetWindow(); if (window != null) return new UIElement(window); } } } catch (Exception) { } } return null; } public void CloseBySelector(Selector selector, TimeSpan timeout, bool Force) { string url = ""; var f = selector.First(); var p = f.Properties.Where(x => x.Name == "url").FirstOrDefault(); if (p != null) url = p.Value; SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows(); foreach (SHDocVw.InternetExplorer _ie in shellWindows) { var filename = System.IO.Path.GetFileNameWithoutExtension(_ie.FullName).ToLower(); if (filename.Equals("iexplore")) { try { var wBrowser = _ie as SHDocVw.WebBrowser; if(wBrowser.LocationURL == url || string.IsNullOrEmpty(url)) { using (var automation = Interfaces.AutomationUtil.getAutomation()) { var _ele = automation.FromHandle(new IntPtr(_ie.HWND)); using (var app = new FlaUI.Core.Application(_ele.Properties.ProcessId.Value, false)) { app.Close(); } } } } catch (Exception ex) { Log.Error(ex, ""); } } } } public bool Match(SelectorItem item, IElement m) { var p = item.Properties.Where(x => x.Name == "xpath").FirstOrDefault(); //if(p != null) //{ // var xpath = p.Value; // var browser = Browser.GetBrowser(); // if(browser != null) // { // MSHTML.IHTMLDocument3 sourceDoc = (MSHTML.IHTMLDocument3)browser.Document; // string documentContents = sourceDoc.documentElement.outerHTML; // HtmlAgilityPack.HtmlDocument targetDoc = new HtmlAgilityPack.HtmlDocument(); // targetDoc.LoadHtml(documentContents); // HtmlAgilityPack.HtmlNode node = targetDoc.DocumentNode.SelectSingleNode(xpath); // if(node != null) // { // var ele = new IEElement(browser, node); // } // } //} return IESelectorItem.Match(item, m.RawElement as MSHTML.IHTMLElement); } public bool ParseMouseMoveAction(ref IRecordEvent e) { if (e.UIElement == null) return false; if (e.UIElement.ProcessId < 1) return false; var p = System.Diagnostics.Process.GetProcessById(e.UIElement.ProcessId); if (p.ProcessName != "iexplore" && p.ProcessName != "iexplore.exe") return false; return true; } } public class GetElementResult : IBodyActivity { public GetElementResult(GetElement activity) { Activity = activity; } public Activity Activity { get; set; } public void AddActivity(Activity a, string Name) { //var aa = new ActivityAction<IEElement>(); //var da = new DelegateInArgument<IEElement>(); //da.Name = Name; //((GetElement)Activity).Body = aa; //aa.Argument = da; var aa = new ActivityAction<IEElement>(); var da = new DelegateInArgument<IEElement> { Name = Name }; aa.Handler = a; ((GetElement)Activity).Body = aa; aa.Argument = da; } public void AddInput(string value, IElement element) { try { AddActivity(new System.Activities.Statements.Assign<string> { To = new Microsoft.VisualBasic.Activities.VisualBasicReference<string>("item.value"), Value = value }, "item"); element.Value = value; } catch (Exception ex) { Log.Error(ex.ToString()); } } } public class RecordEvent : IRecordEvent { public RecordEvent() { SupportVirtualClick = true; } // public AutomationElement Element { get; set; } public UIElement UIElement { get; set; } public IElement Element { get; set; } public Interfaces.Selector.Selector Selector { get; set; } public IBodyActivity a { get; set; } public bool SupportInput { get; set; } public bool SupportSelect { get; set; } public int X { get; set; } public int Y { get; set; } public int OffsetX { get; set; } public int OffsetY { get; set; } public bool ClickHandled { get; set; } public bool SupportVirtualClick { get; set; } public MouseButton Button { get; set; } } }
41.010417
168
0.508446
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
IBM/openrpa
OpenRPA.IE/Plugin.cs
15,750
C#
using System; namespace CommunityCenter.Models.RBAC { public class fn_rbac_CH_ClientSummaryHistory { public DateTime Date { get; set; } public string CollectionID { get; set; } public string SiteCode { get; set; } public int ClientsTotal { get; set; } public int ClientsActive { get; set; } public int ClientsInactive { get; set; } public int ClientsActiveDDR { get; set; } public int ClientsActiveHW { get; set; } public int ClientsActiveSW { get; set; } public int ClientsActivePolicyRequest { get; set; } public int ClientsActiveStatusMessage { get; set; } public int ClientsHealthy { get; set; } public int ClientsUnhealthy { get; set; } public int ClientsHealthUnknown { get; set; } public int ClientsRemediationSuccess { get; set; } public int ClientsRemediationTotal { get; set; } public int ClientsActiveHealthyOrActiveNoResults { get; set; } public int? ClientsInactiveUsingIntune { get; set; } } }
23.586957
70
0.636866
[ "MIT" ]
Eph-It/MEM.CommunityCenter
CommunityCenter/CommunityCenter.Models/RBAC/fn_rbac_CH_ClientSummaryHistory.cs
1,087
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Windows; using System.Windows.Controls; namespace AdaptiveCards.Rendering.Wpf { public static class AdaptiveFactSetRenderer { public static FrameworkElement Render(AdaptiveFactSet factSet, AdaptiveRenderContext context) { if (factSet.Facts.Count == 0) { return null; } var uiFactSet = new Grid(); // grid.Margin = factSet.Theme.FactSetMargins; uiFactSet.Style = context.GetStyle("Adaptive.FactSet"); uiFactSet.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto }); uiFactSet.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); int iRow = 0; foreach (var fact in factSet.Facts) { var uiTitle = context.Render(new AdaptiveTextBlock() { Size = context.Config.FactSet.Title.Size, Color = context.Config.FactSet.Title.Color, IsSubtle = context.Config.FactSet.Title.IsSubtle, Weight = context.Config.FactSet.Title.Weight, Wrap = context.Config.FactSet.Title.Wrap, MaxWidth = context.Config.FactSet.Title.MaxWidth, Text = fact.Title }); var uiValue = context.Render(new AdaptiveTextBlock() { Size = context.Config.FactSet.Value.Size, Color = context.Config.FactSet.Value.Color, IsSubtle = context.Config.FactSet.Value.IsSubtle, Weight = context.Config.FactSet.Value.Weight, Wrap = context.Config.FactSet.Value.Wrap, // MaxWidth is not applicable to the Value field of the Fact // so ignore it. Text = fact.Value }); if (uiTitle != null || uiValue != null) { uiFactSet.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto }); } if (uiTitle != null) { uiTitle.Style = context.GetStyle("Adaptive.Fact.Title"); uiTitle.Margin = new Thickness(left: 0, top: 0, right: context.Config.FactSet.Spacing, bottom: 0); Grid.SetColumn(uiTitle, 0); Grid.SetRow(uiTitle, iRow); uiFactSet.Children.Add(uiTitle); } if (uiValue != null) { uiValue.Style = context.GetStyle("Adaptive.Fact.Value"); Grid.SetColumn(uiValue, 1); Grid.SetRow(uiValue, iRow); uiFactSet.Children.Add(uiValue); } if (uiTitle != null || uiValue != null) { iRow++; } } return (iRow == 0) ? null : uiFactSet; } } }
37.785714
118
0.510712
[ "MIT" ]
AdaptiveCards-Desktop/AdaptiveCards
source/dotnet/Library/AdaptiveCards.Rendering.Wpf/AdaptiveFactSetRenderer.cs
3,174
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.DBforMariaDB.Latest { /// <summary> /// Represents a server firewall rule. /// Latest API Version: 2018-06-01. /// </summary> [Obsolete(@"The 'latest' version is deprecated. Please migrate to the resource in the top-level module: 'azure-nextgen:dbformariadb:FirewallRule'.")] [AzureNextGenResourceType("azure-nextgen:dbformariadb/latest:FirewallRule")] public partial class FirewallRule : Pulumi.CustomResource { /// <summary> /// The end IP address of the server firewall rule. Must be IPv4 format. /// </summary> [Output("endIpAddress")] public Output<string> EndIpAddress { get; private set; } = null!; /// <summary> /// The name of the resource /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The start IP address of the server firewall rule. Must be IPv4 format. /// </summary> [Output("startIpAddress")] public Output<string> StartIpAddress { get; private set; } = null!; /// <summary> /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a FirewallRule resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public FirewallRule(string name, FirewallRuleArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:dbformariadb/latest:FirewallRule", name, args ?? new FirewallRuleArgs(), MakeResourceOptions(options, "")) { } private FirewallRule(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:dbformariadb/latest:FirewallRule", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:dbformariadb:FirewallRule"}, new Pulumi.Alias { Type = "azure-nextgen:dbformariadb/v20180601:FirewallRule"}, new Pulumi.Alias { Type = "azure-nextgen:dbformariadb/v20180601preview:FirewallRule"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing FirewallRule resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static FirewallRule Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new FirewallRule(name, id, options); } } public sealed class FirewallRuleArgs : Pulumi.ResourceArgs { /// <summary> /// The end IP address of the server firewall rule. Must be IPv4 format. /// </summary> [Input("endIpAddress", required: true)] public Input<string> EndIpAddress { get; set; } = null!; /// <summary> /// The name of the server firewall rule. /// </summary> [Input("firewallRuleName")] public Input<string>? FirewallRuleName { get; set; } /// <summary> /// The name of the resource group. The name is case insensitive. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the server. /// </summary> [Input("serverName", required: true)] public Input<string> ServerName { get; set; } = null!; /// <summary> /// The start IP address of the server firewall rule. Must be IPv4 format. /// </summary> [Input("startIpAddress", required: true)] public Input<string> StartIpAddress { get; set; } = null!; public FirewallRuleArgs() { } } }
41.361538
153
0.608704
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/DBforMariaDB/Latest/FirewallRule.cs
5,377
C#
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.34014 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ namespace Bing_Search.Resources { using System; /// <summary> /// 一个强类型的资源类,用于查找本地化的字符串等。 /// </summary> // 此类是由 StronglyTypedResourceBuilder // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen // (以 /str 作为命令选项),或重新生成 VS 项目。 [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class AppResources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal AppResources() { } /// <summary> /// 返回此类使用的缓存的 ResourceManager 实例。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Bing_Search.Resources.AppResources", typeof(AppResources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// 使用此强类型资源类,为所有资源查找 /// 重写当前线程的 CurrentUICulture 属性。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// 查找类似 关于 的本地化字符串。 /// </summary> public static string about { get { return ResourceManager.GetString("about", resourceCulture); } } /// <summary> /// 查找类似 添加 的本地化字符串。 /// </summary> public static string AppBarButtonText { get { return ResourceManager.GetString("AppBarButtonText", resourceCulture); } } /// <summary> /// 查找类似 菜单项 的本地化字符串。 /// </summary> public static string AppBarMenuItemText { get { return ResourceManager.GetString("AppBarMenuItemText", resourceCulture); } } /// <summary> /// 查找类似 爱搜索 的本地化字符串。 /// </summary> public static string ApplicationTitle { get { return ResourceManager.GetString("ApplicationTitle", resourceCulture); } } /// <summary> /// 查找类似 百度 的本地化字符串。 /// </summary> public static string baidu { get { return ResourceManager.GetString("baidu", resourceCulture); } } /// <summary> /// 查找类似 一维条码扫描 的本地化字符串。 /// </summary> public static string barcode { get { return ResourceManager.GetString("barcode", resourceCulture); } } /// <summary> /// 查找类似 倾力呈现 的本地化字符串。 /// </summary> public static string best { get { return ResourceManager.GetString("best", resourceCulture); } } /// <summary> /// 查找类似 必应 的本地化字符串。 /// </summary> public static string bing { get { return ResourceManager.GetString("bing", resourceCulture); } } /// <summary> /// 查找类似 复制 的本地化字符串。 /// </summary> public static string copy { get { return ResourceManager.GetString("copy", resourceCulture); } } /// <summary> /// 查找类似 邮箱: 的本地化字符串。 /// </summary> public static string email { get { return ResourceManager.GetString("email", resourceCulture); } } /// <summary> /// 查找类似 手动对焦 的本地化字符串。 /// </summary> public static string focus { get { return ResourceManager.GetString("focus", resourceCulture); } } /// <summary> /// 查找类似 谷歌 的本地化字符串。 /// </summary> public static string google { get { return ResourceManager.GetString("google", resourceCulture); } } /// <summary> /// 查找类似 下一张 的本地化字符串。 /// </summary> public static string next { get { return ResourceManager.GetString("next", resourceCulture); } } /// <summary> /// 查找类似 在IE中打开 的本地化字符串。 /// </summary> public static string open { get { return ResourceManager.GetString("open", resourceCulture); } } /// <summary> /// 查找类似 上一张 的本地化字符串。 /// </summary> public static string prev { get { return ResourceManager.GetString("prev", resourceCulture); } } /// <summary> /// 查找类似 二维条码扫描 的本地化字符串。 /// </summary> public static string qrcode { get { return ResourceManager.GetString("qrcode", resourceCulture); } } /// <summary> /// 查找类似 刷新 的本地化字符串。 /// </summary> public static string refresh { get { return ResourceManager.GetString("refresh", resourceCulture); } } /// <summary> /// 查找类似 LeftToRight 的本地化字符串。 /// </summary> public static string ResourceFlowDirection { get { return ResourceManager.GetString("ResourceFlowDirection", resourceCulture); } } /// <summary> /// 查找类似 zh-CN 的本地化字符串。 /// </summary> public static string ResourceLanguage { get { return ResourceManager.GetString("ResourceLanguage", resourceCulture); } } /// <summary> /// 查找类似 扫码结果 的本地化字符串。 /// </summary> public static string result { get { return ResourceManager.GetString("result", resourceCulture); } } /// <summary> /// 查找类似 给个好评吧! 的本地化字符串。 /// </summary> public static string review { get { return ResourceManager.GetString("review", resourceCulture); } } /// <summary> /// 查找类似 保存图片 的本地化字符串。 /// </summary> public static string save { get { return ResourceManager.GetString("save", resourceCulture); } } /// <summary> /// 查找类似 海盗湾 的本地化字符串。 /// </summary> public static string tpb { get { return ResourceManager.GetString("tpb", resourceCulture); } } /// <summary> /// 查找类似 免费VPN注册方法(8.1适用) 的本地化字符串。 /// </summary> public static string vpn { get { return ResourceManager.GetString("vpn", resourceCulture); } } /// <summary> /// 查找类似 前进 的本地化字符串。 /// </summary> public static string web_next { get { return ResourceManager.GetString("web_next", resourceCulture); } } /// <summary> /// 查找类似 后退 的本地化字符串。 /// </summary> public static string web_prev { get { return ResourceManager.GetString("web_prev", resourceCulture); } } /// <summary> /// 查找类似 网页: 的本地化字符串。 /// </summary> public static string website { get { return ResourceManager.GetString("website", resourceCulture); } } /// <summary> /// 查找类似 新浪微博: 的本地化字符串。 /// </summary> public static string weibo { get { return ResourceManager.GetString("weibo", resourceCulture); } } } }
29.642405
182
0.481905
[ "MIT" ]
WEdotStudio/Love_Search
Bing_Search/Resources/AppResources.Designer.cs
10,573
C#
namespace RegistroN { partial class FormLogin { /// <summary> /// Variable del diseñador necesaria. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Limpiar los recursos que se estén usando. /// </summary> /// <param name="disposing">true si los recursos administrados se deben desechar; false en caso contrario.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Código generado por el Diseñador de Windows Forms /// <summary> /// Método necesario para admitir el Diseñador. No se puede modificar /// el contenido de este método con el editor de código. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormLogin)); this.label1 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.BackColor = System.Drawing.Color.WhiteSmoke; this.label1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.label1.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(110, 179); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(64, 18); this.label1.TabIndex = 0; this.label1.Text = "Usuario"; this.label1.Click += new System.EventHandler(this.label1_Click); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(203, 177); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(143, 20); this.textBox1.TabIndex = 1; this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged); // // textBox2 // this.textBox2.Location = new System.Drawing.Point(203, 217); this.textBox2.Name = "textBox2"; this.textBox2.PasswordChar = '*'; this.textBox2.Size = new System.Drawing.Size(143, 20); this.textBox2.TabIndex = 3; this.textBox2.TextChanged += new System.EventHandler(this.textBox2_TextChanged); // // label2 // this.label2.AutoSize = true; this.label2.BackColor = System.Drawing.Color.White; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(107, 217); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(87, 16); this.label2.TabIndex = 2; this.label2.Text = "Contraseña"; this.label2.Click += new System.EventHandler(this.label2_Click); // // button1 // this.button1.BackColor = System.Drawing.Color.AliceBlue; this.button1.Font = new System.Drawing.Font("Microsoft Tai Le", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button1.Location = new System.Drawing.Point(107, 306); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(96, 45); this.button1.TabIndex = 4; this.button1.Text = "Aceptar"; this.button1.UseVisualStyleBackColor = false; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.BackColor = System.Drawing.Color.AliceBlue; this.button2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button2.ImageAlign = System.Drawing.ContentAlignment.MiddleRight; this.button2.Location = new System.Drawing.Point(250, 306); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(96, 45); this.button2.TabIndex = 5; this.button2.Text = "Cancelar"; this.button2.UseVisualStyleBackColor = false; this.button2.Click += new System.EventHandler(this.button2_Click); // // pictureBox1 // this.pictureBox1.BackColor = System.Drawing.Color.Transparent; this.pictureBox1.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("pictureBox1.BackgroundImage"))); this.pictureBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.pictureBox1.Location = new System.Drawing.Point(165, 24); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(123, 121); this.pictureBox1.TabIndex = 6; this.pictureBox1.TabStop = false; // // FormLogin // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.Black; this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.ClientSize = new System.Drawing.Size(452, 375); this.ControlBox = false; this.Controls.Add(this.pictureBox1); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.textBox2); this.Controls.Add(this.label2); this.Controls.Add(this.textBox1); this.Controls.Add(this.label1); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "FormLogin"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Ingreso al Sistema"; this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.PictureBox pictureBox1; } }
48.565217
166
0.605576
[ "MIT" ]
Caballer032597881/RegistroNotas
RegistroN/RegistroN/FormLogin.Designer.cs
7,830
C#
using System; using Publisher = NetOffice.PublisherApi; namespace NetOffice.PublisherApi.Tools { /// <summary> /// Custom task pane UserControl instance may implement this interface to be notified about the lifetime of the custom task pane. /// </summary> public interface ITaskPane : OfficeApi.Tools.ITaskPaneConnection<Publisher.Application> { /// <summary> /// Called when Microsoft Office application is shuting down. This method is not called in case of unexpected termination of the process. /// </summary> void OnDisconnection(); /// <summary> /// Called when the user changes the dock position of the custom task pane. /// </summary> /// <param name="position">the current alignment for the instance</param> void OnDockPositionChanged(NetOffice.OfficeApi.Enums.MsoCTPDockPosition position); /// <summary> /// Called when the user displays or closes the custom task pane. /// </summary> /// <param name="visible">the current visibility for the instance</param> void OnVisibleStateChanged(bool visible); } }
39.793103
145
0.67331
[ "MIT" ]
NetOfficeFw/NetOffice
Source/Publisher/Tools/ITaskPane.cs
1,156
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Debug_the_Code_Holidays_Between_Two_Dates { class Program { static void Main(string[] args) { DateTime startDate = DateTime.ParseExact(Console.ReadLine(), "d.M.yyyy", CultureInfo.InvariantCulture); DateTime endDate = DateTime.ParseExact(Console.ReadLine(), "d.M.yyyy", CultureInfo.InvariantCulture); int holidaysCount = 0; for (DateTime date = startDate; date <= endDate; date = date.AddDays(1)) if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday) { holidaysCount++; } Console.WriteLine(holidaysCount); } } }
30.678571
115
0.627474
[ "MIT" ]
danielstaikov/Practice-Integer-Numbers
Debug the Code Holidays Between Two Dates/Holidays Between Two Dates.cs
861
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable namespace Azure.ResourceManager.AppService.Models { /// <summary> The GitHub action code configuration. </summary> public partial class GitHubActionCodeConfiguration { /// <summary> Initializes a new instance of GitHubActionCodeConfiguration. </summary> public GitHubActionCodeConfiguration() { } /// <summary> Initializes a new instance of GitHubActionCodeConfiguration. </summary> /// <param name="runtimeStack"> Runtime stack is used to determine the workflow file content for code base apps. </param> /// <param name="runtimeVersion"> Runtime version is used to determine what build version to set in the workflow file. </param> internal GitHubActionCodeConfiguration(string runtimeStack, string runtimeVersion) { RuntimeStack = runtimeStack; RuntimeVersion = runtimeVersion; } /// <summary> Runtime stack is used to determine the workflow file content for code base apps. </summary> public string RuntimeStack { get; set; } /// <summary> Runtime version is used to determine what build version to set in the workflow file. </summary> public string RuntimeVersion { get; set; } } }
41.757576
135
0.690131
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/websites/Azure.ResourceManager.AppService/src/Generated/Models/GitHubActionCodeConfiguration.cs
1,378
C#
#if (PARKITECT) public class CustomOngoingEffectProduct : OngoingEffectProduct { public CustomOngoingEffectProduct() { } public override void Initialize() { this.gameObject.SetActive(true); base.Initialize(); } } #endif
15.529412
62
0.659091
[ "MIT" ]
pollend/Parkitect_Mod_Bootstrap
Model/Proxy/Shop/Products/CustomOngoingEffectProduct.cs
266
C#
using System; using System.Collections.Generic; using System.Linq; using AoC.Common; namespace AoC.Y2021.Days; public class Day22 : DayBase { private readonly List<CubeInstruction> _instructions = new(); private readonly List<CubeInstruction> _overlaps = new(); public Day22(PuzzleInput input) : base(input) { } public override IComparable PartOne() => Reboot(true); public override IComparable PartTwo() => Reboot(); public long Reboot(bool initializeOnly = false) { var instructions = _puzzleInput.GetLines().Select(ParseInstruction); foreach (var instruction in instructions) { if (instruction.IsRebootStep && initializeOnly) { break; } ProcessInstruction(instruction); } return CountEnabledCubes(); } private CubeInstruction ParseInstruction(string input) { bool on = input[1] == 'n'; int firstIndex = input.IndexOf('=') + 1; int secondIndex = input.IndexOf('=', firstIndex) + 1; int thirdIndex = input.IndexOf('=', secondIndex) + 1; var xRange = input[firstIndex..(secondIndex - 3)]; var yRange = input[secondIndex..(thirdIndex - 3)]; var zRange = input[thirdIndex..]; var xs = xRange.Split("..").Select(int.Parse).ToArray(); var ys = yRange.Split("..").Select(int.Parse).ToArray(); var zs = zRange.Split("..").Select(int.Parse).ToArray(); var cube = new Cube(xs[0], ys[0], zs[0], xs[1], ys[1], zs[1]); return new CubeInstruction(cube, on); } private void ProcessInstruction(CubeInstruction instruction) { _overlaps.Clear(); foreach (var prevInstructions in _instructions) { if (instruction.IsOverlapping(prevInstructions)) { var overlapCube = instruction.Overlaps(prevInstructions); _overlaps.Add(new CubeInstruction(overlapCube, !prevInstructions.On)); } } _instructions.AddRange(_overlaps); if (instruction.On) { _instructions.Add(instruction); } } private long CountEnabledCubes() { long cubeOn = 0; foreach (var instruction in _instructions) { cubeOn += instruction.On ? instruction.Count : -instruction.Count; } return cubeOn; } private readonly struct CubeInstruction { private readonly Cube _cube; public readonly bool On; public long Count => _cube.Count; public CubeInstruction(in Cube cube, bool on) { _cube = cube; On = on; } public bool IsOverlapping(in CubeInstruction cubeInstruction) => _cube.IsOverlapping(cubeInstruction._cube); public Cube Overlaps(in CubeInstruction cubeInstruction) => _cube.Overlaps(cubeInstruction._cube); public bool IsRebootStep => _cube.MinX < -50 || _cube.MaxX > 50 || _cube.MinY < -50 || _cube.MaxY > 50 || _cube.MinZ < -50 || _cube.MaxZ > 50; } private readonly struct Cube { public readonly int MinX, MinY, MinZ; public readonly int MaxX, MaxY, MaxZ; private readonly long _xRange, _yRange, _zRange; public Cube(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { MinX = minX; MinY = minY; MinZ = minZ; MaxX = maxX; MaxY = maxY; MaxZ = maxZ; _xRange = 1 + MaxX - MinX; _yRange = 1 + MaxY - MinY; _zRange = 1 + MaxZ - MinZ; } public long Count => _xRange * _yRange * _zRange; public bool IsOverlapping(in Cube cube) => !(MaxX < cube.MinX || MinX > cube.MaxX || MaxY < cube.MinY || MinY > cube.MaxY || MaxZ < cube.MinZ || MinZ > cube.MaxZ); public Cube Overlaps(in Cube cube) { var minX = Math.Max(MinX, cube.MinX); var minY = Math.Max(MinY, cube.MinY); var minZ = Math.Max(MinZ, cube.MinZ); var maxX = Math.Min(MaxX, cube.MaxX); var maxY = Math.Min(MaxY, cube.MaxY); var maxZ = Math.Min(MaxZ, cube.MaxZ); return new Cube(minX, minY, minZ, maxX, maxY, maxZ); } } }
32.444444
116
0.571918
[ "Unlicense" ]
EwoutSchrotenboer/AdventOfCode2021
src/AoC.Y2021/Days/Day22.cs
4,380
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.IO; using System.Globalization; using OfficeOpenXml; using OfficeOpenXml.Style; using Db2File.Code.Common; namespace Db2File.Code.File { class ExcelFileWriter : IFileWriter { private static CultureInfo _decimalCultureInfo; private ExcelPackage _package; private IList<ColumnRelation> _columnRelations; private Boolean _disposed; public String SheetName { get; set; } static ExcelFileWriter() { _decimalCultureInfo = (CultureInfo)CultureInfo.CurrentCulture.Clone(); _decimalCultureInfo.NumberFormat.NumberDecimalSeparator = "."; } public ExcelFileWriter(String fileName, Encoding fileEncoding, IList<ColumnRelation> columnRelations) { _disposed = false; _columnRelations = columnRelations; _package = new ExcelPackage(new FileInfo(fileName)); SheetName = "Sheet1"; } public void CreateHeader() { var sheet = _package.Workbook.Worksheets[SheetName] != null ? _package.Workbook.Worksheets[SheetName] : _package.Workbook.Worksheets.Add(SheetName); for (Int32 i = 0; i < _columnRelations.Count; i++) { sheet.Cells[1, i + 1].Value = _columnRelations[i].FileColumnName; sheet.Cells[1, i + 1].Style.Numberformat.Format = GetCellFormat(_columnRelations[i].FileColumnName); sheet.Cells[1, i + 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; } } public void Write(IDataReader reader) { var sheet = _package.Workbook.Worksheets[SheetName] != null ? _package.Workbook.Worksheets[SheetName] : _package.Workbook.Worksheets.Add(SheetName); var rowIndex = 2; while (reader.Read()) { var columns = new List<String>(); for (Int32 i = 0; i < _columnRelations.Count; i++) { sheet.Cells[rowIndex, i + 1].Value = reader[_columnRelations[i].DbColumnName]; sheet.Cells[rowIndex, i + 1].Style.Numberformat.Format = GetCellFormat(reader[_columnRelations[i].DbColumnName], _columnRelations[i].FileColumnFormat); } rowIndex++; } sheet.Cells.AutoFitColumns(0); _package.Save(); } public void Dispose() { if (!_disposed) { if (_package != null) _package.Dispose(); _disposed = true; } } private String GetCellFormat(Object @value, String format = "") { if (@value is DateTime) { var dateTime = (DateTime)@value; if (dateTime.TimeOfDay.TotalMilliseconds > 0) { format = String.IsNullOrWhiteSpace(format) ? "yyyy-MM-dd hh:mm:ss" : format; } else { format = String.IsNullOrWhiteSpace(format) ? "yyyy-MM-dd" : format; } return format; } if (@value is Double || @value is Single || @value is Decimal) { format = String.IsNullOrWhiteSpace(format) ? "#,##0.00" : format; return format; } if (@value is SByte || @value is Byte || @value is Int16 || @value is UInt16 || @value is Int32 || @value is UInt32 || @value is Int64 || @value is UInt64) { format = String.IsNullOrWhiteSpace(format) ? "#,##0" : format; return format; } return "@"; } } }
35.88785
171
0.557552
[ "MIT" ]
AlexanderPro/Db2File
Db2File/Code/File/ExcelFileWriter.cs
3,842
C#
using System; using System.Threading.Tasks; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.ApplicationInsights.Extensibility.Implementation; using Microsoft.ApplicationInsights.Kubernetes.Utilities; using Microsoft.Extensions.Logging; using static Microsoft.ApplicationInsights.Kubernetes.StringUtils; #if !NETSTANDARD1_3 && !NETSTANDARD1_6 using System.Diagnostics; using System.Globalization; #endif namespace Microsoft.ApplicationInsights.Kubernetes { /// <summary> /// Telemetry Initializer for K8s Environment /// </summary> internal class KubernetesTelemetryInitializer : ITelemetryInitializer { public const string Container = "Container"; public const string Deployment = "Deployment"; public const string K8s = "Kubernetes"; public const string Node = "Node"; public const string Pod = "Pod"; public const string ReplicaSet = "ReplicaSet"; public const string ProcessString = "Process"; public const string CPU = "CPU"; public const string Memory = "Memory"; private readonly ILogger _logger; private readonly SDKVersionUtils _sdkVersionUtils; private readonly DateTime _timeoutAt; internal readonly IK8sEnvironmentFactory _k8sEnvFactory; internal IK8sEnvironment _k8sEnvironment { get; private set; } internal bool _isK8sQueryTimeout = false; private bool _isK8sQueryTimeoutReported = false; public KubernetesTelemetryInitializer( IK8sEnvironmentFactory k8sEnvFactory, TimeSpan timeout, SDKVersionUtils sdkVersionUtils, ILogger<KubernetesTelemetryInitializer> logger) { _k8sEnvironment = null; _logger = logger; _sdkVersionUtils = Arguments.IsNotNull(sdkVersionUtils, nameof(sdkVersionUtils)); _timeoutAt = DateTime.Now.Add(Arguments.IsNotNull(timeout, nameof(timeout))); _k8sEnvFactory = Arguments.IsNotNull(k8sEnvFactory, nameof(k8sEnvFactory)); var _forget = SetK8sEnvironment(); } public void Initialize(ITelemetry telemetry) { if (_k8sEnvironment != null) { #if NETSTANDARD2_0 Stopwatch cpuWatch = Stopwatch.StartNew(); TimeSpan startCPUTime = Process.GetCurrentProcess().TotalProcessorTime; #endif // Setting the container name to role name if (string.IsNullOrEmpty(telemetry.Context.Cloud.RoleName)) { telemetry.Context.Cloud.RoleName = this._k8sEnvironment.ContainerName; } #if NETSTANDARD2_0 SetCustomDimensions(telemetry, cpuWatch, startCPUTime); #else SetCustomDimensions(telemetry); #endif } else { if (_isK8sQueryTimeout) { if (!_isK8sQueryTimeoutReported) { _isK8sQueryTimeoutReported = true; _logger.LogError("Query Kubernetes Environment timeout."); } } } telemetry.Context.GetInternalContext().SdkVersion = _sdkVersionUtils.CurrentSDKVersion; } private async Task SetK8sEnvironment() { Task<IK8sEnvironment> createK8sEnvTask = _k8sEnvFactory.CreateAsync(_timeoutAt); await Task.WhenAny( createK8sEnvTask, Task.Delay(_timeoutAt - DateTime.Now)).ConfigureAwait(false); if(createK8sEnvTask.IsCompleted) { _k8sEnvironment = createK8sEnvTask.Result; } else { _isK8sQueryTimeout = true; _k8sEnvironment = null; } } private void SetCustomDimensions(ITelemetry telemetry) { // Adding pod name into custom dimension // Container SetCustomDimension(telemetry, Invariant($"{K8s}.{Container}.ID"), this._k8sEnvironment.ContainerID); SetCustomDimension(telemetry, Invariant($"{K8s}.{Container}.Name"), this._k8sEnvironment.ContainerName); // Pod SetCustomDimension(telemetry, Invariant($"{K8s}.{Pod}.ID"), this._k8sEnvironment.PodID); SetCustomDimension(telemetry, Invariant($"{K8s}.{Pod}.Name"), this._k8sEnvironment.PodName); SetCustomDimension(telemetry, Invariant($"{K8s}.{Pod}.Labels"), this._k8sEnvironment.PodLabels); // Replica Set SetCustomDimension(telemetry, Invariant($"{K8s}.{ReplicaSet}.Name"), this._k8sEnvironment.ReplicaSetName); // Deployment SetCustomDimension(telemetry, Invariant($"{K8s}.{Deployment}.Name"), this._k8sEnvironment.DeploymentName); // Ndoe SetCustomDimension(telemetry, Invariant($"{K8s}.{Node}.ID"), this._k8sEnvironment.NodeUid); SetCustomDimension(telemetry, Invariant($"{K8s}.{Node}.Name"), this._k8sEnvironment.NodeName); } #if NETSTANDARD2_0 private void SetCustomDimensions(ITelemetry telemetry, Stopwatch cpuWatch, TimeSpan startCPUTime) { SetCustomDimensions(telemetry); // Add CPU/Memory metrics to telemetry. Process process = Process.GetCurrentProcess(); TimeSpan endCPUTime = process.TotalProcessorTime; cpuWatch.Stop(); string cpuString = "NaN"; if (cpuWatch.ElapsedMilliseconds > 0) { int processorCount = Environment.ProcessorCount; Debug.Assert(processorCount > 0, $"How could process count be {processorCount}?"); // A very simple but not that accruate evaluation of how much CPU the process is take out of a core. double CPUPercentage = (endCPUTime - startCPUTime).TotalMilliseconds / (double)(cpuWatch.ElapsedMilliseconds); cpuString = CPUPercentage.ToString("P2", CultureInfo.InvariantCulture); } long memoryInBytes = process.VirtualMemorySize64; SetCustomDimension(telemetry, Invariant($"{ProcessString}.{CPU}(%)"), cpuString); SetCustomDimension(telemetry, Invariant($"{ProcessString}.{Memory}"), memoryInBytes.GetReadableSize()); } #endif private void SetCustomDimension(ITelemetry telemetry, string key, string value) { if (telemetry == null) { _logger.LogError("telemetry object is null in telememtry initializer."); return; } if (string.IsNullOrEmpty(key)) { _logger.LogError("Key is required to set custom dimension."); return; } if (string.IsNullOrEmpty(value)) { _logger.LogError(Invariant($"Value is required to set custom dimension. Key: {key}")); return; } if (!telemetry.Context.Properties.ContainsKey(key)) { telemetry.Context.Properties.Add(key, value); } else { string existingValue = telemetry.Context.Properties[key]; if (string.Equals(existingValue, value, System.StringComparison.OrdinalIgnoreCase)) { _logger.LogTrace(Invariant($"The telemetry already contains the property of {key} with the same value of {existingValue}.")); } else { telemetry.Context.Properties[key] = value; _logger.LogDebug(Invariant($"The telemetry already contains the property of {key} with value {existingValue}. The new value is: {value}")); } } } } }
39.231527
159
0.612255
[ "MIT" ]
AzureMentor/ApplicationInsights-Kubernetes
src/ApplicationInsights.Kubernetes/TelemetryInitializers/KubernetesTelemetryInitializer.cs
7,966
C#
using Elastic.Xunit.XunitPlumbing; using Nest; using System.ComponentModel; namespace Examples.Cat { public class DataframeanalyticsPage : ExampleBase { [U(Skip = "Example not implemented")] [Description("cat/dataframeanalytics.asciidoc:124")] public void Line124() { // tag::7c6f205c98da14c68d3d936639462dd3[] var response0 = new SearchResponse<object>(); // end::7c6f205c98da14c68d3d936639462dd3[] response0.MatchesExample(@"GET _cat/ml/data_frame/analytics?v"); } } }
24.85
67
0.746479
[ "Apache-2.0" ]
adamralph/elasticsearch-net
tests/Examples/Cat/DataframeanalyticsPage.cs
497
C#
// Copyright 2013-2015 Serilog Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #if FILE_IO using Serilog.Core; using Serilog.Events; namespace Serilog.Sinks.IOFile { /// <summary> /// An instance of this sink may be substituted when an instance of the /// <see cref="FileSink"/> is unable to be constructed. /// </summary> class NullSink : ILogEventSink { public void Emit(LogEvent logEvent) { } } } #endif
29
75
0.699797
[ "Apache-2.0" ]
johncrn/serilog
src/Serilog/Sinks/IOFile/NullSink.cs
988
C#
using FluentSpotify.API; using FluentSpotify.CLI; using FluentSpotify.Model; using FluentSpotify.Playback; using FluentSpotify.UI; using FluentSpotify.UI.Controller; using FluentSpotify.Util; using FluentSpotify.Web; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.ApplicationModel.Core; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Navigation; using MS = Microsoft.UI.Xaml.Controls; // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace FluentSpotify { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public static MainPage Current; public ElementTheme WindowsDefaultTheme; private readonly ThrottledExecution throttledExecution = new ThrottledExecution(TimeSpan.FromMilliseconds(1000)); private readonly IDictionary<string, Playlist> loadedPlaylists = new Dictionary<string, Playlist>(); private DeviceListController deviceListController; private string lastNav; private string lastTrack; private bool isMute; public MainPage() { this.InitializeComponent(); Current = this; WindowsDefaultTheme = RequestedTheme; switch (AppSettings.AppTheme) { case AppSettings.Theme.Light: RequestedTheme = ElementTheme.Light; break; case AppSettings.Theme.Dark: RequestedTheme = ElementTheme.Dark; break; } var titleBar = ApplicationView.GetForCurrentView().TitleBar; titleBar.ButtonBackgroundColor = Colors.Transparent; titleBar.ButtonInactiveBackgroundColor = Colors.Transparent; var coreTitleBar = CoreApplication.GetCurrentView().TitleBar; coreTitleBar.ExtendViewIntoTitleBar = true; deviceListController = new DeviceListController(this, DeviceFlyout); ContentFrame.Navigate(typeof(HomePage)); } protected async override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); if (e.Parameter is CmdOptions options) { if (string.IsNullOrEmpty(options.PlayerId)) return; Log.Info($"CMD specifies being attached to a player, transferring playback... playerId={options.PlayerId}"); await Spotify.Playback.TransferPlayback(options.PlayerId); } } private void AddPlaylist(Playlist playlist) { NavView.MenuItems.Add(new MS.NavigationViewItem { Content = playlist.Name, Icon = new SymbolIcon(Symbol.MusicInfo), Tag = "list-" + playlist.Id }); loadedPlaylists[playlist.Id] = playlist; } private void NavView_ItemInvoked(MS.NavigationView sender, MS.NavigationViewItemInvokedEventArgs args) { var tag = args.InvokedItemContainer.Tag as string; if (args.IsSettingsInvoked) tag = "settings"; if (tag == lastNav) return; if (tag.StartsWith("list-")) { var id = tag.Substring("list-".Length); var playlist = loadedPlaylists[id]; ContentFrame.Navigate(typeof(PlaylistPage), playlist, args.RecommendedNavigationTransitionInfo); } else if (tag == "settings") { ContentFrame.Navigate(typeof(SettingsPage)); } else if (tag == "home") { ContentFrame.Navigate(typeof(HomePage)); } else if (tag == "liked") { ContentFrame.Navigate(typeof(LibraryPage)); } lastNav = tag; } private async void Page_Loaded(object sender, RoutedEventArgs e) { Spotify.Initialize(); if (!Spotify.Auth.KeyStore.Authenticated) await new LoginDialog().ShowAsync(); var account = await Spotify.Account.GetAccount(); UserNameLabel.Text = account.DisplayName; UserImage.ProfilePicture = new BitmapImage() { UriSource = new Uri(account.ImageUrl, UriKind.Absolute), DecodePixelWidth = (int)Math.Floor(UserImage.Width), DecodePixelHeight = (int)Math.Floor(UserImage.Height) }; ; ; loadedPlaylists.Clear(); var playlists = await Spotify.Account.GetPlaylists(); foreach (var list in playlists) AddPlaylist(list); PlaybackContainer.Navigate(new Uri("ms-appx-web:///Assets/DrmContainer.html", UriKind.Absolute)); Spotify.Playback.PlaybackStateChanged += Playback_PlaybackStateChanged; Spotify.Playback.TrackPositionChanged += Playback_TrackPositionChanged; TimeSlider.ThumbToolTipValueConverter = new PercentageToTimeConverter(); Spotify.Playback.LocalPlayer = new LocalPlayer(PlaybackContainer); await deviceListController.ReloadDeviceList(); if (deviceListController.IsOtherDeviceActive()) { Spotify.Playback.CurrentPlayer = new RemotePlayer(deviceListController.GetCurrentlyActivePlayer()); await Spotify.Playback.CurrentPlayer.Initialize(); } else { Spotify.Playback.CurrentPlayer = Spotify.Playback.LocalPlayer; // Player will be initialized later } Log.Info("Data download and init complete"); } private void Playback_TrackPositionChanged(object sender, EventArgs e) { var player = Spotify.Playback.CurrentPlayer; _ = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { PlaybackFontIcon.Glyph = player.IsPlaying ? ((char)59241).ToString() : ((char)59240).ToString(); if (player.CurrentTrack == null) return; var pos = player.Position; var percentage = player.Position / player.CurrentTrack.Duration.TotalMilliseconds * 100; TimeSlider.Value = percentage; ElapsedTimeLabel.Text = TimeSpan.FromMilliseconds(pos).ToString(@"m\:ss"); }); } private void Playback_PlaybackStateChanged(object sender, EventArgs e) { var player = Spotify.Playback.CurrentPlayer; _ = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { if (player.IsPlaying && player.CurrentTrack?.Id != lastTrack) { SongLabel.Text = player.CurrentTrack.Name; ArtistLabel.Text = player.CurrentTrack.ArtistsString; TotalTimeLabel.Text = player.CurrentTrack.DurationString; var image = player.CurrentTrack.Images.FindByResolution(300); ThumbnailImage.Source = new BitmapImage() { UriSource = new Uri(image.Url, UriKind.Absolute), DecodePixelWidth = (int)Math.Floor(ThumbnailImage.Width), DecodePixelHeight = (int)Math.Floor(ThumbnailImage.Height) }; lastTrack = player.CurrentTrack.Id; } TimeSlider.IsEnabled = player.CurrentTrack != null; }); } private void SwitchThemeButton_Tapped(object sender, TappedRoutedEventArgs e) { if (RequestedTheme == ElementTheme.Light) { RequestedTheme = ElementTheme.Dark; AppSettings.AppTheme = AppSettings.Theme.Dark; } else { RequestedTheme = ElementTheme.Light; AppSettings.AppTheme = AppSettings.Theme.Light; } } private async void PlaybackContainer_DOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args) { await Spotify.Playback.LocalPlayer.Initialize(); } private async void PrevButton_Click(object sender, RoutedEventArgs e) { var player = Spotify.Playback.CurrentPlayer; if (player.Position > 3000) await player.Seek(0); else await player.Previous(); } private async void PlayPauseButton_Click(object sender, RoutedEventArgs e) { var player = Spotify.Playback.CurrentPlayer; await player.TogglePlayback(); } private async void NextButton_Click(object sender, RoutedEventArgs e) { var player = Spotify.Playback.CurrentPlayer; await player.Next(); } private void VolumeSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e) { var player = Spotify.Playback.CurrentPlayer; player?.SetVolume(e.NewValue / 100.0); MuteFontIcon.Glyph = ((char)59239).ToString(); isMute = false; } private void PlaybackContainer_ScriptNotify(object sender, NotifyEventArgs e) { var val = JObject.Parse(e.Value); Spotify.Playback.LocalPlayer.HandleEvent(val); } private void SearchBox_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args) { var player = Spotify.Playback.CurrentPlayer; if (args.ChosenSuggestion != null) { var track = args.ChosenSuggestion as Track; player.PlayTrack(track); } else { var query = args.QueryText; } } private void SearchBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args) { if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput) { var query = sender.Text; if (query.Length < 3) { sender.ItemsSource = null; return; } throttledExecution.Run(async () => { var results = await Spotify.Search.Search(query, 5); sender.ItemsSource = results; }); } } private void SearchBox_SuggestionChosen(AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args) { } private void TimeSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e) { // TODO: Only update if changed by user /*var player = Spotify.Playback.CurrentPlayer; if (ignoreNextSeek) { ignoreNextSeek = false; return; } var ms = player.CurrentTrack.Duration.TotalMilliseconds * (e.NewValue / 100.0); await player.Seek((int)ms);*/ } private async void MuteButton_Click(object sender, RoutedEventArgs e) { var player = Spotify.Playback.CurrentPlayer; if (isMute) { player?.SetVolume(VolumeSlider.Value / 100.0); MuteFontIcon.Glyph = ((char)59239).ToString(); } else { MuteFontIcon.Glyph = ((char)59215).ToString(); await player.SetVolume(0); } isMute = !isMute; } private async void RepeatButton_CheckedChanged(object sender, RoutedEventArgs e) { var b = RepeatButton.IsChecked; var player = Spotify.Playback.CurrentPlayer; if (b.HasValue) { if (b.Value) await player.SetRepeat(RepeatMode.Context); else await player.SetRepeat(RepeatMode.Off); RepeatFontIcon.Glyph = ((char)59630).ToString(); } else { await player.SetRepeat(RepeatMode.Track); RepeatFontIcon.Glyph = ((char)59629).ToString(); } } private async void ShuffleButton_CheckedChanged(object sender, RoutedEventArgs e) { var player = Spotify.Playback.CurrentPlayer; if (ShuffleButton.IsChecked.Value) { await player.SetShuffle(true); } else { await player.SetShuffle(false); } } private void ScrollViewer_ViewChanging(object sender, ScrollViewerViewChangingEventArgs e) { if (ContentFrame.Content is IScrollNotify notify) notify.OnScroll(e.NextView.VerticalOffset, ScrollViewer.ExtentHeight - ScrollViewer.ViewportHeight); } private void UserPanel_PointerEntered(object sender, PointerRoutedEventArgs e) { UserPanel.Background = Resources["SystemChromeLowColor"] as Brush; } private void UserPanel_PointerExited(object sender, PointerRoutedEventArgs e) { UserPanel.Background = new SolidColorBrush(Colors.Transparent); } } }
35.311392
233
0.592558
[ "Apache-2.0" ]
Twometer/FluentSpotify
FluentSpotify/MainPage.xaml.cs
13,950
C#
using System.Collections.Generic; [System.Serializable] public class GameData { public int currentLvl; public List<float> timeList = new List<float>(); public GameData(GameControl gameData) { currentLvl = gameData.currentLvl; timeList = gameData.timeList; } }
19.933333
52
0.685619
[ "MIT" ]
Nordicebear-Games/draw-car-and-race
Draw Car and Race/Assets/Scripts/Save System/GameData.cs
301
C#
//------------------------------------------------------------------------------ // Symbooglix // // // Copyright 2014-2017 Daniel Liew // // This file is licensed under the MIT license. // See LICENSE.txt for details. //------------------------------------------------------------------------------ using System; namespace Symbooglix { namespace Util { public interface IYAMLWriter { void WriteAsYAML(System.CodeDom.Compiler.IndentedTextWriter TW); } } }
23.434783
80
0.410019
[ "MIT" ]
boogie-org/symbooglix
src/Symbooglix/Util/IYAMLWriter.cs
539
C#
namespace CineMagic.Services.GetDataFromTMDB.DTOs { using Newtonsoft.Json; public class BackdropDTO { [JsonProperty("file_path")] public string FilePath { get; set; } [JsonProperty("iso_639_1")] public string ISO { get; set; } } }
20.142857
50
0.620567
[ "MIT" ]
sevginmustafa/CineMagic
CineMagic/Services/CineMagic.Services/GetDataFromTMDB/DTOs/BackdropDTO.cs
284
C#
using ICSharpCode.CodeConverter; using ICSharpCode.CodeConverter.Shared; using ICSharpCode.CodeConverter.VB; using Microsoft.CodeAnalysis; using Xunit; namespace CodeConverter.Tests.VB { public class StatementTests : ConverterTestBase { [Fact] public void EmptyStatement() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { if (true) ; while (true) ; for (;;) ; do ; while (true); ; } }", @"Friend Class TestClass Private Sub TestMethod() If True Then End If While True End While While True End While Do Loop While True End Sub End Class"); } [Fact] public void AssignmentStatement() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { int b; b = 0; } }", @"Friend Class TestClass Private Sub TestMethod() Dim b As Integer b = 0 End Sub End Class"); } [Fact] public void AssignmentStatementInDeclaration() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { int b = 0; } }", @"Friend Class TestClass Private Sub TestMethod() Dim b As Integer = 0 End Sub End Class"); } [Fact] public void AssignmentStatementInVarDeclaration() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { var b = 0; } }", @"Friend Class TestClass Private Sub TestMethod() Dim b = 0 End Sub End Class"); } [Fact] public void ObjectInitializationStatement() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { string b; b = new string(""test""); } }", @"Friend Class TestClass Private Sub TestMethod() Dim b As String b = New String(""test"") End Sub End Class"); } [Fact] public void ObjectInitializationStatementInDeclaration() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { string b = new string(""test""); } }", @"Friend Class TestClass Private Sub TestMethod() Dim b As String = New String(""test"") End Sub End Class"); } [Fact] public void ObjectInitializationStatementInVarDeclaration() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { var b = new string(""test""); } }", @"Friend Class TestClass Private Sub TestMethod() Dim b = New String(""test"") End Sub End Class"); } [Fact] public void ArrayDeclarationStatement() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { int[] b; } }", @"Friend Class TestClass Private Sub TestMethod() Dim b As Integer() End Sub End Class"); } [Fact] public void ArrayInitializationStatement() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { int[] b = { 1, 2, 3 }; } }", @"Friend Class TestClass Private Sub TestMethod() Dim b As Integer() = {1, 2, 3} End Sub End Class"); } [Fact] public void ArrayInitializationStatementInVarDeclaration() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { var b = { 1, 2, 3 }; } }", @"Friend Class TestClass Private Sub TestMethod() Dim b = {1, 2, 3} End Sub End Class"); } [Fact] public void ArrayInitializationStatementWithType() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { int[] b = new int[] { 1, 2, 3 }; } }", @"Friend Class TestClass Private Sub TestMethod() Dim b As Integer() = New Integer() {1, 2, 3} End Sub End Class"); } [Fact] public void ArrayInitializationStatementWithLength() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { int[] b = new int[3] { 1, 2, 3 }; } }", @"Friend Class TestClass Private Sub TestMethod() Dim b As Integer() = New Integer(2) {1, 2, 3} End Sub End Class"); } [Fact] public void MultidimensionalArrayDeclarationStatement() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { int[,] b; } }", @"Friend Class TestClass Private Sub TestMethod() Dim b As Integer(,) End Sub End Class"); } [Fact] public void MultidimensionalArrayInitializationStatement() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { int[,] b = { {1, 2}, {3, 4} }; } }", @"Friend Class TestClass Private Sub TestMethod() Dim b As Integer(,) = { {1, 2}, {3, 4}} End Sub End Class"); } [Fact] public void MultidimensionalArrayInitializationStatementWithType() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { int[,] b = new int[,] { {1, 2}, {3, 4} }; } }", @"Friend Class TestClass Private Sub TestMethod() Dim b As Integer(,) = New Integer(,) { {1, 2}, {3, 4}} End Sub End Class"); } [Fact] public void MultidimensionalArrayInitializationStatementWithLengths() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { int[,] b = new int[2, 2] { {1, 2}, {3, 4} } } }", @"Friend Class TestClass Private Sub TestMethod() Dim b As Integer(,) = New Integer(1, 1) { {1, 2}, {3, 4}} End Sub End Class"); } [Fact] public void JaggedArrayDeclarationStatement() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { int[][] b; } }", @"Friend Class TestClass Private Sub TestMethod() Dim b As Integer()() End Sub End Class"); } [Fact] public void JaggedArrayInitializationStatement() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { int[][] b = { new int[] { 1, 2 }, new int[] { 3, 4 } }; } }", @"Friend Class TestClass Private Sub TestMethod() Dim b As Integer()() = {New Integer() {1, 2}, New Integer() {3, 4}} End Sub End Class"); } [Fact] public void JaggedArrayInitializationStatementWithType() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { int[][] b = new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 } }; } }", @"Friend Class TestClass Private Sub TestMethod() Dim b As Integer()() = New Integer()() {New Integer() {1, 2}, New Integer() {3, 4}} End Sub End Class"); } [Fact] public void JaggedArrayInitializationStatementWithLength() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { int[][] b = new int[2][] { new int[] { 1, 2 }, new int[] { 3, 4 } }; } }", @"Friend Class TestClass Private Sub TestMethod() Dim b As Integer()() = New Integer(1)() {New Integer() {1, 2}, New Integer() {3, 4}} End Sub End Class"); } [Fact] public void DeclarationStatements() { TestConversionCSharpToVisualBasic( @"class Test { void TestMethod() { the_beginning: int value = 1; const double myPIe = System.Math.PI; var text = ""This is my text!""; goto the_beginning; } }", @"Friend Class Test Private Sub TestMethod() the_beginning: Dim value As Integer = 1 Const myPIe As Double = System.Math.PI Dim text = ""This is my text!"" GoTo the_beginning End Sub End Class"); } [Fact] public void IfStatementWithoutBlock() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod (int a) { int b; if (a == 0) b = 0; else b = 3; } }", @"Friend Class TestClass Private Sub TestMethod(ByVal a As Integer) Dim b As Integer If a = 0 Then b = 0 Else b = 3 End If End Sub End Class"); } [Fact] public void IfStatement() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod (int a) { int b; if (a == 0) { b = 0; } else if (a == 1) { b = 1; } else if (a == 2 || a == 3) { b = 2; } else { b = 3; } } }", @"Friend Class TestClass Private Sub TestMethod(ByVal a As Integer) Dim b As Integer If a = 0 Then b = 0 ElseIf a = 1 Then b = 1 ElseIf a = 2 OrElse a = 3 Then b = 2 Else b = 3 End If End Sub End Class"); } [Fact] public void BlockStatement() { TestConversionCSharpToVisualBasic(@"class TestClass { public static void TestMethod() { { var x = 1; Console.WriteLine(x); } { var x = 2; Console.WriteLine(x); } } }", @"Friend Class TestClass Public Shared Sub TestMethod() If True Then Dim x = 1 Console.WriteLine(x) End If If True Then Dim x = 2 Console.WriteLine(x) End If End Sub End Class"); } [Fact] public void WhileStatement() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { int b; b = 0; while (b == 0) { if (b == 2) continue; if (b == 3) break; b = 1; } } }", @"Friend Class TestClass Private Sub TestMethod() Dim b As Integer b = 0 While b = 0 If b = 2 Then Continue While If b = 3 Then Exit While b = 1 End While End Sub End Class"); } [Fact] public void UnsafeStatements() { var convertedCode = ProjectConversion.ConvertText<CSToVBConversion>(@"class TestClass { void TestMethod() { int b; b = 0; while (b == 0) { if (b == 2) { unsafe { int ab = 32; int* p = &ab; Console.WriteLine(""value of ab is {0}"", *p); } } if (b == 3) break; b = 1; } } }", CodeWithOptions.DefaultMetadataReferences).ConvertedCode; Assert.Contains("CONVERSION ERROR", convertedCode); Assert.Contains("unsafe", convertedCode); Assert.Contains("UnsafeStatementSyntax", convertedCode); Assert.Contains("If b = 2 Then", convertedCode); Assert.Contains("End If", convertedCode); } [Fact] public void DoWhileStatement() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { int b; b = 0; do { if (b == 2) continue; if (b == 3) break; b = 1; } while (b == 0); } }", @"Friend Class TestClass Private Sub TestMethod() Dim b As Integer b = 0 Do If b = 2 Then Continue Do If b = 3 Then Exit Do b = 1 Loop While b = 0 End Sub End Class"); } [Fact] public void ForEachStatementWithExplicitType() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod(int[] values) { foreach (int val in values) { if (val == 2) continue; if (val == 3) break; } } }", @"Friend Class TestClass Private Sub TestMethod(ByVal values As Integer()) For Each val As Integer In values If val = 2 Then Continue For If val = 3 Then Exit For Next End Sub End Class"); } [Fact] public void ForEachStatementWithVar() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod(int[] values) { foreach (var val in values) { if (val == 2) continue; if (val == 3) break; } } }", @"Friend Class TestClass Private Sub TestMethod(ByVal values As Integer()) For Each val In values If val = 2 Then Continue For If val = 3 Then Exit For Next End Sub End Class"); } [Fact] public void SyncLockStatement() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod(object nullObject) { if (nullObject == null) throw new ArgumentNullException(nameof(nullObject)); lock (nullObject) { Console.WriteLine(nullObject); } } }", @"Friend Class TestClass Private Sub TestMethod(ByVal nullObject As Object) If nullObject Is Nothing Then Throw New ArgumentNullException(NameOf(nullObject)) SyncLock nullObject Console.WriteLine(nullObject) End SyncLock End Sub End Class"); } [Fact] public void ForWithUnknownConditionAndSingleStatement() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { for (i = 0; unknownCondition; i++) b[i] = s[i]; } }", @"Friend Class TestClass Private Sub TestMethod() i = 0 While unknownCondition b(i) = s(i) i += 1 End While End Sub End Class"); } [Fact] public void ForWithUnknownConditionAndBlock() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { for (int i = 0; unknownCondition; i++) { b[i] = s[i]; } } }", @"Friend Class TestClass Private Sub TestMethod() Dim i As Integer = 0 While unknownCondition b(i) = s(i) i += 1 End While End Sub End Class"); } [Fact] public void ForWithSingleStatement() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { for (i = 0; i < end; i++) b[i] = s[i]; } }", @"Friend Class TestClass Private Sub TestMethod() For i = 0 To [end] - 1 b(i) = s(i) Next End Sub End Class"); } [Fact] public void ForWithBlock() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod() { for (i = 0; i < end; i++) { b[i] = s[i]; } } }", @"Friend Class TestClass Private Sub TestMethod() For i = 0 To [end] - 1 b(i) = s(i) Next End Sub End Class"); } [Fact] public void LabeledAndForStatement() { TestConversionCSharpToVisualBasic(@"class GotoTest1 { static void Main() { int x = 200, y = 4; int count = 0; string[,] array = new string[x, y]; for (int i = 0; i < x; i++) for (int j = 0; j < y; j++) array[i, j] = (++count).ToString(); Console.Write(""Enter the number to search for: ""); string myNumber = Console.ReadLine(); for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { if (array[i, j].Equals(myNumber)) { goto Found; } } } Console.WriteLine(""The number {0} was not found."", myNumber); goto Finish; Found: Console.WriteLine(""The number {0} is found."", myNumber); Finish: Console.WriteLine(""End of search.""); Console.WriteLine(""Press any key to exit.""); Console.ReadKey(); } }", @"Friend Class GotoTest1 Private Shared Sub Main() Dim x As Integer = 200, y As Integer = 4 Dim count As Integer = 0 Dim array As String(,) = New String(x - 1, y - 1) {} For i As Integer = 0 To x - 1 For j As Integer = 0 To y - 1 array(i, j) = (System.Threading.Interlocked.Increment(count)).ToString() Next Next Console.Write(""Enter the number to search for: "") Dim myNumber As String = Console.ReadLine() For i As Integer = 0 To x - 1 For j As Integer = 0 To y - 1 If array(i, j).Equals(myNumber) Then GoTo Found End If Next Next Console.WriteLine(""The number {0} was not found."", myNumber) GoTo Finish Found: Console.WriteLine(""The number {0} is found."", myNumber) Finish: Console.WriteLine(""End of search."") Console.WriteLine(""Press any key to exit."") Console.ReadKey() End Sub End Class"); } [Fact] public void ThrowStatement() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod(object nullObject) { if (nullObject == null) throw new ArgumentNullException(nameof(nullObject)); } }", @"Friend Class TestClass Private Sub TestMethod(ByVal nullObject As Object) If nullObject Is Nothing Then Throw New ArgumentNullException(NameOf(nullObject)) End Sub End Class"); } [Fact] public void AddRemoveHandler() { TestConversionCSharpToVisualBasic(@"using System; class TestClass { public event EventHandler MyEvent; void TestMethod(EventHandler e) { this.MyEvent += e; this.MyEvent += MyHandler; } void TestMethod2(EventHandler e) { this.MyEvent -= e; this.MyEvent -= MyHandler; } void MyHandler(object sender, EventArgs e) { } }", @"Imports System Friend Class TestClass Public Event MyEvent As EventHandler Private Sub TestMethod(ByVal e As EventHandler) AddHandler Me.MyEvent, e AddHandler Me.MyEvent, AddressOf MyHandler End Sub Private Sub TestMethod2(ByVal e As EventHandler) RemoveHandler Me.MyEvent, e RemoveHandler Me.MyEvent, AddressOf MyHandler End Sub Private Sub MyHandler(ByVal sender As Object, ByVal e As EventArgs) End Sub End Class"); } [Fact] public void SelectCase1() { TestConversionCSharpToVisualBasic(@"class TestClass { void TestMethod(int number) { switch (number) { case 0: case 1: case 2: Console.Write(""number is 0, 1, 2""); break; case 3: Console.Write(""section 3""); goto case 5; case 4: Console.Write(""section 4""); goto default; default: Console.Write(""default section""); break; case 5: Console.Write(""section 5""); break; } } }", @"Friend Class TestClass Private Sub TestMethod(ByVal number As Integer) Select Case number Case 0, 1, 2 Console.Write(""number is 0, 1, 2"") Case 3 Console.Write(""section 3"") GoTo _Select0_Case5 Case 4 Console.Write(""section 4"") GoTo _Select0_CaseDefault Case 5 _Select0_Case5: Console.Write(""section 5"") Case Else _Select0_CaseDefault: Console.Write(""default section"") End Select End Sub End Class"); } [Fact] public void TryCatch() { TestConversionCSharpToVisualBasic(@"class TestClass { static bool Log(string message) { Console.WriteLine(message); return false; } void TestMethod(int number) { try { Console.WriteLine(""try""); } catch (Exception e) { Console.WriteLine(""catch1""); } catch { Console.WriteLine(""catch all""); } finally { Console.WriteLine(""finally""); } try { Console.WriteLine(""try""); } catch (System.IO.IOException) { Console.WriteLine(""catch1""); } catch (Exception e) when (Log(e.Message)) { Console.WriteLine(""catch2""); } try { Console.WriteLine(""try""); } finally { Console.WriteLine(""finally""); } } }", @"Friend Class TestClass Private Shared Function Log(ByVal message As String) As Boolean Console.WriteLine(message) Return False End Function Private Sub TestMethod(ByVal number As Integer) Try Console.WriteLine(""try"") Catch e As Exception Console.WriteLine(""catch1"") Catch Console.WriteLine(""catch all"") Finally Console.WriteLine(""finally"") End Try Try Console.WriteLine(""try"") Catch __unusedIOException1__ As System.IO.IOException Console.WriteLine(""catch1"") Catch e As Exception When Log(e.Message) Console.WriteLine(""catch2"") End Try Try Console.WriteLine(""try"") Finally Console.WriteLine(""finally"") End Try End Sub End Class"); } [Fact] public void Yield() { TestConversionCSharpToVisualBasic(@"class TestClass { IEnumerable<int> TestMethod(int number) { if (number < 0) yield break; for (int i = 0; i < number; i++) yield return i; } }", @"Friend Class TestClass Private Iterator Function TestMethod(ByVal number As Integer) As IEnumerable(Of Integer) If number < 0 Then Return For i As Integer = 0 To number - 1 Yield i Next End Function End Class"); } } }
22.957926
97
0.509611
[ "MIT" ]
CoderNate/CodeConverter
Tests/VB/StatementTests.cs
23,465
C#
// Tree.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2009-October-28 13:29:50> // // ------------------------------------------------------------------ // // This module defines classes for zlib compression and // decompression. This code is derived from the jzlib implementation of // zlib. In keeping with the license for jzlib, the copyright to that // code is below. // // ------------------------------------------------------------------ // // Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the distribution. // // 3. The names of the authors may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, // INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // ----------------------------------------------------------------------- // // This program is based on zlib-1.1.3; credit to authors // Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) // and contributors of zlib. // // ----------------------------------------------------------------------- using System; namespace BnSDat.Zlib { internal sealed partial class DeflateManager { #region Nested type: Tree private sealed class Tree { internal const int Buf_size = 8 * 2; private static readonly int HEAP_SIZE = (2 * InternalConstants.L_CODES + 1); internal static readonly sbyte[] bl_order = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; // The lengths of the bit length codes are sent in order of decreasing // probability, to avoid transmitting the lengths for unused bit // length codes. // see definition of array dist_code below //internal const int DIST_CODE_LEN = 512; private static readonly sbyte[] _dist_code = { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 }; internal static readonly sbyte[] LengthCode = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15 , 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17 , 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19 , 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20 , 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21 , 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22 , 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23 , 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24 , 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24 , 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25 , 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25 , 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26 , 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26 , 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27 , 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27 , 27, 28 }; internal static readonly int[] LengthBase = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0 }; internal static readonly int[] DistanceBase = { 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144 , 8192, 12288, 16384, 24576 }; internal short[] dyn_tree; // the dynamic tree internal int max_code; // largest code with non zero frequency internal StaticTree staticTree; // the corresponding static tree /// <summary> /// Map from a distance to a distance code. /// </summary> /// <remarks> /// No side effects. _dist_code[256] and _dist_code[257] are never used. /// </remarks> internal static int DistanceCode(int dist) { return (dist < 256) ? _dist_code[dist] : _dist_code[256 + SharedUtils.URShift(dist, 7)]; } // Compute the optimal bit lengths for a tree and update the total bit length // for the current block. // IN assertion: the fields freq and dad are set, heap[heap_max] and // above are the tree nodes sorted by increasing frequency. // OUT assertions: the field len is set to the optimal bit length, the // array bl_count contains the frequencies for each bit length. // The length opt_len is updated; static_len is also updated if stree is // not null. internal void gen_bitlen(DeflateManager s) { short[] tree = dyn_tree; short[] stree = staticTree.treeCodes; int[] extra = staticTree.extraBits; int base_Renamed = staticTree.extraBase; int max_length = staticTree.maxLength; int h; // heap index int n, m; // iterate over the tree elements int bits; // bit length int xbits; // extra bits short f; // frequency int overflow = 0; // number of elements with bit length too large for (bits = 0; bits <= InternalConstants.MAX_BITS; bits++) { s.bl_count[bits] = 0; } // In a first pass, compute the optimal bit lengths (which may // overflow in the case of the bit length tree). tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n * 2 + 1] * 2 + 1] + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n * 2 + 1] = (short)bits; // We overwrite tree[n*2+1] which is no longer needed if (n > max_code) { continue; // not a leaf node } s.bl_count[bits]++; xbits = 0; if (n >= base_Renamed) { xbits = extra[n - base_Renamed]; } f = tree[n * 2]; s.opt_len += f * (bits + xbits); if (stree != null) { s.static_len += f * (stree[n * 2 + 1] + xbits); } } if (overflow == 0) { return; } // This happens for example on obj2 and pic of the Calgary corpus // Find the first bit length which could increase: do { bits = max_length - 1; while (s.bl_count[bits] == 0) { bits--; } s.bl_count[bits]--; // move one leaf down the tree s.bl_count[bits + 1] = (short)(s.bl_count[bits + 1] + 2); // move one overflow item as its brother s.bl_count[max_length]--; // The brother of the overflow item also moves one step up, // but this does not affect bl_count[max_length] overflow -= 2; } while (overflow > 0); for (bits = max_length; bits != 0; bits--) { n = s.bl_count[bits]; while (n != 0) { m = s.heap[--h]; if (m > max_code) { continue; } if (tree[m * 2 + 1] != bits) { s.opt_len = (int)(s.opt_len + (bits - (long)tree[m * 2 + 1]) * tree[m * 2]); tree[m * 2 + 1] = (short)bits; } n--; } } } // Construct one Huffman tree and assigns the code bit strings and lengths. // Update the total bit length for the current block. // IN assertion: the field freq is set for all tree elements. // OUT assertions: the fields len and code are set to the optimal bit length // and corresponding code. The length opt_len is updated; static_len is // also updated if stree is not null. The field max_code is set. internal void build_tree(DeflateManager s) { short[] tree = dyn_tree; short[] stree = staticTree.treeCodes; int elems = staticTree.elems; int n, m; // iterate over heap elements int max_code = -1; // largest code with non zero frequency int node; // new node being created // Construct the initial heap, with least frequent element in // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. // heap[0] is not used. s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2] != 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n * 2 + 1] = 0; } } // The pkzip format requires that at least one distance code exists, // and that at least one bit should be sent even if there is only one // possible code. So to avoid special checks later on we force at least // two codes of non zero frequency. while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); tree[node * 2] = 1; s.depth[node] = 0; s.opt_len--; if (stree != null) { s.static_len -= stree[node * 2 + 1]; } // node is 0 or 1 so it does not have extra bits } this.max_code = max_code; // The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, // establish sub-heaps of increasing lengths: for (n = s.heap_len / 2; n >= 1; n--) { s.pqdownheap(tree, n); } // Construct the Huffman tree by repeatedly combining the least two // frequent nodes. node = elems; // next internal node of the tree do { // n = node of least frequency n = s.heap[1]; s.heap[1] = s.heap[s.heap_len--]; s.pqdownheap(tree, 1); m = s.heap[1]; // m = node of next least frequency s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency s.heap[--s.heap_max] = m; // Create a new node father of n and m tree[node * 2] = unchecked((short)(tree[n * 2] + tree[m * 2])); s.depth[node] = (sbyte)(Math.Max((byte)s.depth[n], (byte)s.depth[m]) + 1); tree[n * 2 + 1] = tree[m * 2 + 1] = (short)node; // and insert the new node in the heap s.heap[1] = node++; s.pqdownheap(tree, 1); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1]; // At this point, the fields freq and dad are set. We can now // generate the bit lengths. gen_bitlen(s); // The field len is now set, we can generate the bit codes gen_codes(tree, max_code, s.bl_count); } // Generate the codes for a given tree and bit counts (which need not be // optimal). // IN assertion: the array bl_count contains the bit length statistics for // the given tree and the field len is set for all tree elements. // OUT assertion: the field code is set for all tree elements of non // zero code length. internal static void gen_codes(short[] tree, int max_code, short[] bl_count) { var next_code = new short[InternalConstants.MAX_BITS + 1]; // next code value for each bit length short code = 0; // running code value int bits; // bit index int n; // code index // The distribution counts are first used to generate the code values // without bit reversal. for (bits = 1; bits <= InternalConstants.MAX_BITS; bits++) { unchecked { next_code[bits] = code = (short)((code + bl_count[bits - 1]) << 1); } } // Check that the bit counts in bl_count are consistent. The last code // must be all ones. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { int len = tree[n * 2 + 1]; if (len == 0) { continue; } // Now reverse the bits tree[n * 2] = unchecked((short)(bi_reverse(next_code[len]++, len))); } } // Reverse the first len bits of a code, using straightforward code (a faster // method would use a table) // IN assertion: 1 <= len <= 15 internal static int bi_reverse(int code, int len) { int res = 0; do { res |= code & 1; code >>= 1; //SharedUtils.URShift(code, 1); res <<= 1; } while (--len > 0); return res >> 1; } } #endregion } }
41.936345
118
0.432062
[ "MIT" ]
Leayal/BnS-Tools
BnS-Dat/Zlib/Tree.cs
20,425
C#
using System; using Android.App; using Android.Content.PM; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Plugin.CurrentActivity; namespace FoodHub.Droid { [Activity(Label = "FoodHub", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle savedInstanceState) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; CrossCurrentActivity.Current.Init(this, savedInstanceState); // Adding this one to allow permission for retrieving images in phone base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); LoadApplication(new App()); } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults) { Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults); Plugin.Permissions.PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults); // Adding this one to allow permission for retrieving images in phone base.OnRequestPermissionsResult(requestCode, permissions, grantResults); } } }
49.636364
202
0.733822
[ "Apache-2.0" ]
HectorTran97/FoodHub-App
FoodHub/FoodHub.Android/MainActivity.cs
1,640
C#
using Microsoft.Bot.Solutions.Resources; namespace Microsoft.Bot.Solutions.Util { public class CommonUtil { public const double ScoreThreshold = 0.5f; public const int MaxReadSize = 3; public const int MaxDisplaySize = 6; public const string DialogTurnResultCancelAllDialogs = "cancelAllDialogs"; } }
21.875
82
0.697143
[ "MIT" ]
AllcryptoquickDevelopment/AI
solutions/Virtual-Assistant/src/csharp/microsoft.bot.solutions/Util/CommonUtil.cs
352
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using BrokerageApi.V1.Gateways; using BrokerageApi.V1.Infrastructure; using FluentAssertions; using FluentAssertions.Extensions; using NUnit.Framework; namespace BrokerageApi.Tests.V1.Gateways { [TestFixture] public class ElementTypeGatewayTests : DatabaseTests { private ElementTypeGateway _classUnderTest; [SetUp] public void Setup() { _classUnderTest = new ElementTypeGateway(BrokerageContext); } [Test] public async Task GetsElementTypeById() { // Arrange var service = new Service { Id = 1, Name = "Supported Living", Position = 1, IsArchived = false, }; var elementType = new ElementType { Id = 1, ServiceId = 1, Name = "Day Opportunities (daily)", CostType = ElementCostType.Daily, NonPersonalBudget = false, IsArchived = false }; await BrokerageContext.Services.AddAsync(service); await BrokerageContext.ElementTypes.AddAsync(elementType); await BrokerageContext.SaveChangesAsync(); // Act var result = await _classUnderTest.GetByIdAsync(elementType.Id); // Assert result.Should().BeEquivalentTo(elementType); } } }
26.964912
76
0.570592
[ "MIT" ]
LBHackney-IT/lbh-asc-brokerage-api
BrokerageApi.Tests/V1/Gateways/ElementTypeGatewayTests.cs
1,537
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Xml.XPath; namespace MS.Internal.Xml.XPath { internal class ForwardPositionQuery : CacheOutputQuery { public ForwardPositionQuery(Query input) : base(input) { Debug.Assert(input != null); } protected ForwardPositionQuery(ForwardPositionQuery other) : base(other) { } public override object Evaluate(XPathNodeIterator context) { base.Evaluate(context); XPathNavigator node; while ((node = base.input.Advance()) != null) { outputBuffer.Add(node.Clone()); } return this; } public override XPathNavigator MatchNode(XPathNavigator context) { return input.MatchNode(context); } public override XPathNodeIterator Clone() { return new ForwardPositionQuery(this); } } }
25.613636
92
0.627329
[ "MIT" ]
2E0PGS/corefx
src/System.Private.Xml/src/System/Xml/XPath/Internal/ForwardPositionQuery.cs
1,127
C#
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.CommandLine; using System.CommandLine.Invocation; using System.Threading.Tasks; using FluentAssertions; using Microsoft.DotNet.Interactive.Telemetry; using Microsoft.Extensions.DependencyInjection; using MLS.Agent.CommandLine; using Xunit; using Xunit.Abstractions; namespace MLS.Agent.Tests.CommandLine { public class TelemetryTests : IDisposable { private readonly FakeTelemetry _fakeTelemetry; private readonly ITestOutputHelper _output; private readonly TestConsole _console = new TestConsole(); private readonly Parser _parser; public TelemetryTests(ITestOutputHelper output) { _fakeTelemetry = new FakeTelemetry(); _output = output; _parser = CommandLineParser.Create(new ServiceCollection(), startServer: (options, invocationContext) => { }, demo: (options, console, context, startOptions) => { return Task.CompletedTask; }, tryGithub: (options, c) => { return Task.CompletedTask; }, pack: (options, console) => { return Task.CompletedTask; }, verify: (options, console, startupOptions) => { return Task.FromResult(1); }, telemetry: _fakeTelemetry, firstTimeUseNoticeSentinel: new NopFirstTimeUseNoticeSentinel()); } public void Dispose() { _output.WriteLine(_console.Error.ToString()); } [Fact] public async Task Hosted_is_does_not_send_any_telemetry() { await _parser.InvokeAsync("hosted", _console); _fakeTelemetry.LogEntries.Should().BeEmpty(); } [Fact] public async Task Invalid_command_is_does_not_send_any_telemetry() { await _parser.InvokeAsync("invalidcommand", _console); _fakeTelemetry.LogEntries.Should().BeEmpty(); } [Fact] public async Task Show_first_time_message_if_environment_variable_is_not_set() { var environmentVariableName = FirstTimeUseNoticeSentinel.SkipFirstTimeExperienceEnvironmentVariableName; var currentState = Environment.GetEnvironmentVariable(environmentVariableName); Environment.SetEnvironmentVariable(environmentVariableName, null); try { await _parser.InvokeAsync(String.Empty, _console); _console.Out.ToString().Should().Contain(Telemetry.WelcomeMessage); } finally { Environment.SetEnvironmentVariable(environmentVariableName, currentState); } } [Fact] public async Task Do_not_show_first_time_message_if_environment_variable_is_set() { var environmentVariableName = FirstTimeUseNoticeSentinel.SkipFirstTimeExperienceEnvironmentVariableName; var currentState = Environment.GetEnvironmentVariable(environmentVariableName); Environment.SetEnvironmentVariable(environmentVariableName, null); Environment.SetEnvironmentVariable(environmentVariableName, "1"); try { await _parser.InvokeAsync(String.Empty, _console); _console.Out.ToString().Should().NotContain(Telemetry.WelcomeMessage); } finally { Environment.SetEnvironmentVariable(environmentVariableName, currentState); } } } }
41.483871
129
0.626231
[ "MIT" ]
Aroo2016/try
MLS.Agent.Tests/CommandLine/TelemetryTests.cs
3,860
C#
using System; // Declare an integer variable and assign it with the value 254 in hexadecimal format (0x##). // Use Windows Calculator to find its hexadecimal representation // Print the variable and ensure that the result is 254. class Program { static void Main() { int hexVar = 0xFE; //binary - 1111 1110 //hexadecimal - F E Console.WriteLine("Decimal value of hexadecimal number FE is: {0}", hexVar); } }
27.235294
93
0.654428
[ "MIT" ]
ReniGetskova/CSharp-Part-1
PrimitiveDataTypesAndVariables/03VariableInHexadecimalFormat/HexadecimalNumber.cs
465
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.KinesisAnalyticsV2.Outputs { [OutputType] public sealed class ApplicationApplicationConfigurationSqlApplicationConfigurationReferenceDataSourceReferenceSchemaRecordFormatMappingParametersJsonMappingParameters { /// <summary> /// The path to the top-level parent that contains the records. /// </summary> public readonly string RecordRowPath; [OutputConstructor] private ApplicationApplicationConfigurationSqlApplicationConfigurationReferenceDataSourceReferenceSchemaRecordFormatMappingParametersJsonMappingParameters(string recordRowPath) { RecordRowPath = recordRowPath; } } }
36
184
0.756944
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/KinesisAnalyticsV2/Outputs/ApplicationApplicationConfigurationSqlApplicationConfigurationReferenceDataSourceReferenceSchemaRecordFormatMappingParametersJsonMappingParameters.cs
1,008
C#
using System.Collections; using UnityEngine; using UnityEngine.UI; public class WaveManager : MonoBehaviour { public float initialHealth; public float waveTimer; public float spawnInterval; public float spawnIntervalDecreaseBy; public float enemyHealthIncreaseBy; public GameObject circleEnemy; public GameObject squareEnemy; public GameObject wavesTextObject; public int maxWaves; public int enemiesToSpawn; private bool gameOver; private float healthIncreaseBy; private int enemiesSpawned; private int waveNumber; private int counter; // Use this for initialization void Start() { SetInitialDifficulty(); healthIncreaseBy = enemyHealthIncreaseBy; counter = 2; waveNumber = 1; gameOver = false; } IEnumerator CreateEnemies() { for (int i = 0; i < enemiesToSpawn + (counter*2); i++) { yield return new WaitForSeconds(spawnInterval); SpawnEnemy(); } } public void SpawnWave() { //Debug.Log("SpawnWave called"); if (GameObject.FindGameObjectsWithTag("Enemy").Length > 0 || gameOver) { return; } counter += 1; StartCoroutine(CreateEnemies()); enemyHealthIncreaseBy += healthIncreaseBy; spawnInterval -= spawnIntervalDecreaseBy; UpdateWaveText(); } public void setGameOver(bool gameStatus) { gameOver = gameStatus; } private void SpawnEnemy() { if ((counter % 2) == 0) { //changes enemy type every other wave GameObject instance = Instantiate(circleEnemy); //TODO: increase enemy health as waves increase instance.GetComponent<EnemyBehavior>().setHealth(initialHealth + enemyHealthIncreaseBy); enemiesSpawned++; } else { GameObject instance = Instantiate(squareEnemy); //TODO: increase enemy health as waves increase instance.GetComponent<EnemyBehavior>().setHealth(initialHealth + enemyHealthIncreaseBy); enemiesSpawned++; } } private void UpdateWaveText() { waveNumber += 1; wavesTextObject.GetComponent<Text>().text = "Round \n" + waveNumber + "/" + maxWaves; } private void SetInitialDifficulty() { circleEnemy.GetComponent<EnemyBehavior>().setHealth(initialHealth); squareEnemy.GetComponent<EnemyBehavior>().setHealth(initialHealth); } }
31.227848
108
0.651804
[ "MIT" ]
Pachwenko/tower-defense-unity
Assets/Scripts/WaveManager.cs
2,469
C#
using UnityEngine; using System.Collections; using System.Collections.Generic; using Pathfinding; #if UNITY_5_5_OR_NEWER using UnityEngine.Profiling; #endif #if NETFX_CORE using Thread = Pathfinding.WindowsStore.Thread; #else using Thread = System.Threading.Thread; #endif [ExecuteInEditMode] [AddComponentMenu("Pathfinding/Pathfinder")] /// <summary> /// Core component for the A* %Pathfinding System. /// This class handles all of the pathfinding system, calculates all paths and stores the info.\n /// This class is a singleton class, meaning there should only exist at most one active instance of it in the scene.\n /// It might be a bit hard to use directly, usually interfacing with the pathfinding system is done through the <see cref="Pathfinding.Seeker"/> class. /// /// \nosubgrouping /// \ingroup relevant /// </summary> [HelpURL("http://arongranberg.com/astar/docs/class_astar_path.php")] public class AstarPath : VersionedMonoBehaviour { /// <summary>The version number for the A* %Pathfinding Project</summary> public static readonly System.Version Version = new System.Version(4, 2, 15); /// <summary>Information about where the package was downloaded</summary> public enum AstarDistribution { WebsiteDownload, AssetStore, PackageManager }; /// <summary>Used by the editor to guide the user to the correct place to download updates</summary> public static readonly AstarDistribution Distribution = AstarDistribution.WebsiteDownload; /// <summary> /// Which branch of the A* %Pathfinding Project is this release. /// Used when checking for updates so that /// users of the development versions can get notifications of development /// updates. /// </summary> public static readonly string Branch = "master"; /// <summary> /// See Pathfinding.AstarData /// Deprecated: /// </summary> [System.Obsolete] public System.Type[] graphTypes { get { return data.graphTypes; } } /// <summary>Holds all graph data</summary> [UnityEngine.Serialization.FormerlySerializedAs("astarData")] public AstarData data; /// <summary> /// Holds all graph data. /// Deprecated: The 'astarData' field has been renamed to 'data' /// </summary> [System.Obsolete("The 'astarData' field has been renamed to 'data'")] public AstarData astarData { get { return data; } } /// <summary> /// Returns the active AstarPath object in the scene. /// Note: This is only set if the AstarPath object has been initialized (which happens in Awake). /// </summary> #if UNITY_4_6 || UNITY_4_3 public static new AstarPath active; #else public static AstarPath active; #endif /// <summary>Shortcut to Pathfinding.AstarData.graphs</summary> public NavGraph[] graphs { get { if (data == null) data = new AstarData(); return data.graphs; } } #region InspectorDebug /// <summary> /// @name Inspector - Debug /// @{ /// </summary> /// <summary> /// Visualize graphs in the scene view (editor only). /// [Open online documentation to see images] /// </summary> public bool showNavGraphs = true; /// <summary> /// Toggle to show unwalkable nodes. /// /// Note: Only relevant in the editor /// /// See: <see cref="unwalkableNodeDebugSize"/> /// </summary> public bool showUnwalkableNodes = true; /// <summary> /// The mode to use for drawing nodes in the sceneview. /// /// Note: Only relevant in the editor /// /// See: Pathfinding.GraphDebugMode /// </summary> public GraphDebugMode debugMode; /// <summary> /// Low value to use for certain <see cref="debugMode"/> modes. /// For example if <see cref="debugMode"/> is set to G, this value will determine when the node will be completely red. /// /// Note: Only relevant in the editor /// /// See: <see cref="debugRoof"/> /// See: <see cref="debugMode"/> /// </summary> public float debugFloor = 0; /// <summary> /// High value to use for certain <see cref="debugMode"/> modes. /// For example if <see cref="debugMode"/> is set to G, this value will determine when the node will be completely green. /// /// For the penalty debug mode, the nodes will be colored green when they have a penalty less than <see cref="debugFloor"/> and red /// when their penalty is greater or equal to this value and something between red and green otherwise. /// /// Note: Only relevant in the editor /// /// See: <see cref="debugFloor"/> /// See: <see cref="debugMode"/> /// </summary> public float debugRoof = 20000; /// <summary> /// If set, the <see cref="debugFloor"/> and <see cref="debugRoof"/> values will not be automatically recalculated. /// /// Note: Only relevant in the editor /// </summary> public bool manualDebugFloorRoof = false; /// <summary> /// If enabled, nodes will draw a line to their 'parent'. /// This will show the search tree for the latest path. /// /// Note: Only relevant in the editor /// /// TODO: Add a showOnlyLastPath flag to indicate whether to draw every node or only the ones visited by the latest path. /// </summary> public bool showSearchTree = false; /// <summary> /// Size of the red cubes shown in place of unwalkable nodes. /// /// Note: Only relevant in the editor. Does not apply to grid graphs. /// See: <see cref="showUnwalkableNodes"/> /// </summary> public float unwalkableNodeDebugSize = 0.3F; /// <summary> /// The amount of debugging messages. /// Use less debugging to improve performance (a bit) or just to get rid of the Console spamming. /// Use more debugging (heavy) if you want more information about what the pathfinding scripts are doing. /// The InGame option will display the latest path log using in-game GUI. /// /// [Open online documentation to see images] /// </summary> public PathLog logPathResults = PathLog.Normal; /// <summary>@}</summary> #endregion #region InspectorSettings /// <summary> /// @name Inspector - Settings /// @{ /// </summary> /// <summary> /// Maximum distance to search for nodes. /// When searching for the nearest node to a point, this is the limit (in world units) for how far away it is allowed to be. /// /// This is relevant if you try to request a path to a point that cannot be reached and it thus has to search for /// the closest node to that point which can be reached (which might be far away). If it cannot find a node within this distance /// then the path will fail. /// /// [Open online documentation to see images] /// /// See: Pathfinding.NNConstraint.constrainDistance /// </summary> public float maxNearestNodeDistance = 100; /// <summary> /// Max Nearest Node Distance Squared. /// See: <see cref="maxNearestNodeDistance"/> /// </summary> public float maxNearestNodeDistanceSqr { get { return maxNearestNodeDistance*maxNearestNodeDistance; } } /// <summary> /// If true, all graphs will be scanned during Awake. /// This does not include loading from the cache. /// If you disable this, you will have to call \link Scan AstarPath.active.Scan() \endlink yourself to enable pathfinding. /// Alternatively you could load a saved graph from a file. /// /// See: <see cref="Scan"/> /// See: <see cref="ScanAsync"/> /// </summary> public bool scanOnStartup = true; /// <summary> /// Do a full GetNearest search for all graphs. /// Additional searches will normally only be done on the graph which in the first fast search seemed to have the closest node. /// With this setting on, additional searches will be done on all graphs since the first check is not always completely accurate.\n /// More technically: GetNearestForce on all graphs will be called if true, otherwise only on the one graph which's GetNearest search returned the best node.\n /// Usually faster when disabled, but higher quality searches when enabled. /// When using a a navmesh or recast graph, for best quality, this setting should be combined with the Pathfinding.NavMeshGraph.accurateNearestNode setting set to true. /// Note: For the PointGraph this setting doesn't matter much as it has only one search mode. /// </summary> public bool fullGetNearestSearch = false; /// <summary> /// Prioritize graphs. /// Graphs will be prioritized based on their order in the inspector. /// The first graph which has a node closer than <see cref="prioritizeGraphsLimit"/> will be chosen instead of searching all graphs. /// </summary> public bool prioritizeGraphs = false; /// <summary> /// Distance limit for <see cref="prioritizeGraphs"/>. /// See: <see cref="prioritizeGraphs"/> /// </summary> public float prioritizeGraphsLimit = 1F; /// <summary> /// Reference to the color settings for this AstarPath object. /// Color settings include for example which color the nodes should be in, in the sceneview. /// </summary> public AstarColor colorSettings; /// <summary> /// Stored tag names. /// See: AstarPath.FindTagNames /// See: AstarPath.GetTagNames /// </summary> [SerializeField] protected string[] tagNames = null; /// <summary> /// The distance function to use as a heuristic. /// The heuristic, often referred to as just 'H' is the estimated cost from a node to the target. /// Different heuristics affect how the path picks which one to follow from multiple possible with the same length /// See: <see cref="Pathfinding.Heuristic"/> for more details and descriptions of the different modes. /// See: <a href="https://en.wikipedia.org/wiki/Admissible_heuristic">Wikipedia: Admissible heuristic</a> /// See: <a href="https://en.wikipedia.org/wiki/A*_search_algorithm">Wikipedia: A* search algorithm</a> /// See: <a href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm">Wikipedia: Dijkstra's Algorithm</a> /// </summary> public Heuristic heuristic = Heuristic.Euclidean; /// <summary> /// The scale of the heuristic. /// If a value lower than 1 is used, the pathfinder will search more nodes (slower). /// If 0 is used, the pathfinding algorithm will be reduced to dijkstra's algorithm. This is equivalent to setting <see cref="heuristic"/> to None. /// If a value larger than 1 is used the pathfinding will (usually) be faster because it expands fewer nodes, but the paths may no longer be the optimal (i.e the shortest possible paths). /// /// Usually you should leave this to the default value of 1. /// /// See: https://en.wikipedia.org/wiki/Admissible_heuristic /// See: https://en.wikipedia.org/wiki/A*_search_algorithm /// See: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm /// </summary> public float heuristicScale = 1F; /// <summary> /// Number of pathfinding threads to use. /// Multithreading puts pathfinding in another thread, this is great for performance on 2+ core computers since the framerate will barely be affected by the pathfinding at all. /// - None indicates that the pathfinding is run in the Unity thread as a coroutine /// - Automatic will try to adjust the number of threads to the number of cores and memory on the computer. /// Less than 512mb of memory or a single core computer will make it revert to using no multithreading. /// /// It is recommended that you use one of the "Auto" settings that are available. /// The reason is that even if your computer might be beefy and have 8 cores. /// Other computers might only be quad core or dual core in which case they will not benefit from more than /// 1 or 3 threads respectively (you usually want to leave one core for the unity thread). /// If you use more threads than the number of cores on the computer it is mostly just wasting memory, it will not run any faster. /// The extra memory usage is not trivially small. Each thread needs to keep a small amount of data for each node in all the graphs. /// It is not the full graph data but it is proportional to the number of nodes. /// The automatic settings will inspect the machine it is running on and use that to determine the number of threads so that no memory is wasted. /// /// The exception is if you only have one (or maybe two characters) active at time. Then you should probably just go with one thread always since it is very unlikely /// that you will need the extra throughput given by more threads. Keep in mind that more threads primarily increases throughput by calculating different paths on different /// threads, it will not calculate individual paths any faster. /// /// Note that if you are modifying the pathfinding core scripts or if you are directly modifying graph data without using any of the /// safe wrappers (like <see cref="AddWorkItem)"/> multithreading can cause strange errors and pathfinding stopping to work if you are not careful. /// For basic usage (not modding the pathfinding core) it should be safe. /// /// Note: WebGL does not support threads at all (since javascript is single-threaded) so no threads will be used on that platform. /// /// See: CalculateThreadCount /// </summary> public ThreadCount threadCount = ThreadCount.One; /// <summary> /// Max number of milliseconds to spend each frame for pathfinding. /// At least 500 nodes will be searched each frame (if there are that many to search). /// When using multithreading this value is irrelevant. /// </summary> public float maxFrameTime = 1F; /// <summary> /// Throttle graph updates and batch them to improve performance. /// If toggled, graph updates will batched and executed less often (specified by <see cref="graphUpdateBatchingInterval)"/>. /// /// This can have a positive impact on pathfinding throughput since the pathfinding threads do not need /// to be stopped as often, and it reduces the overhead per graph update. /// All graph updates are still applied however, they are just batched together so that more of them are /// applied at the same time. /// /// However do not use this if you want minimal latency between a graph update being requested /// and it being applied. /// /// This only applies to graph updates requested using the <see cref="UpdateGraphs"/> method. Not those requested /// using <see cref="RegisterSafeUpdate"/> or <see cref="AddWorkItem"/>. /// /// If you want to apply graph updates immediately at some point, you can call <see cref="FlushGraphUpdates"/>. /// /// See: graph-updates (view in online documentation for working links) /// </summary> public bool batchGraphUpdates = false; /// <summary> /// Minimum number of seconds between each batch of graph updates. /// If <see cref="batchGraphUpdates"/> is true, this defines the minimum number of seconds between each batch of graph updates. /// /// This can have a positive impact on pathfinding throughput since the pathfinding threads do not need /// to be stopped as often, and it reduces the overhead per graph update. /// All graph updates are still applied however, they are just batched together so that more of them are /// applied at the same time. /// /// Do not use this if you want minimal latency between a graph update being requested /// and it being applied. /// /// This only applies to graph updates requested using the <see cref="UpdateGraphs"/> method. Not those requested /// using <see cref="RegisterSafeUpdate"/> or <see cref="AddWorkItem"/>. /// /// See: graph-updates (view in online documentation for working links) /// </summary> public float graphUpdateBatchingInterval = 0.2F; /// <summary> /// Batch graph updates. /// Deprecated: This field has been renamed to <see cref="batchGraphUpdates"/>. /// </summary> [System.Obsolete("This field has been renamed to 'batchGraphUpdates'")] public bool limitGraphUpdates { get { return batchGraphUpdates; } set { batchGraphUpdates = value; } } /// <summary> /// Limit for how often should graphs be updated. /// Deprecated: This field has been renamed to <see cref="graphUpdateBatchingInterval"/>. /// </summary> [System.Obsolete("This field has been renamed to 'graphUpdateBatchingInterval'")] public float maxGraphUpdateFreq { get { return graphUpdateBatchingInterval; } set { graphUpdateBatchingInterval = value; } } /// <summary>@}</summary> #endregion #region DebugVariables /// <summary> /// @name Debug Members /// @{ /// </summary> #if ProfileAstar /// <summary> /// How many paths has been computed this run. From application start.\n /// Debugging variable /// </summary> public static int PathsCompleted = 0; public static System.Int64 TotalSearchedNodes = 0; public static System.Int64 TotalSearchTime = 0; #endif /// <summary> /// The time it took for the last call to Scan() to complete. /// Used to prevent automatically rescanning the graphs too often (editor only) /// </summary> public float lastScanTime { get; private set; } /// <summary> /// The path to debug using gizmos. /// This is the path handler used to calculate the last path. /// It is used in the editor to draw debug information using gizmos. /// </summary> [System.NonSerialized] public PathHandler debugPathData; /// <summary>The path ID to debug using gizmos</summary> [System.NonSerialized] public ushort debugPathID; /// <summary> /// Debug string from the last completed path. /// Will be updated if <see cref="logPathResults"/> == PathLog.InGame /// </summary> string inGameDebugPath; /* @} */ #endregion #region StatusVariables /// <summary> /// Backing field for <see cref="isScanning"/>. /// Cannot use an auto-property because they cannot be marked with System.NonSerialized. /// </summary> [System.NonSerialized] bool isScanningBacking; /// <summary> /// Set while any graphs are being scanned. /// It will be true up until the FloodFill is done. /// /// Note: Not to be confused with graph updates. /// /// Used to better support Graph Update Objects called for example in OnPostScan /// /// See: IsAnyGraphUpdateQueued /// See: IsAnyGraphUpdateInProgress /// </summary> public bool isScanning { get { return isScanningBacking; } private set { isScanningBacking = value; } } /// <summary> /// Number of parallel pathfinders. /// Returns the number of concurrent processes which can calculate paths at once. /// When using multithreading, this will be the number of threads, if not using multithreading it is always 1 (since only 1 coroutine is used). /// See: IsUsingMultithreading /// </summary> public int NumParallelThreads { get { return pathProcessor.NumThreads; } } /// <summary> /// Returns whether or not multithreading is used. /// \exception System.Exception Is thrown when it could not be decided if multithreading was used or not. /// This should not happen if pathfinding is set up correctly. /// Note: This uses info about if threads are running right now, it does not use info from the settings on the A* object. /// </summary> public bool IsUsingMultithreading { get { return pathProcessor.IsUsingMultithreading; } } /// <summary> /// Returns if any graph updates are waiting to be applied. /// Deprecated: Use IsAnyGraphUpdateQueued instead /// </summary> [System.Obsolete("Fixed grammar, use IsAnyGraphUpdateQueued instead")] public bool IsAnyGraphUpdatesQueued { get { return IsAnyGraphUpdateQueued; } } /// <summary> /// Returns if any graph updates are waiting to be applied. /// Note: This is false while the updates are being performed. /// Note: This does *not* includes other types of work items such as navmesh cutting or anything added by <see cref="RegisterSafeUpdate"/> or <see cref="AddWorkItem"/>. /// </summary> public bool IsAnyGraphUpdateQueued { get { return graphUpdates.IsAnyGraphUpdateQueued; } } /// <summary> /// Returns if any graph updates are being calculated right now. /// Note: This does *not* includes other types of work items such as navmesh cutting or anything added by <see cref="RegisterSafeUpdate"/> or <see cref="AddWorkItem"/>. /// /// See: IsAnyWorkItemInProgress /// </summary> public bool IsAnyGraphUpdateInProgress { get { return graphUpdates.IsAnyGraphUpdateInProgress; } } /// <summary> /// Returns if any work items are in progress right now. /// Note: This includes pretty much all types of graph updates. /// Such as normal graph updates, navmesh cutting and anything added by <see cref="RegisterSafeUpdate"/> or <see cref="AddWorkItem"/>. /// </summary> public bool IsAnyWorkItemInProgress { get { return workItems.workItemsInProgress; } } /// <summary> /// Returns if this code is currently being exectuted inside a work item. /// Note: This includes pretty much all types of graph updates. /// Such as normal graph updates, navmesh cutting and anything added by <see cref="RegisterSafeUpdate"/> or <see cref="AddWorkItem"/>. /// /// In contrast to <see cref="IsAnyWorkItemInProgress"/> this is only true when work item code is being executed, it is not /// true in-between the updates to a work item that takes several frames to complete. /// </summary> internal bool IsInsideWorkItem { get { return workItems.workItemsInProgressRightNow; } } #endregion #region Callbacks /// <summary>@name Callbacks</summary> /* Callbacks to pathfinding events. * These allow you to hook in to the pathfinding process.\n * Callbacks can be used like this: * \snippet MiscSnippets.cs AstarPath.Callbacks */ /// <summary>@{</summary> /// <summary> /// Called on Awake before anything else is done. /// This is called at the start of the Awake call, right after <see cref="active"/> has been set, but this is the only thing that has been done.\n /// Use this when you want to set up default settings for an AstarPath component created during runtime since some settings can only be changed in Awake /// (such as multithreading related stuff) /// <code> /// // Create a new AstarPath object on Start and apply some default settings /// public void Start () { /// AstarPath.OnAwakeSettings += ApplySettings; /// AstarPath astar = gameObject.AddComponent<AstarPath>(); /// } /// /// public void ApplySettings () { /// // Unregister from the delegate /// AstarPath.OnAwakeSettings -= ApplySettings; /// // For example threadCount should not be changed after the Awake call /// // so here's the only place to set it if you create the component during runtime /// AstarPath.active.threadCount = ThreadCount.One; /// } /// </code> /// </summary> public static System.Action OnAwakeSettings; /// <summary>Called for each graph before they are scanned</summary> public static OnGraphDelegate OnGraphPreScan; /// <summary>Called for each graph after they have been scanned. All other graphs might not have been scanned yet.</summary> public static OnGraphDelegate OnGraphPostScan; /// <summary>Called for each path before searching. Be careful when using multithreading since this will be called from a different thread.</summary> public static OnPathDelegate OnPathPreSearch; /// <summary>Called for each path after searching. Be careful when using multithreading since this will be called from a different thread.</summary> public static OnPathDelegate OnPathPostSearch; /// <summary>Called before starting the scanning</summary> public static OnScanDelegate OnPreScan; /// <summary>Called after scanning. This is called before applying links, flood-filling the graphs and other post processing.</summary> public static OnScanDelegate OnPostScan; /// <summary>Called after scanning has completed fully. This is called as the last thing in the Scan function.</summary> public static OnScanDelegate OnLatePostScan; /// <summary>Called when any graphs are updated. Register to for example recalculate the path whenever a graph changes.</summary> public static OnScanDelegate OnGraphsUpdated; /// <summary> /// Called when pathID overflows 65536 and resets back to zero. /// Note: This callback will be cleared every time it is called, so if you want to register to it repeatedly, register to it directly on receiving the callback as well. /// </summary> public static System.Action On65KOverflow; /// <summary>Deprecated:</summary> [System.ObsoleteAttribute] public System.Action OnGraphsWillBeUpdated; /// <summary>Deprecated:</summary> [System.ObsoleteAttribute] public System.Action OnGraphsWillBeUpdated2; /* @} */ #endregion #region MemoryStructures /// <summary>Processes graph updates</summary> readonly GraphUpdateProcessor graphUpdates; /// <summary>Holds a hierarchical graph to speed up some queries like if there is a path between two nodes</summary> internal readonly HierarchicalGraph hierarchicalGraph = new HierarchicalGraph(); /// <summary> /// Handles navmesh cuts. /// See: <see cref="Pathfinding.NavmeshCut"/> /// </summary> public readonly NavmeshUpdates navmeshUpdates = new NavmeshUpdates(); /// <summary>Processes work items</summary> readonly WorkItemProcessor workItems; /// <summary>Holds all paths waiting to be calculated and calculates them</summary> PathProcessor pathProcessor; bool graphUpdateRoutineRunning = false; /// <summary>Makes sure QueueGraphUpdates will not queue multiple graph update orders</summary> bool graphUpdatesWorkItemAdded = false; /// <summary> /// Time the last graph update was done. /// Used to group together frequent graph updates to batches /// </summary> float lastGraphUpdate = -9999F; /// <summary>Held if any work items are currently queued</summary> PathProcessor.GraphUpdateLock workItemLock; /// <summary>Holds all completed paths waiting to be returned to where they were requested</summary> internal readonly PathReturnQueue pathReturnQueue; /// <summary> /// Holds settings for heuristic optimization. /// See: heuristic-opt (view in online documentation for working links) /// </summary> public EuclideanEmbedding euclideanEmbedding = new EuclideanEmbedding(); #endregion /// <summary> /// Shows or hides graph inspectors. /// Used internally by the editor /// </summary> public bool showGraphs = false; /// <summary> /// The next unused Path ID. /// Incremented for every call to GetNextPathID /// </summary> private ushort nextFreePathID = 1; private AstarPath () { pathReturnQueue = new PathReturnQueue(this); // Make sure that the pathProcessor is never null pathProcessor = new PathProcessor(this, pathReturnQueue, 1, false); workItems = new WorkItemProcessor(this); graphUpdates = new GraphUpdateProcessor(this); // Forward graphUpdates.OnGraphsUpdated to AstarPath.OnGraphsUpdated graphUpdates.OnGraphsUpdated += () => { if (OnGraphsUpdated != null) { OnGraphsUpdated(this); } }; } /// <summary> /// Returns tag names. /// Makes sure that the tag names array is not null and of length 32. /// If it is null or not of length 32, it creates a new array and fills it with 0,1,2,3,4 etc... /// See: AstarPath.FindTagNames /// </summary> public string[] GetTagNames () { if (tagNames == null || tagNames.Length != 32) { tagNames = new string[32]; for (int i = 0; i < tagNames.Length; i++) { tagNames[i] = ""+i; } tagNames[0] = "Basic Ground"; } return tagNames; } /// <summary> /// Used outside of play mode to initialize the AstarPath object even if it has not been selected in the inspector yet. /// This will set the <see cref="active"/> property and deserialize all graphs. /// /// This is useful if you want to do changes to the graphs in the editor outside of play mode, but cannot be sure that the graphs have been deserialized yet. /// In play mode this method does nothing. /// </summary> public static void FindAstarPath () { if (Application.isPlaying) return; if (active == null) active = GameObject.FindObjectOfType<AstarPath>(); if (active != null && (active.data.graphs == null || active.data.graphs.Length == 0)) active.data.DeserializeGraphs(); } /// <summary> /// Tries to find an AstarPath object and return tag names. /// If an AstarPath object cannot be found, it returns an array of length 1 with an error message. /// See: AstarPath.GetTagNames /// </summary> public static string[] FindTagNames () { FindAstarPath(); return active != null? active.GetTagNames () : new string[1] { "There is no AstarPath component in the scene" }; } /// <summary>Returns the next free path ID</summary> internal ushort GetNextPathID () { if (nextFreePathID == 0) { nextFreePathID++; if (On65KOverflow != null) { System.Action tmp = On65KOverflow; On65KOverflow = null; tmp(); } } return nextFreePathID++; } void RecalculateDebugLimits () { debugFloor = float.PositiveInfinity; debugRoof = float.NegativeInfinity; bool ignoreSearchTree = !showSearchTree || debugPathData == null; for (int i = 0; i < graphs.Length; i++) { if (graphs[i] != null && graphs[i].drawGizmos) { graphs[i].GetNodes(node => { if (node.Walkable && (ignoreSearchTree || Pathfinding.Util.GraphGizmoHelper.InSearchTree(node, debugPathData, debugPathID))) { if (debugMode == GraphDebugMode.Penalty) { debugFloor = Mathf.Min(debugFloor, node.Penalty); debugRoof = Mathf.Max(debugRoof, node.Penalty); } else if (debugPathData != null) { var rnode = debugPathData.GetPathNode(node); switch (debugMode) { case GraphDebugMode.F: debugFloor = Mathf.Min(debugFloor, rnode.F); debugRoof = Mathf.Max(debugRoof, rnode.F); break; case GraphDebugMode.G: debugFloor = Mathf.Min(debugFloor, rnode.G); debugRoof = Mathf.Max(debugRoof, rnode.G); break; case GraphDebugMode.H: debugFloor = Mathf.Min(debugFloor, rnode.H); debugRoof = Mathf.Max(debugRoof, rnode.H); break; } } } }); } } if (float.IsInfinity(debugFloor)) { debugFloor = 0; debugRoof = 1; } // Make sure they are not identical, that will cause the color interpolation to fail if (debugRoof-debugFloor < 1) debugRoof += 1; } Pathfinding.Util.RetainedGizmos gizmos = new Pathfinding.Util.RetainedGizmos(); /// <summary>Calls OnDrawGizmos on graph generators</summary> private void OnDrawGizmos () { // Make sure the singleton pattern holds // Might not hold if the Awake method // has not been called yet if (active == null) active = this; if (active != this || graphs == null) { return; } // In Unity one can select objects in the scene view by simply clicking on them with the mouse. // Graph gizmos interfere with this however. If we would draw a mesh here the user would // not be able to select whatever was behind it because the gizmos would block them. // (presumably Unity cannot associate the gizmos with the AstarPath component because we are using // Graphics.DrawMeshNow to draw most gizmos). It turns out that when scene picking happens // then Event.current.type will be 'mouseUp'. We will therefore ignore all events which are // not repaint events to make sure that the gizmos do not interfere with any kind of scene picking. // This will not have any visual impact as only repaint events will result in any changes on the screen. // From testing it seems the only events that can happen during OnDrawGizmos are the mouseUp and repaint events. if (Event.current.type != EventType.Repaint) return; colorSettings.PushToStatic(this); AstarProfiler.StartProfile("OnDrawGizmos"); if (workItems.workItemsInProgress || isScanning) { // If updating graphs, graph info might not be valid right now // so just draw the same thing as last frame. // Also if the scene has multiple cameras (or in the editor if we have a scene view and a game view) we // just calculate the mesh once and then redraw the existing one for the other cameras. // This improves performance quite a bit. gizmos.DrawExisting(); } else { if (showNavGraphs && !manualDebugFloorRoof) { RecalculateDebugLimits(); } Profiler.BeginSample("Graph.OnDrawGizmos"); // Loop through all graphs and draw their gizmos for (int i = 0; i < graphs.Length; i++) { if (graphs[i] != null && graphs[i].drawGizmos) graphs[i].OnDrawGizmos(gizmos, showNavGraphs); } Profiler.EndSample(); if (showNavGraphs) { euclideanEmbedding.OnDrawGizmos(); if (debugMode == GraphDebugMode.HierarchicalNode) hierarchicalGraph.OnDrawGizmos(gizmos); } } gizmos.FinalizeDraw(); AstarProfiler.EndProfile("OnDrawGizmos"); } #if !ASTAR_NO_GUI /// <summary> /// Draws the InGame debugging (if enabled), also shows the fps if 'L' is pressed down. /// See: <see cref="logPathResults"/> PathLog /// </summary> private void OnGUI () { if (logPathResults == PathLog.InGame && inGameDebugPath != "") { GUI.Label(new Rect(5, 5, 400, 600), inGameDebugPath); } } #endif /// <summary> /// Prints path results to the log. What it prints can be controled using <see cref="logPathResults"/>. /// See: <see cref="logPathResults"/> /// See: PathLog /// See: Pathfinding.Path.DebugString /// </summary> /// <summary> /// Checks if any work items need to be executed /// then runs pathfinding for a while (if not using multithreading because /// then the calculation happens in other threads) /// and then returns any calculated paths to the /// scripts that requested them. /// /// See: PerformBlockingActions /// See: PathProcessor.TickNonMultithreaded /// See: PathReturnQueue.ReturnPaths /// </summary> private void Update () { // This class uses the [ExecuteInEditMode] attribute // So Update is called even when not playing // Don't do anything when not in play mode if (!Application.isPlaying) return; navmeshUpdates.Update(); // Execute blocking actions such as graph updates // when not scanning if (!isScanning) { PerformBlockingActions(); } // Calculates paths when not using multithreading pathProcessor.TickNonMultithreaded(); // Return calculated paths pathReturnQueue.ReturnPaths(true); } private void PerformBlockingActions (bool force = false) { if (workItemLock.Held && pathProcessor.queue.AllReceiversBlocked) { // Return all paths before starting blocking actions // since these might change the graph and make returned paths invalid (at least the nodes) pathReturnQueue.ReturnPaths(false); Profiler.BeginSample("Work Items"); if (workItems.ProcessWorkItems(force)) { // At this stage there are no more work items, resume pathfinding threads workItemLock.Release(); } Profiler.EndSample(); } } /// <summary> /// Call during work items to queue a flood fill. /// Deprecated: This method has been moved. Use the method on the context object that can be sent with work item delegates instead /// <code> /// AstarPath.active.AddWorkItem(new AstarWorkItem(() => { /// // Safe to update graphs here /// var node = AstarPath.active.GetNearest(transform.position).node; /// node.Walkable = false; /// })); /// </code> /// /// See: <see cref="Pathfinding.IWorkItemContext"/> /// </summary> [System.Obsolete("This method has been moved. Use the method on the context object that can be sent with work item delegates instead")] public void QueueWorkItemFloodFill () { throw new System.Exception("This method has been moved. Use the method on the context object that can be sent with work item delegates instead"); } /// <summary> /// If a WorkItem needs to have a valid flood fill during execution, call this method to ensure there are no pending flood fills. /// Deprecated: This method has been moved. Use the method on the context object that can be sent with work item delegates instead /// <code> /// AstarPath.active.AddWorkItem(new AstarWorkItem(() => { /// // Safe to update graphs here /// var node = AstarPath.active.GetNearest(transform.position).node; /// node.Walkable = false; /// })); /// </code> /// /// See: <see cref="Pathfinding.IWorkItemContext"/> /// </summary> [System.Obsolete("This method has been moved. Use the method on the context object that can be sent with work item delegates instead")] public void EnsureValidFloodFill () { throw new System.Exception("This method has been moved. Use the method on the context object that can be sent with work item delegates instead"); } /// <summary> /// Add a work item to be processed when pathfinding is paused. /// Convenience method that is equivalent to /// <code> /// AddWorkItem(new AstarWorkItem(callback)); /// </code> /// /// See: <see cref="AddWorkItem(AstarWorkItem)"/> /// </summary> public void AddWorkItem (System.Action callback) { AddWorkItem(new AstarWorkItem(callback)); } /// <summary> /// Add a work item to be processed when pathfinding is paused. /// Convenience method that is equivalent to /// <code> /// AddWorkItem(new AstarWorkItem(callback)); /// </code> /// /// See: <see cref="AddWorkItem(AstarWorkItem)"/> /// </summary> public void AddWorkItem (System.Action<IWorkItemContext> callback) { AddWorkItem(new AstarWorkItem(callback)); } /// <summary> /// Add a work item to be processed when pathfinding is paused. /// /// The work item will be executed when it is safe to update nodes. This is defined as between the path searches. /// When using more threads than one, calling this often might decrease pathfinding performance due to a lot of idling in the threads. /// Not performance as in it will use much CPU power, but performance as in the number of paths per second will probably go down /// (though your framerate might actually increase a tiny bit). /// /// You should only call this function from the main unity thread (i.e normal game code). /// /// <code> /// AstarPath.active.AddWorkItem(new AstarWorkItem(() => { /// // Safe to update graphs here /// var node = AstarPath.active.GetNearest(transform.position).node; /// node.Walkable = false; /// })); /// </code> /// /// <code> /// AstarPath.active.AddWorkItem(() => { /// // Safe to update graphs here /// var node = AstarPath.active.GetNearest(transform.position).node; /// node.position = (Int3)transform.position; /// }); /// </code> /// /// See: <see cref="FlushWorkItems"/> /// </summary> public void AddWorkItem (AstarWorkItem item) { workItems.AddWorkItem(item); // Make sure pathfinding is stopped and work items are processed if (!workItemLock.Held) { workItemLock = PausePathfindingSoon(); } #if UNITY_EDITOR // If not playing, execute instantly if (!Application.isPlaying) { FlushWorkItems(); } #endif } #region GraphUpdateMethods /// <summary> /// Will apply queued graph updates as soon as possible, regardless of <see cref="batchGraphUpdates"/>. /// Calling this multiple times will not create multiple callbacks. /// This function is useful if you are limiting graph updates, but you want a specific graph update to be applied as soon as possible regardless of the time limit. /// Note that this does not block until the updates are done, it merely bypasses the <see cref="batchGraphUpdates"/> time limit. /// /// See: <see cref="FlushGraphUpdates"/> /// </summary> public void QueueGraphUpdates () { if (!graphUpdatesWorkItemAdded) { graphUpdatesWorkItemAdded = true; var workItem = graphUpdates.GetWorkItem(); // Add a new work item which first // sets the graphUpdatesWorkItemAdded flag to false // and then processes the graph updates AddWorkItem(new AstarWorkItem(() => { graphUpdatesWorkItemAdded = false; lastGraphUpdate = Time.realtimeSinceStartup; workItem.init(); }, workItem.update)); } } /// <summary> /// Waits a moment with updating graphs. /// If batchGraphUpdates is set, we want to keep some space between them to let pathfinding threads running and then calculate all queued calls at once /// </summary> IEnumerator DelayedGraphUpdate () { graphUpdateRoutineRunning = true; yield return new WaitForSeconds(graphUpdateBatchingInterval-(Time.realtimeSinceStartup-lastGraphUpdate)); QueueGraphUpdates(); graphUpdateRoutineRunning = false; } /// <summary> /// Update all graphs within bounds after delay seconds. /// The graphs will be updated as soon as possible. /// /// See: FlushGraphUpdates /// See: batchGraphUpdates /// See: graph-updates (view in online documentation for working links) /// </summary> public void UpdateGraphs (Bounds bounds, float delay) { UpdateGraphs(new GraphUpdateObject(bounds), delay); } /// <summary> /// Update all graphs using the GraphUpdateObject after delay seconds. /// This can be used to, e.g make all nodes in a region unwalkable, or set them to a higher penalty. /// /// See: FlushGraphUpdates /// See: batchGraphUpdates /// See: graph-updates (view in online documentation for working links) /// </summary> public void UpdateGraphs (GraphUpdateObject ob, float delay) { StartCoroutine(UpdateGraphsInternal(ob, delay)); } /// <summary>Update all graphs using the GraphUpdateObject after delay seconds</summary> IEnumerator UpdateGraphsInternal (GraphUpdateObject ob, float delay) { yield return new WaitForSeconds(delay); UpdateGraphs(ob); } /// <summary> /// Update all graphs within bounds. /// The graphs will be updated as soon as possible. /// /// This is equivalent to /// <code> /// UpdateGraphs(new GraphUpdateObject(bounds)); /// </code> /// /// See: FlushGraphUpdates /// See: batchGraphUpdates /// See: graph-updates (view in online documentation for working links) /// </summary> public void UpdateGraphs (Bounds bounds) { UpdateGraphs(new GraphUpdateObject(bounds)); } /// <summary> /// Update all graphs using the GraphUpdateObject. /// This can be used to, e.g make all nodes in a region unwalkable, or set them to a higher penalty. /// The graphs will be updated as soon as possible (with respect to <see cref="batchGraphUpdates)"/> /// /// See: FlushGraphUpdates /// See: batchGraphUpdates /// See: graph-updates (view in online documentation for working links) /// </summary> public void UpdateGraphs (GraphUpdateObject ob) { graphUpdates.AddToQueue(ob); // If we should limit graph updates, start a coroutine which waits until we should update graphs if (batchGraphUpdates && Time.realtimeSinceStartup-lastGraphUpdate < graphUpdateBatchingInterval) { if (!graphUpdateRoutineRunning) { StartCoroutine(DelayedGraphUpdate()); } } else { // Otherwise, graph updates should be carried out as soon as possible QueueGraphUpdates(); } } /// <summary> /// Forces graph updates to complete in a single frame. /// This will force the pathfinding threads to finish calculating the path they are currently calculating (if any) and then pause. /// When all threads have paused, graph updates will be performed. /// Warning: Using this very often (many times per second) can reduce your fps due to a lot of threads waiting for one another. /// But you probably wont have to worry about that. /// /// Note: This is almost identical to <see cref="FlushWorkItems"/>, but added for more descriptive name. /// This function will also override any time limit delays for graph updates. /// This is because graph updates are implemented using work items. /// So calling this function will also execute any other work items (if any are queued). /// /// Will not do anything if there are no graph updates queued (not even execute other work items). /// </summary> public void FlushGraphUpdates () { if (IsAnyGraphUpdateQueued) { QueueGraphUpdates(); FlushWorkItems(); } } #endregion /// <summary> /// Forces work items to complete in a single frame. /// This will force all work items to run immidiately. /// This will force the pathfinding threads to finish calculating the path they are currently calculating (if any) and then pause. /// When all threads have paused, work items will be executed (which can be e.g graph updates). /// /// Warning: Using this very often (many times per second) can reduce your fps due to a lot of threads waiting for one another. /// But you probably wont have to worry about that /// /// Note: This is almost (note almost) identical to <see cref="FlushGraphUpdates"/>, but added for more descriptive name. /// /// Will not do anything if there are no queued work items waiting to run. /// </summary> public void FlushWorkItems () { if (workItems.anyQueued) { var graphLock = PausePathfinding(); PerformBlockingActions(true); graphLock.Release(); } } /// <summary> /// Make sure work items are executed. /// /// See: AddWorkItem /// /// Deprecated: Use <see cref="FlushWorkItems()"/> instead. /// </summary> /// <param name="unblockOnComplete">If true, pathfinding will be allowed to start running immediately after completing all work items.</param> /// <param name="block">If true, work items that usually take more than one frame to complete will be forced to complete during this call. /// If false, then after this call there might still be work left to do.</param> [System.Obsolete("Use FlushWorkItems() instead")] public void FlushWorkItems (bool unblockOnComplete, bool block) { var graphLock = PausePathfinding(); // Run tasks PerformBlockingActions(block); graphLock.Release(); } /// <summary> /// Forces thread safe callbacks to run. /// Deprecated: Use <see cref="FlushWorkItems"/> instead /// </summary> [System.Obsolete("Use FlushWorkItems instead")] public void FlushThreadSafeCallbacks () { FlushWorkItems(); } /// <summary> /// Calculates number of threads to use. /// If count is not Automatic, simply returns count casted to an int. /// Returns: An int specifying how many threads to use, 0 means a coroutine should be used for pathfinding instead of a separate thread. /// /// If count is set to Automatic it will return a value based on the number of processors and memory for the current system. /// If memory is <= 512MB or logical cores are <= 1, it will return 0. If memory is <= 1024 it will clamp threads to max 2. /// Otherwise it will return the number of logical cores clamped to 6. /// /// When running on WebGL this method always returns 0 /// </summary> public static int CalculateThreadCount (ThreadCount count) { #if UNITY_WEBGL return 0; #else if (count == ThreadCount.AutomaticLowLoad || count == ThreadCount.AutomaticHighLoad) { int logicalCores = Mathf.Max(1, SystemInfo.processorCount); int memory = SystemInfo.systemMemorySize; if (memory <= 0) { Debug.LogError("Machine reporting that is has <= 0 bytes of RAM. This is definitely not true, assuming 1 GiB"); memory = 1024; } if (logicalCores <= 1) return 0; if (memory <= 512) return 0; return 1; } else { return (int)count > 0 ? 1 : 0; } #endif } /// <summary> /// Sets up all needed variables and scans the graphs. /// Calls Initialize, starts the ReturnPaths coroutine and scans all graphs. /// Also starts threads if using multithreading /// See: <see cref="OnAwakeSettings"/> /// </summary> protected override void Awake () { base.Awake(); // Very important to set this. Ensures the singleton pattern holds active = this; if (FindObjectsOfType(typeof(AstarPath)).Length > 1) { Debug.LogError("You should NOT have more than one AstarPath component in the scene at any time.\n" + "This can cause serious errors since the AstarPath component builds around a singleton pattern."); } // Disable GUILayout to gain some performance, it is not used in the OnGUI call useGUILayout = false; // This class uses the [ExecuteInEditMode] attribute // So Awake is called even when not playing // Don't do anything when not in play mode if (!Application.isPlaying) return; if (OnAwakeSettings != null) { OnAwakeSettings(); } // To make sure all graph modifiers have been enabled before scan (to avoid script execution order issues) GraphModifier.FindAllModifiers(); RelevantGraphSurface.FindAllGraphSurfaces(); InitializePathProcessor(); InitializeProfiler(); ConfigureReferencesInternal(); InitializeAstarData(); // Flush work items, possibly added in InitializeAstarData to load graph data FlushWorkItems(); euclideanEmbedding.dirty = true; navmeshUpdates.OnEnable(); if (scanOnStartup && (!data.cacheStartup || data.file_cachedStartup == null)) { Scan(); } } /// <summary>Initializes the <see cref="pathProcessor"/> field</summary> void InitializePathProcessor () { int numThreads = CalculateThreadCount(threadCount); // Outside of play mode everything is synchronous, so no threads are used. if (!Application.isPlaying) numThreads = 0; // Trying to prevent simple modding to add support for more than one thread if (numThreads > 1) { threadCount = ThreadCount.One; numThreads = 1; } int numProcessors = Mathf.Max(numThreads, 1); bool multithreaded = numThreads > 0; pathProcessor = new PathProcessor(this, pathReturnQueue, numProcessors, multithreaded); pathProcessor.OnPathPreSearch += path => { var tmp = OnPathPreSearch; if (tmp != null) tmp(path); }; pathProcessor.OnPathPostSearch += path => { var tmp = OnPathPostSearch; if (tmp != null) tmp(path); }; // Sent every time the path queue is unblocked pathProcessor.OnQueueUnblocked += () => { if (euclideanEmbedding.dirty) { euclideanEmbedding.RecalculateCosts(); } }; if (multithreaded) { graphUpdates.EnableMultithreading(); } } /// <summary>Does simple error checking</summary> internal void VerifyIntegrity () { if (active != this) { throw new System.Exception("Singleton pattern broken. Make sure you only have one AstarPath object in the scene"); } if (data == null) { throw new System.NullReferenceException("data is null... A* not set up correctly?"); } if (data.graphs == null) { data.graphs = new NavGraph[0]; data.UpdateShortcuts(); } } /// <summary>\cond internal</summary> /// <summary> /// Internal method to make sure <see cref="active"/> is set to this object and that <see cref="data"/> is not null. /// Also calls OnEnable for the <see cref="colorSettings"/> and initializes data.userConnections if it wasn't initialized before /// /// Warning: This is mostly for use internally by the system. /// </summary> public void ConfigureReferencesInternal () { active = this; data = data ?? new AstarData(); colorSettings = colorSettings ?? new AstarColor(); colorSettings.PushToStatic(this); } /// <summary>\endcond</summary> /// <summary>Calls AstarProfiler.InitializeFastProfile</summary> void InitializeProfiler () { AstarProfiler.InitializeFastProfile(new string[14] { "Prepare", //0 "Initialize", //1 "CalculateStep", //2 "Trace", //3 "Open", //4 "UpdateAllG", //5 "Add", //6 "Remove", //7 "PreProcessing", //8 "Callback", //9 "Overhead", //10 "Log", //11 "ReturnPaths", //12 "PostPathCallback" //13 }); } /// <summary> /// Initializes the AstarData class. /// Searches for graph types, calls Awake on <see cref="data"/> and on all graphs /// /// See: AstarData.FindGraphTypes /// </summary> void InitializeAstarData () { data.FindGraphTypes(); data.Awake(); data.UpdateShortcuts(); } /// <summary>Cleans up meshes to avoid memory leaks</summary> void OnDisable () { gizmos.ClearCache(); } /// <summary> /// Clears up variables and other stuff, destroys graphs. /// Note that when destroying an AstarPath object, all static variables such as callbacks will be cleared. /// </summary> void OnDestroy () { // This class uses the [ExecuteInEditMode] attribute // So OnDestroy is called even when not playing // Don't do anything when not in play mode if (!Application.isPlaying) return; if (logPathResults == PathLog.Heavy) Debug.Log("+++ AstarPath Component Destroyed - Cleaning Up Pathfinding Data +++"); if (active != this) return; // Block until the pathfinding threads have // completed their current path calculation PausePathfinding(); navmeshUpdates.OnDisable(); euclideanEmbedding.dirty = false; FlushWorkItems(); // Don't accept any more path calls to this AstarPath instance. // This will cause all pathfinding threads to exit (if any exist) pathProcessor.queue.TerminateReceivers(); if (logPathResults == PathLog.Heavy) Debug.Log("Processing Possible Work Items"); // Stop the graph update thread (if it is running) graphUpdates.DisableMultithreading(); // Try to join pathfinding threads pathProcessor.JoinThreads(); if (logPathResults == PathLog.Heavy) Debug.Log("Returning Paths"); // Return all paths pathReturnQueue.ReturnPaths(false); if (logPathResults == PathLog.Heavy) Debug.Log("Destroying Graphs"); // Clean up graph data data.OnDestroy(); if (logPathResults == PathLog.Heavy) Debug.Log("Cleaning up variables"); // Clear variables up, static variables are good to clean up, otherwise the next scene might get weird data // Clear all callbacks OnAwakeSettings = null; OnGraphPreScan = null; OnGraphPostScan = null; OnPathPreSearch = null; OnPathPostSearch = null; OnPreScan = null; OnPostScan = null; OnLatePostScan = null; On65KOverflow = null; OnGraphsUpdated = null; active = null; } #region ScanMethods /// <summary> /// Floodfills starting from the specified node. /// /// Deprecated: Deprecated: Not meaningful anymore. The HierarchicalGraph takes care of things automatically behind the scenes /// </summary> [System.Obsolete("Not meaningful anymore. The HierarchicalGraph takes care of things automatically behind the scenes")] public void FloodFill (GraphNode seed) { } /// <summary> /// Floodfills starting from 'seed' using the specified area. /// /// Deprecated: Not meaningful anymore. The HierarchicalGraph takes care of things automatically behind the scenes /// </summary> [System.Obsolete("Not meaningful anymore. The HierarchicalGraph takes care of things automatically behind the scenes")] public void FloodFill (GraphNode seed, uint area) { } /// <summary> /// Floodfills all graphs and updates areas for every node. /// The different colored areas that you see in the scene view when looking at graphs /// are called just 'areas', this method calculates which nodes are in what areas. /// See: Pathfinding.Node.area /// /// Deprecated: Avoid using. This will force a full recalculation of the connected components. In most cases the HierarchicalGraph class takes care of things automatically behind the scenes now. /// </summary> [ContextMenu("Flood Fill Graphs")] [System.Obsolete("Avoid using. This will force a full recalculation of the connected components. In most cases the HierarchicalGraph class takes care of things automatically behind the scenes now.")] public void FloodFill () { hierarchicalGraph.RecalculateAll(); workItems.OnFloodFill(); } /// <summary> /// Returns a new global node index. /// Warning: This method should not be called directly. It is used by the GraphNode constructor. /// </summary> internal int GetNewNodeIndex () { return pathProcessor.GetNewNodeIndex(); } /// <summary> /// Initializes temporary path data for a node. /// Warning: This method should not be called directly. It is used by the GraphNode constructor. /// </summary> internal void InitializeNode (GraphNode node) { pathProcessor.InitializeNode(node); } /// <summary> /// Internal method to destroy a given node. /// This is to be called after the node has been disconnected from the graph so that it cannot be reached from any other nodes. /// It should only be called during graph updates, that is when the pathfinding threads are either not running or paused. /// /// Warning: This method should not be called by user code. It is used internally by the system. /// </summary> internal void DestroyNode (GraphNode node) { pathProcessor.DestroyNode(node); } /// <summary> /// Blocks until all pathfinding threads are paused and blocked. /// Deprecated: Use <see cref="PausePathfinding"/> instead. Make sure to call Release on the returned lock. /// </summary> [System.Obsolete("Use PausePathfinding instead. Make sure to call Release on the returned lock.", true)] public void BlockUntilPathQueueBlocked () { } /// <summary> /// Blocks until all pathfinding threads are paused and blocked. /// /// <code> /// var graphLock = AstarPath.active.PausePathfinding(); /// // Here we can modify the graphs safely. For example by adding a new node to a point graph /// var node = AstarPath.active.data.pointGraph.AddNode((Int3) new Vector3(3, 1, 4)); /// /// // Allow pathfinding to resume /// graphLock.Release(); /// </code> /// /// Returns: A lock object. You need to call <see cref="Pathfinding.PathProcessor.GraphUpdateLock.Release"/> on that object to allow pathfinding to resume. /// Note: In most cases this should not be called from user code. Use the <see cref="AddWorkItem"/> method instead. /// /// See: <see cref="AddWorkItem"/> /// </summary> public PathProcessor.GraphUpdateLock PausePathfinding () { return pathProcessor.PausePathfinding(true); } /// <summary>Blocks the path queue so that e.g work items can be performed</summary> PathProcessor.GraphUpdateLock PausePathfindingSoon () { return pathProcessor.PausePathfinding(false); } /// <summary> /// Scans a particular graph. /// Calling this method will recalculate the specified graph. /// This method is pretty slow (depending on graph type and graph complexity of course), so it is advisable to use /// smaller graph updates whenever possible. /// /// <code> /// // Recalculate all graphs /// AstarPath.active.Scan(); /// /// // Recalculate only the first grid graph /// var graphToScan = AstarPath.active.data.gridGraph; /// AstarPath.active.Scan(graphToScan); /// /// // Recalculate only the first and third graphs /// var graphsToScan = new [] { AstarPath.active.data.graphs[0], AstarPath.active.data.graphs[2] }; /// AstarPath.active.Scan(graphsToScan); /// </code> /// /// See: graph-updates (view in online documentation for working links) /// See: ScanAsync /// </summary> public void Scan (NavGraph graphToScan) { if (graphToScan == null) throw new System.ArgumentNullException(); Scan(new NavGraph[] { graphToScan }); } /// <summary> /// Scans all specified graphs. /// /// Calling this method will recalculate all specified graphs or all graphs if the graphsToScan parameter is null. /// This method is pretty slow (depending on graph type and graph complexity of course), so it is advisable to use /// smaller graph updates whenever possible. /// /// <code> /// // Recalculate all graphs /// AstarPath.active.Scan(); /// /// // Recalculate only the first grid graph /// var graphToScan = AstarPath.active.data.gridGraph; /// AstarPath.active.Scan(graphToScan); /// /// // Recalculate only the first and third graphs /// var graphsToScan = new [] { AstarPath.active.data.graphs[0], AstarPath.active.data.graphs[2] }; /// AstarPath.active.Scan(graphsToScan); /// </code> /// /// See: graph-updates (view in online documentation for working links) /// See: ScanAsync /// </summary> /// <param name="graphsToScan">The graphs to scan. If this parameter is null then all graphs will be scanned</param> public void Scan (NavGraph[] graphsToScan = null) { var prevProgress = new Progress(); Profiler.BeginSample("Scan"); Profiler.BeginSample("Init"); foreach (var p in ScanAsync(graphsToScan)) { if (prevProgress.description != p.description) { #if !NETFX_CORE && UNITY_EDITOR Profiler.EndSample(); Profiler.BeginSample(p.description); // Log progress to the console System.Console.WriteLine(p.description); prevProgress = p; #endif } } Profiler.EndSample(); Profiler.EndSample(); } /// <summary> /// Scans a particular graph asynchronously. This is a IEnumerable, you can loop through it to get the progress /// <code> /// foreach (Progress progress in AstarPath.active.ScanAsync()) { /// Debug.Log("Scanning... " + progress.description + " - " + (progress.progress*100).ToString("0") + "%"); /// } /// </code> /// You can scan graphs asyncronously by yielding when you loop through the progress. /// Note that this does not guarantee a good framerate, but it will allow you /// to at least show a progress bar during scanning. /// <code> /// IEnumerator Start () { /// foreach (Progress progress in AstarPath.active.ScanAsync()) { /// Debug.Log("Scanning... " + progress.description + " - " + (progress.progress*100).ToString("0") + "%"); /// yield return null; /// } /// } /// </code> /// /// See: Scan /// </summary> public IEnumerable<Progress> ScanAsync (NavGraph graphToScan) { if (graphToScan == null) throw new System.ArgumentNullException(); return ScanAsync(new NavGraph[] { graphToScan }); } /// <summary> /// Scans all specified graphs asynchronously. This is a IEnumerable, you can loop through it to get the progress /// /// <code> /// foreach (Progress progress in AstarPath.active.ScanAsync()) { /// Debug.Log("Scanning... " + progress.description + " - " + (progress.progress*100).ToString("0") + "%"); /// } /// </code> /// You can scan graphs asyncronously by yielding when you loop through the progress. /// Note that this does not guarantee a good framerate, but it will allow you /// to at least show a progress bar during scanning. /// <code> /// IEnumerator Start () { /// foreach (Progress progress in AstarPath.active.ScanAsync()) { /// Debug.Log("Scanning... " + progress.description + " - " + (progress.progress*100).ToString("0") + "%"); /// yield return null; /// } /// } /// </code> /// /// See: Scan /// </summary> /// <param name="graphsToScan">The graphs to scan. If this parameter is null then all graphs will be scanned</param> public IEnumerable<Progress> ScanAsync (NavGraph[] graphsToScan = null) { if (graphsToScan == null) graphsToScan = graphs; if (graphsToScan == null) { yield break; } if (isScanning) throw new System.InvalidOperationException("Another async scan is already running"); isScanning = true; VerifyIntegrity(); var graphUpdateLock = PausePathfinding(); // Make sure all paths that are in the queue to be returned // are returned immediately // Some modifiers (e.g the funnel modifier) rely on // the nodes being valid when the path is returned pathReturnQueue.ReturnPaths(false); if (!Application.isPlaying) { data.FindGraphTypes(); GraphModifier.FindAllModifiers(); } int startFrame = Time.frameCount; yield return new Progress(0.05F, "Pre processing graphs"); // Yes, this constraint is trivial to circumvent // the code is the same because it is annoying // to have to have separate code for the free // and the pro version that does essentially the same thing. // I would appreciate if you purchased the pro version of the A* Pathfinding Project // if you need async scanning. if (Time.frameCount != startFrame) { throw new System.Exception("Async scanning can only be done in the pro version of the A* Pathfinding Project"); } if (OnPreScan != null) { OnPreScan(this); } GraphModifier.TriggerEvent(GraphModifier.EventType.PreScan); data.LockGraphStructure(); var watch = System.Diagnostics.Stopwatch.StartNew(); // Destroy previous nodes for (int i = 0; i < graphsToScan.Length; i++) { if (graphsToScan[i] != null) { ((IGraphInternals)graphsToScan[i]).DestroyAllNodes(); } } // Loop through all graphs and scan them one by one for (int i = 0; i < graphsToScan.Length; i++) { // Skip null graphs if (graphsToScan[i] == null) continue; // Just used for progress information // This graph will advance the progress bar from minp to maxp float minp = Mathf.Lerp(0.1F, 0.8F, (float)(i)/(graphsToScan.Length)); float maxp = Mathf.Lerp(0.1F, 0.8F, (float)(i+0.95F)/(graphsToScan.Length)); var progressDescriptionPrefix = "Scanning graph " + (i+1) + " of " + graphsToScan.Length + " - "; // Like a foreach loop but it gets a little complicated because of the exception // handling (it is not possible to yield inside try-except clause). var coroutine = ScanGraph(graphsToScan[i]).GetEnumerator(); while (true) { try { if (!coroutine.MoveNext()) break; } catch { isScanning = false; data.UnlockGraphStructure(); graphUpdateLock.Release(); throw; } yield return coroutine.Current.MapTo(minp, maxp, progressDescriptionPrefix); } } data.UnlockGraphStructure(); yield return new Progress(0.8F, "Post processing graphs"); if (OnPostScan != null) { OnPostScan(this); } GraphModifier.TriggerEvent(GraphModifier.EventType.PostScan); FlushWorkItems(); yield return new Progress(0.9F, "Computing areas"); hierarchicalGraph.RecalculateIfNecessary(); yield return new Progress(0.95F, "Late post processing"); // Signal that we have stopped scanning here // Note that no yields can happen after this point // since then other parts of the system can start to interfere isScanning = false; if (OnLatePostScan != null) { OnLatePostScan(this); } GraphModifier.TriggerEvent(GraphModifier.EventType.LatePostScan); euclideanEmbedding.dirty = true; euclideanEmbedding.RecalculatePivots(); // Perform any blocking actions FlushWorkItems(); // Resume pathfinding threads graphUpdateLock.Release(); watch.Stop(); lastScanTime = (float)watch.Elapsed.TotalSeconds; System.GC.Collect(); if (logPathResults != PathLog.None && logPathResults != PathLog.OnlyErrors) { Debug.Log("Scanning - Process took "+(lastScanTime*1000).ToString("0")+" ms to complete"); } } IEnumerable<Progress> ScanGraph (NavGraph graph) { if (OnGraphPreScan != null) { yield return new Progress(0, "Pre processing"); OnGraphPreScan(graph); } yield return new Progress(0, ""); foreach (var p in ((IGraphInternals)graph).ScanInternal()) { yield return p.MapTo(0, 0.95f); } yield return new Progress(0.95f, "Assigning graph indices"); // Assign the graph index to every node in the graph graph.GetNodes(node => node.GraphIndex = (uint)graph.graphIndex); if (OnGraphPostScan != null) { yield return new Progress(0.99f, "Post processing"); OnGraphPostScan(graph); } } #endregion private static int waitForPathDepth = 0; /// <summary> /// Wait for the specified path to be calculated. /// Normally it takes a few frames for a path to get calculated and returned. /// /// Deprecated: This method has been renamed to <see cref="BlockUntilCalculated"/>. /// </summary> [System.Obsolete("This method has been renamed to BlockUntilCalculated")] public static void WaitForPath (Path path) { BlockUntilCalculated(path); } /// <summary> /// Blocks until the path has been calculated. /// /// Normally it takes a few frames for a path to be calculated and returned. /// This function will ensure that the path will be calculated when this function returns /// and that the callback for that path has been called. /// /// If requesting a lot of paths in one go and waiting for the last one to complete, /// it will calculate most of the paths in the queue (only most if using multithreading, all if not using multithreading). /// /// Use this function only if you really need to. /// There is a point to spreading path calculations out over several frames. /// It smoothes out the framerate and makes sure requesting a large /// number of paths at the same time does not cause lag. /// /// Note: Graph updates and other callbacks might get called during the execution of this function. /// /// When the pathfinder is shutting down. I.e in OnDestroy, this function will not do anything. /// /// \throws Exception if pathfinding is not initialized properly for this scene (most likely no AstarPath object exists) /// or if the path has not been started yet. /// Also throws an exception if critical errors occur such as when the pathfinding threads have crashed (which should not happen in normal cases). /// This prevents an infinite loop while waiting for the path. /// /// See: Pathfinding.Path.WaitForPath /// See: Pathfinding.Path.BlockUntilCalculated /// </summary> /// <param name="path">The path to wait for. The path must be started, otherwise an exception will be thrown.</param> public static void BlockUntilCalculated (Path path) { if (active == null) throw new System.Exception("Pathfinding is not correctly initialized in this scene (yet?). " + "AstarPath.active is null.\nDo not call this function in Awake"); if (path == null) throw new System.ArgumentNullException("Path must not be null"); if (active.pathProcessor.queue.IsTerminating) return; if (path.PipelineState == PathState.Created) { throw new System.Exception("The specified path has not been started yet."); } waitForPathDepth++; if (waitForPathDepth == 5) { Debug.LogError("You are calling the BlockUntilCalculated function recursively (maybe from a path callback). Please don't do this."); } if (path.PipelineState < PathState.ReturnQueue) { if (active.IsUsingMultithreading) { while (path.PipelineState < PathState.ReturnQueue) { if (active.pathProcessor.queue.IsTerminating) { waitForPathDepth--; throw new System.Exception("Pathfinding Threads seem to have crashed."); } // Wait for threads to calculate paths Thread.Sleep(1); active.PerformBlockingActions(true); } } else { while (path.PipelineState < PathState.ReturnQueue) { if (active.pathProcessor.queue.IsEmpty && path.PipelineState != PathState.Processing) { waitForPathDepth--; throw new System.Exception("Critical error. Path Queue is empty but the path state is '" + path.PipelineState + "'"); } // Calculate some paths active.pathProcessor.TickNonMultithreaded(); active.PerformBlockingActions(true); } } } active.pathReturnQueue.ReturnPaths(false); waitForPathDepth--; } /// <summary> /// Will send a callback when it is safe to update nodes. This is defined as between the path searches. /// This callback will only be sent once and is nulled directly after the callback has been sent. /// When using more threads than one, calling this often might decrease pathfinding performance due to a lot of idling in the threads. /// Not performance as in it will use much CPU power, /// but performance as in the number of paths per second will probably go down (though your framerate might actually increase a tiny bit) /// /// You should only call this function from the main unity thread (i.e normal game code). /// /// Version: Since version 4.0 this is equivalent to AddWorkItem(new AstarWorkItem(callback)). Previously the /// callbacks added using this method would not be ordered with respect to other work items, so they could be /// executed before other work items or after them. /// /// Deprecated: Use <see cref="AddWorkItem(System.Action)"/> instead. Note the slight change in behavior (mentioned above). /// </summary> [System.Obsolete("Use AddWorkItem(System.Action) instead. Note the slight change in behavior (mentioned in the documentation).")] public static void RegisterSafeUpdate (System.Action callback) { active.AddWorkItem(new AstarWorkItem(callback)); } /// <summary> /// Adds the path to a queue so that it will be calculated as soon as possible. /// The callback specified when constructing the path will be called when the path has been calculated. /// Usually you should use the Seeker component instead of calling this function directly. /// </summary> /// <param name="path">The path that should be enqueued.</param> /// <param name="pushToFront">If true, the path will be pushed to the front of the queue, bypassing all waiting paths and making it the next path to be calculated. /// This can be useful if you have a path which you want to prioritize over all others. Be careful to not overuse it though. /// If too many paths are put in the front of the queue often, this can lead to normal paths having to wait a very long time before being calculated.</param> public static void StartPath (Path path, bool pushToFront = false) { // Copy to local variable to avoid multithreading issues var astar = active; if (System.Object.ReferenceEquals(astar, null)) { Debug.LogError("There is no AstarPath object in the scene or it has not been initialized yet"); return; } if (path.PipelineState != PathState.Created) { throw new System.Exception("The path has an invalid state. Expected " + PathState.Created + " found " + path.PipelineState + "\n" + "Make sure you are not requesting the same path twice"); } if (astar.pathProcessor.queue.IsTerminating) { path.FailWithError("No new paths are accepted"); return; } if (astar.graphs == null || astar.graphs.Length == 0) { Debug.LogError("There are no graphs in the scene"); path.FailWithError("There are no graphs in the scene"); Debug.LogError(path.errorLog); return; } path.Claim(astar); // Will increment p.state to PathState.PathQueue ((IPathInternals)path).AdvanceState(PathState.PathQueue); if (pushToFront) { astar.pathProcessor.queue.PushFront(path); } else { astar.pathProcessor.queue.Push(path); } // Outside of play mode, all path requests are synchronous if (!Application.isPlaying) { BlockUntilCalculated(path); } } /// <summary> /// Cached NNConstraint.None to avoid unnecessary allocations. /// This should ideally be fixed by making NNConstraint an immutable class/struct. /// </summary> static readonly NNConstraint NNConstraintNone = NNConstraint.None; /// <summary> /// Returns the nearest node to a position using the specified NNConstraint. /// Searches through all graphs for their nearest nodes to the specified position and picks the closest one.\n /// Using the NNConstraint.None constraint. /// /// <code> /// // Find the closest node to this GameObject's position /// GraphNode node = AstarPath.active.GetNearest(transform.position).node; /// /// if (node.Walkable) { /// // Yay, the node is walkable, we can place a tower here or something /// } /// </code> /// /// See: Pathfinding.NNConstraint /// </summary> public NNInfo GetNearest (Vector3 position) { return GetNearest(position, NNConstraintNone); } /// <summary> /// Returns the nearest node to a position using the specified NNConstraint. /// Searches through all graphs for their nearest nodes to the specified position and picks the closest one. /// The NNConstraint can be used to specify constraints on which nodes can be chosen such as only picking walkable nodes. /// /// <code> /// GraphNode node = AstarPath.active.GetNearest(transform.position, NNConstraint.Default).node; /// </code> /// /// <code> /// var constraint = NNConstraint.None; /// /// // Constrain the search to walkable nodes only /// constraint.constrainWalkability = true; /// constraint.walkable = true; /// /// // Constrain the search to only nodes with tag 3 or tag 5 /// // The 'tags' field is a bitmask /// constraint.constrainTags = true; /// constraint.tags = (1 << 3) | (1 << 5); /// /// var info = AstarPath.active.GetNearest(transform.position, constraint); /// var node = info.node; /// var closestPoint = info.position; /// </code> /// /// See: Pathfinding.NNConstraint /// </summary> public NNInfo GetNearest (Vector3 position, NNConstraint constraint) { return GetNearest(position, constraint, null); } /// <summary> /// Returns the nearest node to a position using the specified NNConstraint. /// Searches through all graphs for their nearest nodes to the specified position and picks the closest one. /// The NNConstraint can be used to specify constraints on which nodes can be chosen such as only picking walkable nodes. /// See: Pathfinding.NNConstraint /// </summary> public NNInfo GetNearest (Vector3 position, NNConstraint constraint, GraphNode hint) { // Cache property lookup var graphs = this.graphs; float minDist = float.PositiveInfinity; NNInfoInternal nearestNode = new NNInfoInternal(); int nearestGraph = -1; if (graphs != null) { for (int i = 0; i < graphs.Length; i++) { NavGraph graph = graphs[i]; // Check if this graph should be searched if (graph == null || !constraint.SuitableGraph(i, graph)) { continue; } NNInfoInternal nnInfo; if (fullGetNearestSearch) { // Slower nearest node search // this will try to find a node which is suitable according to the constraint nnInfo = graph.GetNearestForce(position, constraint); } else { // Fast nearest node search // just find a node close to the position without using the constraint that much // (unless that comes essentially 'for free') nnInfo = graph.GetNearest(position, constraint); } GraphNode node = nnInfo.node; // No node found in this graph if (node == null) { continue; } // Distance to the closest point on the node from the requested position float dist = ((Vector3)nnInfo.clampedPosition-position).magnitude; if (prioritizeGraphs && dist < prioritizeGraphsLimit) { // The node is close enough, choose this graph and discard all others minDist = dist; nearestNode = nnInfo; nearestGraph = i; break; } else { // Choose the best node found so far if (dist < minDist) { minDist = dist; nearestNode = nnInfo; nearestGraph = i; } } } } // No matches found if (nearestGraph == -1) { return new NNInfo(); } // Check if a constrained node has already been set if (nearestNode.constrainedNode != null) { nearestNode.node = nearestNode.constrainedNode; nearestNode.clampedPosition = nearestNode.constClampedPosition; } if (!fullGetNearestSearch && nearestNode.node != null && !constraint.Suitable(nearestNode.node)) { // Otherwise, perform a check to force the graphs to check for a suitable node NNInfoInternal nnInfo = graphs[nearestGraph].GetNearestForce(position, constraint); if (nnInfo.node != null) { nearestNode = nnInfo; } } if (!constraint.Suitable(nearestNode.node) || (constraint.constrainDistance && (nearestNode.clampedPosition - position).sqrMagnitude > maxNearestNodeDistanceSqr)) { return new NNInfo(); } // Convert to NNInfo which doesn't have all the internal fields return new NNInfo(nearestNode); } /// <summary> /// Returns the node closest to the ray (slow). /// Warning: This function is brute-force and very slow, use with caution /// </summary> public GraphNode GetNearest (Ray ray) { if (graphs == null) return null; float minDist = Mathf.Infinity; GraphNode nearestNode = null; Vector3 lineDirection = ray.direction; Vector3 lineOrigin = ray.origin; for (int i = 0; i < graphs.Length; i++) { NavGraph graph = graphs[i]; graph.GetNodes(node => { Vector3 pos = (Vector3)node.position; Vector3 p = lineOrigin+(Vector3.Dot(pos-lineOrigin, lineDirection)*lineDirection); float tmp = Mathf.Abs(p.x-pos.x); tmp *= tmp; if (tmp > minDist) return; tmp = Mathf.Abs(p.z-pos.z); tmp *= tmp; if (tmp > minDist) return; float dist = (p-pos).sqrMagnitude; if (dist < minDist) { minDist = dist; nearestNode = node; } return; }); } return nearestNode; } }
37.201493
200
0.707548
[ "MIT" ]
I-AM-INSANE/WizardSurvival
Assets/UploadedMaterials/AstarPathfindingProject/Core/AstarPath.cs
79,760
C#
using System.Collections.Generic; namespace Alpinely.TownCrier { /// <summary> /// Factory class for creating "mail-merged" MailMessage objects /// </summary> public class MergedEmailFactory { protected MailMessageWrapper Message; public MergedEmailFactory(ITemplateParser templateParser) { Message = new MailMessageWrapper(templateParser); } public MailMessageWrapper WithTokenValues(IDictionary<string, object> tokenValues) { Message.TokenValues = tokenValues; return Message; } } }
26.217391
90
0.651741
[ "MIT" ]
flightlog/flsserver
src/Alpinely.TownCrier/MergedEmailFactory.cs
603
C#
using Niantic.ARDK.AR; using Niantic.ARDK.Utilities.Logging; using UnityEngine; using UnityEngine.Rendering; using Object = UnityEngine.Object; namespace Niantic.ARDK.Rendering { internal sealed class _ARKitFrameRenderer: ARFrameRenderer { // Rendering resources private CommandBuffer _commandBuffer; private Texture2D _textureY, _textureCbCr; protected override Shader Shader { get; } public _ARKitFrameRenderer(RenderTarget target) : base(target) { Shader = Resources.Load<Shader>("ARKitFrame"); } public _ARKitFrameRenderer ( RenderTarget target, float near, float far, Shader customShader = null ) : base(target, near, far) { Shader = customShader ? customShader : Resources.Load<Shader>("ARKitFrame"); ARLog._Debug("Loaded: " + (Shader != null ? Shader.name : null)); } protected override GraphicsFence? OnConfigurePipeline ( RenderTarget target, Resolution targetResolution, Resolution sourceResolution, Material renderMaterial ) { if (target.IsTargetingTexture) { // When not targeting a camera, we do not create a command buffer. // This is because currently, executing the command buffer manually // causes the GPU to hang on iOS. Could be a driver or Unity issue. return null; } _commandBuffer = new CommandBuffer { name = "ARKitFrameRenderer" }; _commandBuffer.ClearRenderTarget(true, true, Color.clear); _commandBuffer.Blit(null, target.Identifier, renderMaterial); #if UNITY_2019_1_OR_NEWER return _commandBuffer.CreateAsyncGraphicsFence(); #else return _commandBuffer.CreateGPUFence(); #endif } protected override void OnAddToCamera(Camera camera) { ARSessionBuffersHelper.AddBackgroundBuffer(camera, _commandBuffer); } protected override void OnRemoveFromCamera(Camera camera) { ARSessionBuffersHelper.RemoveBackgroundBuffer(camera, _commandBuffer); } protected override void OnIssueCommands() { // This call raises GPU exceptions on iOS // Graphics.ExecuteCommandBuffer(_commandBuffer); // As an alternative, we blit to the target var target = Target.RenderTexture; BlitToTexture(ref target); } protected override bool OnUpdateState ( IARFrame frame, Matrix4x4 projectionTransform, Matrix4x4 displayTransform, Material material ) { // We require a biplanar input from ARKit if (frame.CapturedImageTextures.Length < 2) return false; var nativeResolution = frame.Camera.ImageResolution; var yResolution = nativeResolution; var uvResolution = new Resolution { width = nativeResolution.width / 2, height = nativeResolution.height / 2 }; // Update source textures CreateOrUpdateExternalTexture (ref _textureY, yResolution, TextureFormat.R8, frame.CapturedImageTextures[0]); CreateOrUpdateExternalTexture (ref _textureCbCr, uvResolution, TextureFormat.RG16, frame.CapturedImageTextures[1]); // Bind textures and the display transform material.SetTexture(PropertyBindings.YChannel, _textureY); material.SetTexture(PropertyBindings.CbCrChannel, _textureCbCr); material.SetMatrix(PropertyBindings.DisplayTransform, displayTransform); return true; } protected override void OnRelease() { _commandBuffer?.Dispose(); if (_textureY != null) Object.Destroy(_textureY); if (_textureCbCr != null) Object.Destroy(_textureCbCr); } } }
27.540741
93
0.681011
[ "MIT" ]
mactrix-markjohn/FurnishAR
FurnishAR/Assets/ARDK/Rendering/FrameRenderer/_ARKitFrameRenderer.cs
3,720
C#
using FluentEmail.Core.Interfaces; using FluentEmail.Mailgun; using Microsoft.Extensions.DependencyInjection.Extensions; using System; using System.Collections.Generic; using System.Net.Mail; using System.Text; namespace Microsoft.Extensions.DependencyInjection { public static class FluentEmailMailgunBuilderExtensions { public static FluentEmailServicesBuilder AddMailGunSender(this FluentEmailServicesBuilder builder, string domainName, string apiKey) { builder.Services.TryAdd(ServiceDescriptor.Scoped<ISender>(x => new MailgunSender(domainName, apiKey))); return builder; } } }
32.25
140
0.765891
[ "MIT" ]
Noctis-/FluentEmail
src/Senders/FluentEmail.Mailgun/FluentEmailMailgunBuilderExtensions.cs
647
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.Ecs.Model.V20140526 { public class CreateDiskReplicaPairResponse : AcsResponse { private string requestId; private string pairId; public string RequestId { get { return requestId; } set { requestId = value; } } public string PairId { get { return pairId; } set { pairId = value; } } } }
22.526316
63
0.688474
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-ecs/Ecs/Model/V20140526/CreateDiskReplicaPairResponse.cs
1,284
C#
using System; using System.Collections.Generic; using Android.Runtime; using Java.Interop; namespace Com.Microsoft.Identity.Common.Internal.Telemetry.Events { // Metadata.xml XPath class reference: path="/api/package[@name='com.microsoft.identity.common.internal.telemetry.events']/class[@name='HttpEndEvent']" [global::Android.Runtime.Register ("com/microsoft/identity/common/internal/telemetry/events/HttpEndEvent", DoNotGenerateAcw=true)] public partial class HttpEndEvent : global::Com.Microsoft.Identity.Common.Internal.Telemetry.Events.BaseEvent { static readonly JniPeerMembers _members = new XAPeerMembers ("com/microsoft/identity/common/internal/telemetry/events/HttpEndEvent", typeof (HttpEndEvent)); internal static new IntPtr class_ref { get { return _members.JniPeerType.PeerReference.Handle; } } [global::System.Diagnostics.DebuggerBrowsable (global::System.Diagnostics.DebuggerBrowsableState.Never)] [global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)] public override global::Java.Interop.JniPeerMembers JniPeerMembers { get { return _members; } } [global::System.Diagnostics.DebuggerBrowsable (global::System.Diagnostics.DebuggerBrowsableState.Never)] [global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)] protected override IntPtr ThresholdClass { get { return _members.JniPeerType.PeerReference.Handle; } } [global::System.Diagnostics.DebuggerBrowsable (global::System.Diagnostics.DebuggerBrowsableState.Never)] [global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)] protected override global::System.Type ThresholdType { get { return _members.ManagedPeerType; } } protected HttpEndEvent (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) { } // Metadata.xml XPath constructor reference: path="/api/package[@name='com.microsoft.identity.common.internal.telemetry.events']/class[@name='HttpEndEvent']/constructor[@name='HttpEndEvent' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe HttpEndEvent () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { const string __id = "()V"; if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { var __r = _members.InstanceMethods.StartCreateInstance (__id, ((object) this).GetType (), null); SetHandle (__r.Handle, JniHandleOwnership.TransferLocalRef); _members.InstanceMethods.FinishCreateInstance (__id, this, null); } finally { } } static Delegate cb_putStatusCode_I; #pragma warning disable 0169 static Delegate GetPutStatusCode_IHandler () { if (cb_putStatusCode_I == null) cb_putStatusCode_I = JNINativeWrapper.CreateDelegate ((_JniMarshal_PPI_L) n_PutStatusCode_I); return cb_putStatusCode_I; } static IntPtr n_PutStatusCode_I (IntPtr jnienv, IntPtr native__this, int statusCode) { var __this = global::Java.Lang.Object.GetObject<global::Com.Microsoft.Identity.Common.Internal.Telemetry.Events.HttpEndEvent> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.PutStatusCode (statusCode)); } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/package[@name='com.microsoft.identity.common.internal.telemetry.events']/class[@name='HttpEndEvent']/method[@name='putStatusCode' and count(parameter)=1 and parameter[1][@type='int']]" [Register ("putStatusCode", "(I)Lcom/microsoft/identity/common/internal/telemetry/events/HttpEndEvent;", "GetPutStatusCode_IHandler")] public virtual unsafe global::Com.Microsoft.Identity.Common.Internal.Telemetry.Events.HttpEndEvent PutStatusCode (int statusCode) { const string __id = "putStatusCode.(I)Lcom/microsoft/identity/common/internal/telemetry/events/HttpEndEvent;"; try { JniArgumentValue* __args = stackalloc JniArgumentValue [1]; __args [0] = new JniArgumentValue (statusCode); var __rm = _members.InstanceMethods.InvokeVirtualObjectMethod (__id, this, __args); return global::Java.Lang.Object.GetObject<global::Com.Microsoft.Identity.Common.Internal.Telemetry.Events.HttpEndEvent> (__rm.Handle, JniHandleOwnership.TransferLocalRef); } finally { } } } }
49.397727
237
0.777088
[ "MIT" ]
moljac/MSAL-Bindings
externals/code-generated-MCW/com.microsoft.identity-common/3.0.9/plain/generated/src/Com.Microsoft.Identity.Common.Internal.Telemetry.Events.HttpEndEvent.cs
4,347
C#
using System.Diagnostics; using System.Windows; using System.Windows.Input; using HelixToolkit.Wpf.SharpDX.Model.Scene2D; using SharpDX; namespace HelixToolkit.Wpf.SharpDX.Elements2D { public abstract class Clickable2D : Border2D { public static long DoubleClickThreshold = 300; #region Dependency Properties public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(Clickable2D), new PropertyMetadata(null)); public ICommand Command { set { SetValue(CommandProperty, value); } get { return (ICommand)GetValue(CommandProperty); } } #endregion #region Events public static readonly RoutedEvent Clicked2DEvent = EventManager.RegisterRoutedEvent("Clicked2D", RoutingStrategy.Bubble, typeof(Mouse2DRoutedEventHandler), typeof(Clickable2D)); public event Mouse2DRoutedEventHandler Clicked2D { add { AddHandler(Clicked2DEvent, value); } remove { RemoveHandler(Clicked2DEvent, value); } } public static readonly RoutedEvent DoubleClicked2DEvent = EventManager.RegisterRoutedEvent("DoubleClicked2D", RoutingStrategy.Bubble, typeof(Mouse2DRoutedEventHandler), typeof(Clickable2D)); public event Mouse2DRoutedEventHandler DoubleClicked2D { add { AddHandler(DoubleClicked2DEvent, value); } remove { RemoveHandler(DoubleClicked2DEvent, value); } } #endregion private long lastClickedTime = 0; public Clickable2D() { MouseDown2D += Clickable2D_MouseDown2D; MouseEnter2D += Clickable2D_MouseEnter2D; MouseLeave2D += Clickable2D_MouseLeave2D; } protected override SceneNode2D OnCreateSceneNode() { return new ClickableNode2D(); } private void Clickable2D_MouseLeave2D(object sender, Mouse2DEventArgs e) { } private void Clickable2D_MouseEnter2D(object sender, Mouse2DEventArgs e) { } private void Clickable2D_MouseDown2D(object sender, Mouse2DEventArgs e) { if(e.InputArgs is TouchEventArgs || (e.InputArgs is MouseEventArgs && (e.InputArgs as MouseEventArgs).LeftButton == MouseButtonState.Pressed)) { long time = e.InputArgs.Timestamp; if (time - lastClickedTime < DoubleClickThreshold) { RaiseEvent(new Mouse2DEventArgs(DoubleClicked2DEvent, this)); #if DEBUG Debug.WriteLine("DoubleClicked2DEvent"); #endif } else { RaiseEvent(new Mouse2DEventArgs(Clicked2DEvent, this)); #if DEBUG Debug.WriteLine("Clicked2DEvent"); #endif Command?.Execute(e); } lastClickedTime = time; } } } }
31.77551
174
0.611111
[ "MIT" ]
NaBian/helix-toolkit
Source/HelixToolkit.Wpf.SharpDX/Model/Elements2D/Abstract/Clickable2D.cs
3,116
C#
/* Copyright (c) 2017 Marcin Szeniak (https://github.com/Klocman/) Apache License Version 2.0 */ using System; using Klocman.Extensions; using Klocman.IO; using Klocman.Native; namespace UninstallTools.Factory.InfoAdders { public class MsiInfoAdder : IMissingInfoAdder { public void AddMissingInformation(ApplicationUninstallerEntry target) { //Debug.Assert(target.UninstallerKind != UninstallerType.Msiexec); if (target.UninstallerKind != UninstallerType.Msiexec) return; ApplyMsiInfo(target, target.BundleProviderKey); } public string[] RequiredValueNames { get; } = { nameof(ApplicationUninstallerEntry.UninstallerKind), nameof(ApplicationUninstallerEntry.BundleProviderKey) }; public bool RequiresAllValues { get; } = true; public bool AlwaysRun { get; } = false; public string[] CanProduceValueNames { get; } = { nameof(ApplicationUninstallerEntry.RawDisplayName), nameof(ApplicationUninstallerEntry.DisplayVersion), nameof(ApplicationUninstallerEntry.Publisher), nameof(ApplicationUninstallerEntry.InstallLocation), nameof(ApplicationUninstallerEntry.InstallSource), nameof(ApplicationUninstallerEntry.UninstallerFullFilename), nameof(ApplicationUninstallerEntry.DisplayIcon), nameof(ApplicationUninstallerEntry.AboutUrl), nameof(ApplicationUninstallerEntry.InstallDate) }; public InfoAdderPriority Priority { get; } = InfoAdderPriority.RunFirst; /// <summary> /// A valid guid is REQUIRED. It doesn't have to be set on the entry, but should be. /// </summary> private static void ApplyMsiInfo(ApplicationUninstallerEntry entry, Guid guid) { //IMPORTANT: If MsiGetProductInfo returns null it means that the guid is invalid or app is not installed if (MsiTools.MsiGetProductInfo(guid, MsiWrapper.INSTALLPROPERTY.PRODUCTNAME) == null) return; FillInMissingInfoMsiHelper(() => entry.RawDisplayName, x => entry.RawDisplayName = x, guid, MsiWrapper.INSTALLPROPERTY.INSTALLEDPRODUCTNAME, MsiWrapper.INSTALLPROPERTY.PRODUCTNAME); FillInMissingInfoMsiHelper(() => entry.DisplayVersion, x => entry.DisplayVersion = ApplicationEntryTools.CleanupDisplayVersion(x), guid, MsiWrapper.INSTALLPROPERTY.VERSIONSTRING, MsiWrapper.INSTALLPROPERTY.VERSION); FillInMissingInfoMsiHelper(() => entry.Publisher, x => entry.Publisher = x, guid, MsiWrapper.INSTALLPROPERTY.PUBLISHER); FillInMissingInfoMsiHelper(() => entry.InstallLocation, x => entry.InstallLocation = x, guid, MsiWrapper.INSTALLPROPERTY.INSTALLLOCATION); FillInMissingInfoMsiHelper(() => entry.InstallSource, x => entry.InstallSource = x, guid, MsiWrapper.INSTALLPROPERTY.INSTALLSOURCE); FillInMissingInfoMsiHelper(() => entry.UninstallerFullFilename, x => entry.UninstallerFullFilename = x, guid, MsiWrapper.INSTALLPROPERTY.LOCALPACKAGE); FillInMissingInfoMsiHelper(() => entry.DisplayIcon, x => entry.DisplayIcon = x, guid, MsiWrapper.INSTALLPROPERTY.PRODUCTICON); FillInMissingInfoMsiHelper(() => entry.AboutUrl, x => entry.AboutUrl = x, guid, MsiWrapper.INSTALLPROPERTY.HELPLINK, MsiWrapper.INSTALLPROPERTY.URLUPDATEINFO, MsiWrapper.INSTALLPROPERTY.URLINFOABOUT); if (!entry.InstallDate.IsDefault()) return; var temp = MsiTools.MsiGetProductInfo(guid, MsiWrapper.INSTALLPROPERTY.INSTALLDATE); if (!temp.IsNotEmpty()) return; try { entry.InstallDate = new DateTime(int.Parse(temp.Substring(0, 4)), int.Parse(temp.Substring(4, 2)), int.Parse(temp.Substring(6, 2))); } catch { // Date had invalid format, default to nothing } } private static void FillInMissingInfoMsiHelper(Func<string> get, Action<string> set, Guid guid, params MsiWrapper.INSTALLPROPERTY[] properties) { if (string.IsNullOrEmpty(get())) { foreach (var item in properties) { var temp = MsiTools.MsiGetProductInfo(guid, item); //IMPORTANT: Do not assign empty strings, they will mess up automatic property creation later on. if (temp.IsNotEmpty()) set(temp); } } } } }
45.082569
149
0.619658
[ "Apache-2.0" ]
102464/Bulk-Crap-Uninstaller
source/UninstallTools/Factory/InfoAdders/MsiInfoAdder.cs
4,914
C#
using Libmirobot.GCode.InstructionParameters; using Libmirobot.GCode.Instructions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace libmirobotTests.GCodeInstructions { [TestClass] public class CartesianModeAbsoluteLinMotionInstructionShould { [TestMethod] public void ProduceCorrectlyFormattedGCode() { var testObject = new CartesianModeAbsoluteLinMotionInstruction(); var testResult = testObject.GenerateGCode(new MotionInstructionParameter { PositioningParameter1 = 1.1f, PositioningParameter2 = 2.2f, PositioningParameter3 = 3.3f, PositioningParameter4 = 4.4f, PositioningParameter5 = 5.5f, PositioningParameter6 = 6.6f, Speed = 2000 }); Assert.AreEqual("M20 G90 G1 X1.1 Y2.2 Z3.3 A4.4 B5.5 C6.6 F2000", testResult); } } }
32.1
90
0.630322
[ "MIT" ]
da84/libmirobot
Libmirobot/libmirobotTests/GCodeInstructions/CartesianModeAbsoluteLinMotionInstructionShould.cs
965
C#
namespace Shapes { using System; public abstract class Shape { private double width; private double height; public Shape(double width, double height) { this.Width = width; this.Height = height; } public double Width { get { return this.width; } set { if (value <= 0) { throw new ArgumentOutOfRangeException("Width cannot be negative or zero"); } this.width = value; } } public double Height { get { return this.height; } set { if (value <= 0) { throw new ArgumentOutOfRangeException("Height cannot be negative or zero"); } this.height = value; } } public abstract double CalculateSurface(); } }
22.909091
95
0.431548
[ "MIT" ]
Camyul/Modul_1
Object-Oriented-Programming/05. OOP-Principles-Part-2/01. Shapes/Shape.cs
1,010
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.3615 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Pololu.SimpleMotorController.SmcExample2.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Pololu.SimpleMotorController.SmcExample2.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
45.390625
207
0.606196
[ "MIT" ]
pololu/pololu-usb-sdk
SimpleMotorController/SmcExample2/Properties/Resources.Designer.cs
2,907
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Cosmonaut.Exceptions; using Cosmonaut.Internal; namespace Cosmonaut.Extensions { internal static class CosmosSqlQueryExtensions { private static readonly Regex SingleIdentifierMatchRegex = new Regex("from ([a-zA-Z0-9]+)?", RegexOptions.IgnoreCase); private static readonly Regex IdentifierMatchRegex = new Regex("from ([a-zA-Z0-9]+)? ([a-zA-Z0-9]+)?", RegexOptions.IgnoreCase); private static readonly Regex IdentifierWithAsMatchRegex = new Regex("from ([a-zA-Z0-9]+)? as ([a-zA-Z0-9]+)?", RegexOptions.IgnoreCase); private static readonly IEnumerable<string> PostSelectCosmosSqlOperators = new[] {"where", "order", "join", "as", "select", "by"}; internal static string EnsureQueryIsCollectionSharingFriendly<TEntity>(this string sql) where TEntity : class { var isSharedQuery = typeof(TEntity).UsesSharedCollection(); if (!isSharedQuery) return sql; var identifier = GetCollectionIdentifier(sql); var cosmosEntityNameValue = $"{typeof(TEntity).GetSharedCollectionEntityName()}"; var hasExistingWhereClause = sql.IndexOf(" where ", StringComparison.OrdinalIgnoreCase) >= 0; if (!hasExistingWhereClause) { var whereClause = $"where {identifier}.{nameof(ISharedCosmosEntity.CosmosEntityName)} = '{cosmosEntityNameValue}'"; var hasOrderBy = sql.IndexOf(" order by ", StringComparison.OrdinalIgnoreCase) >= 0; if(!hasOrderBy) return $"{sql} {whereClause}"; var splitSql = Regex.Split(sql, " order by ", RegexOptions.IgnoreCase); return $"{splitSql[0]} {whereClause} order by {splitSql[1]}"; } return GetQueryWithExistingWhereClauseInjectedWithSharedCollection(sql, identifier, cosmosEntityNameValue); } // internal static SqlParameterCollection ConvertToSqlParameterCollection(this object obj) // { // var sqlParameterCollection = new SqlParameterCollection(); // // if (obj == null) // return sqlParameterCollection; // // foreach (var propertyInfo in InternalTypeCache.Instance.GetPropertiesFromCache(obj.GetType())) // { // var propertyName = propertyInfo.Name.StartsWith("@") ? propertyInfo.Name : $"@{propertyInfo.Name}"; // var propertyValue = propertyInfo.GetValue(obj); // var sqlparameter = new SqlParameter(propertyName, propertyValue); // sqlParameterCollection.Add(sqlparameter); // } // // return sqlParameterCollection; // } // // internal static SqlParameterCollection ConvertDictionaryToSqlParameterCollection(this IDictionary<string, object> dictionary) // { // var sqlParameterCollection = new SqlParameterCollection(); // // if (dictionary == null) // return sqlParameterCollection; // // foreach (var pair in dictionary) // { // var key = pair.Key.StartsWith("@") ? pair.Key : $"@{pair.Key}"; // var sqlparameter = new SqlParameter(key, pair.Value); // sqlParameterCollection.Add(sqlparameter); // } // // return sqlParameterCollection; // } private static string GetQueryWithExistingWhereClauseInjectedWithSharedCollection(string sql, string identifier, string cosmosEntityNameValue) { var splitQuery = Regex.Split(sql, " where ", RegexOptions.IgnoreCase); var firstPartQuery = splitQuery[0]; var secondPartQuery = splitQuery[1]; var sharedCollectionExpressionQuery = $"{identifier}.{nameof(ISharedCosmosEntity.CosmosEntityName)} = '{cosmosEntityNameValue}'"; return $"{firstPartQuery} where {sharedCollectionExpressionQuery} and {secondPartQuery}"; } private static string GetCollectionIdentifier(string sql) { var matchedWithAs = IdentifierWithAsMatchRegex.Match(sql); if (matchedWithAs.Success) { return GetPorentialIdentifierWithTheAsKeyword(sql, matchedWithAs); } var matchedGroups = IdentifierMatchRegex.Match(sql); if (matchedGroups.Success && matchedGroups.Groups.Count == 3) { return GetPotentialIdentifierWith3MatchedGroups(matchedGroups); } if (matchedGroups.Success && matchedGroups.Groups.Count == 2) { var potentialIdentifier = matchedGroups.Groups[1].Value; if (!PostSelectCosmosSqlOperators.Contains(potentialIdentifier, StringComparer.OrdinalIgnoreCase)) { return matchedGroups.Groups[1].Value; } } var singleIdentifierMatch = SingleIdentifierMatchRegex.Match(sql); if (singleIdentifierMatch.Success && !PostSelectCosmosSqlOperators.Contains(singleIdentifierMatch.Groups[1].Value)) { return singleIdentifierMatch.Groups[1].Value; } throw new InvalidSqlQueryException(sql); } private static string GetPotentialIdentifierWith3MatchedGroups(Match matchedGroups) { var potentialIdentifier = matchedGroups.Groups[2].Value; return PostSelectCosmosSqlOperators.Contains(potentialIdentifier, StringComparer.OrdinalIgnoreCase) ? matchedGroups.Groups[1].Value : potentialIdentifier; } private static string GetPorentialIdentifierWithTheAsKeyword(string sql, Match matchedWithAs) { var potentialIdentifierFromAs = matchedWithAs.Groups[2].Value; if (PostSelectCosmosSqlOperators.Contains(potentialIdentifierFromAs, StringComparer.OrdinalIgnoreCase)) { throw new InvalidSqlQueryException(sql); } return potentialIdentifierFromAs; } } }
42.367347
166
0.63359
[ "MIT" ]
yncardoso/Cosmonaut
src/Cosmonaut/Extensions/CosmosSqlQueryExtensions.cs
6,230
C#
// <developer>niklas@protocol7.com</developer> // <completed>100</completed> using System; namespace SharpVectors.Dom.Css { /// <summary> /// Internal class that stores a style in a declaration block /// </summary> internal sealed class CssStyleBlock { #region Constructors internal CssStyleBlock(string name, string val, string priority, CssStyleSheetType origin) { Name = name.Trim(); Value = val.Trim(); Priority = priority.Trim(); Origin = origin; } internal CssStyleBlock(string name, string val, string priority, int specificity, CssStyleSheetType origin) : this(name, val, priority, origin) { Specificity = specificity; } internal CssStyleBlock(CssStyleBlock style, int specificity, CssStyleSheetType origin) : this(style.Name, style.Value, style.Priority, origin) { Specificity = specificity; } #endregion #region Public properties internal string CssText { get { string ret = Name + ":" + Value; if(Priority != null && Priority.Length > 0) { ret += " !" + Priority; } return ret; } } /// <summary> /// The type of the owner stylesheet /// </summary> internal CssStyleSheetType Origin; /// <summary> /// The property name /// </summary> internal string Name; /// <summary> /// The value of the style /// </summary> internal string Value; /// <summary> /// The prioroty of the style, e.g. "important" /// </summary> internal string Priority; /// <summary> /// The calculated specificity of the owner selector /// </summary> internal int Specificity = -1; public CssValue CssValue; #endregion } }
21.782051
92
0.640377
[ "MIT" ]
dotnet-campus/dotnetCampus.Svg2XamlTool
src/dotnetCampus.Svg2XamlTool/SharpVectors/SharpVectorCss/Css/CssStyleBlock.cs
1,699
C#
using Flux.NewRelic.DeploymentReporter.Logic.EventStrategies; using System.Threading.Tasks; namespace Flux.NewRelic.DeploymentReporter.Logic { public interface IFluxEventFactory { IEventStrategy Get(Models.Flux.Kind kind); } }
25.7
63
0.743191
[ "MIT" ]
Nordes/Flux.NewRelic
Flux.NewRelic/Logic/IFluxEventFactory.cs
259
C#
using System; using DesignPatterns.Creational.AbstractFactory; namespace AbstractFactory { public class ConcreteFactory1 : AbstractFactory { private ConcreteProductA1 ConcreteProductA1 { get => default; set { } } private ConcreteProductB1 ConcreteProductB1 { get => default; set { } } public override AbstractProductA MakeProductA() { return new ConcreteProductA1(); } public override AbstractProductB MakeProductB() { return new ConcreteProductB1(); } public override IProduct Make(string productType) { return productType switch { "AbstractProductA" => new ConcreteProductA1(), "AbstractProductB" => new ConcreteProductB1(), _ => throw new ArgumentException("Wrong product type", productType) }; } public override string[] GetAllProducts() { return new[] {"AbstractProductA", "AbstractProductB"}; } } }
25.2
83
0.556437
[ "MIT" ]
daviur/DesignPatterns
AbstractFactory/ConcreteFactory1.cs
1,134
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; namespace GlobalMiddlewarePipeline { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } private IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "GlobalMiddlewarePipeline", Version = "v1" }); }); services.AddScoped<GlobalExceptionFilter>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "GlobalMiddlewarePipeline v1")); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
35.976744
116
0.649644
[ "MIT" ]
NMillard/CSharpDesignPatterns
src/ExceptionHandling/GlobalMiddlewarePipeline/Startup.cs
1,547
C#
using System; using System.Collections.Generic; using System.Linq; namespace nswag_liquid_slim.ViewModels { public class GridParameters { public string Filter { get; set; } = ""; public string? SortBy { get; set; } public bool IncludeCount { get; set; } = false; public SortDirection SortDirection { get; set; } = SortDirection.Asc; public int Page { get; set; } = 0; public int PageSize { get; set; } = 10; internal string? SortExpression => SortBy == null ? null : $"{SortBy} {SortDirection}"; internal int RecordIndex => Page * PageSize; internal bool HasFilter => !string.IsNullOrWhiteSpace(Filter) && Filter.Length >= 3; } public enum SortDirection { Asc, Desc } public class GridData<T> { public IEnumerable<T> Items { get; set; } = Enumerable.Empty<T>(); public int? Total { get; set; } } }
22.444444
77
0.564356
[ "MIT" ]
wivuu/nswag-liquid-slim
ViewModels/Grids.cs
1,010
C#
namespace DotNetInterceptTester.My_System.Net.WebClient { public class DownloadFile_System_Net_WebClient_System_String_System_String { public static bool _DownloadFile_System_Net_WebClient_System_String_System_String( ) { //Parameters System.String address = null; System.String fileName = null; //Exception Exception exception_Real = null; Exception exception_Intercepted = null; InterceptionMaintenance.disableInterception( ); try { returnValue_Real = System.Net.WebClient.DownloadFile(address,fileName); } catch( Exception e ) { exception_Real = e; } InterceptionMaintenance.enableInterception( ); try { returnValue_Intercepted = System.Net.WebClient.DownloadFile(address,fileName); } catch( Exception e ) { exception_Intercepted = e; } } } }
19.666667
85
0.692655
[ "MIT" ]
SecurityInnovation/Holodeck
Test/Automation/DotNetInterceptTester/DotNetInterceptTester/System.Net.WebClient.DownloadFile(String, String).cs
885
C#