content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using Domain.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace DataAccessLayer.Builders { public class ApplicationUserBuilder : IEntityTypeConfiguration<ApplicationUser> { public void Configure(EntityTypeBuilder<ApplicationUser> builder) { _ = builder ?? throw new NullReferenceException(nameof(builder)); builder.ToTable("Users"); builder.HasKey(x => x.Id); builder.Property(x => x.FirstName).IsRequired(); builder.Property(x => x.LastName).IsRequired(); builder.Property(x => x.Email).IsRequired(); builder.OwnsMany(x => x.Ratings, x => { x.ToTable("Ratings"); x.WithOwner().HasForeignKey("AppUserId"); x.Property<Guid>("Id"); x.Property(a => a.Value).IsRequired(); x.HasKey("Id"); }); builder.HasMany(x => x.UserGroups) .WithOne(x => x.ApplicationUser) .HasForeignKey(ug => ug.AppUserId) .OnDelete(DeleteBehavior.Cascade); builder.HasOne(x => x.Vehicle) .WithOne() .HasForeignKey<Vehicle>(v => v.AppUserId) .OnDelete(DeleteBehavior.Cascade); } } }
28.641026
80
0.698299
[ "MIT" ]
carpool-team/carpool
src/API/RestService/DataAccessLayer/Builders/ApplicationUserBuilder.cs
1,119
C#
using System.Collections.Generic; using NUnit.Framework; namespace Stott.Optimizely.Csp.Test.TestCases { public static class CommonTestCases { public static IEnumerable<TestCaseData> EmptyNullOrWhitespaceStrings { get { yield return new TestCaseData((string)null); yield return new TestCaseData(string.Empty); yield return new TestCaseData(" "); } } } }
23.85
76
0.597484
[ "Apache-2.0" ]
GeekInTheNorth/Stott.Optimizely.Csp
src/Stott.Optimizely.Csp.Test/TestCases/CommonTestCases.cs
479
C#
namespace PRGReaderLibrary { using System; public class ScheduleCode : BaseCode, IBinaryObject { public ScheduleCode(byte[] code = null, FileVersion version = FileVersion.Current) : base(144, version) { Code = code; } #region Binary data public static int GetCount(FileVersion version = FileVersion.Current) { switch (version) { case FileVersion.Current: return 8; default: throw new FileVersionNotImplementedException(version); } } public static int GetSize(FileVersion version = FileVersion.Current) { switch (version) { case FileVersion.Current: return 144; default: throw new FileVersionNotImplementedException(version); } } /// <summary> /// FileVersion.Current - need 144 bytes /// </summary> /// <param name="bytes"></param> /// <param name="offset"></param> /// <param name="version"></param> public ScheduleCode(byte[] bytes, int offset = 0, FileVersion version = FileVersion.Current) : base(bytes, 144, offset, version) {} /// <summary> /// FileVersion.Current - 144 bytes /// </summary> /// <returns></returns> public new byte[] ToBytes() => base.ToBytes(); #endregion } }
26.116667
90
0.507339
[ "MIT" ]
Fance/T3000_CrossPlatform
PRGReaderLibrary/Types/ScheduleCode.cs
1,569
C#
namespace FlatFile.FixedLength { public enum Padding { Left, Right } }
12.25
30
0.55102
[ "MIT" ]
Peter-LaComb/FlatFile
FlatFile.FixedLength/Padding.cs
98
C#
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ using System; using System.Web.Http; using OpsLogix.WAP.RunPowerShell.ApiClient.DataContracts; namespace OpsLogix.WAP.RunPowerShell.Api.Controllers { public class AdminSettingsController : ApiController { public static AdminSettings settings; static AdminSettingsController() { settings = new AdminSettings { EndpointAddress = "http://dummyservice", Username = "testUser", Password = "Password" }; } [HttpGet] public AdminSettings GetAdminSettings() { return settings; } [HttpPut] public void UpdateAdminSettings(AdminSettings newSettings) { if (newSettings == null) { throw Utility.ThrowResponseException(this.Request, System.Net.HttpStatusCode.BadRequest, ErrorMessages.NullInput); } settings = newSettings; } } }
27.418605
131
0.527566
[ "MIT" ]
opslogix/Tenant-Automation-Azure-Pack-Rp
OpsLogix.WAP.RunPowerShell.Api/Controllers/AdminSettingsController.cs
1,181
C#
using NUnit.Framework; using Elements = SharpReact.Core.MockUI.Test.Elements; using Props = SharpReact.Core.MockUI.Test.Props; using Components = SharpReact.Core.MockUI.Test.Components; using System; using SharpReact.Core.Properties; using SharpReact.Core.MockUI.Test; using System.Collections.Generic; using SharpReact.Core.Exceptions; namespace SharpReact.Core.Test { public class SharpRendererTest { protected SharpRenderer<Elements.ContentControl, Elements.UIElement> renderer; protected Elements.ContentControl root; [SetUp] public void SetUp() { root = new Elements.ContentControl(); // need to reset counters per test, otherwise they will accumulate. Components.SharpTestComponentTestCounter.ResetCounter(); } protected SharpRenderer<Elements.ContentControl, Elements.UIElement> CreateRenderer(Func<SharpProp> createTree) { return new MockUIRenderer(createTree, root); } public class CompareProperties: SharpRendererTest { [SetUp] public new void SetUp() { renderer = CreateRenderer(null); } [TestFixture] public class ComparingUIElement: CompareProperties { [Test] public void WhenBothAreNull_ReturnsTrue() { var actual = renderer.CompareProperties<Props.UIElement>(null, null); Assert.That(actual, Is.True); } [Test] public void WhenFirstHasValueAndOtherIsNull_ReturnsFalse() { var actual = renderer.CompareProperties(new Props.UIElement(), null); Assert.That(actual, Is.False); } [Test] public void WhenSecondHasValueAndOtherIsNull_ReturnsFalse() { var actual = renderer.CompareProperties(null, new Props.UIElement()); Assert.That(actual, Is.False); } [Test] public void WhenBothAreCleanInstances_ReturnsTrue() { var actual = renderer.CompareProperties(new Props.UIElement(), new Props.UIElement()); Assert.That(actual, Is.True); } [Test] public void WhenFirstHasPropertySetAndOtherDoesNot_ReturnsFalse() { var actual = renderer.CompareProperties(new Props.UIElement { IsEnabled = true }, new Props.UIElement()); Assert.That(actual, Is.False); } [Test] public void WhenSecondHasPropertySetAndOtherDoesNot_ReturnsFalse() { var actual = renderer.CompareProperties(new Props.UIElement(), new Props.UIElement { IsEnabled = true }); Assert.That(actual, Is.False); } } [TestFixture] public class ComparingButton : CompareProperties { [Test] public void WhenBothAreNull_ReturnsTrue() { var actual = renderer.CompareProperties<Props.Button>(null, null); Assert.That(actual, Is.True); } [Test] public void WhenFirstHasValueAndOtherIsNull_ReturnsFalse() { var actual = renderer.CompareProperties(new Props.Button(), null); Assert.That(actual, Is.False); } [Test] public void WhenSecondHasValueAndOtherIsNull_ReturnsFalse() { var actual = renderer.CompareProperties(null, new Props.Button()); Assert.That(actual, Is.False); } [Test] public void WhenBothAreCleanInstances_ReturnsTrue() { var actual = renderer.CompareProperties(new Props.Button(), new Props.Button()); Assert.That(actual, Is.True); } [Test] public void WhenFirstHasInheritedPropertySetAndOtherDoesNot_ReturnsFalse() { var actual = renderer.CompareProperties(new Props.Button { IsEnabled = true }, new Props.Button()); Assert.That(actual, Is.False); } [Test] public void WhenSecondHasInheritedPropertySetAndOtherDoesNot_ReturnsFalse() { var actual = renderer.CompareProperties(new Props.Button(), new Props.Button { IsEnabled = true }); Assert.That(actual, Is.False); } } [TestFixture] public class ComparingContentControl: CompareProperties { [Test] public void WhenBothHaveNoChildren_ReturnsTrue() { var actual = renderer.CompareProperties(new Props.ContentControl(), new Props.ContentControl()); Assert.That(actual, Is.True); } [Test] public void WhenFirstHasChildrenAndOtherDoesNot_ReturnsFalse() { var actual = renderer.CompareProperties(new Props.ContentControl { Content = new Props.UIElement() }, new Props.ContentControl()); Assert.That(actual, Is.False); } [Test] public void WhenSecondHasChildrenAndOtherDoesNot_ReturnsFalse() { var actual = renderer.CompareProperties(new Props.ContentControl(), new Props.ContentControl { Content = new Props.UIElement() }); Assert.That(actual, Is.False); } } } public class Render : SharpRendererTest { [TestFixture] public class SingleButton : Render { [Test] public void NullRender_ResultsInNullElement() { renderer = CreateRenderer(() => null); renderer.Render(NewState.Empty); var actual = root.Content; Assert.That(actual, Is.Null); } [Test] public void InitialSimpleButtonRender_CreatesButtonElement() { renderer = CreateRenderer(() => new Props.Button()); renderer.Render(NewState.Empty); var actual = root.Content; Assert.That(actual, Is.TypeOf<Elements.Button>()); } [Test] public void InitialSimpleButtonRender_ComponentEventsAreCalledInCorrectOrder() { var button = new Props.Button(); renderer = CreateRenderer(() => button); renderer.Render(NewState.Empty); var component = button.Component; Assert.That(component.WillMountCounter(), Is.EqualTo(new int[] { 0 })); Assert.That(component.DidMountCounter(), Is.EqualTo(new int[] { 1 })); Assert.That(component.ShouldUpdateCounter(), Is.EqualTo(new int[] { 2 })); Assert.That(component.WillReceivePropsCounter(), Is.EqualTo(new int[] { 3 })); Assert.That(component.DidUpdateCounter(), Is.EqualTo(new int[] { 4 })); } [Test] public void AfterSecondPassThatYieldsNull_OriginalElementIsRemoved() { int pass = 0; renderer = CreateRenderer(() => { return pass == 0 ? new Props.Button() : null; } ); renderer.Render(NewState.Empty); pass++; renderer.Render(NewState.Empty); var actual = root.Content; Assert.That(actual, Is.Null); } [Test] public void AfterSecondPassForSimpleButtonThatYieldsNull_WillUnmountWasCalledOnce() { int pass = 0; var button = new Props.Button(); renderer = CreateRenderer(() => { return pass == 0 ? button : null; } ); renderer.Render(NewState.Empty); pass++; renderer.Render(NewState.Empty); var component = button.Component; Assert.That(component.WillUnmountCounter().Count, Is.EqualTo(1)); } [Test] public void WhenClickIsImplemented_ItRaisesEvent() { bool clicked = false; renderer = CreateRenderer(() => new Props.Button { Click = (s, e) => clicked = true }); renderer.Render(NewState.Empty); var actual = (Elements.Button)root.Content; actual.OnClick(EventArgs.Empty); Assert.That(clicked, Is.True); } [Test] public void WhenClickIsImplementedAndRemovedOnSecondPass_ItDoesNotRaiseEvent() { int pass = 0; bool clicked = false; renderer = CreateRenderer(() => new Props.Button { Click = pass == 0 ? (s, e) => clicked = true : (EventHandler)null }); renderer.Render(NewState.Empty); pass++; renderer.Render(NewState.Empty); var actual = (Elements.Button)root.Content; actual.OnClick(EventArgs.Empty); Assert.That(clicked, Is.False); } } [TestFixture] public class SingleButtonWithText : Render { [Test] public void AfterSecondPassForButtonThatYieldsNull_ContentWillUnmountWasCalledOnce() { int pass = 0; var button = new Props.Button { Content = new Props.TextBlock() }; renderer = CreateRenderer(() => { return pass == 0 ? button : null; } ); renderer.Render(NewState.Empty); pass++; renderer.Render(NewState.Empty); var component = (Components.ISharpWpfTestComponent)button.Content.Component; Assert.That(component.WillUnmountCounter.Count, Is.EqualTo(1)); } [Test] public void ButtonWithTextBlockRender_CreatesButtonElementWithTextBlock() { renderer = CreateRenderer(() => new Props.Button { Content = new Props.TextBlock() }); renderer.Render(NewState.Empty); var actual = root.Content; Assert.That(actual, Is.TypeOf<Elements.Button>()); var button = (Elements.Button)actual; Assert.That(button.Content, Is.TypeOf<Elements.TextBlock>()); } [Test] public void ButtonWithTextBlockRender_AllEventsAreCalledInCorrectOrder() { var textBlock = new Props.TextBlock(); var button = new Props.Button { Content = textBlock }; renderer = CreateRenderer(() => button); renderer.Render(NewState.Empty); var textBlockComponent = textBlock.Component; var buttonComponent = button.Component; int index = 0; Assert.That(buttonComponent.WillMountCounter(), Is.EqualTo(new int[] { index++ })); Assert.That(buttonComponent.DidMountCounter(), Is.EqualTo(new int[] { index++ })); Assert.That(buttonComponent.ShouldUpdateCounter(), Is.EqualTo(new int[] { index++ })); Assert.That(buttonComponent.WillReceivePropsCounter(), Is.EqualTo(new int[] { index++ })); Assert.That(textBlockComponent.WillMountCounter(), Is.EqualTo(new int[] { index++ })); Assert.That(textBlockComponent.DidMountCounter(), Is.EqualTo(new int[] { index++ })); Assert.That(textBlockComponent.ShouldUpdateCounter(), Is.EqualTo(new int[] { index++ })); Assert.That(textBlockComponent.WillReceivePropsCounter(), Is.EqualTo(new int[] { index++ })); Assert.That(textBlockComponent.DidUpdateCounter(), Is.EqualTo(new int[] { index++ })); Assert.That(buttonComponent.DidUpdateCounter(), Is.EqualTo(new int[] { index++ })); } [Test] public void WhenClickIsImplemented_ItRaisesEvent() { bool clicked = false; renderer = CreateRenderer(() => new Props.Button { Content = new Props.TextBlock(), Click = (s, e) => clicked = true }); renderer.Render(NewState.Empty); var actual = (Elements.Button)root.Content; actual.OnClick(EventArgs.Empty); Assert.That(clicked, Is.True); } [Test] public void WhenClickIsImplementedAndRemovedOnSecondPass_ItDoesNotRaiseEvent() { int pass = 0; bool clicked = false; renderer = CreateRenderer(() => new Props.Button { Content = new Props.TextBlock(), Click = pass == 0 ? (s, e) => clicked = true : (EventHandler)null }); renderer.Render(NewState.Empty); pass++; renderer.Render(NewState.Empty); var actual = (Elements.Button)root.Content; actual.OnClick(EventArgs.Empty); Assert.That(clicked, Is.False); } } [TestFixture] public class Panel: Render { [Test] public void WhenNoChildren_NoChildrenAreCreated() { renderer = CreateRenderer(() => new Props.StackPanel()); renderer.Render(NewState.Empty); var actual = (Elements.StackPanel)root.Content; Assert.That(actual.Children.Count, Is.Zero); } [Test] public void WhenHasASingleChild_ChildIsCreated() { var content = new Props.StackPanel { Children = { new Props.TextBlock() } }; renderer = CreateRenderer(() => new Props.StackPanel { Children = { new Props.TextBlock() } }); renderer.Render(NewState.Empty); var actual = (Elements.StackPanel)root.Content; Assert.That(actual.Children.Count, Is.EqualTo(1)); Assert.That(actual.Children[0], Is.TypeOf<Elements.TextBlock>()); } [Test] public void WhenHasASingleChildAndRecreatedSameType_ChildIsRetained() { renderer = CreateRenderer(() => new Props.StackPanel { Children = { new Props.TextBlock() } }); renderer.Render(NewState.Empty); var actual = (Elements.StackPanel)root.Content; Assert.That(actual.Children.Count, Is.EqualTo(1)); Assert.That(actual.Children[0], Is.TypeOf<Elements.TextBlock>()); } [Test] public void WhenHasASingleChildAndRecreatedSameType_ElementIsRetained() { renderer = CreateRenderer(() => new Props.StackPanel { Children = { new Props.TextBlock() } }); renderer.Render(NewState.Empty); var original = ((Elements.StackPanel)root.Content).Children[0]; renderer.Render(NewState.Empty); var actual = ((Elements.StackPanel)root.Content).Children[0]; Assert.That(actual, Is.SameAs(original)); } [Test] public void WhenHasASingleChildAndRecreatedDifferentType_SingleElementChild() { int pass = 0; renderer = CreateRenderer(() => new Props.StackPanel { Children = { pass == 0 ? (Props.UIElement)new Props.TextBlock() : new Props.Button() } } ); renderer.Render(NewState.Empty); pass++; renderer.Render(NewState.Empty); var actual = (Elements.StackPanel)root.Content; Assert.That(actual.Children.Count, Is.EqualTo(1)); } [Test] public void WhenHasASingleChildAndRecreatedToButton_ElementChildIsButton() { int pass = 0; renderer = CreateRenderer(() => new Props.StackPanel { Children = { pass == 0 ? (Props.UIElement)new Props.TextBlock() : new Props.Button() } } ); renderer.Render(NewState.Empty); pass++; renderer.Render(NewState.Empty); var actual = (Elements.StackPanel)root.Content; var child = actual.Children[0]; Assert.That(child, Is.TypeOf<Elements.Button>()); } [Test, Ignore("For now")] public void WhenMoreThanOneChild_KeysAreRequired() { renderer = CreateRenderer(() => new Props.StackPanel { Children = { new Props.TextBlock(), new Props.Button() } }); Assert.Throws<DuplicateKeyException>(() => renderer.Render(NewState.Empty)); } [Test] public void WhenMoreThanOneChildAndKeysAreUnique_NoExceptionIsThrown() { renderer = CreateRenderer(() => new Props.StackPanel { Children = { new Props.TextBlock { Key = 0 }, new Props.Button { Key = 1 } } }); renderer.Render(NewState.Empty); } [Test] public void WhenTwoChildren_TwoElementsAreInList() { renderer = CreateRenderer(() => new Props.StackPanel { Children = { new Props.TextBlock { Key = 0 }, new Props.Button { Key = 1 } } }); renderer.Render(NewState.Empty); var actual = (Elements.StackPanel)root.Content; Assert.That(actual.Children.Count, Is.EqualTo(2)); } [Test] public void WhenTwoChildren_ElementsAreInCorrectOrder() { renderer = CreateRenderer(() => new Props.StackPanel { Children = { new Props.TextBlock { Key = 0 }, new Props.Button { Key = 1 } } }); renderer.Render(NewState.Empty); var actual = (Elements.StackPanel)root.Content; Assert.That(actual.Children[0], Is.TypeOf<Elements.TextBlock>()); Assert.That(actual.Children[1], Is.TypeOf<Elements.Button>()); } [Test] public void WhenTwoChildrenAndFirstIsRemoved_SingleElementRemains() { int pass = 0; var panel1 = new Props.StackPanel { Children = { new Props.TextBlock { Key = 0 }, new Props.Button { Key = 1 } } }; var panel2 = new Props.StackPanel { Children = { new Props.TextBlock { Key = 0 } } }; renderer = CreateRenderer(() => pass == 0 ? panel1: panel2); renderer.Render(NewState.Empty); pass++; renderer.Render(NewState.Empty); var actual = (Elements.StackPanel)root.Content; Assert.That(actual.Children.Count, Is.EqualTo(1)); } [Test] public void WhenTwoChildrenAndFirstIsRemoved_RemainingElementIsTextBlock() { int pass = 0; var panel1 = new Props.StackPanel { Children = { new Props.TextBlock { Key = 0 }, new Props.Button { Key = 1 } } }; var panel2 = new Props.StackPanel { Children = { new Props.TextBlock { Key = 0 } } }; renderer = CreateRenderer(() => pass == 0 ? panel1 : panel2); renderer.Render(NewState.Empty); pass++; renderer.Render(NewState.Empty); var actual = (Elements.StackPanel)root.Content; Assert.That(actual.Children[0], Is.TypeOf<Elements.TextBlock>()); } [Test] public void WhenTwoChildrenAndSecondIsRemoved_SingleElementRemains() { int pass = 0; var panel1 = new Props.StackPanel { Children = { new Props.TextBlock { Key = 0 }, new Props.Button { Key = 1 } } }; var panel2 = new Props.StackPanel { Children = { new Props.Button { Key = 1 } } }; renderer = CreateRenderer(() => pass == 0 ? panel1 : panel2); renderer.Render(NewState.Empty); pass++; renderer.Render(NewState.Empty); var actual = (Elements.StackPanel)root.Content; Assert.That(actual.Children.Count, Is.EqualTo(1)); } [Test] public void WhenTwoChildrenAndSecondIsRemoved_RemainingElementIsButton() { int pass = 0; var panel1 = new Props.StackPanel { Children = { new Props.TextBlock { Key = 0 }, new Props.Button { Key = 1 } } }; var panel2 = new Props.StackPanel { Children = { new Props.Button { Key = 1 } } }; renderer = CreateRenderer(() => pass == 0 ? panel1 : panel2); renderer.Render(NewState.Empty); pass++; renderer.Render(NewState.Empty); var actual = (Elements.StackPanel)root.Content; Assert.That(actual.Children[0], Is.TypeOf<Elements.Button>()); } } [TestFixture] public class SimpleComposite: Render { [Test] public void WhenRender_ElementIsTextBlock() { renderer = CreateRenderer(() => new Props.SimpleComposite()); renderer.Render(NewState.Empty); var actual = root.Content; Assert.That(actual, Is.TypeOf<Elements.TextBlock>()); } [Test] public void WhenRender_ComponentIsCreated() { var props = new Props.SimpleComposite(); renderer = CreateRenderer(() => props); renderer.Render(NewState.Empty); Assert.That(props.Component, Is.Not.Null); } } [TestFixture] public class NestedComposite : Render { [Test] public void WhenRender_ElementIsTextBlock() { renderer = CreateRenderer(() => new Props.NestedComposite()); renderer.Render(NewState.Empty); var actual = root.Content; Assert.That(actual, Is.TypeOf<Elements.TextBlock>()); } [Test] public void WhenRender_RootComponentIsCreated() { var props = new Props.NestedComposite(); renderer = CreateRenderer(() => props); renderer.Render(NewState.Empty); Assert.That(props.Component, Is.Not.Null); } [Test] public void WhenRender_GeneratedIsAssignedRenderedProperty() { var props = new Props.NestedComposite(); renderer = CreateRenderer(() => props); renderer.Render(NewState.Empty); Assert.That(props.Generated, Is.TypeOf<Props.SimpleComposite>()); } [Test] public void WhenRender_NestedComponentIsCreated() { var props = new Props.NestedComposite(); renderer = CreateRenderer(() => props); renderer.Render(NewState.Empty); Assert.That(props.Generated.Component, Is.Not.Null); } } } [TestFixture] public class CheckPropertyListKeys: SharpRendererTest { [Test] public void WhenPropsIsNull_DoesNotThrow() { MockUIRenderer.CheckPropertyListKeys(null, "sourceProperty", "sourceType"); } [Test] public void WhenSinglePropWithKey_DoesNotThrow() { MockUIRenderer.CheckPropertyListKeys(new List<ISharpProp> { new Props.TextBlock { Key = 1 } }, "sourceProperty", "sourceType"); } [Test] public void WhenTwoPropsWithDifferentKeys_DoesNotThrow() { MockUIRenderer.CheckPropertyListKeys(new List<ISharpProp> { new Props.TextBlock { Key = 1 }, new Props.TextBlock { Key = 2 } }, "sourceProperty", "sourceType"); } [Test, Ignore("For now")] public void WhenTwoPropsWithEqualKeys_DoesThrowException() { Assert.Throws<DuplicateKeyException>(() => MockUIRenderer.CheckPropertyListKeys(new List<ISharpProp> { new Props.TextBlock { Key = 1 }, new Props.TextBlock { Key = 1 } }, "sourceProperty", "sourceType") ); } } [TestFixture] public class VisitAllCollection: SharpRendererTest { [SetUp] public new void SetUp() { // no need to render anything for these tests renderer = CreateRenderer(() => null); } [Test] public void WhenPreviousIsNullAndNextIsNull_ElementsListIsEmpty() { var actual = renderer.VisitAllCollection(0, new NewState(), previous: null, next: null, "sourceProperty", "sourceType"); Assert.That(actual.Length, Is.Zero); } [Test] public void WhenNullPreviousAndSingleNext_OneElementIsInList() { var actual = renderer.VisitAllCollection(0, new NewState(), previous: null, next: new List<ISharpProp> { new Props.TextBlock() }, "sourceProperty", "sourceType"); Assert.That(actual.Length, Is.EqualTo(1)); } [Test] public void WhenNullPreviousAndSingleTextBlock_ElementIsTextBlock() { var actual = renderer.VisitAllCollection(0, new NewState(), previous: null, next: new List<ISharpProp> { new Props.TextBlock() }, "sourceProperty", "sourceType"); Assert.That(actual[0], Is.TypeOf<Elements.TextBlock>()); } [Test] public void WhenTextBlockPreviousAndNullNext_NoElementsInList() { var actual = renderer.VisitAllCollection(0, new NewState(), previous: new List<ISharpProp> { new Props.TextBlock() }, next: null, "sourceProperty", "sourceType"); Assert.That(actual.Length, Is.Zero); } [Test] public void WhenTextBlockPreviousAndNextIsButton_OneElementInList() { var textBlockProp = new Props.TextBlock(); // makes sure component and element are created textBlockProp.Init(); textBlockProp.Component.WillMount(); var element = (Elements.UIElement)textBlockProp.Component.Element; //var elements = new List<Elements.UIElement> { element }; var actual = renderer.VisitAllCollection(0, new NewState(), previous: new List<ISharpProp> { textBlockProp }, next: new List<ISharpProp> { new Props.Button() }, "sourceProperty", "sourceType"); Assert.That(actual.Length, Is.EqualTo(1)); } } [TestFixture] public class UpdateExistingElement: SharpRendererTest { [SetUp] public new void SetUp() { renderer = CreateRenderer(() => null); } [Test] public void WhenTextBlock_CreatesComponents() { var element = new Elements.TextBlock(); var props = new Props.TextBlock(); renderer.UpdateExistingElement(element, props); Assert.That(props.Component, Is.Not.Null); } [Test] public void WhenTextBlock_UpdatesProperties() { var element = new Elements.TextBlock(); var props = new Props.TextBlock { Text = "test", IsEnabled = true, Focusable = true }; renderer.UpdateExistingElement(element, props); Assert.That(element.Text, Is.EqualTo(props.Text)); Assert.That(element.IsEnabled, Is.True); Assert.That(element.Focusable, Is.True); } [Test] public void WhenTextBlock_PreviousElementIsRemoved() { var element = new Elements.TextBlock(); var props = new Props.TextBlock(); renderer.UpdateExistingElement(element, props); renderer.UpdateExistingElement(new Elements.TextBlock(), props); Assert.That(props.Component.Element, Is.Not.SameAs(element)); } [Test] public void WhenContentControl_CreatesComponents() { var element = new Elements.ContentControl { Content = new Elements.TextBlock() }; var props = new Props.ContentControl { Content = new Props.TextBlock() }; renderer.UpdateExistingElement(element, props); Assert.That(props.Component, Is.Not.Null); Assert.That(props.Content.Component, Is.Not.Null); } [Test] public void WhenContentControl_UpdatesProperties() { var element = new Elements.ContentControl { Content = new Elements.TextBlock() }; var content = new Props.TextBlock { Text = "test", IsEnabled = true, Focusable = true }; var props = new Props.ContentControl { Content = content }; renderer.UpdateExistingElement(element, props); var actual = (Elements.TextBlock)element.Content; Assert.That(actual.Text, Is.EqualTo(content.Text)); Assert.That(actual.IsEnabled, Is.True); Assert.That(actual.Focusable, Is.True); } [Test] public void WhenContentControl_PreviousElementsAreRemoved() { var element = new Elements.ContentControl { Content = new Elements.TextBlock() }; var content = new Props.TextBlock { Text = "test", IsEnabled = true, Focusable = true }; var props = new Props.ContentControl { Content = content }; renderer.UpdateExistingElement(element, props); renderer.UpdateExistingElement(new Elements.ContentControl { Content = new Elements.TextBlock() }, props); var actual = (Elements.TextBlock)element.Content; Assert.That(props.Component.Element, Is.Not.SameAs(element)); Assert.That(content.Component.Element, Is.Not.SameAs(element.Content)); } } [TestFixture] public class ComparePropertyLists: SharpRendererTest { [SetUp] public new void SetUp() { renderer = CreateRenderer(() => null); } [Test] public void WhenBothListNull_ReturnsTrue() { var actual = renderer.ComparePropertyLists(null, null); Assert.That(actual, Is.True); } [Test] public void WhenFirstIsNullAndOtherIsNot_ReturnsFalse() { var actual = renderer.ComparePropertyLists(null, new ISharpProp[0]); Assert.That(actual, Is.False); } [Test] public void WhenSecondIsNullAndOtherIsNot_ReturnsFalse() { var actual = renderer.ComparePropertyLists(new ISharpProp[0], null); Assert.That(actual, Is.False); } [Test] public void WhenBothAreEmpty_ReturnsTrue() { var actual = renderer.ComparePropertyLists(new ISharpProp[0], new ISharpProp[0]); Assert.That(actual, Is.True); } } } }
42.257794
155
0.497886
[ "MIT" ]
MihaMarkic/SharpReact
src/Test/SharpReact.Core.Test/SharpRendererTest.cs
35,245
C#
//---------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //------------------------------------------------------------------------------ using System; using System.Globalization; using System.Threading.Tasks; using Windows.ApplicationModel.Core; using Windows.Networking.Connectivity; using Windows.Security.Authentication.Web; using Microsoft.Identity.Client.Core; using Microsoft.Identity.Client.Exceptions; using Microsoft.Identity.Client.Http; using Microsoft.Identity.Client.UI; namespace Microsoft.Identity.Client.Platforms.uap { internal class WebUI : IWebUI { private readonly bool useCorporateNetwork; private readonly bool silentMode; public RequestContext RequestContext { get; set; } public WebUI(CoreUIParent parent, RequestContext requestContext) { useCorporateNetwork = parent.UseCorporateNetwork; silentMode = parent.UseHiddenBrowser; } public async Task<AuthorizationResult> AcquireAuthorizationAsync(Uri authorizationUri, Uri redirectUri, RequestContext requestContext) { bool ssoMode = string.Equals(redirectUri.OriginalString, Constants.UapWEBRedirectUri, StringComparison.OrdinalIgnoreCase); WebAuthenticationResult webAuthenticationResult; WebAuthenticationOptions options = (useCorporateNetwork && (ssoMode || redirectUri.Scheme == Constants.MsAppScheme)) ? WebAuthenticationOptions.UseCorporateNetwork : WebAuthenticationOptions.None; ThrowOnNetworkDown(); if (silentMode) { options |= WebAuthenticationOptions.SilentMode; } try { webAuthenticationResult = await CoreApplication.MainView.CoreWindow.Dispatcher.RunTaskAsync( async () => { if (ssoMode) { return await WebAuthenticationBroker.AuthenticateAsync(options, authorizationUri) .AsTask() .ConfigureAwait(false); } else { return await WebAuthenticationBroker .AuthenticateAsync(options, authorizationUri, redirectUri) .AsTask() .ConfigureAwait(false); } }) .ConfigureAwait(false); } catch (Exception ex) { requestContext.Logger.ErrorPii(ex); throw new MsalException(MsalClientException.AuthenticationUiFailedError, "WAB authentication failed", ex); } AuthorizationResult result = ProcessAuthorizationResult(webAuthenticationResult, requestContext); return result; } private void ThrowOnNetworkDown() { var profile = NetworkInformation.GetInternetConnectionProfile(); var isConnected = (profile != null && profile.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess); if (!isConnected) { throw new MsalClientException(MsalClientException.NetworkNotAvailableError, MsalErrorMessage.NetworkNotAvailable); } } private static AuthorizationResult ProcessAuthorizationResult(WebAuthenticationResult webAuthenticationResult, RequestContext requestContext) { AuthorizationResult result; switch (webAuthenticationResult.ResponseStatus) { case WebAuthenticationStatus.Success: result = new AuthorizationResult(AuthorizationStatus.Success, webAuthenticationResult.ResponseData); break; case WebAuthenticationStatus.ErrorHttp: result = new AuthorizationResult(AuthorizationStatus.ErrorHttp, webAuthenticationResult.ResponseErrorDetail.ToString(CultureInfo.InvariantCulture)); break; case WebAuthenticationStatus.UserCancel: result = new AuthorizationResult(AuthorizationStatus.UserCancel, null); break; default: result = new AuthorizationResult(AuthorizationStatus.UnknownError, null); break; } return result; } public void ValidateRedirectUri(Uri redirectUri) { RedirectUriHelper.Validate(redirectUri, usesSystemBrowser: false); } } }
41.671141
134
0.593332
[ "MIT" ]
stefangossner/microsoft-authentication-library-for-dotnet
src/Microsoft.Identity.Client/Platforms/uap/WebUI.cs
6,211
C#
using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using Orchard.ContentManagement; using Orchard.Logging; using Orchard.Rules.Models; using Orchard.Rules.Services; using Orchard.Tasks.Scheduling; namespace Orchard.Rules.Handlers { [UsedImplicitly] public class ScheduledActionTaskHandler : IScheduledTaskHandler { private readonly IRulesManager _rulesManager; public ScheduledActionTaskHandler( IRulesManager rulesManager) { _rulesManager = rulesManager; } public ILogger Logger { get; set; } public void Process(ScheduledTaskContext context) { if (context.Task.TaskType == "TriggerRule") { Logger.Information("Triggering Rule item #{0} version {1} scheduled at {2} utc", context.Task.ContentItem.Id, context.Task.ContentItem.Version, context.Task.ScheduledUtc); var scheduledActionTask = context.Task.ContentItem.As<ScheduledActionTaskPart>(); _rulesManager.ExecuteActions(scheduledActionTask.ScheduledActions.Select(x => x.ActionRecord), new Dictionary<string, object>()); } } } }
35.638889
145
0.645362
[ "BSD-3-Clause" ]
ArsenShnurkov/OrchardCMS-1.7.3-for-mono
src/Orchard.Web/Modules/Orchard.Rules/Handlers/ScheduledActionTaskHandler.cs
1,285
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerOneMoving : MonoBehaviour { public float rotation = 100f; public float playerOneSpeed = 10f; public KeyCode LFT; public KeyCode RHT; public Rigidbody2D structureRb; Rigidbody2D rb; // Start is called before the first frame update void Start() { rb = GetComponent<Rigidbody2D>(); } // Update is called once per frame void Update() { if (Input.GetKey(LFT)) { rb.velocity = new Vector2(-playerOneSpeed, 0); rb.AddTorque(-rotation * Time.deltaTime); } if (Input.GetKey(RHT)) { rb.velocity = new Vector2(playerOneSpeed, 0); rb.AddTorque(rotation * Time.deltaTime); } } }
23.361111
58
0.599287
[ "Unlicense" ]
HarricChen/HarryCodeLabFinal
FortressBattle/Assets/Script/PlayerOneMoving.cs
843
C#
using System.Linq; using AElf.Sdk.CSharp; using AElf.Types; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; namespace AElf.Contracts.Consensus.AEDPoS { // ReSharper disable once InconsistentNaming public partial class AEDPoSContract { private BytesValue GetConsensusBlockExtraData(BytesValue input, bool isGeneratingTransactions = false) { var triggerInformation = new AElfConsensusTriggerInformation(); triggerInformation.MergeFrom(input.Value); Assert(triggerInformation.Pubkey.Any(), "Invalid pubkey."); if (!TryToGetCurrentRoundInformation(out var currentRound)) { Assert(false, "Failed to get current round information."); } var publicKeyBytes = triggerInformation.Pubkey; var pubkey = publicKeyBytes.ToHex(); var information = new AElfConsensusHeaderInformation(); switch (triggerInformation.Behaviour) { case AElfConsensusBehaviour.UpdateValue: information = GetConsensusExtraDataToPublishOutValue(currentRound, pubkey, triggerInformation); if (!isGeneratingTransactions) { information.Round = information.Round.GetUpdateValueRound(pubkey); } break; case AElfConsensusBehaviour.TinyBlock: information = GetConsensusExtraDataForTinyBlock(currentRound, pubkey, triggerInformation); break; case AElfConsensusBehaviour.NextRound: information = GetConsensusExtraDataForNextRound(currentRound, pubkey, triggerInformation); break; case AElfConsensusBehaviour.NextTerm: information = GetConsensusExtraDataForNextTerm(pubkey, triggerInformation); break; } if (!isGeneratingTransactions) { information.Round.DeleteSecretSharingInformation(); } return information.ToBytesValue(); } private AElfConsensusHeaderInformation GetConsensusExtraDataToPublishOutValue(Round currentRound, string pubkey, AElfConsensusTriggerInformation triggerInformation) { currentRound.RealTimeMinersInformation[pubkey].ProducedTinyBlocks = currentRound .RealTimeMinersInformation[pubkey].ProducedTinyBlocks.Add(1); currentRound.RealTimeMinersInformation[pubkey].ProducedBlocks = currentRound.RealTimeMinersInformation[pubkey].ProducedBlocks.Add(1); currentRound.RealTimeMinersInformation[pubkey].ActualMiningTimes .Add(Context.CurrentBlockTime); Assert(triggerInformation.InValue != null, "In value should not be null."); var outValue = Hash.FromMessage(triggerInformation.InValue); var signature = Hash.FromTwoHashes(outValue, triggerInformation.InValue); // Just initial signature value. var previousInValue = Hash.Empty; // Just initial previous in value. if (TryToGetPreviousRoundInformation(out var previousRound) && !IsFirstRoundOfCurrentTerm(out _)) { if (triggerInformation.PreviousInValue != null && triggerInformation.PreviousInValue != Hash.Empty) { Context.LogDebug( () => $"Previous in value in trigger information: {triggerInformation.PreviousInValue}"); // Self check. if (previousRound.RealTimeMinersInformation.ContainsKey(pubkey) && Hash.FromMessage(triggerInformation.PreviousInValue) != previousRound.RealTimeMinersInformation[pubkey].OutValue) { Context.LogDebug(() => "Failed to produce block at previous round?"); previousInValue = Hash.Empty; } else { previousInValue = triggerInformation.PreviousInValue; } signature = previousRound.CalculateSignature(triggerInformation.PreviousInValue); } else { var fakePreviousInValue = Hash.FromString(pubkey.Append(Context.CurrentHeight.ToString())); if (previousRound.RealTimeMinersInformation.ContainsKey(pubkey) && previousRound.RoundNumber != 1) { var appointedPreviousInValue = previousRound.RealTimeMinersInformation[pubkey].InValue; if (appointedPreviousInValue != null) { fakePreviousInValue = appointedPreviousInValue; } Context.LogDebug(() => $"TEST:\n{previousRound.ToString(pubkey)}\nInValue: {fakePreviousInValue}"); signature = previousRound.CalculateSignature(fakePreviousInValue); } else { // This miner appears first time in current round, like as a replacement of evil miner. signature = previousRound.CalculateSignature(fakePreviousInValue); } } } var updatedRound = currentRound.ApplyNormalConsensusData(pubkey, previousInValue, outValue, signature); Context.LogDebug( () => $"Previous in value after ApplyNormalConsensusData: " + $"{updatedRound.RealTimeMinersInformation[pubkey].PreviousInValue}"); updatedRound.RealTimeMinersInformation[pubkey].ImpliedIrreversibleBlockHeight = Context.CurrentHeight; // Update secret pieces of latest in value. UpdateLatestSecretPieces(updatedRound, pubkey, triggerInformation); // To publish Out Value. return new AElfConsensusHeaderInformation { SenderPubkey = pubkey.ToByteString(), Round = updatedRound, Behaviour = triggerInformation.Behaviour }; } private void UpdateLatestSecretPieces(Round updatedRound, string pubkey, AElfConsensusTriggerInformation triggerInformation) { foreach (var encryptedPiece in triggerInformation.EncryptedPieces) { updatedRound.RealTimeMinersInformation[pubkey].EncryptedPieces .Add(encryptedPiece.Key, encryptedPiece.Value); } foreach (var decryptedPiece in triggerInformation.DecryptedPieces) { if (updatedRound.RealTimeMinersInformation.ContainsKey(decryptedPiece.Key)) { updatedRound.RealTimeMinersInformation[decryptedPiece.Key].DecryptedPieces[pubkey] = decryptedPiece.Value; } } foreach (var revealedInValue in triggerInformation.RevealedInValues) { if (updatedRound.RealTimeMinersInformation.ContainsKey(revealedInValue.Key) && (updatedRound.RealTimeMinersInformation[revealedInValue.Key].PreviousInValue == Hash.Empty || updatedRound.RealTimeMinersInformation[revealedInValue.Key].PreviousInValue == null)) { updatedRound.RealTimeMinersInformation[revealedInValue.Key].PreviousInValue = revealedInValue.Value; } } } private AElfConsensusHeaderInformation GetConsensusExtraDataForTinyBlock(Round currentRound, string pubkey, AElfConsensusTriggerInformation triggerInformation) { currentRound.RealTimeMinersInformation[pubkey].ProducedTinyBlocks = currentRound .RealTimeMinersInformation[pubkey].ProducedTinyBlocks.Add(1); currentRound.RealTimeMinersInformation[pubkey].ProducedBlocks = currentRound.RealTimeMinersInformation[pubkey].ProducedBlocks.Add(1); currentRound.RealTimeMinersInformation[pubkey].ActualMiningTimes .Add(Context.CurrentBlockTime); return new AElfConsensusHeaderInformation { SenderPubkey = pubkey.ToByteString(), Round = currentRound.GetTinyBlockRound(pubkey), Behaviour = triggerInformation.Behaviour }; } private AElfConsensusHeaderInformation GetConsensusExtraDataForNextRound(Round currentRound, string pubkey, AElfConsensusTriggerInformation triggerInformation) { GenerateNextRoundInformation(currentRound, Context.CurrentBlockTime, out var nextRound); if (!nextRound.RealTimeMinersInformation.Keys.Contains(pubkey)) { return new AElfConsensusHeaderInformation { SenderPubkey = pubkey.ToByteString(), Round = nextRound, Behaviour = triggerInformation.Behaviour }; } RevealSharedInValues(currentRound, pubkey); nextRound.RealTimeMinersInformation[pubkey].ProducedBlocks = nextRound.RealTimeMinersInformation[pubkey].ProducedBlocks.Add(1); Context.LogDebug(() => $"Mined blocks: {nextRound.GetMinedBlocks()}"); nextRound.ExtraBlockProducerOfPreviousRound = pubkey; nextRound.RealTimeMinersInformation[pubkey].ProducedTinyBlocks = 1; nextRound.RealTimeMinersInformation[pubkey].ActualMiningTimes .Add(Context.CurrentBlockTime); return new AElfConsensusHeaderInformation { SenderPubkey = pubkey.ToByteString(), Round = nextRound, Behaviour = triggerInformation.Behaviour }; } private AElfConsensusHeaderInformation GetConsensusExtraDataForNextTerm(string pubkey, AElfConsensusTriggerInformation triggerInformation) { var firstRoundOfNextTerm = GenerateFirstRoundOfNextTerm(pubkey, State.MiningInterval.Value); Assert(firstRoundOfNextTerm.RoundId != 0, "Failed to generate new round information."); if (firstRoundOfNextTerm.RealTimeMinersInformation.ContainsKey(pubkey)) { firstRoundOfNextTerm.RealTimeMinersInformation[pubkey].ProducedTinyBlocks = 1; } return new AElfConsensusHeaderInformation { SenderPubkey = pubkey.ToByteString(), Round = firstRoundOfNextTerm, Behaviour = triggerInformation.Behaviour }; } } }
45.636364
132
0.608656
[ "MIT" ]
booggzen/AElf
contract/AElf.Contracts.Consensus.AEDPoS/AEDPoSContract_GetConsensusBlockExtraData.cs
11,044
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.Data.Entity.Metadata; namespace Microsoft.Data.Entity.FunctionalTests { public abstract class OneToOneQueryFixtureBase { protected static Model CreateModel() { var model = new Model(); var modelBuilder = new ModelBuilder(model); modelBuilder .Entity<Person>( e => e.OneToOne(p => p.Address, a => a.Resident)); modelBuilder.Entity<Address>(); return model; } protected static void AddTestData(DbContext context) { var address1 = new Address { Street = "3 Dragons Way", City = "Meereen" }; var address2 = new Address { Street = "42 Castle Black", City = "The Wall" }; var address3 = new Address { Street = "House of Black and White", City = "Braavos" }; context.Set<Person>().AddRange( new[] { new Person { Name = "Daenerys Targaryen", Address = address1 }, new Person { Name = "John Snow", Address = address2 }, new Person { Name = "Arya Stark", Address = address3 } } ); context.Set<Address>().AddRange( new[] { address1, address2, address3 } ); context.SaveChanges(); } } public class Person { public int Id { get; set; } public string Name { get; set; } public Address Address { get; set; } } public class Address { public int Id { get; set; } public string Street { get; set; } public string City { get; set; } public Person Resident { get; set; } } }
30.776119
111
0.504365
[ "Apache-2.0" ]
matteo-mosca-easydom/EntityFramework
test/EntityFramework.FunctionalTests/OneToOneQueryFixtureBase.cs
2,062
C#
using System; namespace GR.Core.Attributes.Documentation { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true)] public class AuthorAttribute : Attribute { /// <summary> /// Name /// </summary> private string _name; /// <summary> /// Version /// </summary> private double _version; /// <inheritdoc /> /// <summary> /// Constructor /// </summary> /// <param name="name"></param> /// <param name="version"></param> /// <param name="changes"></param> public AuthorAttribute(string name, double version = 1.0, string changes = null) { _name = name; _version = version; } } }
24.8125
92
0.526448
[ "MIT" ]
indrivo/GEAR
src/GR.Extensions/GR.Core.Extension/GR.Core/Attributes/Documentation/AuthorAttribute.cs
796
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Testing { /// <summary> /// To aid with testing, we define a special type of text file that can encode additional /// information in it. This prevents a test writer from having to carry around multiple sources /// of information that must be reconstituted. For example, instead of having to keep around the /// contents of a file *and* and the location of the cursor, the tester can just provide a /// string with the "$" character in it. This allows for easy creation of "FIT" tests where all /// that needs to be provided are strings that encode every bit of state necessary in the string /// itself. /// /// The current set of encoded features we support are: /// /// $$ - The position in the file. There can be at most one of these. /// /// [| ... |] - A span of text in the file. There can be many of these and they can be nested /// and/or overlap the $ position. /// /// {|Name: ... |} A span of text in the file annotated with an identifier. There can be many of /// these, including ones with the same name. /// /// Additional encoded features can be added on a case by case basis. /// </summary> public static class TestFileMarkupParser { private const string PositionString = "$$"; private const string SpanStartString = "[|"; private const string SpanEndString = "|]"; private const string NamedSpanStartString = "{|"; private const string NamedSpanEndString = "|}"; private static readonly Regex s_namedSpanStartRegex = new Regex( @"\{\| ([^:|[\]{}]+) \:", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace); private static void Parse(string input, out string output, out IList<int> positions, out IDictionary<string, IList<TextSpan>> spans) { positions = new List<int>(); spans = new Dictionary<string, IList<TextSpan>>(); var outputBuilder = new StringBuilder(); var currentIndexInInput = 0; var inputOutputOffset = 0; // A stack of span starts along with their associated annotation name. [||] spans simply // have empty string for their annotation name. var spanStartStack = new Stack<Tuple<int, string>>(); while (true) { var matches = new List<(int, string)>(); AddMatch(input, PositionString, currentIndexInInput, matches); AddMatch(input, SpanStartString, currentIndexInInput, matches); AddMatch(input, SpanEndString, currentIndexInInput, matches); AddMatch(input, NamedSpanEndString, currentIndexInInput, matches); var namedSpanStartMatch = s_namedSpanStartRegex.Match(input, currentIndexInInput); if (namedSpanStartMatch.Success) { matches.Add((namedSpanStartMatch.Index, namedSpanStartMatch.Value)); } if (matches.Count == 0) { // No more markup to process. break; } var orderedMatches = matches.OrderBy(t => t.Item1).ToList(); if (orderedMatches.Count >= 2 && spanStartStack.Count > 0 && matches[0].Item1 == matches[1].Item1 - 1) { // We have a slight ambiguity with cases like these: // // [|] [|} // // Is it starting a new match, or ending an existing match. As a workaround, we // special case these and consider it ending a match if we have something on the // stack already. if ((matches[0].Item2 == SpanStartString && matches[1].Item2 == SpanEndString && spanStartStack.Peek().Item2?.Length == 0) || (matches[0].Item2 == SpanStartString && matches[1].Item2 == NamedSpanEndString && spanStartStack.Peek().Item2 != string.Empty)) { orderedMatches.RemoveAt(0); } } // Order the matches by their index var firstMatch = orderedMatches[0]; var matchIndexInInput = firstMatch.Item1; var matchString = firstMatch.Item2; var matchIndexInOutput = matchIndexInInput - inputOutputOffset; outputBuilder.Append(input, currentIndexInInput, matchIndexInInput - currentIndexInInput); currentIndexInInput = matchIndexInInput + matchString.Length; inputOutputOffset += matchString.Length; switch (matchString.Substring(0, 2)) { case PositionString: positions.Add(matchIndexInOutput); break; case SpanStartString: spanStartStack.Push(Tuple.Create(matchIndexInOutput, string.Empty)); break; case SpanEndString: if (spanStartStack.Count == 0) { throw new ArgumentException(string.Format("Saw {0} without matching {1}", SpanEndString, SpanStartString)); } if (spanStartStack.Peek().Item2.Length > 0) { throw new ArgumentException(string.Format("Saw {0} without matching {1}", NamedSpanStartString, NamedSpanEndString)); } PopSpan(spanStartStack, spans, matchIndexInOutput); break; case NamedSpanStartString: var name = namedSpanStartMatch.Groups[1].Value; spanStartStack.Push(Tuple.Create(matchIndexInOutput, name)); break; case NamedSpanEndString: if (spanStartStack.Count == 0) { throw new ArgumentException(string.Format("Saw {0} without matching {1}", NamedSpanEndString, NamedSpanStartString)); } if (spanStartStack.Peek().Item2.Length == 0) { throw new ArgumentException(string.Format("Saw {0} without matching {1}", SpanStartString, SpanEndString)); } PopSpan(spanStartStack, spans, matchIndexInOutput); break; default: throw new InvalidOperationException(); } } if (spanStartStack.Count > 0) { throw new ArgumentException(string.Format("Saw {0} without matching {1}", SpanStartString, SpanEndString)); } // Append the remainder of the string. outputBuilder.Append(input.Substring(currentIndexInInput)); output = outputBuilder.ToString(); } private static void PopSpan( Stack<Tuple<int, string>> spanStartStack, IDictionary<string, IList<TextSpan>> spans, int finalIndex) { var spanStartTuple = spanStartStack.Pop(); var span = TextSpan.FromBounds(spanStartTuple.Item1, finalIndex); spans.GetOrAdd(spanStartTuple.Item2, () => new List<TextSpan>()).Add(span); } private static void AddMatch(string input, string value, int currentIndex, List<(int index, string value)> matches) { var index = input.IndexOf(value, currentIndex); if (index >= 0) { matches.Add((index, value)); } } public static void GetPositionsAndSpans(string input, out string output, out IList<int> positions, out IDictionary<string, IList<TextSpan>> spans) { Parse(input, out output, out positions, out spans); } public static void GetPositionAndSpans(string input, out string output, out int? cursorPositionOpt, out IDictionary<string, IList<TextSpan>> spans) { Parse(input, out output, out var positions, out spans); cursorPositionOpt = positions.SingleOrDefault(); } public static void GetPositionAndSpans(string input, out int? cursorPositionOpt, out IDictionary<string, IList<TextSpan>> spans) { GetPositionAndSpans(input, out var output, out cursorPositionOpt, out spans); } public static void GetPositionAndSpans(string input, out string output, out int cursorPosition, out IDictionary<string, IList<TextSpan>> spans) { GetPositionAndSpans(input, out output, out int? cursorPositionOpt, out spans); if (cursorPositionOpt is null) { throw new ArgumentException("The input did not include a marked cursor position", nameof(input)); } cursorPosition = cursorPositionOpt.Value; } public static void GetSpans(string input, out string output, out IDictionary<string, IList<TextSpan>> spans) { GetPositionAndSpans(input, out output, out int? cursorPositionOpt, out spans); } public static void GetPositionAndSpans(string input, out string output, out int? cursorPositionOpt, out IList<TextSpan> spans) { Parse(input, out output, out var positions, out var dictionary); cursorPositionOpt = positions.SingleOrDefault(); spans = dictionary.GetOrAdd(string.Empty, () => new List<TextSpan>()); } public static void GetPositionAndSpans(string input, out int? cursorPositionOpt, out IList<TextSpan> spans) { GetPositionAndSpans(input, out var output, out cursorPositionOpt, out spans); } public static void GetPositionAndSpans(string input, out string output, out int cursorPosition, out IList<TextSpan> spans) { GetPositionAndSpans(input, out output, out int? pos, out spans); cursorPosition = pos ?? 0; } public static void GetPosition(string input, out string output, out int cursorPosition) { GetPositionAndSpans(input, out output, out cursorPosition, out IList<TextSpan> spans); } public static void GetPositionAndSpan(string input, out string output, out int cursorPosition, out TextSpan span) { GetPositionAndSpans(input, out output, out cursorPosition, out IList<TextSpan> spans); span = spans.Single(); } public static void GetSpans(string input, out string output, out IList<TextSpan> spans) { GetPositionAndSpans(input, out output, out int? pos, out spans); } public static void GetSpan(string input, out string output, out TextSpan span) { GetSpans(input, out output, out IList<TextSpan> spans); span = spans.Single(); } public static string CreateTestFile(string code, int cursor) { return CreateTestFile(code, new Dictionary<string, IList<TextSpan>>(), cursor); } public static string CreateTestFile(string code, IList<TextSpan> spans, int? cursor) { return CreateTestFile(code, new Dictionary<string, IList<TextSpan>> { { string.Empty, spans } }, cursor); } public static string CreateTestFile(string code, IDictionary<string, IList<TextSpan>> spans, int? cursor) { var sb = new StringBuilder(); var anonymousSpans = spans.GetOrAdd(string.Empty, () => new List<TextSpan>()); for (var i = 0; i <= code.Length; i++) { if (i == cursor) { sb.Append(PositionString); } AddSpanString(sb, spans.Where(kvp => kvp.Key != string.Empty), i, start: true); AddSpanString(sb, spans.Where(kvp => kvp.Key?.Length == 0), i, start: true); AddSpanString(sb, spans.Where(kvp => kvp.Key?.Length == 0), i, start: false); AddSpanString(sb, spans.Where(kvp => kvp.Key != string.Empty), i, start: false); if (i < code.Length) { sb.Append(code[i]); } } return sb.ToString(); } private static void AddSpanString( StringBuilder sb, IEnumerable<KeyValuePair<string, IList<TextSpan>>> items, int position, bool start) { foreach (var kvp in items) { foreach (var span in kvp.Value) { if (start && span.Start == position) { if (kvp.Key?.Length == 0) { sb.Append(SpanStartString); } else { sb.Append(NamedSpanStartString); sb.Append(kvp.Key); sb.Append(':'); } } else if (!start && span.End == position) { if (kvp.Key?.Length == 0) { sb.Append(SpanEndString); } else { sb.Append(NamedSpanEndString); } } } } } } }
42.056047
161
0.549274
[ "Apache-2.0" ]
Evangelink/roslyn-sdk
src/Microsoft.CodeAnalysis.Testing/Microsoft.CodeAnalysis.Analyzer.Testing/TestFileMarkupParser.cs
14,259
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Resources.Models.Authorization; using Microsoft.Azure.Graph.RBAC.Models; using Microsoft.WindowsAzure.Commands.Common; using Microsoft.WindowsAzure.Commands.Common.CustomAttributes; using Microsoft.WindowsAzure.Commands.Utilities.Common; using System; using System.Management.Automation; using System.Security; namespace Microsoft.Azure.Commands.ActiveDirectory { /// <summary> /// Creates a new AD servicePrincipal Credential. /// </summary> [Cmdlet("New", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "ADSpCredential", DefaultParameterSetName = ParameterSet.SpObjectIdWithPassword, SupportsShouldProcess = true)] [OutputType(typeof(PSADCredential), typeof(PSADCredentialWrapper))] [Alias("New-" + ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "ADServicePrincipalCredential")] public class NewAzureADSpCredentialCommand : ActiveDirectoryBaseCmdlet { [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSet.SpObjectIdWithCertValue, HelpMessage = "The servicePrincipal object id.")] [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSet.SpObjectIdWithPassword, HelpMessage = "The servicePrincipal object id.")] [ValidateNotNullOrEmpty] [Alias("ServicePrincipalObjectId")] public string ObjectId { get; set; } [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSet.SPNWithCertValue, HelpMessage = "The servicePrincipal name.")] [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSet.SPNWithPassword, HelpMessage = "The servicePrincipal name.")] [ValidateNotNullOrEmpty] [Alias("SPN")] public string ServicePrincipalName { get; set; } [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = ParameterSet.ServicePrincipalObjectWithCertValue, HelpMessage = "The service principal object.")] [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = ParameterSet.ServicePrincipalObjectWithPassword, HelpMessage = "The service principal object.")] [ValidateNotNullOrEmpty] public PSADServicePrincipal ServicePrincipalObject { get; set; } [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSet.SpObjectIdWithPassword, HelpMessage = "The value for the password credential associated with the servicePrincipal that will be valid for one year by default.")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSet.SPNWithPassword, HelpMessage = "The value for the password credential associated with the servicePrincipal that will be valid for one year by default.")] [Parameter(Mandatory = false, ParameterSetName = ParameterSet.ServicePrincipalObjectWithPassword, HelpMessage = "The value for the password credential associated with the servicePrincipal that will be valid for one year by default.")] [ValidateNotNullOrEmpty] #if NETSTANDARD [CmdletParameterBreakingChange(nameof(Password), ChangeDescription = "The Password parameter will be removed in an upcoming breaking change release. After this point, the password will always be automatically generated.")] #endif public SecureString Password { get; set; } [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSet.SpObjectIdWithCertValue, HelpMessage = "The base64 encoded value for the AsymmetricX509Cert associated with the servicePrincipal that will be valid for one year by default.")] [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSet.SPNWithCertValue, HelpMessage = "The base64 encoded value for the AsymmetricX509Cert associated with the servicePrincipal that will be valid for one year by default.")] [Parameter(Mandatory = true, ParameterSetName = ParameterSet.ServicePrincipalObjectWithCertValue, HelpMessage = "The base64 encoded value for the AsymmetricX509Cert associated with the servicePrincipal that will be valid for one year by default.")] [ValidateNotNullOrEmpty] public string CertValue { get; set; } [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The start date after which password or key would be valid. Default value is current time.")] public DateTime StartDate { get; set; } [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The end date till which password or key is valid. Default value is one year after the start date.")] public DateTime EndDate { get; set; } public NewAzureADSpCredentialCommand() { DateTime currentTime = DateTime.UtcNow; StartDate = currentTime; } public override void ExecuteCmdlet() { ExecutionBlock(() => { if (!this.IsParameterBound(c => c.EndDate)) { WriteVerbose(Resources.Properties.Resources.DefaultEndDateUsed); EndDate = StartDate.AddYears(1); } if (this.IsParameterBound(c => c.ServicePrincipalObject)) { ObjectId = ServicePrincipalObject.Id; } if (this.IsParameterBound(c => c.ServicePrincipalName)) { ObjectId = ActiveDirectoryClient.GetObjectIdFromSPN(ServicePrincipalName); } if (Password != null && Password.Length > 0) { string decodedPassword = SecureStringExtensions.ConvertToString(Password); // Create object for password credential var passwordCredential = new PasswordCredential() { EndDate = EndDate, StartDate = StartDate, KeyId = Guid.NewGuid().ToString(), Value = decodedPassword }; if (ShouldProcess(target: ObjectId, action: string.Format("Adding a new password to service principal with objectId {0}", ObjectId))) { WriteObject(ActiveDirectoryClient.CreateSpPasswordCredential(ObjectId, passwordCredential)); } } else if (this.IsParameterBound(c => c.CertValue)) { // Create object for key credential var keyCredential = new KeyCredential() { EndDate = EndDate, StartDate = StartDate, KeyId = Guid.NewGuid().ToString(), Value = CertValue, Type = "AsymmetricX509Cert", Usage = "Verify" }; if (ShouldProcess(target: ObjectId, action: string.Format("Adding a new caertificate to service principal with objectId {0}", ObjectId))) { WriteObject(ActiveDirectoryClient.CreateSpKeyCredential(ObjectId, keyCredential)); } } else { // If no credentials provided, set the password to a randomly generated GUID Password = Guid.NewGuid().ToString().ConvertToSecureString(); string decodedPassword = SecureStringExtensions.ConvertToString(Password); var passwordCredential = new PasswordCredential() { EndDate = EndDate, StartDate = StartDate, KeyId = Guid.NewGuid().ToString(), Value = decodedPassword }; if (ShouldProcess(target: ObjectId, action: string.Format("Adding a new password to service principal with objectId {0}", ObjectId))) { var spCred = new PSADCredentialWrapper(ActiveDirectoryClient.CreateSpPasswordCredential(ObjectId, passwordCredential)); spCred.Secret = Password; WriteObject(spCred); } } }); } } }
58.619632
231
0.627734
[ "MIT" ]
curtand/azure-powershell
src/ResourceManager/Resources/Commands.Resources/ActiveDirectory/Cmdlets/NewAzureADSpCredentialCommand.cs
9,395
C#
using System; using System.Configuration; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text.RegularExpressions; using MongoDB.Driver; using MongoDB.Driver.Builders; using NDesk.Options; namespace VBin.Uploader { public class UploadProgram { static int Main( string[] args ) { long version = -1; string host = "localhost"; int port = 27017; bool showHelp = false; string filespec = null; string sourcePath = "."; bool checkBeforeUpload = false; var os = new OptionSet { { "v|version=", "version", v => version = long.Parse( v.Trim() ) }, { "h|host=", "mongodb host", v => host = v.Trim() }, { "p|port=", "mongodb port", v => port = int.Parse( v.Trim() ) }, { "fileSpec=", "regex file spec to match", v => filespec = v.Trim() }, { "sourcePath=", "source path for the files to upload", v => sourcePath = v.Trim() }, { "m|md5", "Check if file exists using mongo's MD5 hash before uploading a new one", v => checkBeforeUpload = true }, { "help", "show help", v => showHelp = true }, }; os.Parse( args ); if( showHelp || (version <= 0) || (new[] { host, sourcePath }.Any( string.IsNullOrWhiteSpace )) ) { Console.WriteLine(); os.WriteOptionDescriptions( Console.Out ); return 1; } if( string.IsNullOrWhiteSpace( filespec ) ) { filespec = @"(?<!vshost)\.((exe)|(dll)|(pdb))$"; } string basePath = version + "\\"; Console.WriteLine( "Uploading to " + basePath ); Console.WriteLine( " FileSpec {0}", filespec ); Console.Title += " - " + basePath; string mongoConnection = "mongodb://" + host + ":" + port; var client = new MongoClient( mongoConnection ); var svr = client.GetServer(); var db = svr.GetDatabase( ConfigurationManager.AppSettings["VBinDatabase"] ); var grid = db.GridFS; var fileSpecRegex = new Regex( filespec, RegexOptions.IgnoreCase ); Console.WriteLine(); foreach( var file in Directory.GetFiles( sourcePath ) ) { if( !fileSpecRegex.IsMatch( Path.GetFileName( file ) ) ) { continue; } using( var strm = File.OpenRead( file ) ) { string remoteFileName = basePath + Path.GetFileName( file ); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine( "{0} -> {1}", file, remoteFileName ); Console.ResetColor(); if( checkBeforeUpload ) { var f = grid.FindOne( Query.EQ( "filename", remoteFileName ) ); if( f != null ) { string hash; using( var md5 = MD5.Create() ) { using( var fstrm = File.OpenRead( file ) ) { hash = BitConverter.ToString( md5.ComputeHash( fstrm ) ).Replace( "-", "" ); } } if( string.Compare( f.MD5, hash, StringComparison.InvariantCultureIgnoreCase ) == 0 ) { Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine( " File already up to date - skipping" ); Console.WriteLine(); Console.ResetColor(); continue; } } } grid.Delete( remoteFileName ); grid.Upload( strm, remoteFileName ); } } Console.WriteLine(); return 0; } } }
34.90411
115
0.380691
[ "MIT" ]
andrevdm/vbin
Source/VBin.Uploader/UploadProgram.cs
5,098
C#
using System; namespace FrontDesk.Core.Exceptions { public class AppointmentTypeNotFoundException : Exception { public AppointmentTypeNotFoundException(string message) : base(message) { } public AppointmentTypeNotFoundException(int appointmentTypeId) : base($"No appointment type with id {appointmentTypeId} found.") { } } }
22.375
132
0.73743
[ "MIT" ]
KunalChoudhary521/pluralsight-ddd-fundamentals
FrontDesk/src/FrontDesk.Core/Exceptions/AppointmentTypeNotFoundException.cs
360
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace timw255.Sitefinity.RestClient.Model { public class WcfMembershipUser : WcfItemBase, IEquatable<WcfMembershipUser> { public bool AvatarImageSmallerWidth { get; set; } public string AvatarImageUrl { get; set; } public string AvatarThumbnailUrl { get; set; } public string Comment { get; set; } public DateTime CreationDate { get; set; } public string DisplayName { get; set; } public string Email { get; set; } public bool IsApproved { get; set; } public bool IsBackendUser { get; set; } public bool IsLockedOut { get; set; } public bool IsLoggedIn { get; set; } public DateTime? LastActivityDate { get; set; } public DateTime? LastLockoutDate { get; set; } public DateTime? LastLoginDate { get; set; } public DateTime? LastPasswordChangedDate { get; set; } public string Password { get; set; } public string PasswordAnswer { get; set; } public string PasswordQuestion { get; set; } public string ProfileData { get; set; } public string ProviderName { get; set; } public object ProviderUserKey { get; set; } public string RoleNamesOfUser { get; set; } public RoleProviderPair[] RolesOfUser { get; set; } public string UserID { get; set; } public string UserName { get; set; } public WcfMembershipUser() { } public bool Equals(WcfMembershipUser other) { if (other == null || !(this.UserID == other.UserID)) { return false; } return this.ProviderName == other.ProviderName; } } }
37
79
0.623243
[ "MIT" ]
timw255/timw255.Sitefinity.RestClient
timw255.Sitefinity.RestClient/Model/WcfMembershipUser.cs
1,852
C#
#region License // // Copyright (c) 2007-2018, Sean Chambers <schambers80@gmail.com> // Copyright (c) 2010, Nathan Brown // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System.Linq; using FluentMigrator.Expressions; using FluentMigrator.Model; using FluentMigrator.Runner.Generators.Generic; using JetBrains.Annotations; using Microsoft.Extensions.Options; namespace FluentMigrator.Runner.Generators.SQLite { // ReSharper disable once InconsistentNaming public class SQLiteGenerator : GenericGenerator { public SQLiteGenerator() : this(new SQLiteQuoter()) { } public SQLiteGenerator( [NotNull] SQLiteQuoter quoter) : this(quoter, new OptionsWrapper<GeneratorOptions>(new GeneratorOptions())) { } public SQLiteGenerator( [NotNull] SQLiteQuoter quoter, [NotNull] IOptions<GeneratorOptions> generatorOptions) : base(new SQLiteColumn(), quoter, new EmptyDescriptionGenerator(), generatorOptions) { CompatibilityMode = generatorOptions.Value.CompatibilityMode ?? CompatibilityMode.STRICT; } public override string RenameTable { get { return "ALTER TABLE {0} RENAME TO {1}"; } } public override string Generate(AlterColumnExpression expression) { return CompatibilityMode.HandleCompatibilty("SQLite does not support alter column"); } public override string Generate(AlterDefaultConstraintExpression expression) { return CompatibilityMode.HandleCompatibilty("SQLite does not support altering of default constraints"); } public override string Generate(CreateForeignKeyExpression expression) { // If a FK name starts with $$IGNORE$$_ then it means it was handled by the CREATE TABLE // routine and we know it's been handled so we should just not bother erroring. if (expression.ForeignKey.Name.StartsWith("$$IGNORE$$_")) return string.Empty; return CompatibilityMode.HandleCompatibilty("Foreign keys are not supported in SQLite"); } public override string Generate(DeleteForeignKeyExpression expression) { return CompatibilityMode.HandleCompatibilty("Foreign keys are not supported in SQLite"); } public override string Generate(CreateSequenceExpression expression) { return CompatibilityMode.HandleCompatibilty("Sequences are not supported in SQLite"); } public override string Generate(DeleteSequenceExpression expression) { return CompatibilityMode.HandleCompatibilty("Sequences are not supported in SQLite"); } public override string Generate(DeleteDefaultConstraintExpression expression) { return CompatibilityMode.HandleCompatibilty("Default constraints are not supported in SQLite"); } public override string Generate(CreateConstraintExpression expression) { if (!expression.Constraint.IsUniqueConstraint) return CompatibilityMode.HandleCompatibilty("Only UNIQUE constraints are supported in SQLite"); // Convert the constraint into a UNIQUE index var idx = new CreateIndexExpression(); idx.Index.Name = expression.Constraint.ConstraintName; idx.Index.TableName = expression.Constraint.TableName; idx.Index.SchemaName = expression.Constraint.SchemaName; idx.Index.IsUnique = true; foreach (var col in expression.Constraint.Columns) idx.Index.Columns.Add(new IndexColumnDefinition { Name = col }); return Generate(idx); } public override string Generate(DeleteConstraintExpression expression) { if (!expression.Constraint.IsUniqueConstraint) return CompatibilityMode.HandleCompatibilty("Only UNIQUE constraints are supported in SQLite"); // Convert the constraint into a drop UNIQUE index var idx = new DeleteIndexExpression(); idx.Index.Name = expression.Constraint.ConstraintName; idx.Index.SchemaName = expression.Constraint.SchemaName; return Generate(idx); } public override string Generate(CreateIndexExpression expression) { // SQLite prefixes the index name, rather than the table name with the schema var indexColumns = new string[expression.Index.Columns.Count]; IndexColumnDefinition columnDef; for (var i = 0; i < expression.Index.Columns.Count; i++) { columnDef = expression.Index.Columns.ElementAt(i); if (columnDef.Direction == Direction.Ascending) { indexColumns[i] = Quoter.QuoteColumnName(columnDef.Name) + " ASC"; } else { indexColumns[i] = Quoter.QuoteColumnName(columnDef.Name) + " DESC"; } } return string.Format(CreateIndex , GetUniqueString(expression) , GetClusterTypeString(expression) , Quoter.QuoteIndexName(expression.Index.Name, expression.Index.SchemaName) , Quoter.QuoteTableName(expression.Index.TableName) , string.Join(", ", indexColumns)); } public override string Generate(DeleteIndexExpression expression) { // SQLite prefixes the index name, rather than the table name with the schema return string.Format(DropIndex, Quoter.QuoteIndexName(expression.Index.Name, expression.Index.SchemaName)); } } }
38.90184
119
0.656521
[ "Apache-2.0" ]
crenan/fluentmigrator
src/FluentMigrator.Runner.SQLite/Generators/SQLite/SQLiteGenerator.cs
6,341
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using JSIL.Internal; using JSIL.Proxies; using Mono.Cecil; using TypeInfo = JSIL.Internal.TypeInfo; namespace JSIL { public class TypeInfoProvider : ITypeInfoSource, IDisposable { protected class ProxiesByNameRecord { public readonly ConcurrentCache<HashedString, ArraySegment<string>> Cache = new ConcurrentCache<HashedString, ArraySegment<string>>(new HashedStringComparer()); public volatile int Count; } protected class MakeTypeInfoArgs { public readonly Dictionary<TypeIdentifier, TypeDefinition> MoreTypes = new Dictionary<TypeIdentifier, TypeDefinition>(TypeIdentifier.Comparer); public readonly Dictionary<TypeIdentifier, TypeInfo> SecondPass = new Dictionary<TypeIdentifier, TypeInfo>(TypeIdentifier.Comparer); public readonly OrderedDictionary<TypeIdentifier, TypeDefinition> TypesToInitialize = new OrderedDictionary<TypeIdentifier, TypeDefinition>(TypeIdentifier.Comparer); public TypeDefinition Definition; } protected readonly HashSet<AssemblyDefinition> Assemblies; protected readonly HashSet<string> ProxyAssemblyNames; protected readonly ConcurrentCache<TypeIdentifier, TypeInfo> TypeInformation; protected readonly ConcurrentCache<string, ModuleInfo> ModuleInformation; protected readonly Dictionary<TypeIdentifier, ProxyInfo> TypeProxies; protected readonly Dictionary<string, HashSet<ProxyInfo>> DirectProxiesByTypeName; protected readonly ConcurrentCache<HashedString, ProxiesByNameRecord> ProxiesByName; protected readonly ConcurrentCache<Tuple<string, string>, bool> TypeAssignabilityCache; protected static readonly ConcurrentCache<string, ModuleInfo>.CreatorFunction<ModuleDefinition> MakeModuleInfo; protected static readonly ConcurrentCache<HashedString, ProxiesByNameRecord>.CreatorFunction<MemberReference> MakeProxiesByName; protected static readonly ConcurrentCache<HashedString, ArraySegment<string>>.CreatorFunction<MemberReference> MakeProxiesByFullName; protected static readonly Predicate<ArraySegment<string>> ShouldAddProxies; protected readonly ConcurrentCache<TypeIdentifier, TypeInfo>.CreatorFunction<MakeTypeInfoArgs> MakeTypeInfo; static TypeInfoProvider () { MakeModuleInfo = (key, module) => new ModuleInfo(module); MakeProxiesByName = _MakeProxiesByName; MakeProxiesByFullName = _MakeProxiesByFullName; ShouldAddProxies = _ShouldAddProxies; } public TypeInfoProvider () { var levelOfParallelism = Math.Max(1, Environment.ProcessorCount / 2); Assemblies = new HashSet<AssemblyDefinition>(); ProxyAssemblyNames = new HashSet<string>(StringComparer.Ordinal); TypeProxies = new Dictionary<TypeIdentifier, ProxyInfo>(TypeIdentifier.Comparer); DirectProxiesByTypeName = new Dictionary<string, HashSet<ProxyInfo>>(StringComparer.Ordinal); ProxiesByName = new ConcurrentCache<HashedString, ProxiesByNameRecord>( levelOfParallelism, 256, new HashedStringComparer() ); TypeAssignabilityCache = new ConcurrentCache<Tuple<string, string>, bool>(levelOfParallelism, 4096); TypeInformation = new ConcurrentCache<TypeIdentifier, TypeInfo>(levelOfParallelism, 4096, TypeIdentifier.Comparer); ModuleInformation = new ConcurrentCache<string, ModuleInfo>(levelOfParallelism, 256, StringComparer.Ordinal); MakeTypeInfo = _MakeTypeInfo; } protected TypeInfoProvider (TypeInfoProvider cloneSource) { Assemblies = new HashSet<AssemblyDefinition>(cloneSource.Assemblies); ProxyAssemblyNames = new HashSet<string>(cloneSource.ProxyAssemblyNames); TypeProxies = new Dictionary<TypeIdentifier, ProxyInfo>(cloneSource.TypeProxies, TypeIdentifier.Comparer); DirectProxiesByTypeName = new Dictionary<string, HashSet<ProxyInfo>>(); foreach (var kvp in cloneSource.DirectProxiesByTypeName) DirectProxiesByTypeName.Add(kvp.Key, new HashSet<ProxyInfo>(kvp.Value)); ProxiesByName = cloneSource.ProxiesByName.Clone(); TypeAssignabilityCache = cloneSource.TypeAssignabilityCache.Clone(); TypeInformation = cloneSource.TypeInformation.Clone(); ModuleInformation = cloneSource.ModuleInformation.Clone(); MakeTypeInfo = _MakeTypeInfo; } public TypeInfoProvider Clone () { return new TypeInfoProvider(this); } public IEnumerable<ProxyInfo> Proxies { get { return TypeProxies.Values; } } private static bool _ShouldAddProxies (ArraySegment<string> proxies) { if (proxies.Array == null) return false; else if (proxies.Count == 0) return false; else return true; } private static ProxiesByNameRecord _MakeProxiesByName (HashedString key, MemberReference mr) { return new ProxiesByNameRecord(); } private static ArraySegment<string> _MakeProxiesByFullName (HashedString key, MemberReference mr) { var icap = mr.DeclaringType as Mono.Cecil.ICustomAttributeProvider; if (icap == null) return ImmutableArrayPool<string>.Empty; CustomAttribute proxyAttribute = null; for (int i = 0, c = icap.CustomAttributes.Count; i < c; i++) { var ca = icap.CustomAttributes[i]; if ((ca.AttributeType.Name == "JSProxy") && (ca.AttributeType.Namespace == "JSIL.Proxy")) { proxyAttribute = ca; break; } } if (proxyAttribute == null) return ImmutableArrayPool<string>.Empty; ArraySegment<string> proxyTargets = ImmutableArrayPool<string>.Empty; var args = proxyAttribute.ConstructorArguments; foreach (var arg in args) { switch (arg.Type.FullName) { case "System.Type": { proxyTargets = new ArraySegment<string>(new string[] { ((TypeReference)arg.Value).FullName }); break; } case "System.Type[]": { var values = (CustomAttributeArgument[])arg.Value; proxyTargets = new ArraySegment<string>((from v in values select ((TypeReference)v.Value).FullName) .ToArray()); break; } case "System.String": { proxyTargets = new ArraySegment<string>(new string[] { (string)arg.Value }); break; } case "System.String[]": { var values = (CustomAttributeArgument[])arg.Value; proxyTargets = new ArraySegment<string>((from v in values select (string)v.Value) .ToArray()); break; } } } return proxyTargets; } private TypeInfo _MakeTypeInfo(TypeIdentifier identifier, MakeTypeInfoArgs args) { var constructed = ConstructTypeInformation(identifier, args.Definition, args.MoreTypes); args.SecondPass.Add(identifier, constructed); foreach (var typedef in args.MoreTypes.Values) EnqueueType(args.TypesToInitialize, typedef); args.MoreTypes.Clear(); return constructed; } ConcurrentCache<Tuple<string, string>, bool> ITypeInfoSource.AssignabilityCache { get { return this.TypeAssignabilityCache; } } public int Count { get { return TypeInformation.Count + ModuleInformation.Count; } } public void DumpSignatureCollectionStats () { int minSize = int.MaxValue, maxSize = int.MinValue; int sum = 0, count = 0; foreach (var kvp in TypeInformation) { var signatures = kvp.Value.MethodSignatures; minSize = Math.Min(minSize, signatures.Counts.Count); maxSize = Math.Max(maxSize, signatures.Counts.Count); sum += signatures.Counts.Count; count += 1; } Console.WriteLine("// method signature collection stats:"); Console.WriteLine( "// total: {0:D6} min: {1:D4} max: {2:D4} average: {3:D4}", sum, minSize, maxSize, (int)Math.Floor((double)sum / count) ); } public void ClearCaches () { TypeAssignabilityCache.Clear(); } public void Dispose () { Assemblies.Clear(); ProxyAssemblyNames.Clear(); TypeInformation.Dispose(); ModuleInformation.Dispose(); TypeProxies.Clear(); DirectProxiesByTypeName.Clear(); ProxiesByName.Dispose(); TypeAssignabilityCache.Clear(); } bool ITypeInfoSource.TryGetProxyNames (TypeReference tr, out ArraySegment<string> result) { result = ImmutableArrayPool<string>.Empty; ProxiesByNameRecord proxiesByFullName; var name = new HashedString(tr.Name); if (!ProxiesByName.TryGet(name, out proxiesByFullName)) return false; if (proxiesByFullName.Count == 0) return false; var fullName = new HashedString(tr.FullName); return proxiesByFullName.Cache.TryGet(fullName, out result); } void ITypeInfoSource.CacheProxyNames (MemberReference mr) { var name = new HashedString(mr.DeclaringType.Name); var proxiesByFullName = ProxiesByName.GetOrCreate( name, mr, MakeProxiesByName ); var fullName = new HashedString(mr.DeclaringType.FullName); if (proxiesByFullName.Cache.TryCreate( fullName, mr, MakeProxiesByFullName, ShouldAddProxies )) Interlocked.Increment(ref proxiesByFullName.Count); } protected IEnumerable<TypeDefinition> ProxyTypesFromAssembly (AssemblyDefinition assembly) { foreach (var module in assembly.Modules) { foreach (var type in module.Types) { foreach (var ca in type.CustomAttributes) { if (ca.AttributeType.FullName == "JSIL.Proxy.JSProxy") { yield return type; break; } } } } } private void Remove (TypeDefinition type) { var identifier = new TypeIdentifier(type); var typeName = type.FullName; var hashedTypeName = new HashedString(typeName); TypeProxies.Remove(identifier); TypeInformation.TryRemove(identifier); DirectProxiesByTypeName.Remove(typeName); ProxiesByName.TryRemove(hashedTypeName); foreach (var nt in type.NestedTypes) Remove(nt); } public void Remove (params AssemblyDefinition[] assemblies) { lock (Assemblies) foreach (var assembly in assemblies) { Assemblies.Remove(assembly); ProxyAssemblyNames.Remove(assembly.FullName); foreach (var module in assembly.Modules) { ModuleInformation.TryRemove(module.FullyQualifiedName); foreach (var type in module.Types) { Remove(type); } } } } public void AddProxyAssemblies (Action<AssemblyDefinition> onProxiesFound, params AssemblyDefinition[] assemblies) { HashSet<ProxyInfo> pl; lock (Assemblies) foreach (var asm in assemblies) { if (ProxyAssemblyNames.Contains(asm.FullName)) continue; else ProxyAssemblyNames.Add(asm.FullName); if (Assemblies.Contains(asm)) continue; else Assemblies.Add(asm); bool foundAProxy = false; foreach (var proxyType in ProxyTypesFromAssembly(asm)) { if (!foundAProxy) { foundAProxy = true; onProxiesFound(asm); } var proxyInfo = new ProxyInfo(this, proxyType); TypeProxies.Add(new TypeIdentifier(proxyType), proxyInfo); foreach (var typeref in proxyInfo.ProxiedTypes) { var name = typeref.FullName; if (!DirectProxiesByTypeName.TryGetValue(name, out pl)) DirectProxiesByTypeName[name] = pl = new HashSet<ProxyInfo>(); pl.Add(proxyInfo); } foreach (var name in proxyInfo.ProxiedTypeNames) { if (!DirectProxiesByTypeName.TryGetValue(name, out pl)) DirectProxiesByTypeName[name] = pl = new HashSet<ProxyInfo>(); pl.Add(proxyInfo); } } } } public ProxyInfo FindTypeProxy(TypeIdentifier identifier) { ProxyInfo proxy; TypeProxies.TryGetValue(identifier, out proxy); return proxy; } public ModuleInfo GetModuleInformation (ModuleDefinition module) { if (module == null) throw new ArgumentNullException("module"); var fullName = module.FullyQualifiedName; return ModuleInformation.GetOrCreate( fullName, module, MakeModuleInfo ); } private void EnqueueType (OrderedDictionary<TypeIdentifier, TypeDefinition> queue, TypeReference typeReference, LinkedListNode<TypeIdentifier> before = null) { var typedef = TypeUtil.GetTypeDefinition(typeReference); if (typedef == null) return; var identifier = new TypeIdentifier(typedef); if (queue.ContainsKey(identifier)) return; if (!TypeInformation.ContainsKey(identifier)) { LinkedListNode<TypeIdentifier> before2; if (before != null) before2 = queue.EnqueueBefore(before, identifier, typedef); else before2 = queue.Enqueue(identifier, typedef); if (typedef.BaseType != null) EnqueueType(queue, typedef.BaseType, before2); if (typedef.DeclaringType != null) EnqueueType(queue, typedef.DeclaringType, before2); foreach (var iface in typedef.Interfaces) EnqueueType(queue, iface, before2); } } public TypeInfo GetTypeInformation (TypeReference type) { if (type == null) throw new ArgumentNullException("type"); TypeInfo result; var typedef = TypeUtil.GetTypeDefinition(type); if (typedef == null) return null; var identifier = new TypeIdentifier(typedef); if (TypeInformation.TryGet(identifier, out result)) return result; var args = new MakeTypeInfoArgs(); EnqueueType(args.TypesToInitialize, type); // We must construct type information in two passes, so that method group construction // behaves correctly and ignores all the right methods. // The first pass walks all the way through the type graph (starting with the current type), // ensuring we have type information for all the types in the graph. We do this iteratively // to avoid overflowing the stack. // After we have type information for all the types in the graph, we then walk over all // the types again, and construct their method groups, since we have the necessary // information to determine which methods are ignored. while (args.TypesToInitialize.Count > 0) { var kvp = args.TypesToInitialize.First; args.TypesToInitialize.Remove(kvp.Key); args.Definition = kvp.Value; TypeInformation.TryCreate( kvp.Key, args, MakeTypeInfo ); } foreach (var ti in args.SecondPass.Values) { ti.Initialize(); ti.ConstructMethodGroups(); } if (!TypeInformation.TryGet(identifier, out result)) return null; else return result; } protected TypeInfo ConstructTypeInformation (TypeIdentifier identifier, TypeDefinition type, Dictionary<TypeIdentifier, TypeDefinition> moreTypes) { var moduleInfo = GetModuleInformation(type.Module); TypeInfo baseType = null, declaringType = null; if (type.BaseType != null) { baseType = GetExisting(type.BaseType); if (baseType == null) throw new InvalidOperationException(String.Format( "Missing type info for base type '{0}' of type '{1}'", type.BaseType, type )); } if (type.DeclaringType != null) { declaringType = GetExisting(type.DeclaringType); if (declaringType == null) throw new InvalidOperationException(String.Format( "Missing type info for declaring type '{0}' of type '{1}'", type.DeclaringType, type )); } var result = new TypeInfo(this, moduleInfo, type, declaringType, baseType, identifier); Action<TypeReference> addType = (tr) => { if (tr == null) return; var td = TypeUtil.GetTypeDefinition(tr); if (td == null) return; var _identifier = new TypeIdentifier(td); if (_identifier.Equals(identifier)) return; else if (moreTypes.ContainsKey(_identifier)) return; moreTypes[_identifier] = td; }; foreach (var member in result.Members.Values) { addType(member.ReturnType); var method = member as Internal.MethodInfo; if (method != null) { foreach (var p in method.Member.Parameters) addType(p.ParameterType); } } return result; } ArraySegment<ProxyInfo> ITypeInfoSource.GetProxies (TypeDefinition type) { var result = new HashSet<ProxyInfo>(); bool isInherited = false; bool isInterface = type.IsInterface; while (type != null) { // Never inherit proxy members from System.Object when processing an interface. if (isInterface && type.FullName == "System.Object") break; HashSet<ProxyInfo> candidates; bool found; lock (Assemblies) found = DirectProxiesByTypeName.TryGetValue(type.FullName, out candidates); if (found) { foreach (var candidate in candidates) { if (isInherited && !candidate.IsInheritable) continue; if (candidate.IsMatch(type, null)) result.Add(candidate); } } if (type.BaseType != null) type = type.BaseType.Resolve(); else break; isInherited = true; } return new ArraySegment<ProxyInfo>(result.ToArray()); } IMemberInfo ITypeInfoSource.Get (MemberReference member) { var typeInfo = GetTypeInformation(member.DeclaringType); if (typeInfo == null) { Console.Error.WriteLine("Warning: type not loaded: {0}", member.DeclaringType.FullName); return null; } var identifier = MemberIdentifier.New(this, member); IMemberInfo result; if (!typeInfo.Members.TryGetValue(identifier, out result)) { // Console.Error.WriteLine("Warning: member not defined: {0}", member.FullName); return null; } return result; } ModuleInfo ITypeInfoSource.Get (ModuleDefinition module) { return GetModuleInformation(module); } TypeInfo ITypeInfoSource.Get (TypeReference type) { return GetTypeInformation(type); } public TypeInfo GetExisting (TypeIdentifier identifier) { TypeInfo result; if (!TypeInformation.TryGet(identifier, out result)) return null; return result; } public TypeInfo GetExisting (TypeReference type) { if (type == null) throw new ArgumentNullException("type"); var resolved = type.Resolve(); if (resolved == null) return null; return GetExisting(resolved); } public TypeInfo GetExisting (TypeDefinition type) { if (type == null) throw new ArgumentNullException("type"); var identifier = new TypeIdentifier(type); return GetExisting(identifier); } public T GetMemberInformation<T> (MemberReference member) where T : class, Internal.IMemberInfo { var typeInformation = GetTypeInformation(member.DeclaringType); var identifier = MemberIdentifier.New(this, member); IMemberInfo result; if (!typeInformation.Members.TryGetValue(identifier, out result)) { // Console.Error.WriteLine("Warning: member not defined: {0}", member.FullName); return null; } return (T)result; } } public class OrderedDictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>> { protected readonly Dictionary<TKey, TValue> Dictionary; protected readonly LinkedList<TKey> LinkedList = new LinkedList<TKey>(); public OrderedDictionary () { Dictionary = new Dictionary<TKey, TValue>(); } public OrderedDictionary (IEqualityComparer<TKey> comparer) { Dictionary = new Dictionary<TKey, TValue>(comparer); } public int Count { get { return Dictionary.Count; } } public TValue this [TKey key] { get { return Dictionary[key]; } } public void Clear () { Dictionary.Clear(); LinkedList.Clear(); } public bool ContainsKey (TKey key) { return Dictionary.ContainsKey(key); } public bool Remove (TKey key) { // Is this right? Maybe enqueueing multiple times shouldn't work. while (LinkedList.Remove(key)) ; return Dictionary.Remove(key); } public bool TryDequeueFirst (out TKey key, out TValue value) { if (LinkedList.Count == 0) { key = default(TKey); value = default(TValue); return false; } var node = LinkedList.First; key = node.Value; LinkedList.Remove(node); value = Dictionary[node.Value]; Dictionary.Remove(node.Value); return true; } public LinkedListNode<TKey> EnqueueBefore (LinkedListNode<TKey> before, TKey key, TValue value) { Dictionary.Add(key, value); return LinkedList.AddBefore(before, key); } public LinkedListNode<TKey> EnqueueAfter (LinkedListNode<TKey> after, TKey key, TValue value) { Dictionary.Add(key, value); return LinkedList.AddAfter(after, key); } public LinkedListNode<TKey> Enqueue (TKey key, TValue value) { Dictionary.Add(key, value); return LinkedList.AddLast(key); } public KeyValuePair<TKey, TValue> First { get { var node = LinkedList.First; return new KeyValuePair<TKey, TValue>(node.Value, Dictionary[node.Value]); } } public KeyValuePair<TKey, TValue> Last { get { var node = LinkedList.Last; return new KeyValuePair<TKey, TValue>(node.Value, Dictionary[node.Value]); } } public IEnumerable<LinkedListNode<TKey>> Keys { get { var current = LinkedList.First; while (current != null) { yield return current; current = current.Next; } } } public KeyValuePair<TKey, TValue> AtIndex (int index) { var node = LinkedList.First; while (node != null) { if (index > 0) { index -= 1; node = node.Next; } else { return new KeyValuePair<TKey, TValue>(node.Value, Dictionary[node.Value]); } } throw new ArgumentOutOfRangeException("index"); } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator () { foreach (var key in LinkedList) yield return new KeyValuePair<TKey, TValue>(key, Dictionary[key]); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () { foreach (var key in LinkedList) yield return new KeyValuePair<TKey, TValue>(key, Dictionary[key]); } public bool Replace (TKey key, TValue newValue) { if (ContainsKey(key)) { Dictionary[key] = newValue; return true; } return false; } private LinkedListNode<TKey> MoveToHeadOrTail (TKey key, bool tail) { var node = LinkedList.Find(key); if (node == null) throw new KeyNotFoundException(key.ToString()); LinkedList.Remove(node); if (tail) LinkedList.AddLast(node); else LinkedList.AddFirst(node); return node; } public LinkedListNode<TKey> MoveToHead (TKey key) { return MoveToHeadOrTail(key, false); } public LinkedListNode<TKey> MoveToTail (TKey key) { return MoveToHeadOrTail(key, true); } public LinkedListNode<TKey> FindNode (TKey key) { return LinkedList.Find(key); } } }
37.329365
177
0.561001
[ "MIT" ]
RedpointGames/JSIL
JSIL/TypeInfoProvider.cs
28,223
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MikuMikuMethods.PMX.IO { /// <summary> /// PMX用エンコードを気にせず文字列を読み書きできるようにしたクラス /// </summary> internal class StringEncoder { private System.Text.Encoding Encoding { get; init; } public StringEncoder(System.Text.Encoding encoding) { Encoding = encoding; } public byte[] Encode(string str) => Encoding.GetBytes(str); public string Decode(byte[] bytes) => Encoding.GetString(bytes, 0, bytes.Length); public string Read(BinaryReader reader) { var length = reader.ReadInt32(); return Decode(reader.ReadBytes(length)); } public void Write(BinaryWriter writer, string str) { var bytes = Encode(str); writer.Write(bytes.Length); writer.Write(bytes); } } }
24.7
89
0.611336
[ "MIT" ]
Inwerwm/MikuMikuMethods
MikuMikuMethodsCore/PMX/IO/StringEncoder.cs
1,050
C#
using System; namespace Paint101.Api { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public class ExtensionAttribute : PluginAttribute { public ExtensionAttribute(string displayName) : base(displayName) { } } }
22.307692
86
0.682759
[ "MIT" ]
kinpa200296/Paint101
Paint101/Paint101.Api/Attributes/ExtensionAttribute.cs
292
C#
using Microsoft.Xna.Framework.Graphics; using Terraria.ModLoader; using Microsoft.Xna.Framework; using System; using System.Linq; using Terraria; using Terraria.Utilities; using System.IO; using System.Collections.Generic; using Terraria.ModLoader.IO; using PathOfModifiers.Projectiles; using PathOfModifiers.Buffs; namespace PathOfModifiers.Affixes.Items.Suffixes { public class WeaponPoison : AffixTiered<TTFloat, TTFloat, TTFloat>, ISuffix { public override double Weight { get; } = 1; public override TTFloat Type1 { get; } = new TTFloat() { TwoWay = false, IsRange = true, Tiers = new TTFloat.WeightedTier[] { new TTFloat.WeightedTier(0f, 3), new TTFloat.WeightedTier(0.16f, 2.5), new TTFloat.WeightedTier(0.33f, 2), new TTFloat.WeightedTier(0.5f, 1.5), new TTFloat.WeightedTier(0.66f, 1), new TTFloat.WeightedTier(0.84f, 0.5), new TTFloat.WeightedTier(1f, 0), }, }; public override TTFloat Type2 { get; } = new TTFloat() { TwoWay = false, IsRange = true, Tiers = new TTFloat.WeightedTier[] { new TTFloat.WeightedTier(0f, 3), new TTFloat.WeightedTier(0.01f, 2.5), new TTFloat.WeightedTier(0.02f, 2), new TTFloat.WeightedTier(0.03f, 1.5), new TTFloat.WeightedTier(0.04f, 1), new TTFloat.WeightedTier(0.05f, 0.5), new TTFloat.WeightedTier(0.06f, 0), }, }; public override TTFloat Type3 { get; } = new TTFloat() { TwoWay = false, IsRange = true, Tiers = new TTFloat.WeightedTier[] { new TTFloat.WeightedTier(9f, 3), new TTFloat.WeightedTier(12f, 2.5), new TTFloat.WeightedTier(15f, 2), new TTFloat.WeightedTier(18f, 1.5), new TTFloat.WeightedTier(21f, 1), new TTFloat.WeightedTier(24f, 0.5), new TTFloat.WeightedTier(27f, 0), }, }; public override WeightedTierName[] TierNames { get; } = new WeightedTierName[] { new WeightedTierName("of Venom", 0.5), new WeightedTierName("of Toxicity", 1), new WeightedTierName("of Misery", 1.5), new WeightedTierName("of Virulence", 2), new WeightedTierName("of Blight", 2.5), new WeightedTierName("of Miasma", 3), }; public override bool CanBeRolled(AffixItemItem pomItem, Item item) { return AffixItemItem.IsWeapon(item); } public override string GetTolltipText(Item item) { return $"{Type1.GetValueFormat()}% chance to Poison({Type2.GetValueFormat()}%) for {Type3.GetValueFormat(1)}s"; } public override void OnHitNPC(Item item, Player player, NPC target, int damage, float knockBack, bool crit) { OnHit(item, player, target, damage); } public override void OnHitPvp(Item item, Player player, Player target, int damage, bool crit) { OnHit(item, player, target, damage); } public override void ProjOnHitNPC(Item item, Player player, Projectile projectile, NPC target, int damage, float knockback, bool crit) { OnHit(item, player, target, damage); } public override void ProjOnHitPvp(Item item, Player player, Projectile projectile, Player target, int damage, bool crit) { OnHit(item, player, target, damage); } void OnHit(Item item, Player player, NPC target, int hitDamage) { if (item == player.HeldItem && Main.rand.NextFloat() < Type1.GetValue()) Bleed(target, hitDamage); } void OnHit(Item item, Player player, Player target, int hitDamage) { if (item == player.HeldItem && Main.rand.NextFloat() < Type1.GetValue()) Bleed(target, hitDamage); } void Bleed(NPC target, int hitDamage) { int damage = (int)MathHelper.Clamp(hitDamage * Type2.GetValue(), 1, int.MaxValue); int duration = (int)MathHelper.Clamp(Type3.GetValue() * 60, 1, int.MaxValue); BuffNPC pomNPC = target.GetGlobalNPC<BuffNPC>(); pomNPC.AddPoisonBuff(target, damage, duration); } void Bleed(Player target, int hitDamage) { int damage = (int)MathHelper.Clamp(hitDamage * Type2.GetValue(), 1, int.MaxValue); int duration = (int)MathHelper.Clamp(Type3.GetValue() * 60, 1, int.MaxValue); target.GetModPlayer<BuffPlayer>().AddPoisonBuff(target, damage, duration); } } }
38.632813
142
0.572295
[ "MIT" ]
Liburia/PathOfModifiers
Affixes/Items/Suffixes/WeaponPoison.cs
4,947
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("_12.RemoveWords")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("_12.RemoveWords")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("afc1acf3-a167-4393-b94d-7c2039f3a053")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.918919
84
0.744833
[ "MIT" ]
danisio/CSharp2-Homeworks
TextFiles/12.RemoveWords/Properties/AssemblyInfo.cs
1,406
C#
// <copyright file="MklFourierTransformProvider.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // https://numerics.mathdotnet.com // // Copyright (c) 2009-2018 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using System.IO; using System.Security; using System.Threading; using MathNet.Numerics.Providers.FourierTransform; using Complex = System.Numerics.Complex; namespace MathNet.Numerics.Providers.MKL.FourierTransform { internal sealed class MklFourierTransformProvider : IFourierTransformProvider, IDisposable { const int MinimumCompatibleRevision = 11; class Kernel { public IntPtr Handle; public int[] Dimensions; public FourierTransformScaling Scaling; public bool Real; public bool Single; } readonly string _hintPath; Kernel _kernel; /// <param name="hintPath">Hint path where to look for the native binaries</param> internal MklFourierTransformProvider(string hintPath) { _hintPath = Path.GetFullPath(hintPath); } /// <summary> /// Try to find out whether the provider is available, at least in principle. /// Verification may still fail if available, but it will certainly fail if unavailable. /// </summary> public bool IsAvailable() { return MklProvider.IsAvailable(hintPath: _hintPath); } /// <summary> /// Initialize and verify that the provided is indeed available. If not, fall back to alternatives like the managed provider /// </summary> [SecuritySafeCritical] public void InitializeVerify() { int revision = MklProvider.Load(hintPath: _hintPath); if (revision < MinimumCompatibleRevision) { throw new NotSupportedException(FormattableString.Invariant($"MKL Native Provider revision r{revision} is too old. Consider upgrading to a newer version. Revision r{MinimumCompatibleRevision} and newer are supported.")); } // we only support exactly one major version, since major version changes imply a breaking change. int fftMajor = SafeNativeMethods.query_capability((int) ProviderCapability.FourierTransformMajor); int fftMinor = SafeNativeMethods.query_capability((int) ProviderCapability.FourierTransformMinor); if (!(fftMajor == 1 && fftMinor >= 0)) { throw new NotSupportedException(FormattableString.Invariant($"MKL Native Provider not compatible. Expecting Fourier transform v1 but provider implements v{fftMajor}.")); } } /// <summary> /// Frees memory buffers, caches and handles allocated in or to the provider. /// Does not unload the provider itself, it is still usable afterwards. /// </summary> [SecuritySafeCritical] public void FreeResources() { Kernel kernel = Interlocked.Exchange(ref _kernel, null); if (kernel != null) { SafeNativeMethods.x_fft_free(ref kernel.Handle); } MklProvider.FreeResources(); } public override string ToString() { return MklProvider.Describe(); } [SecuritySafeCritical] Kernel Configure(int length, FourierTransformScaling scaling, bool real, bool single) { Kernel kernel = Interlocked.Exchange(ref _kernel, null); if (kernel == null) { kernel = new Kernel { Dimensions = new[] {length}, Scaling = scaling, Real = real, Single = single }; if (single) { if (real) SafeNativeMethods.s_fft_create(out kernel.Handle, length, (float)ForwardScaling(scaling, length), (float)BackwardScaling(scaling, length)); else SafeNativeMethods.c_fft_create(out kernel.Handle, length, (float)ForwardScaling(scaling, length), (float)BackwardScaling(scaling, length)); } else { if (real) SafeNativeMethods.d_fft_create(out kernel.Handle, length, ForwardScaling(scaling, length), BackwardScaling(scaling, length)); else SafeNativeMethods.z_fft_create(out kernel.Handle, length, ForwardScaling(scaling, length), BackwardScaling(scaling, length)); } return kernel; } if (kernel.Dimensions.Length != 1 || kernel.Dimensions[0] != length || kernel.Scaling != scaling || kernel.Real != real || kernel.Single != single) { SafeNativeMethods.x_fft_free(ref kernel.Handle); if (single) { if (real) SafeNativeMethods.s_fft_create(out kernel.Handle, length, (float)ForwardScaling(scaling, length), (float)BackwardScaling(scaling, length)); else SafeNativeMethods.c_fft_create(out kernel.Handle, length, (float)ForwardScaling(scaling, length), (float)BackwardScaling(scaling, length)); } else { if (real) SafeNativeMethods.d_fft_create(out kernel.Handle, length, ForwardScaling(scaling, length), BackwardScaling(scaling, length)); else SafeNativeMethods.z_fft_create(out kernel.Handle, length, ForwardScaling(scaling, length), BackwardScaling(scaling, length)); } kernel.Dimensions = new[] {length}; kernel.Scaling = scaling; kernel.Real = real; kernel.Single = single; return kernel; } return kernel; } [SecuritySafeCritical] Kernel Configure(int[] dimensions, FourierTransformScaling scaling, bool single) { if (dimensions.Length == 1) { return Configure(dimensions[0], scaling, false, single); } Kernel kernel = Interlocked.Exchange(ref _kernel, null); if (kernel == null) { kernel = new Kernel { Dimensions = dimensions, Scaling = scaling, Real = false, Single = single }; long length = 1; for (int i = 0; i < dimensions.Length; i++) { length *= dimensions[i]; } if (single) { SafeNativeMethods.c_fft_create_multidim(out kernel.Handle, dimensions.Length, dimensions, (float)ForwardScaling(scaling, length), (float)BackwardScaling(scaling, length)); } else { SafeNativeMethods.z_fft_create_multidim(out kernel.Handle, dimensions.Length, dimensions, ForwardScaling(scaling, length), BackwardScaling(scaling, length)); } return kernel; } bool mismatch = kernel.Dimensions.Length != dimensions.Length || kernel.Scaling != scaling || kernel.Real != false || kernel.Single != single; if (!mismatch) { for (int i = 0; i < dimensions.Length; i++) { if (dimensions[i] != kernel.Dimensions[i]) { mismatch = true; break; } } } if (mismatch) { long length = 1; for (int i = 0; i < dimensions.Length; i++) { length *= dimensions[i]; } SafeNativeMethods.x_fft_free(ref kernel.Handle); if (single) { SafeNativeMethods.c_fft_create_multidim(out kernel.Handle, dimensions.Length, dimensions, (float)ForwardScaling(scaling, length), (float)BackwardScaling(scaling, length)); } else { SafeNativeMethods.z_fft_create_multidim(out kernel.Handle, dimensions.Length, dimensions, ForwardScaling(scaling, length), BackwardScaling(scaling, length)); } kernel.Dimensions = dimensions; kernel.Scaling = scaling; kernel.Real = false; kernel.Single = single; return kernel; } return kernel; } [SecuritySafeCritical] void Release(Kernel kernel) { Kernel existing = Interlocked.Exchange(ref _kernel, kernel); if (existing != null) { SafeNativeMethods.x_fft_free(ref existing.Handle); } } [SecuritySafeCritical] public void Forward(Complex32[] samples, FourierTransformScaling scaling) { Kernel kernel = Configure(samples.Length, scaling, false, true); SafeNativeMethods.c_fft_forward(kernel.Handle, samples); Release(kernel); } [SecuritySafeCritical] public void Forward(Complex[] samples, FourierTransformScaling scaling) { Kernel kernel = Configure(samples.Length, scaling, false, false); SafeNativeMethods.z_fft_forward(kernel.Handle, samples); Release(kernel); } [SecuritySafeCritical] public void Backward(Complex32[] spectrum, FourierTransformScaling scaling) { Kernel kernel = Configure(spectrum.Length, scaling, false, true); SafeNativeMethods.c_fft_backward(kernel.Handle, spectrum); Release(kernel); } [SecuritySafeCritical] public void Backward(Complex[] spectrum, FourierTransformScaling scaling) { Kernel kernel = Configure(spectrum.Length, scaling, false, false); SafeNativeMethods.z_fft_backward(kernel.Handle, spectrum); Release(kernel); } [SecuritySafeCritical] public void ForwardReal(float[] samples, int n, FourierTransformScaling scaling) { Kernel kernel = Configure(n, scaling, true, true); SafeNativeMethods.s_fft_forward(kernel.Handle, samples); Release(kernel); } [SecuritySafeCritical] public void ForwardReal(double[] samples, int n, FourierTransformScaling scaling) { Kernel kernel = Configure(n, scaling, true, false); SafeNativeMethods.d_fft_forward(kernel.Handle, samples); Release(kernel); } [SecuritySafeCritical] public void BackwardReal(float[] spectrum, int n, FourierTransformScaling scaling) { Kernel kernel = Configure(n, scaling, true, true); SafeNativeMethods.s_fft_backward(kernel.Handle, spectrum); Release(kernel); spectrum[n] = 0f; } [SecuritySafeCritical] public void BackwardReal(double[] spectrum, int n, FourierTransformScaling scaling) { Kernel kernel = Configure(n, scaling, true, false); SafeNativeMethods.d_fft_backward(kernel.Handle, spectrum); Release(kernel); spectrum[n] = 0d; } [SecuritySafeCritical] public void ForwardMultidim(Complex32[] samples, int[] dimensions, FourierTransformScaling scaling) { Kernel kernel = Configure(dimensions, scaling, true); SafeNativeMethods.c_fft_forward(kernel.Handle, samples); Release(kernel); } [SecuritySafeCritical] public void ForwardMultidim(Complex[] samples, int[] dimensions, FourierTransformScaling scaling) { Kernel kernel = Configure(dimensions, scaling, false); SafeNativeMethods.z_fft_forward(kernel.Handle, samples); Release(kernel); } [SecuritySafeCritical] public void BackwardMultidim(Complex32[] spectrum, int[] dimensions, FourierTransformScaling scaling) { Kernel kernel = Configure(dimensions, scaling, true); SafeNativeMethods.c_fft_backward(kernel.Handle, spectrum); Release(kernel); } [SecuritySafeCritical] public void BackwardMultidim(Complex[] spectrum, int[] dimensions, FourierTransformScaling scaling) { Kernel kernel = Configure(dimensions, scaling, false); SafeNativeMethods.z_fft_backward(kernel.Handle, spectrum); Release(kernel); } static double ForwardScaling(FourierTransformScaling scaling, long length) { switch (scaling) { case FourierTransformScaling.SymmetricScaling: return Math.Sqrt(1.0/length); case FourierTransformScaling.ForwardScaling: return 1.0/length; default: return 1.0; } } static double BackwardScaling(FourierTransformScaling scaling, long length) { switch (scaling) { case FourierTransformScaling.SymmetricScaling: return Math.Sqrt(1.0/length); case FourierTransformScaling.BackwardScaling: return 1.0/length; default: return 1.0; } } public void Dispose() { FreeResources(); } } }
38.488372
236
0.585566
[ "MIT" ]
NetPro69/mathnet-numerics
src/Providers.MKL/FourierTransform/MklFourierTransformProvider.cs
14,897
C#
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Media.Effects.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Media.Effects { public enum EdgeProfile { Linear = 0, CurvedIn = 1, CurvedOut = 2, BulgedUp = 3, } public enum KernelType { Gaussian = 0, Box = 1, } public enum RenderingBias { Performance = 0, Quality = 1, } public enum SamplingMode { NearestNeighbor = 0, Bilinear = 1, Auto = 2, } public enum ShaderRenderMode { Auto = 0, SoftwareOnly = 1, HardwareOnly = 2, } }
32.92
463
0.735115
[ "MIT" ]
Acidburn0zzz/CodeContracts
Microsoft.Research/Contracts/PresentationCore/Sources/System.Windows.Media.Effects.cs
2,469
C#
using BlazorComponentUtilities; using BlazorStrap.Util; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Forms; using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.Components.Web; using System; using System.Collections.Generic; using System.Globalization; using System.Linq.Expressions; using System.Threading.Tasks; namespace BlazorStrap { public class BSBasicInput<T> : ComponentBase { // Constants private const string _dateFormat = "yyyy-MM-dd"; // Protected variables protected string Classname => new CssBuilder() .AddClass($"form-control-{Size.ToDescriptionString()}", Size != Size.None) .AddClass("is-valid", IsValid) .AddClass("is-invalid", IsInvalid) .AddClass(GetClass()) .AddClass(Class) .Build(); protected string Tag => InputType switch { InputType.Select => "select", InputType.TextArea => "textarea", _ => "input" }; protected ElementReference ElementReference; protected string Type => InputType.ToDescriptionString(); private FieldIdentifier _fieldIdentifier { get; set; } // Dependency Injection [Inject] protected BlazorStrapInterop BlazorStrapInterop { get; set; } // Parameters [Parameter(CaptureUnmatchedValues = true)] public IDictionary<string, object> UnknownParameters { get; set; } [Parameter] public Expression<Func<object>> For { get; set; } [Parameter] public InputType InputType { get; set; } = InputType.Text; [Parameter] public Size Size { get; set; } = Size.None; [Parameter] public string MaxDate { get; set; } = "9999-12-31"; [Parameter] public virtual T Value { get; set; } [Parameter] public virtual T RadioValue { get; set; } [Parameter] public virtual T CheckValue { get; set; } [Parameter] public virtual EventCallback<T> ValueChanged { get; set; } [Parameter] public EventCallback<string> ConversionError { get; set; } [Parameter] public bool IsReadonly { get; set; } [Parameter] public bool IsPlaintext { get; set; } [Parameter] public bool IsDisabled { get; set; } [Parameter] public bool IsChecked { get; set; } [Parameter] public bool IsValid { get; set; } [Parameter] public bool IsInvalid { get; set; } [Parameter] public bool IsMultipleSelect { get; set; } [Parameter] public int? SelectSize { get; set; } [Parameter] public int? SelectedIndex { get; set; } [Parameter] public string Class { get; set; } [Parameter] public bool ValidateOnInput { get; set; } = false; [Parameter] public int DebounceInterval { get; set; } = 500; [Parameter] public RenderFragment ChildContent { get; set; } // Cascading Parameters [CascadingParameter] protected EditContext MyEditContext { get; set; } [CascadingParameter] public BSLabel BSLabel { get; set; } // Overrides protected override void OnParametersSet() { if (For != null) { _fieldIdentifier = FieldIdentifier.Create(For); } } protected override void BuildRenderTree(RenderTreeBuilder builder) { var index = -1; builder?.OpenElement(index++, Tag); builder.AddMultipleAttributes(index++, UnknownParameters); builder.AddAttribute(index++, "class", Classname); builder.AddAttribute(index++, "type", Type); builder.AddAttribute(index++, "readonly", IsReadonly); builder.AddAttribute(index++, "disabled", IsDisabled); builder.AddAttribute(index++, "multiple", IsMultipleSelect); builder.AddAttribute(index++, "size", SelectSize); builder.AddAttribute(index++, "selectedIndex", SelectedIndex); // Build checkbox if (InputType == InputType.Checkbox) { index = BuildCheckbox(builder, index); } // Build Radio else if (InputType == InputType.Radio) { index = BuildRadio(builder, index); } else { builder.AddAttribute(index++, "value", BindConverter.FormatValue(CurrentValueAsString)); index = BuildValidation(builder, index); if (InputType == InputType.Date && !string.IsNullOrEmpty(MaxDate)) { builder.AddAttribute(index++, "max", MaxDate); } } builder.AddContent(index++, ChildContent); builder.AddElementReferenceCapture(index++, er => ElementReference = er); builder.CloseElement(); } // Public Methods public void ForceValidate() { MyEditContext?.Validate(); StateHasChanged(); } public ValueTask<object> Focus() => BlazorStrapInterop.FocusElement(ElementReference); //Protected Methods protected void OnInput(string e) { RateLimitingExceptionForObject.Debounce(e, DebounceInterval, (CurrentValueAsString) => { InvokeAsync(() => OnChange(e)); }); } protected void OnChange(string e) { CurrentValueAsString = e; } private void OnRadioClick() { Value = (T)(object)(RadioValue); ValueChanged.InvokeAsync(Value); } protected void OnClick(MouseEventArgs e) { if (InputType == InputType.Radio) { OnRadioClick(); } else { if (typeof(T) != typeof(bool)) { if (CheckValue != null) { if (Value != null) { Value = default(T); ValueChanged.InvokeAsync(Value); } else { Value = CheckValue; ValueChanged.InvokeAsync(Value); } } } else { var tmp = (bool)(object)Value; Value = (T)(object)(!tmp); } ValueChanged.InvokeAsync(Value); } } protected string FormatValueAsString(T value) { return value switch { null => null, bool @bool => BindConverter.FormatValue(@bool.ToString().ToLowerInvariant(), CultureInfo.InvariantCulture), int @int => BindConverter.FormatValue(@int, CultureInfo.InvariantCulture), long @long => BindConverter.FormatValue(@long, CultureInfo.InvariantCulture), float @float => BindConverter.FormatValue(@float, CultureInfo.InvariantCulture), double @double => BindConverter.FormatValue(@double, CultureInfo.InvariantCulture), decimal @decimal => BindConverter.FormatValue(@decimal, CultureInfo.InvariantCulture), DateTime dateTimeValue => BindConverter.FormatValue(dateTimeValue, _dateFormat, CultureInfo.InvariantCulture), DateTimeOffset dateTimeOffsetValue => BindConverter.FormatValue(dateTimeOffsetValue, _dateFormat, CultureInfo.InvariantCulture), _ => value?.ToString() }; } protected bool TryParseValueFromString(string value, out T result, out string validationErrorMessage) { bool? boolToReturn; Type type = typeof(T); // Moved to static class in adherence to DRY boolToReturn = TryParseString<T>.ToValue(value, out result, out validationErrorMessage); if (typeof(T) == typeof(bool)) { if (InputType != InputType.Select) { result = (T)(object)false; validationErrorMessage = string.Format(CultureInfo.InvariantCulture, "The bool valued must be used with select, checkboxes, or radios."); boolToReturn = false; } } return boolToReturn != null ? boolToReturn.Value : throw new InvalidOperationException($"{GetType()} does not support the type '{typeof(T)}'."); } protected string CurrentValueAsString { get => FormatValueAsString(CurrentValue); set { _ = TryParseValueFromString(value, out T parsedValue, out var validationErrorMessage); CurrentValue = parsedValue; _ = ConversionError.InvokeAsync(validationErrorMessage); } } protected T CurrentValue { get => Value; set { var hasChanged = !EqualityComparer<T>.Default.Equals(value, Value); if (hasChanged) { Value = value; _ = ValueChanged.InvokeAsync(value); } } } // Private Methods private string GetClass() { return InputType switch { InputType.Checkbox => "form-check-input", InputType.Radio => "form-check-input", InputType.File => "form-control-file", InputType.Range => "form-control-range", _ => IsPlaintext ? "form-control-plaintext" : "form-control" }; } private int BuildCheckbox(RenderTreeBuilder builder, int index) { if (BSLabel != null) { if (CurrentValue == null) BSLabel.IsActive = false; else if (CurrentValue.GetType() == typeof(bool)) BSLabel.IsActive = (bool)(object)CurrentValue; else BSLabel.IsActive = true; } builder.AddAttribute(index++, "checked", BindConverter.FormatValue(CurrentValue)); builder.AddAttribute(index++, "onclick", EventCallback.Factory.Create(this, OnClick)); // Kept for rollback if needed remove after next release // if (InputType == InputType.Checkbox) //{ // if(typeof(T) == typeof(string)) // { // Value = ((string)(object)Value).ToLowerInvariant() != "false" ? (T)(object)"true" : (T)(object)"false"; // if (BSLabel != null) // { // if (Convert.ToBoolean(Value, CultureInfo.InvariantCulture)) // BSLabel.IsActive = true; // else // BSLabel.IsActive = false; // } // } // builder.AddAttribute(9, "checked", Convert.ToBoolean(Value, CultureInfo.InvariantCulture)); // builder.AddAttribute(10, "onclick", EventCallback.Factory.Create(this, OnClick)); return index; } private int BuildRadio(RenderTreeBuilder builder, int index) { if (RadioValue != null) { if (RadioValue.Equals(Value)) { if (BSLabel != null) BSLabel.IsActive = true; builder.AddAttribute(index++, "checked", true); builder.AddAttribute(index++, "onclick", EventCallback.Factory.Create(this, OnClick)); } else { if (BSLabel != null) BSLabel.IsActive = false; builder.AddAttribute(index++, "checked", false); builder.AddAttribute(index++, "onclick", EventCallback.Factory.Create(this, OnClick)); } } return index; } private int BuildValidation(RenderTreeBuilder builder, int index) { if (ValidateOnInput != true) { builder.AddAttribute(index++, "onchange", EventCallback.Factory.CreateBinder<string>(this, OnChange, CurrentValueAsString)); } else { builder.AddAttribute(index++, "oninput", EventCallback.Factory.CreateBinder<string>(this, OnInput, CurrentValueAsString)); } return index; } } }
38.338323
157
0.53729
[ "Unlicense" ]
MasterSkriptor/BlazorStrap
src/BlazorStrap/Components/Forms/BSBasicInput.cs
12,807
C#
/** * Copyright 2018 The Nakama Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Runtime.Serialization; namespace Nakama { /// <summary> /// An acknowledgement from the server when a chat message is delivered to a channel. /// </summary> public interface IChannelMessageAck { /// <summary> /// The server-assigned channel ID. /// </summary> string ChannelId { get; } /// <summary> /// A user-defined code for the chat message. /// </summary> int Code { get; } /// <summary> /// The UNIX time when the message was created. /// </summary> string CreateTime { get; } /// <summary> /// A unique ID for the chat message. /// </summary> string MessageId { get; } /// <summary> /// True if the chat message has been stored in history. /// </summary> bool Persistent { get; } /// <summary> /// The UNIX time when the message was updated. /// </summary> string UpdateTime { get; } /// <summary> /// The username of the sender of the message. /// </summary> string Username { get; } /// <summary> /// The name of the chat room, or an empty string if this message was not sent through a chat room. /// </summary> string RoomName { get; } /// <summary> /// The ID of the group, or an empty string if this message was not sent through a group channel. /// </summary> string GroupId { get; } /// <summary> /// The ID of the first DM user, or an empty string if this message was not sent through a DM chat. /// </summary> string UserIdOne { get; } /// <summary> /// The ID of the second DM user, or an empty string if this message was not sent through a DM chat. /// </summary> string UserIdTwo { get; } } /// <inheritdoc cref="IChannelMessageAck"/> internal class ChannelMessageAck : IChannelMessageAck { [DataMember(Name = "channel_id")] public string ChannelId { get; set; } [DataMember(Name = "code")] public int Code { get; set; } [DataMember(Name = "create_time")] public string CreateTime { get; set; } [DataMember(Name = "message_id")] public string MessageId { get; set; } [DataMember(Name = "persistent")] public bool Persistent { get; set; } [DataMember(Name = "update_time")] public string UpdateTime { get; set; } [DataMember(Name = "username")] public string Username { get; set; } [DataMember(Name="room_name")] public string RoomName { get; set; } [DataMember(Name="group_id")] public string GroupId { get; set; } [DataMember(Name="user_id_one")] public string UserIdOne { get; set; } [DataMember(Name="user_id_two")] public string UserIdTwo { get; set; } public override string ToString() { return $"ChannelMessageAck(ChannelId='{ChannelId}', Code={Code}, CreateTime={CreateTime}, MessageId='{MessageId}', Persistent={Persistent}, UpdateTime={UpdateTime}, Username='{Username}', RoomName='{RoomName}', GroupId='{GroupId}', UserIdOne='{UserIdOne}', UserIdTwo='{UserIdTwo}')"; } } }
34.508772
292
0.592527
[ "Apache-2.0" ]
gamelynx/nakama-dotnet
src/Nakama/IChannelMessageAck.cs
3,934
C#
/* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using ASC.Files.Core; using ASC.Files.Core.Security; using System; using System.Collections.Generic; using System.Linq; namespace ASC.Files.Thirdparty.ProviderDao { internal class ProviderSecurityDao : ProviderDaoBase, ISecurityDao { public void Dispose() { } public void SetShare(FileShareRecord r) { using (var securityDao = TryGetSecurityDao()) { securityDao.SetShare(r); } } public IEnumerable<FileShareRecord> GetShares(IEnumerable<FileEntry> entries) { var result = new List<FileShareRecord>(); if (entries == null || !entries.Any()) return result; var defaultSelectorEntries = entries.Where(x => x != null && Default.IsMatch(x.ID)).ToArray(); var otherSelectorEntries = entries.Where(x => x != null && !Default.IsMatch(x.ID)).ToArray(); if (defaultSelectorEntries.Any()) { using (var securityDao = TryGetSecurityDao()) { if (securityDao != null) { var shares = securityDao.GetShares(defaultSelectorEntries); if (shares != null) result.AddRange(shares); } } } if (!otherSelectorEntries.Any()) return result; var files = otherSelectorEntries.Where(x => x.FileEntryType == FileEntryType.File).ToArray(); var folders = otherSelectorEntries.Where(x => x.FileEntryType == FileEntryType.Folder).ToList(); if (files.Any()) { var folderIds = files.Select(x => ((File) x).FolderID).Distinct(); foreach (var folderId in folderIds) { GetFoldersForShare(folderId, folders); } using (var securityDao = TryGetSecurityDao()) { if (securityDao != null) { var pureShareRecords = securityDao.GetPureShareRecords(files); if (pureShareRecords != null) { foreach (var pureShareRecord in pureShareRecords) { if (pureShareRecord == null) continue; pureShareRecord.Level = -1; result.Add(pureShareRecord); } } } } } result.AddRange(GetShareForFolders(folders)); return result; } public IEnumerable<FileShareRecord> GetShares(FileEntry entry) { var result = new List<FileShareRecord>(); if (entry == null) return result; if (Default.IsMatch(entry.ID)) { using (var securityDao = TryGetSecurityDao()) { if (securityDao != null) { var shares = securityDao.GetShares(entry); if (shares != null) result.AddRange(shares); } } return result; } var file = entry as File; var folders = new List<FileEntry>(); var entryFolder = entry as Folder; if (entryFolder != null) { folders.Add(entryFolder); } if (file != null) { GetFoldersForShare(file.FolderID, folders); using (var securityDao = TryGetSecurityDao()) { if (securityDao != null) { var pureShareRecords = securityDao.GetPureShareRecords(entry); if (pureShareRecords != null) { foreach (var pureShareRecord in pureShareRecords) { if (pureShareRecord == null) continue; pureShareRecord.Level = -1; result.Add(pureShareRecord); } } } } } result.AddRange(GetShareForFolders(folders)); return result; } private void GetFoldersForShare(object folderId, ICollection<FileEntry> folders) { var selector = GetSelector(folderId); var folderDao = selector.GetFolderDao(folderId); if (folderDao == null) return; var folder = folderDao.GetFolder(selector.ConvertId(folderId)); if (folder != null) folders.Add(folder); } private List<FileShareRecord> GetShareForFolders(IReadOnlyCollection<FileEntry> folders) { if (!folders.Any()) return new List<FileShareRecord>(); var result = new List<FileShareRecord>(); foreach (var folder in folders) { var selector = GetSelector(folder.ID); var folderDao = selector.GetFolderDao(folder.ID); if (folderDao == null) continue; var parentFolders = folderDao.GetParentFolders(selector.ConvertId(folder.ID)); if (parentFolders == null || !parentFolders.Any()) continue; parentFolders.Reverse(); var pureShareRecords = GetPureShareRecords(parentFolders.Cast<FileEntry>().ToArray()); if (pureShareRecords == null) continue; foreach (var pureShareRecord in pureShareRecords) { if (pureShareRecord == null) continue; pureShareRecord.Level = parentFolders.IndexOf(new Folder { ID = pureShareRecord.EntryId }); pureShareRecord.EntryId = folder.ID; result.Add(pureShareRecord); } } return result; } public void RemoveSubject(Guid subject) { using (var securityDao = TryGetSecurityDao()) { securityDao.RemoveSubject(subject); } } public IEnumerable<FileShareRecord> GetShares(IEnumerable<Guid> subjects) { using (var securityDao = TryGetSecurityDao()) { return securityDao.GetShares(subjects); } } public IEnumerable<FileShareRecord> GetPureShareRecords(IEnumerable<FileEntry> entries) { using (var securityDao = TryGetSecurityDao()) { return securityDao.GetPureShareRecords(entries); } } public IEnumerable<FileShareRecord> GetPureShareRecords(FileEntry entry) { using (var securityDao = TryGetSecurityDao()) { return securityDao.GetPureShareRecords(entry); } } public void DeleteShareRecords(IEnumerable<FileShareRecord> records) { using (var securityDao = TryGetSecurityDao()) { securityDao.DeleteShareRecords(records); } } public bool IsShared(object entryId, FileEntryType type) { using (var securityDao = TryGetSecurityDao()) { return securityDao.IsShared(entryId, type); } } } }
33.806584
111
0.515642
[ "Apache-2.0" ]
Ektai-Solution-Pty-Ltd/CommunityServer
module/ASC.Files.Thirdparty/ProviderDao/ProviderSecutiryDao.cs
8,215
C#
namespace SkorubaIdentityServer4Admin.STS.Identity.Configuration { public class AdvancedConfiguration { public string IssuerUri { get; set; } } }
10.9375
65
0.68
[ "MIT" ]
861191244/IdentityServer4.Admin
templates/template-publish/content/src/SkorubaIdentityServer4Admin.STS.Identity/Configuration/AdvancedConfiguration.cs
177
C#
using UnityEngine; using System.Collections; using UnityEngine.EventSystems; #if MOBILE_INPUT using UnityStandardAssets.CrossPlatformInput; #endif using System.Reflection; namespace Invector { public class vInput : MonoBehaviour { public delegate void OnChangeInputType(InputDevice type); public event OnChangeInputType onChangeInputType; private static vInput _instance; public static vInput instance { get { if (_instance == null) { _instance = GameObject.FindObjectOfType<vInput>(); if (_instance == null) { new GameObject("vInputType", typeof(vInput)); return vInput.instance; } } return _instance; } } public vHUDController hud; void Start() { if (hud == null) hud = vHUDController.instance; } private InputDevice _inputType = InputDevice.MouseKeyboard; [HideInInspector] public InputDevice inputDevice { get { return _inputType; } set { _inputType = value; OnChangeInput(); } } /// <summary> /// GAMEPAD VIBRATION - call this method to use vibration on the gamepad /// </summary> /// <param name="vibTime">duration of the vibration</param> /// <returns></returns> public void GamepadVibration(float vibTime) { if (inputDevice == InputDevice.Joystick) { StartCoroutine(GamepadVibrationRotine(vibTime)); } } private IEnumerator GamepadVibrationRotine(float vibTime) { if (inputDevice == InputDevice.Joystick) { #if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN XInputDotNetPure.GamePad.SetVibration(0, 1, 1); yield return new WaitForSeconds(vibTime); XInputDotNetPure.GamePad.SetVibration(0, 0, 0); #else yield return new WaitForSeconds(0f); #endif } } void OnGUI() { switch (inputDevice) { case InputDevice.MouseKeyboard: if (isJoystickInput()) { inputDevice = InputDevice.Joystick; if (hud != null) { hud.controllerInput = true; hud.FadeText("Control scheme changed to Controller", 2f, 0.5f); } } else if (isMobileInput()) { inputDevice = InputDevice.Mobile; if (hud != null) { hud.controllerInput = true; hud.FadeText("Control scheme changed to Mobile", 2f, 0.5f); } } break; case InputDevice.Joystick: if (isMouseKeyboard()) { inputDevice = InputDevice.MouseKeyboard; if (hud != null) { hud.controllerInput = false; hud.FadeText("Control scheme changed to Keyboard/Mouse", 2f, 0.5f); } } else if (isMobileInput()) { inputDevice = InputDevice.Mobile; if (hud != null) { hud.controllerInput = true; hud.FadeText("Control scheme changed to Mobile", 2f, 0.5f); } } break; case InputDevice.Mobile: if (isMouseKeyboard()) { inputDevice = InputDevice.MouseKeyboard; if (hud != null) { hud.controllerInput = false; hud.FadeText("Control scheme changed to Keyboard/Mouse", 2f, 0.5f); } } else if (isJoystickInput()) { inputDevice = InputDevice.Joystick; if (hud != null) { hud.controllerInput = true; hud.FadeText("Control scheme changed to Controller", 2f, 0.5f); } } break; } } private bool isMobileInput() { #if UNITY_EDITOR && UNITY_MOBILE if (EventSystem.current.IsPointerOverGameObject() && Input.GetMouseButtonDown(0)) { return true; } #elif MOBILE_INPUT if (EventSystem.current.IsPointerOverGameObject() || (Input.touches.Length > 0)) return true; #endif return false; } private bool isMouseKeyboard() { #if MOBILE_INPUT return false; #else // mouse & keyboard buttons if (Event.current.isKey || Event.current.isMouse) return true; // mouse movement if (Input.GetAxis("Mouse X") != 0.0f || Input.GetAxis("Mouse Y") != 0.0f) return true; return false; #endif } private bool isJoystickInput() { // joystick buttons if (Input.GetKey(KeyCode.Joystick1Button0) || Input.GetKey(KeyCode.Joystick1Button1) || Input.GetKey(KeyCode.Joystick1Button2) || Input.GetKey(KeyCode.Joystick1Button3) || Input.GetKey(KeyCode.Joystick1Button4) || Input.GetKey(KeyCode.Joystick1Button5) || Input.GetKey(KeyCode.Joystick1Button6) || Input.GetKey(KeyCode.Joystick1Button7) || Input.GetKey(KeyCode.Joystick1Button8) || Input.GetKey(KeyCode.Joystick1Button9) || Input.GetKey(KeyCode.Joystick1Button10) || Input.GetKey(KeyCode.Joystick1Button11) || Input.GetKey(KeyCode.Joystick1Button12) || Input.GetKey(KeyCode.Joystick1Button13) || Input.GetKey(KeyCode.Joystick1Button14) || Input.GetKey(KeyCode.Joystick1Button15) || Input.GetKey(KeyCode.Joystick1Button16) || Input.GetKey(KeyCode.Joystick1Button17) || Input.GetKey(KeyCode.Joystick1Button18) || Input.GetKey(KeyCode.Joystick1Button19)) { return true; } // joystick axis if (Input.GetAxis("LeftAnalogHorizontal") != 0.0f || Input.GetAxis("LeftAnalogVertical") != 0.0f || Input.GetAxis("RightAnalogHorizontal") != 0.0f || Input.GetAxis("RightAnalogVertical") != 0.0f || Input.GetAxis("LT") != 0.0f || Input.GetAxis("RT") != 0.0f || Input.GetAxis("D-Pad Horizontal") != 0.0f || Input.GetAxis("D-Pad Vertical") != 0.0f) { return true; } return false; } void OnChangeInput() { if (onChangeInputType != null) { onChangeInputType(inputDevice); } } } /// <summary> /// INPUT TYPE - check in real time if you are using a joystick, mobile or mouse/keyboard /// </summary> [HideInInspector] public enum InputDevice { MouseKeyboard, Joystick, Mobile }; [System.Serializable] public class GenericInput { protected InputDevice inputDevice { get { return vInput.instance.inputDevice; } } public bool useInput = true; [SerializeField] private bool isAxisInUse; [SerializeField] private string keyboard; [SerializeField] private bool keyboardAxis; [SerializeField] private string joystick; [SerializeField] private bool joystickAxis; [SerializeField] private string mobile; [SerializeField] private bool mobileAxis; [SerializeField] private bool joystickAxisInvert; [SerializeField] private bool keyboardAxisInvert; [SerializeField] private bool mobileAxisInvert; private float buttomTimer; private bool inButtomTimer; private float multTapTimer; private int multTapCounter; public bool isAxis { get { bool value = false; switch(inputDevice) { case InputDevice.Joystick: value = joystickAxis; break; case InputDevice.MouseKeyboard: value = keyboardAxis; break; case InputDevice.Mobile: value = mobileAxis; break; } return value; } } public bool isAxisInvert { get { bool value = false; switch (inputDevice) { case InputDevice.Joystick: value = joystickAxisInvert; break; case InputDevice.MouseKeyboard: value = keyboardAxisInvert; break; case InputDevice.Mobile: value = mobileAxisInvert; break; } return value; } } /// <summary> /// Initialise a new GenericInput /// </summary> /// <param name="keyboard"></param> /// <param name="joystick"></param> /// <param name="mobile"></param> public GenericInput(string keyboard, string joystick, string mobile) { this.keyboard = keyboard; this.joystick = joystick; this.mobile = mobile; } /// <summary> /// Initialise a new GenericInput /// </summary> /// <param name="keyboard"></param> /// <param name="joystick"></param> /// <param name="mobile"></param> public GenericInput(string keyboard, bool keyboardAxis, string joystick, bool joystickAxis, string mobile, bool mobileAxis) { this.keyboard = keyboard; this.keyboardAxis = keyboardAxis; this.joystick = joystick; this.joystickAxis = joystickAxis; this.mobile = mobile; this.mobileAxis = mobileAxis; } /// <summary> /// Initialise a new GenericInput /// </summary> /// <param name="keyboard"></param> /// <param name="joystick"></param> /// <param name="mobile"></param> public GenericInput(string keyboard, bool keyboardAxis,bool keyboardInvert, string joystick, bool joystickAxis,bool joystickInvert, string mobile, bool mobileAxis,bool mobileInvert) { this.keyboard = keyboard; this.keyboardAxis = keyboardAxis; this.keyboardAxisInvert = keyboardInvert; this.joystick = joystick; this.joystickAxis = joystickAxis; this.joystickAxisInvert = joystickInvert; this.mobile = mobile; this.mobileAxis = mobileAxis; this.mobileAxisInvert = mobileInvert; } /// <summary> /// Button Name /// </summary> public string buttonName { get { if (vInput.instance != null) { if (vInput.instance.inputDevice == InputDevice.MouseKeyboard) return keyboard.ToString(); else if (vInput.instance.inputDevice == InputDevice.Joystick) return joystick; else return mobile; } return string.Empty; } } /// <summary> /// Check if button is a Key /// </summary> public bool isKey { get { if (vInput.instance != null) { if (System.Enum.IsDefined(typeof(KeyCode), buttonName)) return true; } return false; } } /// <summary> /// Get <see cref="KeyCode"/> value /// </summary> public KeyCode key { get { return (KeyCode)System.Enum.Parse(typeof(KeyCode), buttonName); } } /// <summary> /// Get Button /// </summary> /// <returns></returns> public bool GetButton() { if (string.IsNullOrEmpty(buttonName) || !IsButtonAvailable(this.buttonName)) return false; if (isAxis) return GetAxisButton(); // mobile if (inputDevice == InputDevice.Mobile) { #if MOBILE_INPUT if (CrossPlatformInputManager.GetButton(this.buttonName)) #endif return true; } // keyboard/mouse else if (inputDevice == InputDevice.MouseKeyboard) { if (isKey) { if (Input.GetKey(key)) return true; } else { if (Input.GetButton(this.buttonName)) return true; } } // joystick else if (inputDevice == InputDevice.Joystick) { if (Input.GetButton(this.buttonName)) return true; } return false; } /// <summary> /// Get ButtonDown /// </summary> /// <returns></returns> public bool GetButtonDown() { if (string.IsNullOrEmpty(buttonName) || !IsButtonAvailable(this.buttonName)) return false; if (isAxis) return GetAxisButtonDown(); // mobile if (inputDevice == InputDevice.Mobile) { #if MOBILE_INPUT if (CrossPlatformInputManager.GetButtonDown(this.buttonName)) #endif return true; } // keyboard/mouse else if (inputDevice == InputDevice.MouseKeyboard) { if (isKey) { if (Input.GetKeyDown(key)) return true; } else { if (Input.GetButtonDown(this.buttonName)) return true; } } // joystick else if (inputDevice == InputDevice.Joystick) { if (Input.GetButtonDown(this.buttonName)) return true; } return false; } /// <summary> /// Get Button Up /// </summary> /// <returns></returns> public bool GetButtonUp() { if (string.IsNullOrEmpty(buttonName) || !IsButtonAvailable(this.buttonName)) return false; if (isAxis) return GetAxisButtonUp(); // mobile if (inputDevice == InputDevice.Mobile) { #if MOBILE_INPUT if (CrossPlatformInputManager.GetButtonUp(this.buttonName)) #endif return true; } // keyboard/mouse else if (inputDevice == InputDevice.MouseKeyboard) { if (isKey) { if (Input.GetKeyUp(key)) return true; } else { if (Input.GetButtonUp(this.buttonName)) return true; } } // joystick else if (inputDevice == InputDevice.Joystick) { if (Input.GetButtonUp(this.buttonName)) return true; } return false; } /// <summary> /// Get Axis /// </summary> /// <returns></returns> public float GetAxis() { if (string.IsNullOrEmpty(buttonName) || !IsButtonAvailable(this.buttonName) || isKey) return 0; // mobile if (inputDevice == InputDevice.Mobile) { #if MOBILE_INPUT return CrossPlatformInputManager.GetAxis(this.buttonName); #endif } // keyboard/mouse else if (inputDevice == InputDevice.MouseKeyboard) { return Input.GetAxis(this.buttonName); } // joystick else if (inputDevice == InputDevice.Joystick) { return Input.GetAxis(this.buttonName); } return 0; } /// <summary> /// Get Axis Raw /// </summary> /// <returns></returns> public float GetAxisRaw() { if (string.IsNullOrEmpty(buttonName) || !IsButtonAvailable(this.buttonName) || isKey) return 0; // mobile if (inputDevice == InputDevice.Mobile) { #if MOBILE_INPUT return CrossPlatformInputManager.GetAxisRaw(this.buttonName); #endif } // keyboard/mouse else if (inputDevice == InputDevice.MouseKeyboard) { return Input.GetAxisRaw(this.buttonName); } // joystick else if (inputDevice == InputDevice.Joystick) { return Input.GetAxisRaw(this.buttonName); } return 0; } /// <summary> /// Get Double Button Down Check if button is pressed Within the defined time /// </summary> /// <param name="inputTime"></param> /// <returns></returns> public bool GetDoubleButtonDown(float inputTime = 1) { if (string.IsNullOrEmpty(buttonName) || !IsButtonAvailable(this.buttonName)) return false; if (multTapCounter == 0 && GetButtonDown()) { multTapTimer = Time.time; multTapCounter = 1; return false; } if (multTapCounter == 1 && GetButtonDown()) { var time = multTapTimer + inputTime; var valid = (Time.time < time); multTapTimer = 0; multTapCounter = 0; return valid; } return false; } /// <summary> /// Get Buttom Timer Check if button is pressed for defined time /// </summary> /// <param name="inputTime"> time to check button press</param> /// <returns></returns> public bool GetButtonTimer(float inputTime = 2) { if (string.IsNullOrEmpty(buttonName) || !IsButtonAvailable(this.buttonName)) return false; if (GetButtonDown() && !inButtomTimer) { buttomTimer = Time.time; inButtomTimer = true; } if (inButtomTimer) { var time = buttomTimer + inputTime; var valid = (time - Time.time <= 0); if (GetButtonUp()) { inButtomTimer = false; return valid; } if (valid) { inButtomTimer = false; } return valid; } return false; } /// <summary> /// Get Axis like a button /// </summary> /// <param name="value">Value to check need to be diferent 0</param> /// <returns></returns> public bool GetAxisButton(float value = 0.5f) { if (string.IsNullOrEmpty(buttonName) || !IsButtonAvailable(this.buttonName)) return false; if (isAxisInvert) value *= -1f; if (value > 0) { return GetAxisRaw() >= value; } else if (value < 0) { return GetAxisRaw() <= value; } return false; } /// <summary> /// Get Axis like a buttonDown /// </summary> /// <param name="value">Value to check need to be diferent 0</param> /// <returns></returns> public bool GetAxisButtonDown(float value = 0.5f) { if (string.IsNullOrEmpty(buttonName) || !IsButtonAvailable(this.buttonName)) return false; if (isAxisInvert) value *= -1f; if (value > 0) { if (!isAxisInUse && GetAxisRaw() >= value) { isAxisInUse = true; return true; } else if (isAxisInUse && GetAxisRaw() == 0) { isAxisInUse = false; } } else if (value < 0) { if (!isAxisInUse && GetAxisRaw() <= value) { isAxisInUse = true; return true; } else if (isAxisInUse && GetAxisRaw() == 0) { isAxisInUse = false; } } return false; } /// <summary> /// Get Axis like a buttonUp /// Check if Axis is zero after press /// <returns></returns> public bool GetAxisButtonUp() { if (string.IsNullOrEmpty(buttonName) || !IsButtonAvailable(this.buttonName)) return false; if (isAxisInUse && GetAxisRaw() == 0) { isAxisInUse = false; return true; } else if (!isAxisInUse && GetAxisRaw() != 0) { isAxisInUse = true; } return false; } bool IsButtonAvailable(string btnName) { if (!useInput) return false; try { if (isKey) return true; Input.GetButton(buttonName); return true; } catch (System.Exception exc) { Debug.LogWarning(" Failure to try access button :" + buttonName + "\n" + exc.Message); return false; } } } }
33.172789
190
0.441842
[ "MIT" ]
FR98/ProyectoJuegosUVG
Assets/Invector-3rdPersonController/Basic Locomotion/Scripts/CharacterController/vInput.cs
24,384
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.RecoveryServices.Backup { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ProtectedItemOperationResultsOperations operations. /// </summary> internal partial class ProtectedItemOperationResultsOperations : IServiceOperations<RecoveryServicesBackupClient>, IProtectedItemOperationResultsOperations { /// <summary> /// Initializes a new instance of the ProtectedItemOperationResultsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ProtectedItemOperationResultsOperations(RecoveryServicesBackupClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the RecoveryServicesBackupClient /// </summary> public RecoveryServicesBackupClient Client { get; private set; } /// <summary> /// Fetches the result of any operation on the backup item. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='fabricName'> /// Fabric name associated with the backup item. /// </param> /// <param name='containerName'> /// Container name associated with the backup item. /// </param> /// <param name='protectedItemName'> /// Backup item name whose details are to be fetched. /// </param> /// <param name='operationId'> /// OperationID which represents the operation whose result needs to be /// fetched. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ProtectedItemResource>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, string operationId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (vaultName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fabricName"); } if (containerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "containerName"); } if (protectedItemName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "protectedItemName"); } if (operationId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "operationId"); } string apiVersion = "2021-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("containerName", containerName); tracingParameters.Add("protectedItemName", protectedItemName); tracingParameters.Add("operationId", operationId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/operationResults/{operationId}").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{containerName}", System.Uri.EscapeDataString(containerName)); _url = _url.Replace("{protectedItemName}", System.Uri.EscapeDataString(protectedItemName)); _url = _url.Replace("{operationId}", System.Uri.EscapeDataString(operationId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ProtectedItemResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ProtectedItemResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
45.630662
368
0.583766
[ "MIT" ]
mcgallan/azure-sdk-for-net
sdk/recoveryservices-backup/Microsoft.Azure.Management.RecoveryServices.Backup/src/Generated/ProtectedItemOperationResultsOperations.cs
13,096
C#
using Godot; using System; [Tool] public class Label3DScene : Spatial { [Export] public NodePath viewpath; private Viewport viewport = null; [Export] public NodePath labelpath; private Label2D label2D = null; [Export] public NodePath meshpath; private MeshInstance mesh = null; private SpatialMaterial mat = null; // Called when the node enters the scene tree for the first time. public override void _EnterTree() { GD.Print("Label3D EnterTree"); GD.Print("Label3D EnterTree Complete"); } public override void _Ready() { GD.Print("Label3D Get Ready"); Initialization(); GD.Print("Label3D Get Ready Complete"); } public override void _Process(float delta) { } private void Initialization() { viewport = GetNode<Viewport>(viewpath); label2D = (Label2D)GetNode<Label2D>(labelpath); mesh = GetNode<MeshInstance>(meshpath); SetLabelSize(new Vector2(140, 32)); mat = (SpatialMaterial)mesh.GetActiveMaterial(0); } public Label2D GetLabel() { if (label2D == null) { Initialization(); } return label2D; } public Viewport GetViewPort() { if (viewport == null) { Initialization(); } return viewport; } public void SetMatColor(Color color) { mat.AlbedoColor = color; } public void SetLabelSize(Vector2 size) { label2D.SetRectSize(size); viewport.Size = size; mesh.Scale = new Vector3(size.x / 100, size.y / 100, 1); mesh.Translation = new Vector3(size.x / 200, size.y / 200, 0); } }
18.833333
66
0.697073
[ "MIT" ]
JoluMorsanDev/The-4-hidden-souls
addons/Label3D/3d/Label3DScene.cs
1,469
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace HangfireHealth.Website { public class Job { private static Random _random = new Random(); public void LongRunning() { var now = DateTime.Now; // I think the default timeout is 5 minutes, so go a bit beyond that. var sixMinutes = now.AddMinutes(6); // Spin. while (now < sixMinutes) { now = DateTime.Now; } } public void ShortRunning() { Thread.Sleep(_random.Next(1, 4) * 1000); } } }
18.625
73
0.639262
[ "MIT" ]
stajs/HangfireHealth
src/HangfireHealth.Website/Job.cs
598
C#
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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. // Generated code. DO NOT EDIT! namespace Google.Cloud.Compute.V1.Snippets { // [START compute_v1_generated_ResourcePolicies_Get_async] using Google.Cloud.Compute.V1; using System.Threading.Tasks; public sealed partial class GeneratedResourcePoliciesClientSnippets { /// <summary>Snippet for GetAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task GetRequestObjectAsync() { // Create client ResourcePoliciesClient resourcePoliciesClient = await ResourcePoliciesClient.CreateAsync(); // Initialize request argument(s) GetResourcePolicyRequest request = new GetResourcePolicyRequest { Region = "", ResourcePolicy = "", Project = "", }; // Make the request ResourcePolicy response = await resourcePoliciesClient.GetAsync(request); } } // [END compute_v1_generated_ResourcePolicies_Get_async] }
37.702128
103
0.673251
[ "Apache-2.0" ]
AlexandrTrf/google-cloud-dotnet
apis/Google.Cloud.Compute.V1/Google.Cloud.Compute.V1.GeneratedSnippets/ResourcePoliciesClient.GetRequestObjectAsyncSnippet.g.cs
1,772
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Shared.Core.Dtos { public interface IDto { Guid Id { get; set; } } }
15.5
33
0.686636
[ "Apache-2.0" ]
MurielSoftware/MyArt
Shared.Core/Dtos/IDto.cs
219
C#
//------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace Timetable_Manager.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.0.1.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
41.037037
151
0.597473
[ "MIT" ]
erichstuder/Shuttle
Timetable_Manager/Properties/Settings.Designer.cs
1,112
C#
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* MappedAccess64.cs -- * Ars Magna project, http://arsmagna.ru * ------------------------------------------------------- * Status: poor */ #if !FW35 && !UAP && !WINMOBILE && !PocketPC #region Using directives using System; using System.Collections.Generic; using System.IO; using System.IO.MemoryMappedFiles; using AM.Logging; using CodeJam; using JetBrains.Annotations; using ManagedIrbis.Search; using MoonSharp.Interpreter; #endregion namespace ManagedIrbis.Direct { /// <summary> /// Direct database access with <see cref="MemoryMappedFile"/> /// Прямой доступ к БД с помощью MemoryMappedFile. /// </summary> [PublicAPI] [MoonSharpUserData] public sealed class MappedAccess64 : IDisposable { #region Properties /// <summary> /// Master file. /// </summary> [NotNull] public MappedMstFile64 Mst { get; private set; } /// <summary> /// Cross-reference file. /// </summary> [NotNull] public MappedXrfFile64 Xrf { get; private set; } /// <summary> /// Inverted (index) file. /// </summary> [NotNull] public MappedInvertedFile64 InvertedFile { get; private set; } /// <summary> /// Database path. /// </summary> [NotNull] public string Database { get; private set; } #endregion #region Construction /// <summary> /// Constructor. /// </summary> public MappedAccess64 ( [NotNull] string masterFile ) { Code.NotNullNorEmpty(masterFile, "masterFile"); Database = Path.GetFileNameWithoutExtension(masterFile); Mst = new MappedMstFile64(Path.ChangeExtension(masterFile, ".mst")); Xrf = new MappedXrfFile64(Path.ChangeExtension(masterFile, ".xrf")); InvertedFile = new MappedInvertedFile64(Path.ChangeExtension(masterFile, ".ifp")); } #endregion #region Private members #endregion #region Public methods /// <summary> /// Get max MFN for database. Not next MFN! /// </summary> public int GetMaxMfn() { return Mst.ControlRecord.NextMfn - 1; } /// <summary> /// Read raw record. /// </summary> [CanBeNull] public MstRecord64 ReadRawRecord ( int mfn ) { Code.Positive(mfn, "mfn"); XrfRecord64 xrfRecord = Xrf.ReadRecord(mfn); if (xrfRecord.Offset == 0) { return null; } MstRecord64 result = Mst.ReadRecord(xrfRecord.Offset); return result; } /// <summary> /// Read record with given MFN. /// </summary> [CanBeNull] public MarcRecord ReadRecord ( int mfn ) { Code.Positive(mfn, "mfn"); XrfRecord64 xrfRecord = Xrf.ReadRecord(mfn); if (xrfRecord.Offset == 0 || (xrfRecord.Status & RecordStatus.PhysicallyDeleted) != 0) { return null; } MstRecord64 mstRecord = Mst.ReadRecord(xrfRecord.Offset); MarcRecord result = mstRecord.DecodeRecord(); result.Database = Database; return result; } /// <summary> /// Read all versions of the record. /// </summary> [NotNull] public MarcRecord[] ReadAllRecordVersions ( int mfn ) { Code.Positive(mfn, "mfn"); List<MarcRecord> result = new List<MarcRecord>(); MarcRecord lastVersion = ReadRecord(mfn); if (lastVersion != null) { result.Add(lastVersion); while (true) { long offset = lastVersion.PreviousOffset; if (offset == 0) { break; } MstRecord64 mstRecord = Mst.ReadRecord(offset); MarcRecord previousVersion = mstRecord.DecodeRecord(); previousVersion.Database = lastVersion.Database; previousVersion.Mfn = lastVersion.Mfn; result.Add(previousVersion); lastVersion = previousVersion; } } return result.ToArray(); } /// <summary> /// Read links for the term. /// </summary> [NotNull] [ItemNotNull] public TermLink[] ReadLinks ( [NotNull] string key ) { Code.NotNull(key, "key"); return InvertedFile.SearchExact(key); } /// <summary> /// Read terms. /// </summary> [NotNull] [ItemNotNull] public TermInfo[] ReadTerms ( [NotNull] TermParameters parameters ) { Code.NotNull(parameters, "parameters"); TermInfo[] result = InvertedFile.ReadTerms(parameters); return result; } /// <summary> /// Simple search. /// </summary> [NotNull] public int[] SearchSimple ( [NotNull] string key ) { Code.NotNullNorEmpty(key, "key"); int[] found = InvertedFile.SearchSimple(key); List<int> result = new List<int>(); foreach (int mfn in found) { if (!Xrf.ReadRecord(mfn).Deleted) { result.Add(mfn); } } return result.ToArray(); } /// <summary> /// Simple search and read records. /// </summary> [NotNull] public MarcRecord[] SearchReadSimple ( [NotNull] string key ) { Code.NotNullNorEmpty(key, "key"); int[] mfns = InvertedFile.SearchSimple(key); List<MarcRecord> result = new List<MarcRecord>(mfns.Length); foreach (int mfn in mfns) { try { XrfRecord64 xrfRecord = Xrf.ReadRecord(mfn); if (!xrfRecord.Deleted) { MstRecord64 mstRecord = Mst.ReadRecord(xrfRecord.Offset); if (!mstRecord.Deleted) { MarcRecord irbisRecord = mstRecord.DecodeRecord(); irbisRecord.Database = Database; result.Add(irbisRecord); } } } catch (Exception exception) { Log.TraceException ( "MappedAccess64::SearchReadSimple", exception ); } } return result.ToArray(); } #endregion #region IDisposable members /// <inheritdoc cref="IDisposable.Dispose" /> public void Dispose() { InvertedFile.Dispose(); Xrf.Dispose(); Mst.Dispose(); } #endregion #region Object members #endregion } } #endif
25.884488
94
0.472268
[ "MIT" ]
amironov73/ManagedClient.45
Source/Classic/Libs/ManagedIrbis/Source/Direct/MappedAccess64.cs
7,868
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using ConvertApiDotNet.Constants; using ConvertApiDotNet.Model; namespace ConvertApiDotNet { public static class ConvertApiExtension { #region Convert method extensions /// <summary> /// Waits for the task to complete, unwrapping any exceptions. /// </summary> /// <param name="task">The task. May not be <c>null</c>.</param> private static void WaitAndUnwrapException(this Task task) { task.GetAwaiter().GetResult(); } /// <summary> /// Waits for the task to complete, unwrapping any exceptions. /// </summary> /// <param name="task">The task. May not be <c>null</c>.</param> private static T WaitAndUnwrapException<T>(this Task<T> task) { return task.GetAwaiter().GetResult(); } private static IEnumerable<ConvertApiBaseParam> JoinParameters(ConvertApiBaseParam convertApiFileParam, IEnumerable<ConvertApiBaseParam> parameters) { var paramsList = new List<ConvertApiBaseParam> { convertApiFileParam }; paramsList.AddRange(parameters); return paramsList; } private static string GetPlainExtension(string fromFile) { return Path.GetExtension(fromFile).Replace(".", ""); } private static Task<ConvertApiResponse> BindFile(ConvertApi convertApi, string fromFile, string outputExtension, IEnumerable<ConvertApiBaseParam> parameters) { return convertApi.ConvertAsync(GetPlainExtension(fromFile), outputExtension, JoinParameters(new ConvertApiFileParam(fromFile), parameters)); } private static Task<ConvertApiResponse> BindFile(ConvertApi convertApi, Uri fileUrl, string outputExtension, IEnumerable<ConvertApiBaseParam> parameters) { return convertApi.ConvertAsync("*", outputExtension, JoinParameters(new ConvertApiFileParam(fileUrl), parameters)); } public static FileInfo ConvertFile(this ConvertApi convertApi, string fromFile, string toFile, params ConvertApiBaseParam[] parameters) { var task = BindFile(convertApi, fromFile, GetPlainExtension(toFile), parameters); return task.WaitAndUnwrapException().Files[0].SaveFileAsync(toFile).WaitAndUnwrapException(); } public static IEnumerable<FileInfo> ConvertFile(this ConvertApi convertApi, string fromFile, string outputExtension, string outputDirectory, params ConvertApiBaseParam[] parameters) { var task = BindFile(convertApi, fromFile, outputExtension, parameters); var parallelQuery = task.WaitAndUnwrapException().Files.AsParallel().WithDegreeOfParallelism(6) .Select(s => s.SaveFileAsync(Path.Combine(outputDirectory, s.FileName)).WaitAndUnwrapException()); var l = new List<FileInfo>(); l.AddRange(parallelQuery); return l; } public static FileInfo ConvertRemoteFile(this ConvertApi convertApi, string fileUrl, string toFile, params ConvertApiBaseParam[] parameters) { var task = BindFile(convertApi, new Uri(fileUrl), GetPlainExtension(toFile), parameters); return task.WaitAndUnwrapException().Files[0].SaveFileAsync(toFile).WaitAndUnwrapException(); } public static FileInfo ConvertUrl(this ConvertApi convertApi, string url, string toFile, params ConvertApiBaseParam[] parameters) { var outputExtension = GetPlainExtension(toFile); var task = convertApi.ConvertAsync("web", outputExtension, JoinParameters(new ConvertApiParam("url", url), parameters)); return task.WaitAndUnwrapException().Files[0].SaveFileAsync(toFile).WaitAndUnwrapException(); } #endregion /// <summary> /// Return the count of converted files /// </summary> /// <returns>Files converted</returns> public static int FileCount(this ConvertApiResponse response) { return response.Files.Length; } private static async Task<Stream> AsStreamAsync(Uri url) { var httpResponseMessage = await ConvertApi.GetClient().GetAsync(url, ConvertApiConstants.DownloadTimeoutInSeconds); return await httpResponseMessage.Content.ReadAsStreamAsync(); } private static async Task<FileInfo> SaveFileAsync(Uri url, string fileName) { var fileInfo = new FileInfo(fileName); using (var readFile = await AsStreamAsync(url)) { using (var fileStream = fileInfo.OpenWrite()) readFile.CopyTo(fileStream); } return fileInfo; } #region File Task Methods public static async Task<FileInfo> SaveFileAsync(this ConvertApiResponse response, string fileName) { return await response.Files[0].SaveFileAsync(fileName); } public static async Task<List<FileInfo>> SaveFilesAsync(this ConvertApiResponse response, string outputDirectory) { return await response.Files.SaveFilesAsync(outputDirectory); } public static async Task<Stream> FileStreamAsync(this ProcessedFile processedFile) { return await AsStreamAsync(processedFile.Url); } public static async Task<FileInfo> SaveFileAsync(this ProcessedFile processedFile, string fileName) { return await SaveFileAsync(processedFile.Url, fileName); } public static async Task<List<FileInfo>> SaveFilesAsync(this ProcessedFile[] processedFile, string outputDirectory) { var list = new List<FileInfo>(); foreach (var file in processedFile) { list.Add(await file.SaveFileAsync(Path.Combine(outputDirectory, file.FileName))); } return list; } #endregion } }
39.792208
189
0.658616
[ "MIT" ]
kostas-baltsoft/convertapi-dotnet
ConvertApi/ConvertApiExtension.cs
6,130
C#
using UnityEngine; public class MessageSender : MonoBehaviour { public SpacebrewEvents spacebrewClientEvents; public string pubNameMove; public string pubNameShoot; public void SendMove(string message) { spacebrewClientEvents.SendString(pubNameMove, message); } public void SendShoot(string message) { spacebrewClientEvents.SendString(pubNameShoot, message); } }
21.789474
64
0.7343
[ "MIT" ]
2-REC/multi-unity
UnityMulti/Assets/SpaceBrew/Examples/Scripts/MessageSender.cs
416
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OpenTK; using OpenTK.Input; using System.Drawing; using OpenTK.Graphics.OpenGL; using System.Drawing.Imaging; using System.Threading; using System.Media; namespace OpenTKPlatformerExample { class Game : GameWindow { #region declarations public static int GRIDSIZE = 48; public static int Level = 1; public static SoundPlayer music = new SoundPlayer(Environment.CurrentDirectory + "/Content/menusong.wav"); public static List<Enemy> enemies = new List<Enemy>(); public static Texture2D dot; public static string slevel = ""; public static int introind = 0; public static Random rand = new Random(); public static Texture2D tileSet; public static View view; public static Level level; public static Player player; public static Message[] intro = new Message[] { new Message("Looks like anotherworld is finished.",Color.DarkRed), new Message("Are you sure aboutthat brother? Thisone looks kinda depressing to me..", Color.DarkGreen), new Message("All the enemies.. powerups.. coins..everything is sad,even the sky.", Color.DarkGreen), new Message("Oh don't worry about that.",Color.DarkRed), new Message("SPONGE!",Color.DarkRed), new Message("...",Color.DarkOrange), new Message("Make your lazy ass useful and useyour stupid power to soak the sadness of the newworld.",Color.DarkRed), new Message("B-but it's the 2ndtime this month. And you took away my antidepressant pills last ti-",Color.DarkOrange), new Message("HOW MANY TIMES DO I HAVE TO TELL THIS TO YOU?!",Color.DarkRed), new Message("We are out there risking our lives fighting a giant dragon to save theprincess.",Color.DarkRed), new Message("You might aswell do SOMETHING instead of sittinghere all day crying.",Color.DarkRed), new Message("He is our brother man,don't be so harsh on him.", Color.DarkGreen), new Message("You better not be telling me what to do,you fucking adopted terminal-7 host.",Color.DarkRed), new Message("But M-", Color.DarkGreen), new Message("SHUT YOUR MOUTH IDIOT!",Color.DarkRed), new Message("Do you want us to get DMCA'ed? You can only refer toyour drama queen brother with his real name.",Color.DarkRed), new Message("O-okay brother.", Color.DarkGreen), new Message("Now I have some stuff to do unlikeyou two lifeless losers.",Color.DarkRed), new Message("Do as I said Sponge.If you're lucky, I might consider giving you your stupid tic-tacs back.",Color.DarkRed), new Message("Now get to work.",Color.DarkRed), }; internal static bool corrupt; #endregion public static void Reset() { ObjectHandler.fireballsonscreen = 0; Level = 1; enemies.Clear(); ObjectHandler.objects.Clear(); level = new Level("Content/Levels/Level1.xml"); player = new Player(new Vector2(level.playerStartPos.X + 0.5f, level.playerStartPos.Y + 0.5f) * GRIDSIZE, new Vector2(0, 0.8f)); } //Call when lives are lost public static void Reload() { ObjectHandler.fireballsonscreen = 0; enemies.Clear(); ObjectHandler.objects.Clear(); if (Level == 1) { level = new Level("Content/Levels/Level1.xml"); }else if (Level == 2) { level = new Level("Content/Levels/Desert.xml"); }else if (Level == 3) { level = new Level("Content/Levels/GhostHouse.xml"); }else if (Level == 4) { level = new Level("Content/Levels/GhostEventRoom.xml"); }else if (Level == 5) { level = new Level("Content/Levels/Castle.xml"); }else if (Level ==6) { level = new Level("Content/Levels/Epilogue.xml"); } player = new Player(new Vector2(level.playerStartPos.X + 0.5f, level.playerStartPos.Y + 0.5f) * GRIDSIZE, new Vector2(0, 0.8f)); } public Game() : base(640, 480, new OpenTK.Graphics.GraphicsMode(32, 24, 0, 8)) { Title = ""; slevel = "menu"; WindowBorder = WindowBorder.Fixed; if (SoundManager.volume == -1) SoundManager.volume = 0.1f; DialogBox.cd = intro[0].color; DialogBox.LoadString(intro[0].msg); GL.Enable(EnableCap.Texture2D); GL.Enable(EnableCap.Blend); //Set how the alpha blending function works GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha); ObjectHandler.Load(); Input.Initialize(this); view = new View(Vector2.Zero, 1f, 0.0); } //Window initializer //Loads a certain level public static void LoadLevel(string path) { enemies.Clear(); ObjectHandler.objects.Clear(); level = new Level("Content/Levels/" + path); player = new Player(new Vector2(level.playerStartPos.X + 0.5f, level.playerStartPos.Y + 0.5f) * GRIDSIZE, new Vector2(0, 0.8f)); //Player object } //Load - is called once per game execution. Load textures and stuff here. protected override void OnLoad(EventArgs e) { base.OnLoad(e); //Load certain classes DialogBox.Load(); //Load enemies Slime.Load(); Snail.Load(); GrassBlock.Load(); Ghost.Load(); EventGhost.Load(); Piranha.Load(); //Load the texture tileSet = ContentPipe.LoadTexture("TileSet1.png"); level = new Level("Content/Levels/Menu.xml"); music.PlayLooping(); player = new Player(new Vector2(level.playerStartPos.X + 0.5f, level.playerStartPos.Y + 0.5f) * GRIDSIZE, new Vector2(0, 0.8f)); //Player object view.width = level[0, 0].posX + Width / 2 + 35; #region Create dot texture { int id = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture2D, id); Bitmap bmp = new Bitmap(1, 1); bmp.SetPixel(0, 0, Color.White); BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, 1, 1), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, 1, 1, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmpData.Scan0); dot = new Texture2D(id, 1, 1); bmp.UnlockBits(bmpData); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMinFilter.Linear); } #endregion } //Update - triggers before render - do math here protected override void OnUpdateFrame(FrameEventArgs e) { base.OnUpdateFrame(e); if (slevel == "menu") { Input.EarlyUpdate(); view.SetPosition(player.position, TweenType.Instant, 15); view.Update(); foreach (GameObject o in ObjectHandler.objects.ToArray()) { o.Update(player); } Input.Update(); Input.LateUpdate(); } else { Input.EarlyUpdate(); if (!slevel.Contains("story")) //Levels that contain "story" will not render the level or update anything, just display //the story player.Update(ref level); if (slevel.Contains("story")) { if (DialogBox.UpdateString()) { if (Input.KeyPress(Key.Z) || (Input.A && !Input.lastA)) { if (introind < intro.Length - 1) { introind++; DialogBox.cd = intro[introind].color; DialogBox.LoadString(intro[introind].msg); } else { slevel = "game"; player.invincibletime = Environment.TickCount; DialogBox.cd = Color.White; intro = new Message[] { }; } } } else { if (Input.KeyPress(Key.Z) || (Input.A && !Input.lastA)) { DialogBox.meter = DialogBox.message.Length; } } if (Input.KeyPress(Key.X) || (Input.B && !Input.lastB)) { intro = new Message[] { }; slevel = "game"; player.invincibletime = Environment.TickCount; DialogBox.cd = Color.White; } } Input.Update(); view.SetPosition(player.position, TweenType.QuarticOut, 15); view.Update(); foreach (GameObject o in ObjectHandler.objects.ToArray()) { o.Update(player); } if (0 > ObjectHandler.fireballsonscreen) { ObjectHandler.fireballsonscreen = 0; } else if (ObjectHandler.fireballsonscreen > 2) { ObjectHandler.fireballsonscreen = 2; } Input.LateUpdate(); } } //Render - draw stuff here protected override void OnRenderFrame(FrameEventArgs e) { base.OnRenderFrame(e); if (slevel == "menu") { GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); GL.ClearColor(Color.FromArgb(255, 10, 10, 10)); Spritebatch.Begin(this); view.ApplyTransforms(); foreach (GameObject o in ObjectHandler.objects) { o.Draw(Color.FromArgb(255,90,90,90)); } for (int x = 0; x < level.Width; x++) { for (int y = 0; y < level.Height; y++) { int tileSize = 70; RectangleF sourceRec = new RectangleF(0, 0, 0, 0); sourceRec = new RectangleF(level[x, y].tileX, level[x, y].tileY, tileSize, tileSize); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); Spritebatch.DrawSprite(tileSet, new RectangleF(x * GRIDSIZE, y * GRIDSIZE, GRIDSIZE + 1, GRIDSIZE + 1), Color.FromArgb(255,90,90,90), sourceRec); } } } else { List<Enemy> afterdraw = new List<Enemy>(); //Enemies drawn after tiles - above them. (atm all except piranhas) Color tilec = Color.LightGray; GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); if (slevel.Contains("story")) GL.ClearColor(Color.FromArgb(255, 0, 0, 0)); else if (Level == 1) { GL.ClearColor(Color.FromArgb(255, 10, 10, 10)); tilec = Color.LightGray; } else if (Level == 2) { GL.ClearColor(Color.FromArgb(255, 0, 20, 20)); tilec = Color.LightGray; } else if (Level == 3 || Level == 4 || Level == 5) { GL.ClearColor(Color.FromArgb(255, 0, 0, 16)); tilec = Color.Gray; }else if (Level == 6) { GL.ClearColor(Color.FromArgb(255, 16, 16, 16)); tilec = Color.Gray; } Spritebatch.Begin(this); view.ApplyTransforms(); if (!slevel.Contains("story")) foreach (GameObject o in ObjectHandler.objects) { o.Draw(tilec); } List<Tuple<Block,Vector2>> afterdraws = new List<Tuple<Block, Vector2>>(); if (!slevel.Contains("story")) for (int x = 0; x < level.Width; x++) { for (int y = 0; y < level.Height; y++) { if (level[x, y].type == BlockType.Empty) { Tuple<Block, Vector2> t = new Tuple<Block, Vector2>(level[x, y], new Vector2(x, y)); afterdraws.Add(t); continue; } int tileSize = 70; RectangleF sourceRec = new RectangleF(0, 0, 0, 0); sourceRec = new RectangleF(level[x, y].tileX, level[x, y].tileY, tileSize, tileSize); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); Spritebatch.DrawSprite(tileSet, new RectangleF(x * GRIDSIZE, y * GRIDSIZE, GRIDSIZE + 1, GRIDSIZE + 1), tilec, sourceRec); } } if (!slevel.Contains("story")) foreach (Enemy ex in enemies) { if (ex.enemyType == 5) ex.Draw(); else afterdraw.Add(ex); } if (!slevel.Contains("story")) player.Draw(tilec); foreach (Tuple<Block, Vector2> t in afterdraws.ToArray()) { int tileSize = 70; RectangleF sourceRec = new RectangleF(0, 0, 0, 0); sourceRec = new RectangleF(t.Item1.tileX, t.Item1.tileY, tileSize, tileSize); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); Spritebatch.DrawSprite(tileSet, new RectangleF(t.Item2.X * GRIDSIZE, t.Item2.Y * GRIDSIZE, GRIDSIZE + 1, GRIDSIZE + 1), tilec, sourceRec); } foreach (Enemy ex in afterdraw) { ex.Draw(); } if (!slevel.Contains("story")) view.DrawHUD(); if (slevel.Contains("story")) { GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); DialogBox.DrawString(view.Position.X - 288, view.Position.Y); } } this.SwapBuffers(); } } class Message //Message class for storylines { //Just a touple of string and Color public string msg; public Color color; public Message(string msg, Color color) { this.msg = msg; this.color = color; } } }
43.6625
177
0.492814
[ "MIT" ]
PKTINOS/SpongeGame
Code/Game.cs
17,467
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Shapes { public class Triangle:Shape,IShape { public Triangle(double width, double height) : base(width, height) { } public override double CalculateSurface() { return (this.Heigth * this.Width) / 2; } } }
18.130435
74
0.609113
[ "MIT" ]
lubangelova/C-OOP
Homework/OOP Principles - Part 2/Shapes/Triangle.cs
419
C#
using Arrowgene.Baf.Server.Core; using Arrowgene.Baf.Server.Logging; using Arrowgene.Baf.Server.Packet; using Arrowgene.Buffers; using Arrowgene.Logging; namespace Arrowgene.Baf.Server.PacketHandle { public class RoomChangeSettingHandle : PacketHandler { private static readonly BafLogger Logger = LogProvider.Logger<BafLogger>(typeof(RoomChangeSettingHandle)); public override PacketId Id => PacketId.RoomChangeSettingReq; public RoomChangeSettingHandle(BafServer server) : base(server) { } public override void Handle(BafClient client, BafPacket packet) { IBuffer b = new StreamBuffer(); BafPacket p = new BafPacket(PacketId.RoomChangeSettingRes, b.GetAllBytes()); // client.Send(p); } } }
30.185185
114
0.688344
[ "MIT" ]
sebastian-heinz/Arrowgene.Baf
Arrowgene.Baf.Server/PacketHandle/RoomChangeSettingHandle.cs
815
C#
using System; using NUnit.Framework; using TagLib; using TagLib.IFD; using TagLib.IFD.Entries; using TagLib.Jpeg; using TagLib.Xmp; namespace TagLib.Tests.Images { [TestFixture] public class JpegSegmentSizeTest { private static string sample_file = "samples/sample.jpg"; private static string tmp_file = "samples/tmpwrite_exceed_segment_size.jpg"; private static int max_segment_size = 0xFFFF; private TagTypes contained_types = TagTypes.JpegComment | TagTypes.TiffIFD | TagTypes.XMP; private string CreateDataString (int min_size) { string src = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; ByteVector data = new ByteVector (); for (int i = 0; data.Count < min_size; i++) { int index = i % src.Length; data.Add (src.Substring (index, src.Length - index)); } return data.ToString (); } [Test] public void ExifExceed () { File tmp = Utils.CreateTmpFile (sample_file, tmp_file) as File; CheckTags (tmp); var exif_tag = tmp.GetTag (TagTypes.TiffIFD) as IFDTag; Assert.IsNotNull (exif_tag, "exif tag"); // ensure data is big enough exif_tag.Comment = CreateDataString (max_segment_size); Assert.IsFalse (SaveFile (tmp), "file with exceed exif segment saved"); } [Test] public void XmpExceed () { File tmp = Utils.CreateTmpFile (sample_file, tmp_file) as File; CheckTags (tmp); var xmp_tag = tmp.GetTag (TagTypes.XMP) as XmpTag; Assert.IsNotNull (xmp_tag, "xmp tag"); // ensure data is big enough xmp_tag.Comment = CreateDataString (max_segment_size); Assert.IsFalse (SaveFile (tmp), "file with exceed xmp segment saved"); } [Test] public void JpegCommentExceed () { File tmp = Utils.CreateTmpFile (sample_file, tmp_file) as File; CheckTags (tmp); var com_tag = tmp.GetTag (TagTypes.JpegComment) as JpegCommentTag; Assert.IsNotNull (com_tag, "comment tag"); // ensure data is big enough com_tag.Comment = CreateDataString (max_segment_size); Assert.IsFalse (SaveFile (tmp), "file with exceed comment segment saved"); } private void CheckTags (File file) { Assert.IsTrue (file is Jpeg.File, "not a Jpeg file"); Assert.AreEqual (contained_types, file.TagTypes); Assert.AreEqual (contained_types, file.TagTypesOnDisk); } private bool SaveFile (File file) { try { file.Save (); } catch (Exception) { return false; } return true; } } }
22.757009
84
0.689938
[ "MIT" ]
Hadryan/Qabuze
taglib-sharp/tests/fixtures/TagLib.Tests.Images/JpegSegmentSizeTest.cs
2,435
C#
using ControleDespesas.Domain.Empresas.Commands.Input; using ControleDespesas.Domain.Empresas.Entities; using ControleDespesas.Domain.Pagamentos.Commands.Input; using ControleDespesas.Domain.Pagamentos.Entities; using ControleDespesas.Domain.Pagamentos.Enums; using ControleDespesas.Domain.Pagamentos.Query.Parameters; using ControleDespesas.Domain.Pessoas.Commands.Input; using ControleDespesas.Domain.Pessoas.Entities; using ControleDespesas.Domain.Pessoas.Query.Parameters; using ControleDespesas.Domain.TiposPagamentos.Commands.Input; using ControleDespesas.Domain.TiposPagamentos.Entities; using ControleDespesas.Domain.Usuarios.Commands.Input; using ControleDespesas.Domain.Usuarios.Entities; using ControleDespesas.Domain.Usuarios.Enums; using ControleDespesas.Domain.Usuarios.Query.Results; using ControleDespesas.Infra.Logs; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; namespace ControleDespesas.Test.AppConfigurations.Settings { public class SettingsTest { #region [IConfiguration - appsettings.json] private IConfiguration _configuration { get; } #endregion [IConfiguration - appsettings.json] #region [Dados de teste para API] public string ControleDespesasAPINetCore { get; } public string ChaveAPI { get; } public string ChaveJWT { get; } #endregion [Dados de teste para API] #region [Dados de teste para Banco de Dados] public string ConnectionSQLServerReal { get; } public string ConnectionSQLServerTest { get; } #endregion [Dados de teste para Banco de Dados] #region [Dados de teste para Empresa] public AdicionarEmpresaCommand EmpresaAdicionarCommand { get; } public AtualizarEmpresaCommand EmpresaAtualizarCommand { get; } public Empresa Empresa1 { get; } public Empresa Empresa2 { get; } public Empresa Empresa3 { get; } public Empresa Empresa1Editada { get; } #endregion [Dados de teste para Empresa] #region [Dados de teste para Pessoa] public AdicionarPessoaCommand PessoaAdicionarCommand { get; } public AtualizarPessoaCommand PessoaAtualizarCommand { get; } public ObterPessoasQuery PessoaObterQuery { get; } public Pessoa Pessoa1 { get; } public Pessoa Pessoa2 { get; } public Pessoa Pessoa3 { get; } public Pessoa Pessoa1Editada { get; } #endregion [Dados de teste para Pessoa] #region [Dados de teste para TipoPagamento] public AdicionarTipoPagamentoCommand TipoPagamentoAdicionarCommand { get; } public AtualizarTipoPagamentoCommand TipoPagamentoAtualizarCommand { get; } public TipoPagamento TipoPagamento1 { get; } public TipoPagamento TipoPagamento2 { get; } public TipoPagamento TipoPagamento3 { get; } public TipoPagamento TipoPagamento1Editado { get; } #endregion [Dados de teste para TipoPagamento] #region [Dados de teste para Pagamento] public AdicionarPagamentoCommand PagamentoAdicionarCommand { get; } public AtualizarPagamentoCommand PagamentoAtualizarCommand { get; } public PagamentoQuery PagamentoQuery { get; } public PagamentoQuery PagamentoQueryPagos { get; } public PagamentoQuery PagamentoQueryPendentes { get; } public PagamentoGastosQuery PagamentoGastosQuery { get; } public Pagamento Pagamento1 { get; } public Pagamento Pagamento2 { get; } public Pagamento Pagamento3 { get; } public Pagamento Pagamento1Editado { get; } #endregion [Dados de teste para Pagamento] #region [Dados de teste para Usuario] public AdicionarUsuarioCommand UsuarioAdicionarCommand { get; } public AtualizarUsuarioCommand UsuarioAtualizarCommand { get; } public LoginUsuarioCommand UsuarioLoginCommand { get; } public UsuarioQueryResult UsuarioQR { get; } public Usuario Usuario1 { get; } public Usuario Usuario2 { get; } public Usuario Usuario3 { get; } public Usuario Usuario1Editado { get; } #endregion [Dados de teste para Usuario] #region [Dados de teste para LogRequestResponse] public LogRequestResponse LogRequestResponse1 { get; } public LogRequestResponse LogRequestResponse2 { get; } #endregion [Dados de teste para LogRequestResponse] public SettingsTest() { #region [Setando IConfiguration - appsettings.json] _configuration = new ServiceCollection().AddTransient<IConfiguration>(sp => new ConfigurationBuilder().AddJsonFile("appsettings.json").Build()).BuildServiceProvider().GetService<IConfiguration>(); #endregion [Setando IConfiguration - appsettings.json] #region [Dados de teste para API] ControleDespesasAPINetCore = _configuration.GetValue<string>("SettingsTest:ControleDespesasAPINetCore"); ChaveAPI = _configuration.GetValue<string>("SettingsTest:ChaveAPI"); ChaveJWT = _configuration.GetValue<string>("SettingsTest:ChaveJWT"); #endregion [Dados de teste para API] #region [Setando dados teste para Banco de Dados] ConnectionSQLServerReal = _configuration.GetValue<string>("SettingsTest:ConnectionSQLServerReal"); ConnectionSQLServerTest = _configuration.GetValue<string>("SettingsTest:ConnectionSQLServerTest"); #endregion [Setando dados teste para Banco de Dados] #region [Setando dados de teste para Empresa] EmpresaAdicionarCommand = new AdicionarEmpresaCommand() { Nome = _configuration.GetValue<string>("SettingsTest:EmpresaAdicionarCommand:Nome"), Logo = _configuration.GetValue<string>("SettingsTest:EmpresaAdicionarCommand:Logo") }; EmpresaAtualizarCommand = new AtualizarEmpresaCommand() { Id = _configuration.GetValue<int>("SettingsTest:EmpresaAtualizarCommand:Id"), Nome = _configuration.GetValue<string>("SettingsTest:EmpresaAtualizarCommand:Nome"), Logo = _configuration.GetValue<string>("SettingsTest:EmpresaAtualizarCommand:Logo") }; Empresa1 = new Empresa( _configuration.GetValue<int>("SettingsTest:Empresa1:Id"), _configuration.GetValue<string>("SettingsTest:Empresa1:Nome"), _configuration.GetValue<string>("SettingsTest:Empresa1:Logo") ); Empresa2 = new Empresa( _configuration.GetValue<int>("SettingsTest:Empresa2:Id"), _configuration.GetValue<string>("SettingsTest:Empresa2:Nome"), _configuration.GetValue<string>("SettingsTest:Empresa2:Logo") ); Empresa3 = new Empresa( _configuration.GetValue<int>("SettingsTest:Empresa3:Id"), _configuration.GetValue<string>("SettingsTest:Empresa3:Nome"), _configuration.GetValue<string>("SettingsTest:Empresa3:Logo") ); Empresa1Editada = new Empresa( _configuration.GetValue<int>("SettingsTest:Empresa1Editada:Id"), _configuration.GetValue<string>("SettingsTest:Empresa1Editada:Nome"), _configuration.GetValue<string>("SettingsTest:Empresa1Editada:Logo") ); #endregion [Setando dados de teste para Empresa] #region [Setando dados de teste para Pessoa] PessoaAdicionarCommand = new AdicionarPessoaCommand() { IdUsuario = _configuration.GetValue<int>("SettingsTest:PessoaAdicionarCommand:IdUsuario"), Nome = _configuration.GetValue<string>("SettingsTest:PessoaAdicionarCommand:Nome"), ImagemPerfil = _configuration.GetValue<string>("SettingsTest:PessoaAdicionarCommand:ImagemPerfil") }; PessoaAtualizarCommand = new AtualizarPessoaCommand() { Id = _configuration.GetValue<int>("SettingsTest:PessoaAtualizarCommand:Id"), IdUsuario = _configuration.GetValue<int>("SettingsTest:PessoaAtualizarCommand:IdUsuario"), Nome = _configuration.GetValue<string>("SettingsTest:PessoaAtualizarCommand:Nome"), ImagemPerfil = _configuration.GetValue<string>("SettingsTest:PessoaAtualizarCommand:ImagemPerfil") }; PessoaObterQuery = new ObterPessoasQuery() { IdUsuario = _configuration.GetValue<int>("SettingsTest:PessoaObterQuery:IdUsuario") }; Pessoa1 = new Pessoa( _configuration.GetValue<int>("SettingsTest:Pessoa1:Id"), new Usuario(_configuration.GetValue<int>("SettingsTest:Pessoa1:IdUsuario")), _configuration.GetValue<string>("SettingsTest:Pessoa1:Nome"), _configuration.GetValue<string>("SettingsTest:Pessoa1:ImagemPerfil") ); Pessoa2 = new Pessoa( _configuration.GetValue<int>("SettingsTest:Pessoa2:Id"), new Usuario(_configuration.GetValue<int>("SettingsTest:Pessoa2:IdUsuario")), _configuration.GetValue<string>("SettingsTest:Pessoa2:Nome"), _configuration.GetValue<string>("SettingsTest:Pessoa2:ImagemPerfil") ); Pessoa3 = new Pessoa( _configuration.GetValue<int>("SettingsTest:Pessoa3:Id"), new Usuario(_configuration.GetValue<int>("SettingsTest:Pessoa3:IdUsuario")), _configuration.GetValue<string>("SettingsTest:Pessoa3:Nome"), _configuration.GetValue<string>("SettingsTest:Pessoa3:ImagemPerfil") ); Pessoa1Editada = new Pessoa( _configuration.GetValue<int>("SettingsTest:Pessoa1Editada:Id"), new Usuario(_configuration.GetValue<int>("SettingsTest:Pessoa1Editada:IdUsuario")), _configuration.GetValue<string>("SettingsTest:Pessoa1Editada:Nome"), _configuration.GetValue<string>("SettingsTest:Pessoa1Editada:ImagemPerfil") ); #endregion [Setando dados de teste para Pessoa] #region [Setando dados de teste para TipoPagamento] TipoPagamentoAdicionarCommand = new AdicionarTipoPagamentoCommand() { Descricao = _configuration.GetValue<string>("SettingsTest:TipoPagamentoAdicionarCommand:Descricao") }; TipoPagamentoAtualizarCommand = new AtualizarTipoPagamentoCommand() { Id = _configuration.GetValue<int>("SettingsTest:TipoPagamentoAtualizarCommand:Id"), Descricao = _configuration.GetValue<string>("SettingsTest:TipoPagamentoAtualizarCommand:Descricao") }; TipoPagamento1 = new TipoPagamento( _configuration.GetValue<int>("SettingsTest:TipoPagamento1:Id"), _configuration.GetValue<string>("SettingsTest:TipoPagamento1:Descricao") ); TipoPagamento2 = new TipoPagamento( _configuration.GetValue<int>("SettingsTest:TipoPagamento2:Id"), _configuration.GetValue<string>("SettingsTest:TipoPagamento2:Descricao") ); TipoPagamento3 = new TipoPagamento( _configuration.GetValue<int>("SettingsTest:TipoPagamento3:Id"), _configuration.GetValue<string>("SettingsTest:TipoPagamento3:Descricao") ); TipoPagamento1Editado = new TipoPagamento( _configuration.GetValue<int>("SettingsTest:TipoPagamento1Editado:Id"), _configuration.GetValue<string>("SettingsTest:TipoPagamento1Editado:Descricao") ); #endregion [Setando dados de teste para TipoPagamento] #region [Setando dados de teste para Pagamento] PagamentoAdicionarCommand = new AdicionarPagamentoCommand() { IdTipoPagamento = _configuration.GetValue<int>("SettingsTest:PagamentoAdicionarCommand:IdTipoPagamento"), IdEmpresa = _configuration.GetValue<int>("SettingsTest:PagamentoAdicionarCommand:IdEmpresa"), IdPessoa = _configuration.GetValue<int>("SettingsTest:PagamentoAdicionarCommand:IdPessoa"), Descricao = _configuration.GetValue<string>("SettingsTest:PagamentoAdicionarCommand:Descricao"), Valor = _configuration.GetValue<double>("SettingsTest:PagamentoAdicionarCommand:Valor"), DataVencimento = _configuration.GetValue<DateTime>("SettingsTest:PagamentoAdicionarCommand:DataVencimento"), DataPagamento = _configuration.GetValue<DateTime?>("SettingsTest:PagamentoAdicionarCommand:DataPagamento"), ArquivoPagamento = _configuration.GetValue<string>("SettingsTest:PagamentoAdicionarCommand:ArquivoPagamento"), ArquivoComprovante = _configuration.GetValue<string>("SettingsTest:PagamentoAdicionarCommand:ArquivoComprovante") }; PagamentoAtualizarCommand = new AtualizarPagamentoCommand() { Id = _configuration.GetValue<int>("SettingsTest:PagamentoAtualizarCommand:Id"), IdTipoPagamento = _configuration.GetValue<int>("SettingsTest:PagamentoAtualizarCommand:IdTipoPagamento"), IdEmpresa = _configuration.GetValue<int>("SettingsTest:PagamentoAtualizarCommand:IdEmpresa"), IdPessoa = _configuration.GetValue<int>("SettingsTest:PagamentoAtualizarCommand:IdPessoa"), Descricao = _configuration.GetValue<string>("SettingsTest:PagamentoAtualizarCommand:Descricao"), Valor = _configuration.GetValue<double>("SettingsTest:PagamentoAtualizarCommand:Valor"), DataVencimento = _configuration.GetValue<DateTime>("SettingsTest:PagamentoAtualizarCommand:DataVencimento"), DataPagamento = _configuration.GetValue<DateTime?>("SettingsTest:PagamentoAtualizarCommand:DataPagamento"), ArquivoPagamento = _configuration.GetValue<string>("SettingsTest:PagamentoAtualizarCommand:ArquivoPagamento"), ArquivoComprovante = _configuration.GetValue<string>("SettingsTest:PagamentoAtualizarCommand:ArquivoComprovante") }; PagamentoQuery = new PagamentoQuery() { IdPessoa = _configuration.GetValue<int>("SettingsTest:PagamentoQuery:IdPessoa"), Status = _configuration.GetValue<EPagamentoStatus?>("SettingsTest:PagamentoQuery:Status") }; PagamentoQueryPagos = new PagamentoQuery() { IdPessoa = _configuration.GetValue<int>("SettingsTest:PagamentoQueryPagos:IdPessoa"), Status = _configuration.GetValue<EPagamentoStatus?>("SettingsTest:PagamentoQueryPagos:Status") }; PagamentoQueryPendentes = new PagamentoQuery() { IdPessoa = _configuration.GetValue<int>("SettingsTest:PagamentoQueryPendentes:IdPessoa"), Status = _configuration.GetValue<EPagamentoStatus?>("SettingsTest:PagamentoQueryPendentes:Status") }; PagamentoGastosQuery = new PagamentoGastosQuery() { IdPessoa = _configuration.GetValue<int>("SettingsTest:PagamentoGastosQuery:IdPessoa"), Ano = _configuration.GetValue<int>("SettingsTest:PagamentoGastosQuery:Ano"), Mes = _configuration.GetValue<int>("SettingsTest:PagamentoGastosQuery:Mes") }; Pagamento1 = new Pagamento( _configuration.GetValue<int>("SettingsTest:Pagamento1:Id"), new TipoPagamento( _configuration.GetValue<int>("SettingsTest:Pagamento1:TipoPagamento:Id"), _configuration.GetValue<string>("SettingsTest:Pagamento1:TipoPagamento:Descricao") ), new Empresa( _configuration.GetValue<int>("SettingsTest:Pagamento1:Empresa:Id"), _configuration.GetValue<string>("SettingsTest:Pagamento1:Empresa:Nome"), _configuration.GetValue<string>("SettingsTest:Pagamento1:Empresa:Logo") ), new Pessoa( _configuration.GetValue<int>("SettingsTest:Pagamento1:Pessoa:Id"), new Usuario(_configuration.GetValue<int>("SettingsTest:Pagamento1:Pessoa:IdUsuario")), _configuration.GetValue<string>("SettingsTest:Pagamento1:Pessoa:Nome"), _configuration.GetValue<string>("SettingsTest:Pagamento1:Pessoa:ImagemPerfil") ), _configuration.GetValue<string>("SettingsTest:Pagamento1:Descricao"), _configuration.GetValue<double>("SettingsTest:Pagamento1:Valor"), _configuration.GetValue<DateTime>("SettingsTest:Pagamento1:DataVencimento"), _configuration.GetValue<DateTime?>("SettingsTest:Pagamento1:DataPagamento"), _configuration.GetValue<string>("SettingsTest:Pagamento1:ArquivoPagamento"), _configuration.GetValue<string>("SettingsTest:Pagamento1:ArquivoComprovante") ); Pagamento2 = new Pagamento( _configuration.GetValue<int>("SettingsTest:Pagamento2:Id"), new TipoPagamento( _configuration.GetValue<int>("SettingsTest:Pagamento2:TipoPagamento:Id"), _configuration.GetValue<string>("SettingsTest:Pagamento2:TipoPagamento:Descricao") ), new Empresa( _configuration.GetValue<int>("SettingsTest:Pagamento2:Empresa:Id"), _configuration.GetValue<string>("SettingsTest:Pagamento2:Empresa:Nome"), _configuration.GetValue<string>("SettingsTest:Pagamento2:Empresa:Logo") ), new Pessoa( _configuration.GetValue<int>("SettingsTest:Pagamento2:Pessoa:Id"), new Usuario(_configuration.GetValue<int>("SettingsTest:Pagamento2:Pessoa:IdUsuario")), _configuration.GetValue<string>("SettingsTest:Pagamento2:Pessoa:Nome"), _configuration.GetValue<string>("SettingsTest:Pagamento2:Pessoa:ImagemPerfil") ), _configuration.GetValue<string>("SettingsTest:Pagamento2:Descricao"), _configuration.GetValue<double>("SettingsTest:Pagamento2:Valor"), _configuration.GetValue<DateTime>("SettingsTest:Pagamento2:DataVencimento"), _configuration.GetValue<DateTime?>("SettingsTest:Pagamento2:DataPagamento"), _configuration.GetValue<string>("SettingsTest:Pagamento2:ArquivoPagamento"), _configuration.GetValue<string>("SettingsTest:Pagamento2:ArquivoComprovante") ); Pagamento3 = new Pagamento( _configuration.GetValue<int>("SettingsTest:Pagamento3:Id"), new TipoPagamento( _configuration.GetValue<int>("SettingsTest:Pagamento3:TipoPagamento:Id"), _configuration.GetValue<string>("SettingsTest:Pagamento3:TipoPagamento:Descricao") ), new Empresa( _configuration.GetValue<int>("SettingsTest:Pagamento3:Empresa:Id"), _configuration.GetValue<string>("SettingsTest:Pagamento3:Empresa:Nome"), _configuration.GetValue<string>("SettingsTest:Pagamento3:Empresa:Logo") ), new Pessoa( _configuration.GetValue<int>("SettingsTest:Pagamento3:Pessoa:Id"), new Usuario(_configuration.GetValue<int>("SettingsTest:Pagamento3:Pessoa:IdUsuario")), _configuration.GetValue<string>("SettingsTest:Pagamento3:Pessoa:Nome"), _configuration.GetValue<string>("SettingsTest:Pagamento3:Pessoa:ImagemPerfil") ), _configuration.GetValue<string>("SettingsTest:Pagamento3:Descricao"), _configuration.GetValue<double>("SettingsTest:Pagamento3:Valor"), _configuration.GetValue<DateTime>("SettingsTest:Pagamento3:DataVencimento"), _configuration.GetValue<DateTime?>("SettingsTest:Pagamento3:DataPagamento"), _configuration.GetValue<string>("SettingsTest:Pagamento3:ArquivoPagamento"), _configuration.GetValue<string>("SettingsTest:Pagamento3:ArquivoComprovante") ); Pagamento1Editado = new Pagamento( _configuration.GetValue<int>("SettingsTest:Pagamento1Editado:Id"), new TipoPagamento( _configuration.GetValue<int>("SettingsTest:Pagamento1Editado:TipoPagamento:Id"), _configuration.GetValue<string>("SettingsTest:Pagamento1Editado:TipoPagamento:Descricao") ), new Empresa( _configuration.GetValue<int>("SettingsTest:Pagamento1Editado:Empresa:Id"), _configuration.GetValue<string>("SettingsTest:Pagamento1Editado:Empresa:Nome"), _configuration.GetValue<string>("SettingsTest:Pagamento1Editado:Empresa:Logo") ), new Pessoa( _configuration.GetValue<int>("SettingsTest:Pagamento1Editado:Pessoa:Id"), new Usuario(_configuration.GetValue<int>("SettingsTest:Pagamento1Editado:Pessoa:IdUsuario")), _configuration.GetValue<string>("SettingsTest:Pagamento1Editado:Pessoa:Nome"), _configuration.GetValue<string>("SettingsTest:Pagamento1Editado:Pessoa:ImagemPerfil") ), _configuration.GetValue<string>("SettingsTest:Pagamento1Editado:Descricao"), _configuration.GetValue<double>("SettingsTest:Pagamento1Editado:Valor"), _configuration.GetValue<DateTime>("SettingsTest:Pagamento1Editado:DataVencimento"), _configuration.GetValue<DateTime?>("SettingsTest:Pagamento1Editado:DataPagamento"), _configuration.GetValue<string>("SettingsTest:Pagamento1Editado:ArquivoPagamento"), _configuration.GetValue<string>("SettingsTest:Pagamento1Editado:ArquivoComprovante") ); #endregion [Setando dados de teste para Pagamento] #region[ Setando dados de teste para Usuario] UsuarioAdicionarCommand = new AdicionarUsuarioCommand() { Login = _configuration.GetValue<string>("SettingsTest:UsuarioAdicionarCommand:Login"), Senha = _configuration.GetValue<string>("SettingsTest:UsuarioAdicionarCommand:Senha"), Privilegio = _configuration.GetValue<EPrivilegioUsuario>("SettingsTest:UsuarioAdicionarCommand:Privilegio") }; UsuarioAtualizarCommand = new AtualizarUsuarioCommand() { Id = _configuration.GetValue<int>("SettingsTest:UsuarioAtualizarCommand:Id"), Login = _configuration.GetValue<string>("SettingsTest:UsuarioAtualizarCommand:Login"), Senha = _configuration.GetValue<string>("SettingsTest:UsuarioAtualizarCommand:Senha"), Privilegio = _configuration.GetValue<EPrivilegioUsuario>("SettingsTest:UsuarioAtualizarCommand:Privilegio") }; UsuarioLoginCommand = new LoginUsuarioCommand() { Login = _configuration.GetValue<string>("SettingsTest:UsuarioLoginCommand:Login"), Senha = _configuration.GetValue<string>("SettingsTest:UsuarioLoginCommand:Senha") }; UsuarioQR = new UsuarioQueryResult() { Id = _configuration.GetValue<int>("SettingsTest:UsuarioQR:Id"), Login = _configuration.GetValue<string>("SettingsTest:UsuarioQR:Login"), Senha = _configuration.GetValue<string>("SettingsTest:UsuarioQR:Senha"), Privilegio = _configuration.GetValue<EPrivilegioUsuario>("SettingsTest:UsuarioQR:Privilegio") }; Usuario1 = new Usuario( _configuration.GetValue<int>("SettingsTest:Usuario1:Id"), _configuration.GetValue<string>("SettingsTest:Usuario1:Login"), _configuration.GetValue<string>("SettingsTest:Usuario1:Senha"), _configuration.GetValue<EPrivilegioUsuario>("SettingsTest:Usuario1:Privilegio") ); Usuario2 = new Usuario( _configuration.GetValue<int>("SettingsTest:Usuario2:Id"), _configuration.GetValue<string>("SettingsTest:Usuario2:Login"), _configuration.GetValue<string>("SettingsTest:Usuario2:Senha"), _configuration.GetValue<EPrivilegioUsuario>("SettingsTest:Usuario2:Privilegio") ); Usuario3 = new Usuario( _configuration.GetValue<int>("SettingsTest:Usuario3:Id"), _configuration.GetValue<string>("SettingsTest:Usuario3:Login"), _configuration.GetValue<string>("SettingsTest:Usuario3:Senha"), _configuration.GetValue<EPrivilegioUsuario>("SettingsTest:Usuario3:Privilegio") ); Usuario1Editado = new Usuario( _configuration.GetValue<int>("SettingsTest:Usuario1Editado:Id"), _configuration.GetValue<string>("SettingsTest:Usuario1Editado:Login"), _configuration.GetValue<string>("SettingsTest:Usuario1Editado:Senha"), _configuration.GetValue<EPrivilegioUsuario>("SettingsTest:Usuario1Editado:Privilegio") ); #endregion Setando dados de teste para Usuario] #region [Setando dados de teste para LogRequestResponse] LogRequestResponse1 = new LogRequestResponse() { Id = _configuration.GetValue<int>("SettingsTest:LogRequestResponse1:Id"), MachineName = _configuration.GetValue<string>("SettingsTest:LogRequestResponse1:MachineName"), DataRequest = _configuration.GetValue<DateTime>("SettingsTest:LogRequestResponse1:DataRequest"), DataResponse = _configuration.GetValue<DateTime>("SettingsTest:LogRequestResponse1:DataResponse"), EndPoint = _configuration.GetValue<string>("SettingsTest:LogRequestResponse1:EndPoint"), Request = _configuration.GetValue<string>("SettingsTest:LogRequestResponse1:Request"), Response = _configuration.GetValue<string>("SettingsTest:LogRequestResponse1:Response"), TempoDuracao = _configuration.GetValue<long?>("SettingsTest:LogRequestResponse1:TempoDuracao") }; LogRequestResponse2 = new LogRequestResponse() { Id = _configuration.GetValue<int>("SettingsTest:LogRequestResponse2:Id"), MachineName = _configuration.GetValue<string>("SettingsTest:LogRequestResponse2:MachineName"), DataRequest = _configuration.GetValue<DateTime>("SettingsTest:LogRequestResponse2:DataRequest"), DataResponse = _configuration.GetValue<DateTime>("SettingsTest:LogRequestResponse2:DataResponse"), EndPoint = _configuration.GetValue<string>("SettingsTest:LogRequestResponse2:EndPoint"), Request = _configuration.GetValue<string>("SettingsTest:LogRequestResponse2:Request"), Response = _configuration.GetValue<string>("SettingsTest:LogRequestResponse2:Response"), TempoDuracao = _configuration.GetValue<long?>("SettingsTest:LogRequestResponse2:TempoDuracao") }; #endregion [Setando dados de teste para LogRequestResponse] } } }
54.469903
208
0.663981
[ "MIT" ]
lsantoss/ControleDespesas
ControleDespesas_ApiNetCore21_Dapper/ControleDespesas.Test/AppConfigurations/Settings/SettingsTest.cs
28,054
C#
using Volo.Abp.AspNetCore.Mvc.UI.Bundling; namespace EasyAbp.Abp.AspNetCore.Mvc.UI.Theme.LYear.Bundling { public class LYearThemeGlobalStyleContributor : BundleContributor { public override void ConfigureBundle(BundleConfigurationContext context) { context.Files.RemoveAll(x => x.Contains("bootstrap.css")); context.Files.Add("/themes/lyear/assets/css/bootstrap.min.css"); context.Files.Add("/themes/lyear/assets/css/materialdesignicons.min.css"); context.Files.Add("/themes/lyear/assets/css/style.min.css"); context.Files.Add("/themes/lyear/assets/css/custom.css"); } } }
39.470588
86
0.679583
[ "MIT" ]
EasyAbp/Abp.AspNetCore.Mvc.UI.Theme.LYear
src/Bundling/LYearThemeGlobalStyleContributor.cs
673
C#
namespace HareDu { public enum PolicyAppliedTo { All, Exchanges, Queues } }
12.333333
31
0.522523
[ "Apache-2.0" ]
ahives/HareDu1
src/HareDu/PolicyAppliedTo.cs
111
C#
using GMLParserPL.Configuration; using System.Collections.Generic; namespace GMLParserPL.Translators.BDOT { internal class BUZT_A : BuildingTranslator { public BUZT_A(string bdotClass, string filePath, Config config) : base(bdotClass, filePath, config) { } protected sealed override string GetObjectName(IDictionary<string, object> objectAsDict) { if (config.BUZT_A_IIPObj.ContainsKey(objectAsDict["idIIP"].ToString())) { return config.BUZT_A_IIPObj[objectAsDict["idIIP"].ToString()]; } if (config.BUZT_A_Obj.ContainsKey(objectAsDict["x_kod"].ToString())) return config.BUZT_A_Obj[objectAsDict["x_kod"].ToString()]; return null; } } }
31.64
107
0.638432
[ "MIT" ]
mcegla/GeodataLoaderPL-test
GMLParserPL/Translators/BDOT/BUZT_A.cs
793
C#
using System; using System.Collections.Generic; using System.Net.Mail; namespace Samples.DomainLayer.Persons { /// <summary> /// The person domain class. /// NOTE: The is an example for a fictitious domain. Do not use! /// </summary> public class Person { /// <summary> /// Gets or sets a persons date of birth. /// </summary> public BirthDate DateOfBirth { get; set; } /// <summary> /// Gets or sets the persons id. /// </summary> public Guid Id { get; set; } /// <summary> /// Gets or sets the last four digits. /// </summary> public int LastFourDigits { get; set; } /// <summary> /// Gets or sets the mail. /// </summary> public MailAddress MailAddress { get; set; } /// <summary> /// Gets or sets the persons name. /// </summary> public PersonsName Name { get; set; } /// <summary> /// Gets or sets the organizations the person belongs to. /// </summary> public IEnumerable<Organization> Organizations { get; set; } } }
26.744186
68
0.542609
[ "MIT" ]
Jan-Olof/samples
Samples.DomainLayer/Persons/Person.cs
1,152
C#
namespace Commandos.Model.Map { public class Abilities : NotParsed { public Abilities(object multipleRecords) : base(multipleRecords) { } } }
17.9
72
0.614525
[ "MIT" ]
fhnaseer/CommandosMissionEditor
Commandos.Model/Map/Abilities.cs
181
C#
//------------------------------------------------------------------------------ // <auto-generated> // 這段程式碼是由工具產生的。 // 執行階段版本:4.0.30319.42000 // // 對這個檔案所做的變更可能會造成錯誤的行為,而且如果重新產生程式碼, // 變更將會遺失。 // </auto-generated> //------------------------------------------------------------------------------ // // This source code was auto-generated by xsd, Version=4.0.30319.33440. // namespace Model.Schema.TurnKey.B0201 { using System.Xml.Serialization; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="urn:GEINV:eInvoiceMessage:B0201:3.1")] [System.Xml.Serialization.XmlRootAttribute(Namespace="urn:GEINV:eInvoiceMessage:B0201:3.1", IsNullable=false)] public partial class CancelAllowance { /// <remarks/> public string CancelAllowanceNumber; /// <remarks/> public string AllowanceDate; /// <remarks/> public string BuyerId; /// <remarks/> public string SellerId; /// <remarks/> public string CancelDate; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(DataType="time")] public System.DateTime CancelTime; /// <remarks/> public string CancelReason; /// <remarks/> public string Remark; } }
30.792453
116
0.558211
[ "MIT" ]
uxb2bralph/IFS-EIVO03
Models/Schema/TurnKey/B0201.cs
1,752
C#
//------------------------------------------------------------------------------- // <copyright file="IExtension.cs" company="Appccelerate"> // Copyright (c) 2008-2019 Appccelerate // // 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> //------------------------------------------------------------------------------- namespace Appccelerate.StateMachine.AsyncMachine { using System; using System.Collections.Generic; using System.Threading.Tasks; using Infrastructure; using States; using Transitions; /// <summary> /// Extensions for a state machine have to implement this interface. /// </summary> /// <typeparam name="TState">The type of the state.</typeparam> /// <typeparam name="TEvent">The type of the event.</typeparam> public interface IExtension<TState, TEvent> where TState : IComparable where TEvent : IComparable { /// <summary> /// Called after the state machine was started. /// </summary> /// <param name="stateMachine">The state machine.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> Task StartedStateMachine(IStateMachineInformation<TState, TEvent> stateMachine); /// <summary> /// Called after the state machine stopped. /// </summary> /// <param name="stateMachine">The state machine.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> Task StoppedStateMachine(IStateMachineInformation<TState, TEvent> stateMachine); /// <summary> /// Called after an events was queued. /// </summary> /// <param name="stateMachine">The state machine.</param> /// <param name="eventId">The event id.</param> /// <param name="eventArgument">The event argument.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> Task EventQueued(IStateMachineInformation<TState, TEvent> stateMachine, TEvent eventId, object eventArgument); /// <summary> /// Called after an events was queued with priority. /// </summary> /// <param name="stateMachine">The state machine.</param> /// <param name="eventId">The event id.</param> /// <param name="eventArgument">The event argument.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> Task EventQueuedWithPriority(IStateMachineInformation<TState, TEvent> stateMachine, TEvent eventId, object eventArgument); /// <summary> /// Called after the state machine switched states. /// </summary> /// <param name="stateMachine">The state machine.</param> /// <param name="oldStateDefinition">The old state.</param> /// <param name="newStateDefinition">The new state.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> Task SwitchedState( IStateMachineInformation<TState, TEvent> stateMachine, IStateDefinition<TState, TEvent> oldStateDefinition, IStateDefinition<TState, TEvent> newStateDefinition); /// <summary> /// Called when the state machine enters the initial state. /// </summary> /// <param name="stateMachine">The state machine.</param> /// <param name="state">The state.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> Task EnteringInitialState(IStateMachineInformation<TState, TEvent> stateMachine, TState state); /// <summary> /// Called when the state machine entered the initial state. /// </summary> /// <param name="stateMachine">The state machine.</param> /// <param name="state">The state.</param> /// <param name="context">The context.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> Task EnteredInitialState(IStateMachineInformation<TState, TEvent> stateMachine, TState state, ITransitionContext<TState, TEvent> context); /// <summary> /// Called when an event is firing on the state machine. /// </summary> /// <param name="stateMachine">The state machine.</param> /// <param name="eventId">The event id. Can be replaced by the extension.</param> /// <param name="eventArgument">The event argument. Can be replaced by the extension.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> Task FiringEvent( IStateMachineInformation<TState, TEvent> stateMachine, ref TEvent eventId, ref object eventArgument); /// <summary> /// Called when an event was fired on the state machine. /// </summary> /// <param name="stateMachine">The state machine.</param> /// <param name="context">The transition context.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> Task FiredEvent( IStateMachineInformation<TState, TEvent> stateMachine, ITransitionContext<TState, TEvent> context); /// <summary> /// Called before an entry action exception is handled. /// </summary> /// <param name="stateMachine">The state machine.</param> /// <param name="state">The state.</param> /// <param name="context">The context.</param> /// <param name="exception">The exception. Can be replaced by the extension.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> Task HandlingEntryActionException( IStateMachineInformation<TState, TEvent> stateMachine, IStateDefinition<TState, TEvent> state, ITransitionContext<TState, TEvent> context, ref Exception exception); /// <summary> /// Called after an entry action exception was handled. /// </summary> /// <param name="stateMachine">The state machine.</param> /// <param name="state">The state.</param> /// <param name="context">The context.</param> /// <param name="exception">The exception.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> Task HandledEntryActionException( IStateMachineInformation<TState, TEvent> stateMachine, IStateDefinition<TState, TEvent> state, ITransitionContext<TState, TEvent> context, Exception exception); /// <summary> /// Called before an exit action exception is handled. /// </summary> /// <param name="stateMachine">The state machine.</param> /// <param name="state">The state.</param> /// <param name="context">The context.</param> /// <param name="exception">The exception. Can be replaced by the extension.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> Task HandlingExitActionException( IStateMachineInformation<TState, TEvent> stateMachine, IStateDefinition<TState, TEvent> state, ITransitionContext<TState, TEvent> context, ref Exception exception); /// <summary> /// Called after an exit action exception was handled. /// </summary> /// <param name="stateMachine">The state machine.</param> /// <param name="state">The state.</param> /// <param name="context">The context.</param> /// <param name="exception">The exception.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> Task HandledExitActionException( IStateMachineInformation<TState, TEvent> stateMachine, IStateDefinition<TState, TEvent> state, ITransitionContext<TState, TEvent> context, Exception exception); /// <summary> /// Called before a guard exception is handled. /// </summary> /// <param name="stateMachine">The state machine.</param> /// <param name="transitionDefinition">The transition.</param> /// <param name="transitionContext">The transition context.</param> /// <param name="exception">The exception. Can be replaced by the extension.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> Task HandlingGuardException( IStateMachineInformation<TState, TEvent> stateMachine, ITransitionDefinition<TState, TEvent> transitionDefinition, ITransitionContext<TState, TEvent> transitionContext, ref Exception exception); /// <summary> /// Called after a guard exception was handled. /// </summary> /// <param name="stateMachine">The state machine.</param> /// <param name="transitionDefinition">The transition.</param> /// <param name="transitionContext">The transition context.</param> /// <param name="exception">The exception.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> Task HandledGuardException( IStateMachineInformation<TState, TEvent> stateMachine, ITransitionDefinition<TState, TEvent> transitionDefinition, ITransitionContext<TState, TEvent> transitionContext, Exception exception); /// <summary> /// Called before a transition exception is handled. /// </summary> /// <param name="stateMachine">The state machine.</param> /// <param name="transitionDefinition">The transition.</param> /// <param name="context">The context.</param> /// <param name="exception">The exception. Can be replaced by the extension.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> Task HandlingTransitionException( IStateMachineInformation<TState, TEvent> stateMachine, ITransitionDefinition<TState, TEvent> transitionDefinition, ITransitionContext<TState, TEvent> context, ref Exception exception); /// <summary> /// Called after a transition exception is handled. /// </summary> /// <param name="stateMachine">The state machine.</param> /// <param name="transitionDefinition">The transition.</param> /// <param name="transitionContext">The transition context.</param> /// <param name="exception">The exception.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> Task HandledTransitionException( IStateMachineInformation<TState, TEvent> stateMachine, ITransitionDefinition<TState, TEvent> transitionDefinition, ITransitionContext<TState, TEvent> transitionContext, Exception exception); /// <summary> /// Called when a guard of a transition returns false and therefore the transition is not executed. /// </summary> /// <param name="stateMachineInformation">The state machine.</param> /// <param name="transitionDefinition">The transition.</param> /// <param name="context">The transition context.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> Task SkippedTransition( IStateMachineInformation<TState, TEvent> stateMachineInformation, ITransitionDefinition<TState, TEvent> transitionDefinition, ITransitionContext<TState, TEvent> context); /// <summary> /// Called when a transition is going to be executed. After the guard of the transition evaluated to true. /// </summary> /// <param name="stateMachineInformation">The state machine.</param> /// <param name="transitionDefinition">The transition.</param> /// <param name="context">The transition context.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> Task ExecutingTransition( IStateMachineInformation<TState, TEvent> stateMachineInformation, ITransitionDefinition<TState, TEvent> transitionDefinition, ITransitionContext<TState, TEvent> context); /// <summary> /// Called when a transition was executed. /// </summary> /// <param name="stateMachineInformation">The state machine.</param> /// <param name="transitionDefinition">The transition.</param> /// <param name="context">The transition context.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> Task ExecutedTransition( IStateMachineInformation<TState, TEvent> stateMachineInformation, ITransitionDefinition<TState, TEvent> transitionDefinition, ITransitionContext<TState, TEvent> context); Task EnteringState( IStateMachineInformation<TState, TEvent> stateMachineInformation, IStateDefinition<TState, TEvent> state, ITransitionContext<TState, TEvent> context); void Loaded( IStateMachineInformation<TState, TEvent> stateMachineInformation, IInitializable<TState> loadedCurrentState, IReadOnlyDictionary<TState, TState> loadedHistoryStates); } }
52.039568
147
0.625354
[ "Apache-2.0" ]
wtjerry/statemachine
source/Appccelerate.StateMachine/AsyncMachine/IExtension.cs
14,467
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; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.CloudPhoto.Model.V20170711; namespace Aliyun.Acs.CloudPhoto.Transform.V20170711 { public class ListPhotosResponseUnmarshaller { public static ListPhotosResponse Unmarshall(UnmarshallerContext context) { ListPhotosResponse listPhotosResponse = new ListPhotosResponse(); listPhotosResponse.HttpResponse = context.HttpResponse; listPhotosResponse.Code = context.StringValue("ListPhotos.Code"); listPhotosResponse.Message = context.StringValue("ListPhotos.Message"); listPhotosResponse.NextCursor = context.StringValue("ListPhotos.NextCursor"); listPhotosResponse.TotalCount = context.IntegerValue("ListPhotos.TotalCount"); listPhotosResponse.RequestId = context.StringValue("ListPhotos.RequestId"); listPhotosResponse.Action = context.StringValue("ListPhotos.Action"); List<ListPhotosResponse.ListPhotos_Photo> listPhotosResponse_photos = new List<ListPhotosResponse.ListPhotos_Photo>(); for (int i = 0; i < context.Length("ListPhotos.Photos.Length"); i++) { ListPhotosResponse.ListPhotos_Photo photo = new ListPhotosResponse.ListPhotos_Photo(); photo.Id = context.LongValue("ListPhotos.Photos["+ i +"].Id"); photo.IdStr = context.StringValue("ListPhotos.Photos["+ i +"].IdStr"); photo.Title = context.StringValue("ListPhotos.Photos["+ i +"].Title"); photo.FileId = context.StringValue("ListPhotos.Photos["+ i +"].FileId"); photo.Location = context.StringValue("ListPhotos.Photos["+ i +"].Location"); photo.State = context.StringValue("ListPhotos.Photos["+ i +"].State"); photo.Md5 = context.StringValue("ListPhotos.Photos["+ i +"].Md5"); photo.IsVideo = context.BooleanValue("ListPhotos.Photos["+ i +"].IsVideo"); photo.Remark = context.StringValue("ListPhotos.Photos["+ i +"].Remark"); photo.Size = context.LongValue("ListPhotos.Photos["+ i +"].Size"); photo.Width = context.LongValue("ListPhotos.Photos["+ i +"].Width"); photo.Height = context.LongValue("ListPhotos.Photos["+ i +"].Height"); photo.Ctime = context.LongValue("ListPhotos.Photos["+ i +"].Ctime"); photo.Mtime = context.LongValue("ListPhotos.Photos["+ i +"].Mtime"); photo.TakenAt = context.LongValue("ListPhotos.Photos["+ i +"].TakenAt"); photo.InactiveTime = context.LongValue("ListPhotos.Photos["+ i +"].InactiveTime"); photo.ShareExpireTime = context.LongValue("ListPhotos.Photos["+ i +"].ShareExpireTime"); listPhotosResponse_photos.Add(photo); } listPhotosResponse.Photos = listPhotosResponse_photos; return listPhotosResponse; } } }
50.142857
122
0.725356
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-cloudphoto/CloudPhoto/Transform/V20170711/ListPhotosResponseUnmarshaller.cs
3,510
C#
using System; using System.Linq; using System.Linq.Expressions; using Microsoft.VisualStudio.TestTools.UnitTesting; using TableDependency.SqlClient.Where.UnitTests.Models; using Expression = NCalc.Expression; namespace TableDependency.SqlClient.Where.UnitTests { [TestClass] public class UnitTestMoreCondition { [TestMethod] public void MoreConditions1() { var ids = new[] { 1, 2, 3 }; // Arrange Expression<Func<Product, bool>> expression = p => ids.Contains(p.Id) && p.Code.Trim().Substring(0, 3).Equals("WWW"); // Act var where = new SqlTableDependencyFilter<Product>(expression).Translate(); // Assert Assert.AreEqual("([Id] IN (1,2,3) AND SUBSTRING(LTRIM(RTRIM([Code])), 0, 3) = 'WWW')", where); } [TestMethod] public void MoreConditions2() { var ids = new[] { 1, 2, 3 }; // Arrange Expression<Func<Product, bool>> expression = p => ids.Contains(p.Id) && p.Code.Trim().Substring(0, 3).Equals("WWW") && p.Id == 100; // Act var where = new SqlTableDependencyFilter<Product>(expression).Translate(); // Assert Assert.AreEqual("(([Id] IN (1,2,3) AND SUBSTRING(LTRIM(RTRIM([Code])), 0, 3) = 'WWW') AND ([Id] = 100))", where); } [TestMethod] public void MoreConditions3() { var ids = new[] { 1 }; // Arrange Expression<Func<Product, bool>> expression = p => ids.Contains(p.Id) || (p.Code.Equals("WWW") && p.Code.Substring(0, 3) == "22"); // Act var where = new SqlTableDependencyFilter<Product>(expression).Translate(); // Assert Assert.AreEqual("([Id] IN (1) OR ([Code] = 'WWW' AND (SUBSTRING([Code], 0, 3) = '22')))", where); } [TestMethod] public void MoreConditions4() { var ids = new[] { 1 }; // Arrange Expression<Func<Product, bool>> expression = p => ids.Contains(p.Id) || p.Code.Equals("WWW") && p.Code.Substring(0, 3) == "22" || p.ExcangeRate > 1; // Act var where = new SqlTableDependencyFilter<Product>(expression).Translate(); // Assert Assert.AreEqual("(([Id] IN (1) OR ([Code] = 'WWW' AND (SUBSTRING([Code], 0, 3) = '22'))) OR ([ExcangeRate] > 1))", where); } [TestMethod] public void MoreConditions5() { // 1 OR 0 AND 0 => 0 // (1 OR 0) AND 0 => 0 // 1 OR (0 AND 0) => 1 // Arrange Expression<Func<Product, bool>> expression1 = p => p.Id == 1 || p.Id == 0 && p.Id == 0; Expression<Func<Product, bool>> expression2 = p => (p.Id == 1 || p.Id == 0) && p.Id == 0; Expression<Func<Product, bool>> expression3 = p => p.Id == 1 || (p.Id == 0 && p.Id == 0); // Act var where1 = new SqlTableDependencyFilter<Product>(expression1).Translate(); var where2 = new SqlTableDependencyFilter<Product>(expression2).Translate(); var where3 = new SqlTableDependencyFilter<Product>(expression3).Translate(); // Assert Assert.AreEqual("(([Id] = 1) OR (([Id] = 0) AND ([Id] = 0)))", where1); Assert.AreEqual("((([Id] = 1) OR ([Id] = 0)) AND ([Id] = 0))", where2); Assert.AreEqual("(([Id] = 1) OR (([Id] = 0) AND ([Id] = 0)))", where3); var expr1 = where1.Replace("[Id] = ", string.Empty).Replace("1", "true").Replace("0", "false").Replace("OR", "||").Replace("AND", "&&"); var result1 = new Expression(expr1).Evaluate(); Assert.AreEqual(true, result1); var expr2 = where2.Replace("[Id] = ", string.Empty).Replace("1", "true").Replace("0", "false").Replace("OR", "||").Replace("AND", "&&"); var result2 = new Expression(expr2).Evaluate(); Assert.AreEqual(false, result2); var expr3 = where3.Replace("[Id] = ", string.Empty).Replace("1", "true").Replace("0", "false").Replace("OR", "||").Replace("AND", "&&"); var result3 = new Expression(expr3).Evaluate(); Assert.AreEqual(true, result3); } } }
37.275
148
0.508384
[ "MIT" ]
GeorgeR/monitor-table-change-with-sqltabledependency
Tests/TableDependency.SqlClient.Where.UnitTests/UnitTestMoreCondition.cs
4,475
C#
namespace Autofac.TypedFactories.Test.TestDomain { public class ConcreteDependencyService { } }
18
49
0.740741
[ "MIT" ]
salfab/Autofac.TypedFactories
src/Autofac.TypedFactories.Test/TestDomain/ConcreteDependencyService.cs
110
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using GitTrendingApi.Models; using GitTrendingApi.Utils; using HtmlAgilityPack; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; namespace GitTrendingApi.Controllers { [Produces("application/json")] [Route("api/Repo")] public class RepoController : Controller { static HttpClient Web = new HttpClient(); [Route("Search")] public async Task<Repo> SearchRepo([FromQuery]string Owner, [FromQuery]string Repo) { return await RepoUtil.GetRepoAsync(Owner, Repo); } [Route("ReadMe/Download")] public async Task<IActionResult> DownloadReadMe([FromQuery]string Owner, [FromQuery]string Repo, [FromQuery]ReadMeFormat Format = ReadMeFormat.Markdown) { var readme = await GetReadMe(Owner, Repo, Format); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); switch (Format) { case ReadMeFormat.Markdown: { return File(Encoding.UTF8.GetBytes(readme.Content), "application/octet-stream", $"{Owner}-{Repo}.README.md"); } case ReadMeFormat.Html: { return File(Encoding.UTF8.GetBytes(readme.Content), "application/octet-stream", $"{Owner}-{Repo}.README.html"); } default: return null; } } [Route("ReadMe")] public async Task<ReadMeResponse> GetReadMe([FromQuery]string Owner, [FromQuery]string Repo, [FromQuery]ReadMeFormat Format = ReadMeFormat.Markdown) { var readme = await RepoUtil.GetReadMeAsync(Owner, Repo); if (readme != null) { switch (Format) { case ReadMeFormat.Markdown: { return new ReadMeResponse() { Content = readme.GetContent(), Format = Format, Owner=Owner, Repo=Repo }; } case ReadMeFormat.Html: { return new ReadMeResponse() { Content = await readme.GetHtmlAsync(), Format = Format, Owner = Owner, Repo = Repo }; } default: { return null; } } } else { return null; } } [Route("Trending")] public async Task<IEnumerable<TrendingRepo>> GetTrending([FromQuery]string Period = "daily", [FromQuery]string Language = "") { List<TrendingRepo> Repos = new List<TrendingRepo>(); using (var Web = new HttpClient()) { var result = await Web.GetAsync(TrendingReposUtil.GetUrl(Period, Language)); if (result.IsSuccessStatusCode) { var htmlData = await result.Content.ReadAsStringAsync(); var doc = new HtmlDocument(); doc.LoadHtml(htmlData); var baseRepos = doc.DocumentNode.Descendants().Where(x => x.Name == "ol").Select(x => x.ChildNodes).First().Where(x => x.Name == "li").Select(x => x); foreach (HtmlNode repo in baseRepos) { var tempTrendingRepo = new TrendingRepo(); var childDivs = repo.ChildNodes.Where(x => x.Name == "div").Where(x => x.HasAttributes).Where(x => x.GetAttributeValue("class", "") != "float-right"); var repoOwnerData = childDivs.ElementAt(0).ChildNodes.Where(x => x.Name == "h3").First().ChildNodes.Where(x => x.Name == "a").First().ChildNodes; tempTrendingRepo.RepoOwner = TrendingReposUtil.GetRepoOwner(repoOwnerData); tempTrendingRepo.RepoTitle = TrendingReposUtil.GetRepoTitle(repoOwnerData); tempTrendingRepo.RepoDescription = TrendingReposUtil.GetRepoDescription(childDivs.ElementAt(1)); tempTrendingRepo.Language = TrendingReposUtil.GetRepoLanguage(childDivs.ElementAt(2)); tempTrendingRepo.Stars = TrendingReposUtil.GetRepoStars(childDivs.ElementAt(2)); tempTrendingRepo.Forks = TrendingReposUtil.GetRepoForks(childDivs.ElementAt(2)); tempTrendingRepo.StarsToday = TrendingReposUtil.GetRepoStarsToday(childDivs.ElementAt(2)); Repos.Add(tempTrendingRepo); } } } return Repos.OrderByDescending(x=>x.StarsToday); } } }
38.029851
174
0.541209
[ "MIT" ]
BaileysBlog/GitHubTrending
utils/GitTrendingApi/Controllers/RepoController.cs
5,098
C#
using System; namespace NetTelegramBotApi.Types { /// <summary> /// This object represents a venue. /// </summary> public class Venue { /// <summary> /// Venue location /// </summary> public Location Location { get; set; } /// <summary> /// Name of the venue /// </summary> public string Title { get; set; } /// <summary> /// Address of the venue /// </summary> public string Address { get; set; } /// <summary> /// Optional. Foursquare identifier of the venue /// </summary> public string foursquareId { get; set; } } }
21.870968
56
0.504425
[ "MIT" ]
DLMANSOFT/NetTelegramBotApi
NetTelegramBotApi/Types/Venue.cs
680
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(ExampleAPI.Startup))] namespace ExampleAPI { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); } } }
17.315789
51
0.671733
[ "MIT" ]
edgardolopez/RestDemo
REST/ExampleAPI/Startup.cs
331
C#
// ---------------------------------------------------------------------------- // This source code is provided only under the Creative Commons licensing terms stated below. // HVWC Multiplayer Platform alpha v1 by Institute for Digital Intermedia Arts at Ball State University \is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. // Based on a work at https://github.com/HVWC/HVWC. // Work URL: http://idialab.org/mellon-foundation-humanities-virtual-world-consortium/ // Permissions beyond the scope of this license may be available at http://idialab.org/info/. // To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/deed.en_US. // ---------------------------------------------------------------------------- using UnityEngine; using DrupalUnity; /// <summary> /// This class handles the movement of the nav mesh agent on the nav mesh. /// </summary> public class AgentController : MonoBehaviour { #region Fields /// <summary> /// The nav mesh agent. /// </summary> public UnityEngine.AI.NavMeshAgent navMeshAgent; /// <summary> /// The destination of this nav mesh agent. /// </summary> Vector3 destination; #endregion #region Unity Messages /// <summary> /// A message called when the script is enabled. /// </summary> void OnEnable() { DrupalUnityIO.OnPlacardSelected += OnPlacardSelected; } /// <summary> /// A message called when the script updates. /// </summary> void Update () { if(navMeshAgent.isOnNavMesh) { if(!navMeshAgent.pathPending) { navMeshAgent.SetDestination(destination); if(navMeshAgent.remainingDistance <= navMeshAgent.stoppingDistance) { if(!navMeshAgent.hasPath || navMeshAgent.velocity.sqrMagnitude == 0f) { navMeshAgent.Stop(); } } } } } /// <summary> /// A message called when the script is disabled. /// </summary> void OnDisable() { DrupalUnityIO.OnPlacardSelected -= OnPlacardSelected; } #endregion #region Callbacks /// <summary> /// A callback called when a placard is selected in the Drupal Unity Interface. /// </summary> /// <param name="placard"></param> void OnPlacardSelected(Placard placard) { destination = GeographicManager.Instance.GetPosition(placard.location.latitude, placard.location.longitude, placard.location.elevation); navMeshAgent.Resume(); } #endregion }
37.457143
205
0.615942
[ "MIT" ]
dh-199-the-shape-of-roman-history/Roman-Funeral-and-Family
Unity/UnityBuildFiles/AllFunerals/Assets/Scripts/IDIA/Player/AgentController.cs
2,624
C#
using System; using Gw2Sharp.Json.Converters; using Gw2Sharp.WebApi.V2.Models; using Xunit; namespace Gw2Sharp.Tests.Json.Converters { public class BottomUpRectangleConverterTests { [Fact] public void NoWriteTest() { var converter = new BottomUpRectangleConverter(); Assert.Throws<NotImplementedException>(() => converter.Write(default!, default!, default!)); } [Fact] public void CanConvertTest() { var converter = new BottomUpRectangleConverter(); Assert.True(converter.CanConvert(typeof(Rectangle))); } } }
25.44
104
0.632075
[ "MIT" ]
Archomeda/Gw2Sharp
Gw2Sharp.Tests/Json/Converters/BottomUpRectangleConverterTests.cs
636
C#
/* * Copyright 2018 JDCLOUD.COM * * 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. * * SCDN相关接口 * Openapi For JCLOUD cdn * * OpenAPI spec version: v1 * Contact: pid-cdn@jd.com * * NOTE: This class is auto generated by the jdcloud code generator program. */ using JDCloudSDK.Core.Client; using JDCloudSDK.Core.Http; using System; using System.Collections.Generic; using System.Text; namespace JDCloudSDK.Cdn.Client { /// <summary> /// 查询waf地域信息 /// </summary> public class QueryWafRegionsExecutor : JdcloudExecutor { /// <summary> /// 查询waf地域信息接口的Http 请求方法 /// </summary> public override string Method { get { return "GET"; } } /// <summary> /// 查询waf地域信息接口的Http资源请求路径 /// </summary> public override string Url { get { return "/wafRegions"; } } } }
24.45
76
0.625085
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net
sdk/src/Service/Cdn/Client/QueryWafRegionsExecutor.cs
1,543
C#
using PlayGen.ITAlert.Photon.Players.Extensions; using PlayGen.Photon.Players; namespace PlayGen.ITAlert.Photon.Players { // ReSharper disable once InconsistentNaming public class ITAlertPlayerManager : PlayerManager<ITAlertPlayer> { public override ITAlertPlayer Create(int photonId, int? externalId = null, string name = null) { if (name == null) { name = $"player_{photonId}"; } var playerColour = Players.GetUnusedGlyph(); var player = new ITAlertPlayer { PhotonId = photonId, ExternalId = externalId, Name = name, Glyph = playerColour.Glyph, Colour = playerColour.Colour }; _players[photonId] = player; OnPlayersUpdated(); return player; } } }
20.685714
96
0.694751
[ "Apache-2.0" ]
playgen/it-alert
Server/PlayGen.ITAlert.Photon.Players/ITAlertPlayerManager.cs
726
C#
using Microsoft.EntityFrameworkCore.Design; using Microsoft.EntityFrameworkCore.Design.Internal; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Scaffolding; using Microsoft.Extensions.DependencyInjection; using RevEng.Shared; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace RevEng.Core { public class ReverseEngineerRunner { public static ReverseEngineerResult GenerateFiles(ReverseEngineerCommandOptions options) { var errors = new List<string>(); var warnings = new List<string>(); var reporter = new OperationReporter( new OperationReportHandler( m => errors.Add(m), m => warnings.Add(m))); var serviceProvider = ServiceProviderBuilder.Build(options); var scaffolder = serviceProvider.GetService<IReverseEngineerScaffolder>(); var schemas = new List<string>(); options.ConnectionString = SqlServerHelper.SetConnectionString(options.DatabaseType, options.ConnectionString); if (options.DefaultDacpacSchema != null) { schemas.Add(options.DefaultDacpacSchema); } if (options.FilterSchemas) { schemas.AddRange(options.Schemas.Select(s => s.Name)); } if (options.UseNoObjectFilter) { options.Tables = new List<SerializationTableModel>(); } foreach (var table in options.Tables) { table.Name = table.Name.Replace("'", "''"); } var outputDir = !string.IsNullOrEmpty(options.OutputPath) ? Path.IsPathFullyQualified(options.OutputPath) ? options.OutputPath : Path.GetFullPath(Path.Combine(options.ProjectPath, options.OutputPath)) : options.ProjectPath; var outputContextDir = !string.IsNullOrEmpty(options.OutputContextPath) ? Path.IsPathFullyQualified(options.OutputContextPath) ? options.OutputContextPath : Path.GetFullPath(Path.Combine(options.ProjectPath, options.OutputContextPath)) : outputDir; var modelNamespace = string.Empty; var contextNamespace = string.Empty; if (string.IsNullOrEmpty(options.ProjectRootNamespace)) { modelNamespace = !string.IsNullOrEmpty(options.ModelNamespace) ? options.ModelNamespace : PathHelper.GetNamespaceFromOutputPath(outputDir, options.ProjectPath, options.ProjectRootNamespace); contextNamespace = !string.IsNullOrEmpty(options.ContextNamespace) ? options.ContextNamespace : PathHelper.GetNamespaceFromOutputPath(outputContextDir, options.ProjectPath, options.ProjectRootNamespace); } else { modelNamespace = !string.IsNullOrEmpty(options.ModelNamespace) ? options.ProjectRootNamespace + "." + options.ModelNamespace : PathHelper.GetNamespaceFromOutputPath(outputDir, options.ProjectPath, options.ProjectRootNamespace); contextNamespace = !string.IsNullOrEmpty(options.ContextNamespace) ? options.ProjectRootNamespace + "." + options.ContextNamespace : PathHelper.GetNamespaceFromOutputPath(outputContextDir, options.ProjectPath, options.ProjectRootNamespace); } var entityTypeConfigurationPaths = new List<string>(); SavedModelFiles procedurePaths = null; SavedModelFiles functionPaths = null; SavedModelFiles filePaths = ReverseEngineerScaffolder.GenerateDbContext(options, serviceProvider, schemas, outputContextDir, modelNamespace, contextNamespace); if (options.SelectedToBeGenerated != 2) { procedurePaths = ReverseEngineerScaffolder.GenerateStoredProcedures(options, ref errors, serviceProvider, outputContextDir, modelNamespace, contextNamespace); functionPaths = ReverseEngineerScaffolder.GenerateFunctions(options, ref errors, serviceProvider, outputContextDir, modelNamespace, contextNamespace); #if CORE50 || CORE60 if (functionPaths != null) { var dbContextLines = File.ReadAllLines(filePaths.ContextFile).ToList(); var index = dbContextLines.IndexOf(" OnModelCreatingPartial(modelBuilder);"); if (index != -1) { dbContextLines.Insert(index, " OnModelCreatingGeneratedFunctions(modelBuilder);"); File.WriteAllLines(filePaths.ContextFile, dbContextLines); } } #endif RemoveFragments(filePaths.ContextFile, options.ContextClassName, options.IncludeConnectionString, options.UseNoDefaultConstructor); if (!options.UseHandleBars) { PostProcess(filePaths.ContextFile); } entityTypeConfigurationPaths = SplitDbContext(filePaths.ContextFile, options.UseDbContextSplitting, contextNamespace, options.UseNullableReferences); } else if (options.SelectedToBeGenerated == 2 && (options.Tables.Count(t => t.ObjectType == ObjectType.Procedure) > 0 || options.Tables.Count(t => t.ObjectType == ObjectType.ScalarFunction) > 0)) { warnings.Add("Selected stored procedures/scalar functions will not be generated, as 'Entity Types only' was selected"); } if (!options.UseHandleBars) { foreach (var file in filePaths.AdditionalFiles) { PostProcess(file); } } var cleanUpPaths = CreateCleanupPaths(procedurePaths, functionPaths, filePaths); CleanUp(cleanUpPaths, entityTypeConfigurationPaths, outputDir); var allfiles = filePaths.AdditionalFiles.ToList(); if (procedurePaths != null) { allfiles.AddRange(procedurePaths.AdditionalFiles); allfiles.Add(procedurePaths.ContextFile); } if (functionPaths != null) { allfiles.AddRange(functionPaths.AdditionalFiles); allfiles.Add(functionPaths.ContextFile); } var result = new ReverseEngineerResult { EntityErrors = errors, EntityWarnings = warnings, EntityTypeFilePaths = allfiles, ContextFilePath = filePaths.ContextFile, ContextConfigurationFilePaths = entityTypeConfigurationPaths, }; return result; } private static SavedModelFiles CreateCleanupPaths(SavedModelFiles procedurePaths, SavedModelFiles functionPaths, SavedModelFiles filePaths) { var cleanUpPaths = new SavedModelFiles(filePaths.ContextFile, filePaths.AdditionalFiles); if (procedurePaths != null) { cleanUpPaths.AdditionalFiles.Add(procedurePaths.ContextFile); foreach (var additionalFile in procedurePaths.AdditionalFiles) { cleanUpPaths.AdditionalFiles.Add(additionalFile); } } if (functionPaths != null) { cleanUpPaths.AdditionalFiles.Add(functionPaths.ContextFile); foreach (var additionalFile in functionPaths.AdditionalFiles) { cleanUpPaths.AdditionalFiles.Add(additionalFile); } } return cleanUpPaths; } private static List<string> SplitDbContext(string contextFile, bool useDbContextSplitting, string contextNamespace, bool supportNullable) { if (!useDbContextSplitting) { return new List<string>(); } return DbContextSplitter.Split(contextFile, contextNamespace, supportNullable); } private static void RemoveFragments(string contextFile, string contextName, bool includeConnectionString, bool removeDefaultConstructor) { if (string.IsNullOrEmpty(contextFile)) { return; } var finalLines = new List<string>(); var lines = File.ReadAllLines(contextFile).ToList(); if (removeDefaultConstructor) { var index = lines.IndexOf($" public {contextName}()"); if (index != -1) { lines.RemoveAt(index + 3); lines.RemoveAt(index + 2); lines.RemoveAt(index + 1); lines.RemoveAt(index); } } int i = 1; var inConfiguring = false; foreach (var line in lines) { if (!includeConnectionString) { if (line.Trim().Contains("protected override void OnConfiguring")) { inConfiguring = true; continue; } if (inConfiguring && line.Trim() != string.Empty) { continue; } if (inConfiguring && line.Trim() == string.Empty) { inConfiguring = false; continue; } } finalLines.Add(line); i++; } File.WriteAllLines(contextFile, finalLines, Encoding.UTF8); } private static void PostProcess(string file) { if (string.IsNullOrEmpty(file)) { return; } var text = File.ReadAllText(file, Encoding.UTF8); File.WriteAllText(file, PathHelper.Header + Environment.NewLine + text.Replace(";Command Timeout=300", string.Empty, StringComparison.OrdinalIgnoreCase) .Replace(";Trust Server Certificate=True", string.Empty, StringComparison.OrdinalIgnoreCase) .TrimEnd(), Encoding.UTF8) ; } private static void CleanUp(SavedModelFiles filePaths, List<string> entityTypeConfigurationPaths, string outputDir) { var allGeneratedFiles = filePaths.AdditionalFiles.Select(s => Path.GetFullPath(s)).Concat(entityTypeConfigurationPaths).ToHashSet(); if (!string.IsNullOrEmpty(filePaths.ContextFile)) { var contextFolderFiles = Directory.GetFiles(Path.GetDirectoryName(filePaths.ContextFile), "*.cs"); allGeneratedFiles = filePaths.AdditionalFiles.Select(s => Path.GetFullPath(s)).Concat(new List<string> { Path.GetFullPath(filePaths.ContextFile) }).Concat(entityTypeConfigurationPaths).ToHashSet(); foreach (var contextFolderFile in contextFolderFiles) { if (allGeneratedFiles.Contains(contextFolderFile, StringComparer.OrdinalIgnoreCase)) { continue; } TryRemoveFile(contextFolderFile); } } if (filePaths.AdditionalFiles.Count == 0) return; var allowedFolders = allGeneratedFiles.Select(s => Path.GetDirectoryName(s)).Distinct().ToHashSet(); foreach (var modelFile in Directory.GetFiles(outputDir, "*.cs", SearchOption.AllDirectories)) { if (allGeneratedFiles.Contains(modelFile, StringComparer.OrdinalIgnoreCase)) { continue; } if (allowedFolders.Contains(Path.GetDirectoryName(modelFile))) { TryRemoveFile(modelFile); } } } private static void TryRemoveFile(string codeFile) { string firstLine; using (var reader = new StreamReader(codeFile, Encoding.UTF8)) { firstLine = reader.ReadLine() ?? ""; } if (firstLine == PathHelper.Header) { try { File.Delete(codeFile); } catch { } } } } }
39.82716
213
0.569203
[ "MIT" ]
Habiba618/EFCorePowerTools
src/GUI/RevEng.Core/ReverseEngineerRunner.cs
12,906
C#
using Newtonsoft.Json; namespace Nest { [JsonObject] public class ShardIndexing { /// <summary> /// Returns the currently in-flight delete operations /// </summary> [JsonProperty("delete_current")] public long DeleteCurrent { get; internal set; } /// <summary> /// The total amount of time spend on executing delete operations. /// </summary> [JsonProperty("delete_time_in_millis")] public long DeleteTimeInMilliseconds { get; internal set; } /// <summary> /// Returns the number of delete operation executed /// </summary> [JsonProperty("delete_total")] public long DeleteTotal { get; internal set; } /// <summary> /// Returns the currently in-flight indexing operations. /// </summary> [JsonProperty("index_current")] public long IndexCurrent { get; internal set; } /// <summary> /// The number of failed indexing operations /// </summary> [JsonProperty("index_failed")] public long IndexFailed { get; internal set; } /// <summary> /// The total amount of time spend on executing index operations. /// </summary> [JsonProperty("index_time_in_millis")] public long IndexTimeInMilliseconds { get; internal set; } /// <summary> /// The total number of indexing operations /// </summary> [JsonProperty("index_total")] public long IndexTotal { get; internal set; } /// <summary> /// Returns if the index is under merge throttling control /// </summary> [JsonProperty("is_throttled")] public bool IsThrottled { get; internal set; } /// <summary> /// Returns the number of noop update operations /// </summary> [JsonProperty("noop_update_total")] public long NoopUpdateTotal { get; internal set; } /// <summary> /// Gets the amount of time that the index has been under merge throttling control /// </summary> [JsonProperty("throttle_time_in_millis")] public long ThrottleTimeInMilliseconds { get; internal set; } } }
27.942029
84
0.688278
[ "Apache-2.0" ]
Henr1k80/elasticsearch-net
src/Nest/Indices/Monitoring/IndicesStats/ShardIndexing.cs
1,930
C#
//////////////////////////////////////////////////////////////////////////////// //EF Core Provider for LCPI OLE DB. // IBProvider and Contributors. 31.03.2021. using System; using System.Diagnostics; using System.Reflection; namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Dbms.Firebird.V03_0_0.Query.Local.D0.Expressions.Op2.Code{ //////////////////////////////////////////////////////////////////////////////// //using using T_ARG1 =System.Decimal; using T_ARG2 =System.Nullable<System.Double>; using T_RESULT =System.Nullable<System.Double>; //////////////////////////////////////////////////////////////////////////////// //class Op2_Code__Subtract___Decimal__NullableDouble static class Op2_Code__Subtract___Decimal__NullableDouble { public static readonly System.Reflection.MethodInfo MethodInfo_V_V =typeof(Op2_Code__Subtract___Decimal__NullableDouble) .GetTypeInfo() .GetDeclaredMethod(nameof(Exec_V_V)); //----------------------------------------------------------------------- private static T_RESULT Exec_V_V(T_ARG1 a,T_ARG2 b) { if(!b.HasValue) return null; Debug.Assert(b.HasValue); return Op2_Code__Subtract___Decimal__Double.Exec_V_V (a, b.Value); }//Exec_V_V };//class Op2_Code__Subtract___Decimal__NullableDouble //////////////////////////////////////////////////////////////////////////////// }//namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Dbms.Firebird.V03_0_0.Query.Local.D0.Expressions.Op2.Code
33.212766
130
0.573991
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Code/Provider/Source/Basement/EF/Dbms/Firebird/V03_0_0/Query/Local/D0/Expressions/Op2/Code/Subtract/Decimal/Op2_Code__Subtract___Decimal__NullableDouble.cs
1,563
C#
using System.Text.Json.Serialization; using PlatformRacing3.Server.Game.Communication.Messages.Incoming.Json; using PlatformRacing3.Server.Game.Lobby; namespace PlatformRacing3.Server.Game.Communication.Messages.Outgoing.Json { internal sealed class JsonForceMatchOutgoingMessage : JsonPacket { private protected override string InternalType => "force_match"; [JsonPropertyName("roomName")] public string Name { get; set; } [JsonPropertyName("levelID")] public uint LevelId { get; set; } [JsonPropertyName("levelTitle")] public string LevelTitle { get; set; } [JsonPropertyName("version")] public uint LevelVersion { get; set; } [JsonPropertyName("creatorID")] public uint CreatorId { get; set; } [JsonPropertyName("creatorName")] public string CreatorName { get; set; } [JsonPropertyName("levelType")] public string LevelMod { get; set; } [JsonPropertyName("likes")] public uint Likes { get; } [JsonPropertyName("dislikes")] public uint Dislikes { get; } [JsonPropertyName("minRank")] public uint MinRank { get; } [JsonPropertyName("maxRank")] public uint MaxRank { get; } [JsonPropertyName("maxMembers")] public uint MaxMembers { get; } internal JsonForceMatchOutgoingMessage(MatchListing matchListing) { this.Name = matchListing.Name; this.LevelId = matchListing.LevelId; this.LevelTitle = matchListing.LevelTitle; this.LevelVersion = matchListing.LevelVersion; this.CreatorId = matchListing.CreatorId; this.CreatorName = matchListing.CreatorName; string mode = matchListing.LevelMod.ToString(); this.LevelMod = char.ToLowerInvariant(mode[0]) + mode[1..]; this.Likes = matchListing.Likes; this.Dislikes = matchListing.Dislikes; this.MinRank = matchListing.MinRank; this.MaxRank = matchListing.MaxRank; this.MaxMembers = matchListing.MaxMembers; } } }
32.757576
74
0.637373
[ "MIT" ]
CoralCOasa/PlatformRacing3
PlatformRacing3.Server/Game/Communication/Messages/Outgoing/Json/JsonForceMatchOutgoingMessage.cs
2,164
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.md file in the project root for more information. using Microsoft.VisualStudio.ProjectSystem; using Xunit; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.Threading.Tasks { public class TaskDelaySchedulerTests { [Fact] public async Task ScheduleAsyncTask_RunsAsyncMethod() { using var scheduler = new TaskDelayScheduler(TimeSpan.FromMilliseconds(10), IProjectThreadingServiceFactory.Create(), CancellationToken.None); bool taskRan = false; var task = scheduler.ScheduleAsyncTask(ct => { taskRan = true; return Task.CompletedTask; }); await task; Assert.True(taskRan); } [Fact] public async Task ScheduleAsyncTask_SkipsPendingTasks() { using var scheduler = new TaskDelayScheduler(TimeSpan.FromMilliseconds(250), IProjectThreadingServiceFactory.Create(), CancellationToken.None); var tasksRun = new bool[3]; var task1 = scheduler.ScheduleAsyncTask(ct => { tasksRun[0] = true; return Task.CompletedTask; }); var task2 = scheduler.ScheduleAsyncTask(ct => { tasksRun[1] = true; return Task.CompletedTask; }); var task3 = scheduler.ScheduleAsyncTask(ct => { tasksRun[2] = true; return Task.CompletedTask; }); await task1; await task2; await task3; Assert.False(tasksRun[0]); Assert.False(tasksRun[1]); Assert.True(tasksRun[2]); } [Fact] public async Task Dispose_SkipsPendingTasks() { using var scheduler = new TaskDelayScheduler(TimeSpan.FromMilliseconds(250), IProjectThreadingServiceFactory.Create(), CancellationToken.None); bool taskRan = false; var task = scheduler.ScheduleAsyncTask(ct => { taskRan = true; return Task.CompletedTask; }); scheduler.Dispose(); await task; Assert.False(taskRan); } [Fact] public async Task ScheduleAsyncTask_Noop_OriginalSourceTokenCancelled() { var cts = new CancellationTokenSource(); using var scheduler = new TaskDelayScheduler(TimeSpan.FromMilliseconds(250), IProjectThreadingServiceFactory.Create(), cts.Token); cts.Cancel(); bool taskRan = false; var task = scheduler.ScheduleAsyncTask(ct => { taskRan = true; return Task.CompletedTask; }); await task; Assert.False(taskRan); } [Fact] public async Task ScheduleAsyncTask_Noop_RequestTokenCancelled() { using var scheduler = new TaskDelayScheduler(TimeSpan.FromMilliseconds(250), IProjectThreadingServiceFactory.Create(), CancellationToken.None); var cts = new CancellationTokenSource(); cts.Cancel(); bool taskRan = false; var task = scheduler.ScheduleAsyncTask( ct => { taskRan = true; return Task.CompletedTask; }, cts.Token); await task; Assert.False(taskRan); } } }
33.165217
201
0.545097
[ "MIT" ]
brunom/project-system
tests/Microsoft.VisualStudio.ProjectSystem.Managed.UnitTests/Threading/Tasks/TaskDelaySchedulerTests.cs
3,702
C#
using MvvmHelpers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using SQLite.Net.Attributes; namespace XPlat_MovieDB.Models { public class Movie : ObservableObject { private long _id; [PrimaryKey, AutoIncrement] [JsonProperty("id")] public long Id { get { return _id; } set { SetProperty(ref _id, value); } } private int _voteCount; [JsonProperty("vote_count")] public int VoteCount { get { return _voteCount; } set { SetProperty(ref _voteCount, value); } } private double _voteAverage; [JsonProperty("vote_average")] public double VoteAverage { get { return _voteAverage; } set { SetProperty(ref _voteAverage, value); } } private string _title; [JsonProperty("title")] public string Title { get { return _title; } set { SetProperty(ref _title, value); } } private string _posterPath; [JsonProperty("poster_path")] public string PosterPath { get { return $"http://image.tmdb.org/t/p/w300/{_posterPath}"; } set { SetProperty(ref _posterPath, value); } } private string _overview; [JsonProperty("overview")] public string Overview { get { return _overview; } set { SetProperty(ref _overview, value); } } private string _releaseDate; [JsonProperty("release_date")] public string ReleaseDate { get { return _releaseDate; } set { SetProperty(ref _releaseDate, value); } } private bool _isFavorite; [JsonProperty("is_favorite")] public bool IsFavorite { get { return _isFavorite; } set { SetProperty(ref _isFavorite, value); } } } }
25.469136
75
0.556471
[ "MIT" ]
t1agob/Xplatmoviedb
XPlat-MovieDB/XPlat_MovieDB/Models/Movie.cs
2,065
C#
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Text; namespace Aliyun.Log.Model.Data { /// <summary> /// QuriedLog used to present a log in query result. It contains log time, log source(ip/hostname,e.g), /// and multiple of key/value pairs to present the log content /// </summary> public class QueriedLog { private UInt32 _time; private string _source = string.Empty; private List<LogContent> _contents = new List<LogContent>(); /// <summary> /// The log timestamp /// </summary> public UInt32 Time { get { return _time; } set { _time = value; } } /// <summary> /// The log source /// </summary> public string Source { get { return _source; } set { _source = value; } } /// <summary> /// List of key/value pair to present the log content /// </summary> public List<LogContent> Contents { get { return _contents; } set { _contents = value; } } /// <summary> /// default constructor /// </summary> public QueriedLog() { } internal static List<QueriedLog> DeserializeFromJson(JArray json) { List<QueriedLog> logs = new List<QueriedLog>(); for (int i = 0; i < json.Count; ++i) { QueriedLog log = new QueriedLog(); log._time = (UInt32)json[i][LogConst.NAME_GETDATA_TIME]; log._source = (string)json[i][LogConst.NAME_GETDATA_SOURCE]; log._contents = new List<LogContent>(); foreach (var item in json[i].Children<JProperty>()) { if (item.Name.CompareTo(LogConst.NAME_GETDATA_TIME) != 0 && item.Name.CompareTo(LogConst.NAME_GETDATA_SOURCE) != 0) { log._contents.Add(new LogContent(item.Name, (string)json[i][item.Name])); } } logs.Add(log); } return logs; } //used only in testing project internal string Print() { StringBuilder strBuilder = new StringBuilder(); if (_contents != null) { for (int i = 0; i < _contents.Count; ++i) { strBuilder.Append("(" + _contents[i].Key + "," + _contents[i].Value + ")"); } } return strBuilder.ToString(); } } }
29.622222
135
0.496249
[ "MIT" ]
b95678/Aliyun.Log
Aliyun.Log/Aliyun.Log/Model/Data/QueriedLog.cs
2,668
C#
//------------------------------------------------------------------------------ // <自动生成> // 此代码由工具生成。 // // 对此文件的更改可能导致不正确的行为,如果 // 重新生成代码,则所做更改将丢失。 // </自动生成> //------------------------------------------------------------------------------ namespace Test.Framework.Pages { public partial class test { /// <summary> /// form1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; /// <summary> /// alogout 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlAnchor alogout; } }
25
81
0.402353
[ "Apache-2.0" ]
hoofa/IdentityServer4.XPO
Test.Framework/Pages/test.aspx.designer.cs
1,114
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class ReverseString { static void Main() { string text = Console.ReadLine(); string reversed = Reverse(text); Console.WriteLine(reversed); } static string Reverse (string text) { StringBuilder result = new StringBuilder(text.Length); for (int i = text.Length - 1; i >= 0; i--) { result.Append(text[i]); } return result.ToString(); } }
19.172414
62
0.598921
[ "MIT" ]
LPetrova/CSharpAdvance
StringsAndTextProcessingHomework/ReverseString/ReverseString.cs
558
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CWSTeam.Common { /// <summary> /// Common functionality and constants for webservices. /// </summary> public static class WebserviceCommon { /// <summary> /// JSON mime type string /// </summary> public const string JSON_MIME = "application/json"; } }
21.947368
59
0.640288
[ "MIT" ]
Favorablestream/Database-First-ASP.Net-Core
Test API/Common/WebserviceCommon.cs
419
C#
using Com.Moonlay.Models; using System; using System.ComponentModel.DataAnnotations; namespace Com.Danliris.Service.Packing.Inventory.Data.Models.Inventory { public class ProductSKUInventoryDocumentModel : StandardEntity { public ProductSKUInventoryDocumentModel() { } public ProductSKUInventoryDocumentModel( string documentNo, DateTimeOffset date, string referenceNo, string referenceType, int storageId, string storageName, string storageCode, string type, string remark ) { DocumentNo = documentNo; Date = date; ReferenceNo = referenceNo; ReferenceType = referenceType; StorageId = storageId; StorageName = storageName; StorageCode = storageCode; Type = type; Remark = remark; } [MaxLength(64)] public string DocumentNo { get; private set; } public DateTimeOffset Date { get; private set; } [MaxLength(64)] public string ReferenceNo { get; private set; } [MaxLength(256)] public string ReferenceType { get; private set; } public int StorageId { get; private set; } [MaxLength(512)] public string StorageName { get; private set; } [MaxLength(64)] public string StorageCode { get; private set; } [MaxLength(32)] public string Type { get; private set; } public string Remark { get; private set; } } }
29.907407
70
0.582043
[ "MIT" ]
AndreaZain/com-danliris-service-packing-inventory
src/Com.Danliris.Service.Packing.Inventory.Data/Models/Inventory/ProductSKUInventoryDocumentModel.cs
1,617
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Snowlight.Game.Spaces; namespace Snowlight.Communication.Outgoing.Spaces { class SpaceUserAcceptInteract { public static ServerMessage Compose(SpaceActor Actor, SpaceActor TargetActor, uint ActionId) { ServerMessage message = new ServerMessage(Opcodes.USERINTERACTACCEPT); message.AppendParameter(ActionId, false); message.AppendParameter(Actor.UInt32_0, false); message.AppendParameter(Actor.Position.Int32_0, false); message.AppendParameter(Actor.Position.Int32_1, false); message.AppendParameter(TargetActor.UInt32_0, false); message.AppendParameter(TargetActor.Position.Int32_0, false); message.AppendParameter(TargetActor.Position.Int32_1, false); return message; } } }
36.52
100
0.703176
[ "MIT" ]
DaLoE99/Servidores-DaLoE
3/BoomBang/Communication/Outgoing/Spaces/SpaceUserAcceptInteract.cs
915
C#
#region License // Copyright (c) 2011, ClearCanvas Inc. // All rights reserved. // http://www.clearcanvas.ca // // This software is licensed under the Open Software License v3.0. // For the complete license, see http://www.clearcanvas.ca/OSLv3.0 #endregion using System; using ClearCanvas.Common; using ClearCanvas.Desktop.Actions; using ClearCanvas.ImageViewer.BaseTools; using ClearCanvas.ImageViewer.Graphics; using ClearCanvas.ImageViewer.VtkItkAdapters; using itk; using FilterType = itk.itkSmoothingRecursiveGaussianImageFilter; using intensityFilterType = itk.itkRescaleIntensityImageFilter; namespace ClearCanvas.ImageViewer.Tools.ImageProcessing.Filter { [MenuAction("apply", "global-menus/MenuTools/MenuFilter/MenuSmoothingRecursiveGaussian", "Apply")] [MenuAction("apply", "imageviewer-filterdropdownmenu/MenuSmoothingRecursiveGaussian", "Apply")] [EnabledStateObserver("apply", "Enabled", "EnabledChanged")] [ExtensionOf(typeof(ImageViewerToolExtensionPoint))] public class SmoothingRecursiveGaussianFilterTool : ImageViewerTool { public SmoothingRecursiveGaussianFilterTool() { } public void Apply() { if (this.SelectedImageGraphicProvider == null) return; ImageGraphic image = this.SelectedImageGraphicProvider.ImageGraphic; if (image == null) return; if (!(image is GrayscaleImageGraphic)) return; itkImageBase input = ItkHelper.CreateItkImage(image as GrayscaleImageGraphic); itkImageBase output = itkImage.New(input); ItkHelper.CopyToItkImage(image as GrayscaleImageGraphic, input); FilterType filter = FilterType.New(input, output); bool abc = false; if (abc) { byte[] pixels = image.PixelData.Raw; unsafe { byte[] dummy = new byte[512 * 512]; IntPtr bptr = input.Buffer; void* pbptr = bptr.ToPointer(); { filter.SetInput(bptr); } fixed (byte* dummyAddr = &dummy[0]) { *dummyAddr = 1; *(dummyAddr + 1) = 2; IntPtr ptr = new IntPtr(dummyAddr); filter.SetInput(ptr); } fixed (byte* pByte = image.PixelData.Raw) { IntPtr x = new IntPtr((void*)pByte); void* p = x.ToPointer(); filter.SetInput(x);//runtime memory protected exception because it expects x.ToPointer() is ITK::Image_XX* (see implementation of MITK) } } } else { filter.SetInput(input); } filter.NormalizeAcrossScale = false; filter.Sigma = 3; filter.Update(); filter.GetOutput(output); filter.GetOutput(output); ItkHelper.CopyFromItkImage(image as GrayscaleImageGraphic, output); image.Draw(); filter.Dispose(); input.Dispose(); output.Dispose(); } } }
33.49
160
0.566438
[ "Apache-2.0" ]
SNBnani/Xian
ImageViewer/Tools/ImageProcessing/Filter/SmoothingRecursiveGaussianFilterTool.cs
3,349
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Core.Mapping { using System.Data.Entity.Core.Metadata.Edm; using System.Data.Entity.Resources; using System.Data.Entity.Utilities; using System.Diagnostics; /// <summary> /// Mapping metadata for Conditional property mapping on a type. /// Condition Property Mapping specifies a Condition either on the C side property or S side property. /// </summary> /// <example> /// For Example if conceptually you could represent the CS MSL file as following /// --Mapping /// --EntityContainerMapping ( CNorthwind-->SNorthwind ) /// --EntitySetMapping /// --EntityTypeMapping /// --MappingFragment /// --EntityKey /// --ScalarPropertyMap ( CMemberMetadata-->SMemberMetadata ) /// --ScalarPropertyMap ( CMemberMetadata-->SMemberMetadata ) /// --ConditionProperyMap ( constant value-->SMemberMetadata ) /// --EntityTypeMapping /// --MappingFragment /// --EntityKey /// --ScalarPropertyMap ( CMemberMetadata-->SMemberMetadata ) /// --ComplexPropertyMap /// --ComplexTypeMap /// --ScalarPropertyMap ( CMemberMetadata-->SMemberMetadata ) /// --ScalarProperyMap ( CMemberMetadata-->SMemberMetadata ) /// --ConditionProperyMap ( constant value-->SMemberMetadata ) /// --AssociationSetMapping /// --AssociationTypeMapping /// --MappingFragment /// --EndPropertyMap /// --ScalarPropertyMap ( CMemberMetadata-->SMemberMetadata ) /// --ScalarProperyMap ( CMemberMetadata-->SMemberMetadata ) /// --EndPropertyMap /// --ScalarPropertyMap ( CMemberMetadata-->SMemberMetadata ) /// This class represents the metadata for all the condition property map elements in the /// above example. /// </example> public class ConditionPropertyMapping : PropertyMapping { // <summary> // Column EdmMember for which the condition is specified. // </summary> private EdmProperty _column; // <summary> // Value for the condition thats being mapped. // </summary> private readonly object _value; private readonly bool? _isNull; internal ConditionPropertyMapping(EdmProperty propertyOrColumn, object value, bool? isNull) { DebugCheck.NotNull(propertyOrColumn); Debug.Assert((isNull.HasValue) || (value != null), "Either Value or IsNull has to be specified on Condition Mapping"); Debug.Assert(!(isNull.HasValue) || (value == null), "Both Value and IsNull can not be specified on Condition Mapping"); var dataSpace = propertyOrColumn.TypeUsage.EdmType.DataSpace; switch (dataSpace) { case DataSpace.CSpace: base.Property = propertyOrColumn; break; case DataSpace.SSpace: _column = propertyOrColumn; break; default: throw new ArgumentException( Strings.MetadataItem_InvalidDataSpace(dataSpace, typeof(EdmProperty).Name), "propertyOrColumn"); } _value = value; _isNull = isNull; } // <summary> // Construct a new condition Property mapping object // </summary> internal ConditionPropertyMapping( EdmProperty property, EdmProperty column , object value, bool? isNull) : base(property) { Debug.Assert(column == null || column.TypeUsage.EdmType.DataSpace == DataSpace.SSpace); Debug.Assert( (property != null) || (column != null), "Either CDM or Column Members has to be specified for Condition Mapping"); Debug.Assert( (property == null) || (column == null), "Both CDM and Column Members can not be specified for Condition Mapping"); Debug.Assert((isNull.HasValue) || (value != null), "Either Value or IsNull has to be specified on Condition Mapping"); Debug.Assert(!(isNull.HasValue) || (value == null), "Both Value and IsNull can not be specified on Condition Mapping"); _column = column; _value = value; _isNull = isNull; } // <summary> // Value for the condition // </summary> internal object Value { get { return _value; } } // <summary> // Whether the property is being mapped to Null or NotNull // </summary> internal bool? IsNull { get { return _isNull; } } /// <summary> /// Gets an EdmProperty that specifies the mapped property. /// </summary> public override EdmProperty Property { get { return base.Property; } internal set { Debug.Assert(Column == null); base.Property = value; } } /// <summary> /// Gets an EdmProperty that specifies the mapped column. /// </summary> public EdmProperty Column { get { return _column; } internal set { Debug.Assert(Property == null); DebugCheck.NotNull(value); Debug.Assert(value.TypeUsage.EdmType.DataSpace == DataSpace.SSpace); Debug.Assert(!IsReadOnly); _column = value; } } } }
35.675
132
0.58164
[ "Apache-2.0" ]
Cireson/EntityFramework6
src/EntityFramework/Core/Mapping/ConditionPropertyMapping.cs
5,708
C#
using System; using System.Collections; using System.Diagnostics; namespace NS_Glyph { public class Flags { // members protected Type typeEnum; protected Hashtable vals; // indexer virtual public bool this [object flag] { get { if (!Enum.IsDefined(typeEnum,flag)) { throw new ExceptionGlyph("Flags","indexer(get)",null); } return ((bool)this.vals[(int)flag]); } set { if (!Enum.IsDefined(typeEnum,flag)) { throw new ExceptionGlyph("Flags","indexer(set)",null); } this.vals[(int)flag]=value; } } // constructors private Flags() { } public Flags(Type typeEnum) { this.vals=new Hashtable(); this.typeEnum=typeEnum; this.SetAll(false); } // methods public void SetAll(bool val) { System.Array flags=Enum.GetValues(this.typeEnum); foreach (int flag in flags) { this.vals[flag]=val; } } public void Clear() { this.vals.Clear(); } public bool AreAll(bool val) { System.Array flags=Enum.GetValues(this.typeEnum); foreach (int flag in flags) { if ((bool)(this.vals[flag])!=val) return false; } return true; } } }
23.647887
74
0.432996
[ "MIT" ]
Bhaskers-Blu-Org2/Font-Validator
Glyph/Flags.cs
1,679
C#
using System; using Org.BouncyCastle.Math.EC.Endo; using Org.BouncyCastle.Math.EC.Multiplier; using Org.BouncyCastle.Math.Field; using Org.BouncyCastle.Math.Raw; namespace Org.BouncyCastle.Math.EC { public class ECAlgorithms { public static bool IsF2mCurve(ECCurve c) { return IsF2mField(c.Field); } public static bool IsF2mField(IFiniteField field) { return field.Dimension > 1 && field.Characteristic.Equals(BigInteger.Two) && field is IPolynomialExtensionField; } public static bool IsFpCurve(ECCurve c) { return IsFpField(c.Field); } public static bool IsFpField(IFiniteField field) { return field.Dimension == 1; } public static ECPoint SumOfMultiplies(ECPoint[] ps, BigInteger[] ks) { if (ps == null || ks == null || ps.Length != ks.Length || ps.Length < 1) throw new ArgumentException("point and scalar arrays should be non-null, and of equal, non-zero, length"); int count = ps.Length; switch (count) { case 1: return ps[0].Multiply(ks[0]); case 2: return SumOfTwoMultiplies(ps[0], ks[0], ps[1], ks[1]); default: break; } ECPoint p = ps[0]; ECCurve c = p.Curve; ECPoint[] imported = new ECPoint[count]; imported[0] = p; for (int i = 1; i < count; ++i) { imported[i] = ImportPoint(c, ps[i]); } GlvEndomorphism glvEndomorphism = c.GetEndomorphism() as GlvEndomorphism; if (glvEndomorphism != null) { return ImplCheckResult(ImplSumOfMultipliesGlv(imported, ks, glvEndomorphism)); } return ImplCheckResult(ImplSumOfMultiplies(imported, ks)); } public static ECPoint SumOfTwoMultiplies(ECPoint P, BigInteger a, ECPoint Q, BigInteger b) { ECCurve cp = P.Curve; Q = ImportPoint(cp, Q); // Point multiplication for Koblitz curves (using WTNAF) beats Shamir's trick { AbstractF2mCurve f2mCurve = cp as AbstractF2mCurve; if (f2mCurve != null && f2mCurve.IsKoblitz) { return ImplCheckResult(P.Multiply(a).Add(Q.Multiply(b))); } } GlvEndomorphism glvEndomorphism = cp.GetEndomorphism() as GlvEndomorphism; if (glvEndomorphism != null) { return ImplCheckResult( ImplSumOfMultipliesGlv(new ECPoint[] { P, Q }, new BigInteger[] { a, b }, glvEndomorphism)); } return ImplCheckResult(ImplShamirsTrickWNaf(P, a, Q, b)); } /* * "Shamir's Trick", originally due to E. G. Straus * (Addition chains of vectors. American Mathematical Monthly, * 71(7):806-808, Aug./Sept. 1964) * * Input: The points P, Q, scalar k = (km?, ... , k1, k0) * and scalar l = (lm?, ... , l1, l0). * Output: R = k * P + l * Q. * 1: Z <- P + Q * 2: R <- O * 3: for i from m-1 down to 0 do * 4: R <- R + R {point doubling} * 5: if (ki = 1) and (li = 0) then R <- R + P end if * 6: if (ki = 0) and (li = 1) then R <- R + Q end if * 7: if (ki = 1) and (li = 1) then R <- R + Z end if * 8: end for * 9: return R */ public static ECPoint ShamirsTrick(ECPoint P, BigInteger k, ECPoint Q, BigInteger l) { ECCurve cp = P.Curve; Q = ImportPoint(cp, Q); return ImplCheckResult(ImplShamirsTrickJsf(P, k, Q, l)); } public static ECPoint ImportPoint(ECCurve c, ECPoint p) { ECCurve cp = p.Curve; if (!c.Equals(cp)) throw new ArgumentException("Point must be on the same curve"); return c.ImportPoint(p); } public static void MontgomeryTrick(ECFieldElement[] zs, int off, int len) { MontgomeryTrick(zs, off, len, null); } public static void MontgomeryTrick(ECFieldElement[] zs, int off, int len, ECFieldElement scale) { /* * Uses the "Montgomery Trick" to invert many field elements, with only a single actual * field inversion. See e.g. the paper: * "Fast Multi-scalar Multiplication Methods on Elliptic Curves with Precomputation Strategy Using Montgomery Trick" * by Katsuyuki Okeya, Kouichi Sakurai. */ ECFieldElement[] c = new ECFieldElement[len]; c[0] = zs[off]; int i = 0; while (++i < len) { c[i] = c[i - 1].Multiply(zs[off + i]); } --i; if (scale != null) { c[i] = c[i].Multiply(scale); } ECFieldElement u = c[i].Invert(); while (i > 0) { int j = off + i--; ECFieldElement tmp = zs[j]; zs[j] = c[i].Multiply(u); u = u.Multiply(tmp); } zs[off] = u; } /** * Simple shift-and-add multiplication. Serves as reference implementation * to verify (possibly faster) implementations, and for very small scalars. * * @param p * The point to multiply. * @param k * The multiplier. * @return The result of the point multiplication <code>kP</code>. */ public static ECPoint ReferenceMultiply(ECPoint p, BigInteger k) { BigInteger x = k.Abs(); ECPoint q = p.Curve.Infinity; int t = x.BitLength; if (t > 0) { if (x.TestBit(0)) { q = p; } for (int i = 1; i < t; i++) { p = p.Twice(); if (x.TestBit(i)) { q = q.Add(p); } } } return k.SignValue < 0 ? q.Negate() : q; } public static ECPoint ValidatePoint(ECPoint p) { if (!p.IsValid()) throw new InvalidOperationException("Invalid point"); return p; } public static ECPoint CleanPoint(ECCurve c, ECPoint p) { ECCurve cp = p.Curve; if (!c.Equals(cp)) throw new ArgumentException("Point must be on the same curve", "p"); return c.DecodePoint(p.GetEncoded(false)); } internal static ECPoint ImplCheckResult(ECPoint p) { if (!p.IsValidPartial()) throw new InvalidOperationException("Invalid result"); return p; } internal static ECPoint ImplShamirsTrickJsf(ECPoint P, BigInteger k, ECPoint Q, BigInteger l) { ECCurve curve = P.Curve; ECPoint infinity = curve.Infinity; // TODO conjugate co-Z addition (ZADDC) can return both of these ECPoint PaddQ = P.Add(Q); ECPoint PsubQ = P.Subtract(Q); ECPoint[] points = new ECPoint[] { Q, PsubQ, P, PaddQ }; curve.NormalizeAll(points); ECPoint[] table = new ECPoint[] { points[3].Negate(), points[2].Negate(), points[1].Negate(), points[0].Negate(), infinity, points[0], points[1], points[2], points[3] }; byte[] jsf = WNafUtilities.GenerateJsf(k, l); ECPoint R = infinity; int i = jsf.Length; while (--i >= 0) { int jsfi = jsf[i]; // NOTE: The shifting ensures the sign is extended correctly int kDigit = ((jsfi << 24) >> 28), lDigit = ((jsfi << 28) >> 28); int index = 4 + (kDigit * 3) + lDigit; R = R.TwicePlus(table[index]); } return R; } internal static ECPoint ImplShamirsTrickWNaf(ECPoint P, BigInteger k, ECPoint Q, BigInteger l) { bool negK = k.SignValue < 0, negL = l.SignValue < 0; BigInteger kAbs = k.Abs(), lAbs = l.Abs(); int minWidthP = WNafUtilities.GetWindowSize(kAbs.BitLength, 8); int minWidthQ = WNafUtilities.GetWindowSize(lAbs.BitLength, 8); WNafPreCompInfo infoP = WNafUtilities.Precompute(P, minWidthP, true); WNafPreCompInfo infoQ = WNafUtilities.Precompute(Q, minWidthQ, true); // When P, Q are 'promoted' (i.e. reused several times), switch to fixed-point algorithm { ECCurve c = P.Curve; int combSize = FixedPointUtilities.GetCombSize(c); if (!negK && !negL && k.BitLength <= combSize && l.BitLength <= combSize && infoP.IsPromoted && infoQ.IsPromoted) { return ImplShamirsTrickFixedPoint(P, k, Q, l); } } int widthP = System.Math.Min(8, infoP.Width); int widthQ = System.Math.Min(8, infoQ.Width); ECPoint[] preCompP = negK ? infoP.PreCompNeg : infoP.PreComp; ECPoint[] preCompQ = negL ? infoQ.PreCompNeg : infoQ.PreComp; ECPoint[] preCompNegP = negK ? infoP.PreComp : infoP.PreCompNeg; ECPoint[] preCompNegQ = negL ? infoQ.PreComp : infoQ.PreCompNeg; byte[] wnafP = WNafUtilities.GenerateWindowNaf(widthP, kAbs); byte[] wnafQ = WNafUtilities.GenerateWindowNaf(widthQ, lAbs); return ImplShamirsTrickWNaf(preCompP, preCompNegP, wnafP, preCompQ, preCompNegQ, wnafQ); } internal static ECPoint ImplShamirsTrickWNaf(ECEndomorphism endomorphism, ECPoint P, BigInteger k, BigInteger l) { bool negK = k.SignValue < 0, negL = l.SignValue < 0; k = k.Abs(); l = l.Abs(); int minWidth = WNafUtilities.GetWindowSize(System.Math.Max(k.BitLength, l.BitLength), 8); WNafPreCompInfo infoP = WNafUtilities.Precompute(P, minWidth, true); ECPoint Q = EndoUtilities.MapPoint(endomorphism, P); WNafPreCompInfo infoQ = WNafUtilities.PrecomputeWithPointMap(Q, endomorphism.PointMap, infoP, true); int widthP = System.Math.Min(8, infoP.Width); int widthQ = System.Math.Min(8, infoQ.Width); ECPoint[] preCompP = negK ? infoP.PreCompNeg : infoP.PreComp; ECPoint[] preCompQ = negL ? infoQ.PreCompNeg : infoQ.PreComp; ECPoint[] preCompNegP = negK ? infoP.PreComp : infoP.PreCompNeg; ECPoint[] preCompNegQ = negL ? infoQ.PreComp : infoQ.PreCompNeg; byte[] wnafP = WNafUtilities.GenerateWindowNaf(widthP, k); byte[] wnafQ = WNafUtilities.GenerateWindowNaf(widthQ, l); return ImplShamirsTrickWNaf(preCompP, preCompNegP, wnafP, preCompQ, preCompNegQ, wnafQ); } private static ECPoint ImplShamirsTrickWNaf(ECPoint[] preCompP, ECPoint[] preCompNegP, byte[] wnafP, ECPoint[] preCompQ, ECPoint[] preCompNegQ, byte[] wnafQ) { int len = System.Math.Max(wnafP.Length, wnafQ.Length); ECCurve curve = preCompP[0].Curve; ECPoint infinity = curve.Infinity; ECPoint R = infinity; int zeroes = 0; for (int i = len - 1; i >= 0; --i) { int wiP = i < wnafP.Length ? (int)(sbyte)wnafP[i] : 0; int wiQ = i < wnafQ.Length ? (int)(sbyte)wnafQ[i] : 0; if ((wiP | wiQ) == 0) { ++zeroes; continue; } ECPoint r = infinity; if (wiP != 0) { int nP = System.Math.Abs(wiP); ECPoint[] tableP = wiP < 0 ? preCompNegP : preCompP; r = r.Add(tableP[nP >> 1]); } if (wiQ != 0) { int nQ = System.Math.Abs(wiQ); ECPoint[] tableQ = wiQ < 0 ? preCompNegQ : preCompQ; r = r.Add(tableQ[nQ >> 1]); } if (zeroes > 0) { R = R.TimesPow2(zeroes); zeroes = 0; } R = R.TwicePlus(r); } if (zeroes > 0) { R = R.TimesPow2(zeroes); } return R; } internal static ECPoint ImplSumOfMultiplies(ECPoint[] ps, BigInteger[] ks) { int count = ps.Length; bool[] negs = new bool[count]; WNafPreCompInfo[] infos = new WNafPreCompInfo[count]; byte[][] wnafs = new byte[count][]; for (int i = 0; i < count; ++i) { BigInteger ki = ks[i]; negs[i] = ki.SignValue < 0; ki = ki.Abs(); int minWidth = WNafUtilities.GetWindowSize(ki.BitLength, 8); WNafPreCompInfo info = WNafUtilities.Precompute(ps[i], minWidth, true); int width = System.Math.Min(8, info.Width); infos[i] = info; wnafs[i] = WNafUtilities.GenerateWindowNaf(width, ki); } return ImplSumOfMultiplies(negs, infos, wnafs); } internal static ECPoint ImplSumOfMultipliesGlv(ECPoint[] ps, BigInteger[] ks, GlvEndomorphism glvEndomorphism) { BigInteger n = ps[0].Curve.Order; int len = ps.Length; BigInteger[] abs = new BigInteger[len << 1]; for (int i = 0, j = 0; i < len; ++i) { BigInteger[] ab = glvEndomorphism.DecomposeScalar(ks[i].Mod(n)); abs[j++] = ab[0]; abs[j++] = ab[1]; } if (glvEndomorphism.HasEfficientPointMap) { return ImplSumOfMultiplies(glvEndomorphism, ps, abs); } ECPoint[] pqs = new ECPoint[len << 1]; for (int i = 0, j = 0; i < len; ++i) { ECPoint p = ps[i]; ECPoint q = EndoUtilities.MapPoint(glvEndomorphism, p); pqs[j++] = p; pqs[j++] = q; } return ImplSumOfMultiplies(pqs, abs); } internal static ECPoint ImplSumOfMultiplies(ECEndomorphism endomorphism, ECPoint[] ps, BigInteger[] ks) { int halfCount = ps.Length, fullCount = halfCount << 1; bool[] negs = new bool[fullCount]; WNafPreCompInfo[] infos = new WNafPreCompInfo[fullCount]; byte[][] wnafs = new byte[fullCount][]; ECPointMap pointMap = endomorphism.PointMap; for (int i = 0; i < halfCount; ++i) { int j0 = i << 1, j1 = j0 + 1; BigInteger kj0 = ks[j0]; negs[j0] = kj0.SignValue < 0; kj0 = kj0.Abs(); BigInteger kj1 = ks[j1]; negs[j1] = kj1.SignValue < 0; kj1 = kj1.Abs(); int minWidth = WNafUtilities.GetWindowSize(System.Math.Max(kj0.BitLength, kj1.BitLength), 8); ECPoint P = ps[i]; WNafPreCompInfo infoP = WNafUtilities.Precompute(P, minWidth, true); ECPoint Q = EndoUtilities.MapPoint(endomorphism, P); WNafPreCompInfo infoQ = WNafUtilities.PrecomputeWithPointMap(Q, pointMap, infoP, true); int widthP = System.Math.Min(8, infoP.Width); int widthQ = System.Math.Min(8, infoQ.Width); infos[j0] = infoP; infos[j1] = infoQ; wnafs[j0] = WNafUtilities.GenerateWindowNaf(widthP, kj0); wnafs[j1] = WNafUtilities.GenerateWindowNaf(widthQ, kj1); } return ImplSumOfMultiplies(negs, infos, wnafs); } private static ECPoint ImplSumOfMultiplies(bool[] negs, WNafPreCompInfo[] infos, byte[][] wnafs) { int len = 0, count = wnafs.Length; for (int i = 0; i < count; ++i) { len = System.Math.Max(len, wnafs[i].Length); } ECCurve curve = infos[0].PreComp[0].Curve; ECPoint infinity = curve.Infinity; ECPoint R = infinity; int zeroes = 0; for (int i = len - 1; i >= 0; --i) { ECPoint r = infinity; for (int j = 0; j < count; ++j) { byte[] wnaf = wnafs[j]; int wi = i < wnaf.Length ? (int)(sbyte)wnaf[i] : 0; if (wi != 0) { int n = System.Math.Abs(wi); WNafPreCompInfo info = infos[j]; ECPoint[] table = (wi < 0 == negs[j]) ? info.PreComp : info.PreCompNeg; r = r.Add(table[n >> 1]); } } if (r == infinity) { ++zeroes; continue; } if (zeroes > 0) { R = R.TimesPow2(zeroes); zeroes = 0; } R = R.TwicePlus(r); } if (zeroes > 0) { R = R.TimesPow2(zeroes); } return R; } private static ECPoint ImplShamirsTrickFixedPoint(ECPoint p, BigInteger k, ECPoint q, BigInteger l) { ECCurve c = p.Curve; int combSize = FixedPointUtilities.GetCombSize(c); if (k.BitLength > combSize || l.BitLength > combSize) { /* * TODO The comb works best when the scalars are less than the (possibly unknown) order. * Still, if we want to handle larger scalars, we could allow customization of the comb * size, or alternatively we could deal with the 'extra' bits either by running the comb * multiple times as necessary, or by using an alternative multiplier as prelude. */ throw new InvalidOperationException("fixed-point comb doesn't support scalars larger than the curve order"); } FixedPointPreCompInfo infoP = FixedPointUtilities.Precompute(p); FixedPointPreCompInfo infoQ = FixedPointUtilities.Precompute(q); ECLookupTable lookupTableP = infoP.LookupTable; ECLookupTable lookupTableQ = infoQ.LookupTable; int widthP = infoP.Width; int widthQ = infoQ.Width; // TODO This shouldn't normally happen, but a better "solution" is desirable anyway if (widthP != widthQ) { FixedPointCombMultiplier m = new FixedPointCombMultiplier(); ECPoint r1 = m.Multiply(p, k); ECPoint r2 = m.Multiply(q, l); return r1.Add(r2); } int width = widthP; int d = (combSize + width - 1) / width; ECPoint R = c.Infinity; int fullComb = d * width; uint[] K = Nat.FromBigInteger(fullComb, k); uint[] L = Nat.FromBigInteger(fullComb, l); int top = fullComb - 1; for (int i = 0; i < d; ++i) { uint secretIndexK = 0, secretIndexL = 0; for (int j = top - i; j >= 0; j -= d) { uint secretBitK = K[j >> 5] >> (j & 0x1F); secretIndexK ^= secretBitK >> 1; secretIndexK <<= 1; secretIndexK ^= secretBitK; uint secretBitL = L[j >> 5] >> (j & 0x1F); secretIndexL ^= secretBitL >> 1; secretIndexL <<= 1; secretIndexL ^= secretBitL; } ECPoint addP = lookupTableP.LookupVar((int)secretIndexK); ECPoint addQ = lookupTableQ.LookupVar((int)secretIndexL); ECPoint T = addP.Add(addQ); R = R.TwicePlus(T); } return R.Add(infoP.Offset).Add(infoQ.Offset); } } }
34.690516
128
0.493693
[ "MIT" ]
Zaharkov/bc-csharp
crypto/src/math/ec/ECAlgorithms.cs
20,849
C#
using UnityEditor; using UnityEditor.UI; namespace XFramework.UI.Editor { [CustomEditor(typeof(LongOrDoubleBtn), true)] [CanEditMultipleObjects] public class LongPressBtnEditor : ButtonEditor { SerializedProperty m_maxTime; SerializedProperty m_isLongPressTrigger; SerializedProperty m_OnLongClick; SerializedProperty m_OnDoubleClick; protected override void OnEnable() { base.OnEnable(); m_maxTime = serializedObject.FindProperty("maxTime"); m_isLongPressTrigger = serializedObject.FindProperty("isLongPressTrigger"); m_OnLongClick = serializedObject.FindProperty("onLongClick"); m_OnDoubleClick = serializedObject.FindProperty("onDoubleClick"); } public override void OnInspectorGUI() { bool temp = ((LongOrDoubleBtn)target).isLongPressTrigger; EditorGUILayout.PropertyField(m_isLongPressTrigger); if (temp) { EditorGUILayout.PropertyField(m_maxTime); } serializedObject.ApplyModifiedProperties(); base.OnInspectorGUI(); if (temp) { EditorGUILayout.PropertyField(m_OnLongClick); } else { EditorGUILayout.PropertyField(m_OnDoubleClick); } serializedObject.ApplyModifiedProperties(); } } }
29.96
87
0.606809
[ "Apache-2.0" ]
xdedzl/XFramework
XFramework/Assets/XFramework/Core/Editor/Modules/UI/LongOrDoubleBtnEditor.cs
1,500
C#
// MvxRecyclerViewHolder.cs // (c) Copyright Cirrious Ltd. http://www.cirrious.com // MvvmCross is licensed using Microsoft Public License (Ms-PL) // Contributions and inspirations noted in readme.md and license.txt // // Project Lead - Stuart Lodge, @slodge, me@slodge.com using System; using System.Windows.Input; using Android.Views; using MvvmCross.Binding.BindingContext; using MvvmCross.Binding.Droid.BindingContext; namespace MvvmCross.Droid.Support.V7.RecyclerView { public class MvxRecyclerViewHolder : Android.Support.V7.Widget.RecyclerView.ViewHolder, IMvxRecyclerViewHolder, IMvxBindingContextOwner { private readonly IMvxBindingContext _bindingContext; private object _cachedDataContext; private ICommand _click, _longClick; private bool _clickOverloaded, _longClickOverloaded; public IMvxBindingContext BindingContext { get { return _bindingContext; } set { throw new NotImplementedException("BindingContext is readonly in the list item"); } } public object DataContext { get { return _bindingContext.DataContext; } set { _bindingContext.DataContext = value; } } public ICommand Click { get { return this._click; } set { this._click = value; if (this._click != null) this.EnsureClickOverloaded(); } } private void EnsureClickOverloaded() { if (this._clickOverloaded) return; this._clickOverloaded = true; this.ItemView.Click += (sender, args) => ExecuteCommandOnItem(this.Click); } public ICommand LongClick { get { return this._longClick; } set { this._longClick = value; if (this._longClick != null) this.EnsureLongClickOverloaded(); } } private void EnsureLongClickOverloaded() { if (this._longClickOverloaded) return; this._longClickOverloaded = true; this.ItemView.LongClick += (sender, args) => ExecuteCommandOnItem(this.LongClick); } protected virtual void ExecuteCommandOnItem(ICommand command) { if (command == null) return; var item = DataContext; if (item == null) return; if (!command.CanExecute(item)) return; command.Execute(item); } public MvxRecyclerViewHolder(View itemView, IMvxAndroidBindingContext context) : base(itemView) { this._bindingContext = context; } public void OnAttachedToWindow() { if (_cachedDataContext != null && DataContext == null) DataContext = _cachedDataContext; } public void OnDetachedFromWindow() { _cachedDataContext = DataContext; DataContext = null; } protected override void Dispose(bool disposing) { if (disposing) { _bindingContext.ClearAllBindings(); _cachedDataContext = null; } base.Dispose(disposing); } } }
30.240741
139
0.597979
[ "MIT" ]
miki3003/food-by-me
lib/MvvmCross.Droid.Support.V7.RecyclerView/MvxRecyclerViewHolder.cs
3,266
C#
using System; using System.Data; using System.Data.OleDb; namespace OMeta.Sql { #if ENTERPRISE using System.Runtime.InteropServices; [ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual), ComDefaultInterface(typeof(IDomains))] #endif public class SqlDomains : Domains { public SqlDomains() { } override internal void LoadAll() { try { string select = "SELECT * FROM INFORMATION_SCHEMA.DOMAINS"; OleDbConnection cn = new OleDbConnection(dbRoot.ConnectionString); cn.Open(); cn.ChangeDatabase("[" + this.Database.Name + "]"); OleDbDataAdapter adapter = new OleDbDataAdapter(select, cn); DataTable metaData = new DataTable(); adapter.Fill(metaData); cn.Close(); PopulateArray(metaData); } catch {} } } }
19.6
103
0.697704
[ "MIT" ]
kiler398/OMeta
src/OpenMeta/Sql/Domains.cs
784
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 NPOI.SS.UserModel; using NPOI.XSSF.Model; using NPOI.OpenXmlFormats.Spreadsheet; using NPOI.SS.Util; using System; using NPOI.SS.Formula.PTG; using NPOI.SS.Formula; using NPOI.SS; using NPOI.Util; using NPOI.SS.Formula.Eval; using System.Globalization; namespace NPOI.XSSF.UserModel { /** * High level representation of a cell in a row of a spreadsheet. * <p> * Cells can be numeric, formula-based or string-based (text). The cell type * specifies this. String cells cannot conatin numbers and numeric cells cannot * contain strings (at least according to our model). Client apps should do the * conversions themselves. Formula cells have the formula string, as well as * the formula result, which can be numeric or string. * </p> * <p> * Cells should have their number (0 based) before being Added to a row. Only * cells that have values should be Added. * </p> */ public class XSSFCell : ICell { private static String FALSE_AS_STRING = "0"; private static String TRUE_AS_STRING = "1"; /** * the xml bean Containing information about the cell's location, value, * data type, formatting, and formula */ private CT_Cell _cell; /** * the XSSFRow this cell belongs to */ private XSSFRow _row; /** * 0-based column index */ private int _cellNum; /** * Table of strings shared across this workbook. * If two cells contain the same string, then the cell value is the same index into SharedStringsTable */ private SharedStringsTable _sharedStringSource; /** * Table of cell styles shared across all cells in a workbook. */ private StylesTable _stylesSource; /** * Construct a XSSFCell. * * @param row the parent row. * @param cell the xml bean Containing information about the cell. */ public XSSFCell(XSSFRow row, CT_Cell cell) { _cell = cell; _row = row; if (cell.r != null) { _cellNum = new CellReference(cell.r).Col; } else { int prevNum = row.LastCellNum; if (prevNum != -1) { _cellNum = (row as XSSFRow).GetCell(prevNum - 1, MissingCellPolicy.RETURN_NULL_AND_BLANK).ColumnIndex + 1; } } _sharedStringSource = ((XSSFWorkbook)row.Sheet.Workbook).GetSharedStringSource(); _stylesSource = ((XSSFWorkbook)row.Sheet.Workbook).GetStylesSource(); } /// <summary> /// Copy cell value, formula and style, from srcCell per cell copy policy /// If srcCell is null, clears the cell value and cell style per cell copy policy /// /// This does not shift references in formulas. Use {@link XSSFRowShifter} to shift references in formulas. /// </summary> /// <param name="srcCell">The cell to take value, formula and style from</param> /// <param name="policy">The policy for copying the information, see {@link CellCopyPolicy}</param> /// <exception cref="ArgumentException">if copy cell style and srcCell is from a different workbook</exception> public void CopyCellFrom(ICell srcCell, CellCopyPolicy policy) { // Copy cell value (cell type is updated implicitly) if (policy.IsCopyCellValue) { if (srcCell != null) { CellType copyCellType = srcCell.CellType; if (copyCellType == CellType.Formula && !policy.IsCopyCellFormula) { // Copy formula result as value // FIXME: Cached value may be stale copyCellType = srcCell.CachedFormulaResultType; } switch (copyCellType) { case CellType.Boolean: SetCellValue(srcCell.BooleanCellValue); break; case CellType.Error: SetCellErrorValue(srcCell.ErrorCellValue); break; case CellType.Formula: SetCellFormula(srcCell.CellFormula); break; case CellType.Numeric: // DataFormat is not copied unless policy.isCopyCellStyle is true if (DateUtil.IsCellDateFormatted(srcCell)) { SetCellValue(srcCell.DateCellValue); } else { SetCellValue(srcCell.NumericCellValue); } break; case CellType.String: SetCellValue(srcCell.StringCellValue); break; case CellType.Blank: SetBlankInternal(); break; default: throw new ArgumentException("Invalid cell type " + srcCell.CellType); } } else { //srcCell is null SetBlankInternal(); } } // Copy CellStyle if (policy.IsCopyCellStyle) { if (srcCell != null) { CellStyle = (srcCell.CellStyle); } else { // clear cell style CellStyle = (null); } } if (policy.IsMergeHyperlink) { // if srcCell doesn't have a hyperlink and destCell has a hyperlink, don't clear destCell's hyperlink IHyperlink srcHyperlink = srcCell.Hyperlink; if (srcHyperlink != null) { Hyperlink = new XSSFHyperlink(srcHyperlink); } } else if (policy.IsCopyHyperlink) { // overwrite the hyperlink at dest cell with srcCell's hyperlink // if srcCell doesn't have a hyperlink, clear the hyperlink (if one exists) at destCell IHyperlink srcHyperlink = srcCell.Hyperlink; if (srcHyperlink == null) { Hyperlink = (null); } else { Hyperlink = new XSSFHyperlink(srcHyperlink); } } } /** * @return table of strings shared across this workbook */ protected SharedStringsTable GetSharedStringSource() { return _sharedStringSource; } /** * @return table of cell styles shared across this workbook */ protected StylesTable GetStylesSource() { return _stylesSource; } /** * Returns the sheet this cell belongs to * * @return the sheet this cell belongs to */ public ISheet Sheet { get { return _row.Sheet; } } /** * Returns the row this cell belongs to * * @return the row this cell belongs to */ public IRow Row { get { return _row; } } /** * Get the value of the cell as a bool. * <p> * For strings, numbers, and errors, we throw an exception. For blank cells we return a false. * </p> * @return the value of the cell as a bool * @throws InvalidOperationException if the cell type returned by {@link #CellType} * is not CellType.Boolean, CellType.Blank or CellType.Formula */ public bool BooleanCellValue { get { CellType cellType = CellType; switch (cellType) { case CellType.Blank: return false; case CellType.Boolean: return _cell.IsSetV() && TRUE_AS_STRING.Equals(_cell.v); case CellType.Formula: //YK: should throw an exception if requesting bool value from a non-bool formula return _cell.IsSetV() && TRUE_AS_STRING.Equals(_cell.v); default: throw TypeMismatch(CellType.Boolean, cellType, false); } } } /** * Set a bool value for the cell * * @param value the bool value to Set this cell to. For formulas we'll Set the * precalculated value, for bools we'll Set its value. For other types we * will change the cell to a bool cell and Set its value. */ public void SetCellValue(bool value) { _cell.t = (ST_CellType.b); _cell.v = (value ? TRUE_AS_STRING : FALSE_AS_STRING); } /** * Get the value of the cell as a number. * <p> * For strings we throw an exception. For blank cells we return a 0. * For formulas or error cells we return the precalculated value; * </p> * @return the value of the cell as a number * @throws InvalidOperationException if the cell type returned by {@link #CellType} is CellType.String * @exception NumberFormatException if the cell value isn't a parsable <code>double</code>. * @see DataFormatter for turning this number into a string similar to that which Excel would render this number as. */ public double NumericCellValue { get { CellType cellType = CellType; switch (cellType) { case CellType.Blank: return 0.0; case CellType.Formula: case CellType.Numeric: if (_cell.IsSetV()) { if (string.IsNullOrEmpty(_cell.v)) return 0.0; try { return Double.Parse(_cell.v, CultureInfo.InvariantCulture); } catch (FormatException) { throw TypeMismatch(CellType.Numeric, CellType.String, false); } } else { return 0.0; } default: throw TypeMismatch(CellType.Numeric, cellType, false); } } } /** * Set a numeric value for the cell * * @param value the numeric value to Set this cell to. For formulas we'll Set the * precalculated value, for numerics we'll Set its value. For other types we * will change the cell to a numeric cell and Set its value. */ public void SetCellValue(double value) { if (Double.IsInfinity(value)) { // Excel does not support positive/negative infInities, // rather, it gives a #DIV/0! error in these cases. _cell.t = (ST_CellType.e); _cell.v = (FormulaError.DIV0.String); } else if (Double.IsNaN(value)) { // Excel does not support Not-a-Number (NaN), // instead it immediately generates an #NUM! error. _cell.t = (ST_CellType.e); _cell.v = (FormulaError.NUM.String); } else { _cell.t = (ST_CellType.n); _cell.v = (value.ToString(CultureInfo.InvariantCulture)); } } /** * Get the value of the cell as a string * <p> * For numeric cells we throw an exception. For blank cells we return an empty string. * For formulaCells that are not string Formulas, we throw an exception * </p> * @return the value of the cell as a string */ public String StringCellValue { get { return this.RichStringCellValue.String; } } /** * Get the value of the cell as a XSSFRichTextString * <p> * For numeric cells we throw an exception. For blank cells we return an empty string. * For formula cells we return the pre-calculated value if a string, otherwise an exception * </p> * @return the value of the cell as a XSSFRichTextString */ public IRichTextString RichStringCellValue { get { CellType cellType = CellType; XSSFRichTextString rt; switch (cellType) { case CellType.Blank: rt = new XSSFRichTextString(""); break; case CellType.String: if (_cell.t == ST_CellType.inlineStr) { if (_cell.IsSetIs()) { //string is expressed directly in the cell defInition instead of implementing the shared string table. rt = new XSSFRichTextString(_cell.@is); } else if (_cell.IsSetV()) { //cached result of a formula rt = new XSSFRichTextString(_cell.v); } else { rt = new XSSFRichTextString(""); } } else if (_cell.t == ST_CellType.str) { //cached formula value rt = new XSSFRichTextString(_cell.IsSetV() ? _cell.v : ""); } else { if (_cell.IsSetV()) { int idx = Int32.Parse(_cell.v); rt = new XSSFRichTextString(_sharedStringSource.GetEntryAt(idx)); } else { rt = new XSSFRichTextString(""); } } break; case CellType.Formula: CheckFormulaCachedValueType(CellType.String, GetBaseCellType(false)); rt = new XSSFRichTextString(_cell.IsSetV() ? _cell.v : ""); break; default: throw TypeMismatch(CellType.String, cellType, false); } rt.SetStylesTableReference(_stylesSource); return rt; } } private static void CheckFormulaCachedValueType(CellType expectedTypeCode, CellType cachedValueType) { if (cachedValueType != expectedTypeCode) { throw TypeMismatch(expectedTypeCode, cachedValueType, true); } } /** * Set a string value for the cell. * * @param str value to Set the cell to. For formulas we'll Set the formula * cached string result, for String cells we'll Set its value. For other types we will * change the cell to a string cell and Set its value. * If value is null then we will change the cell to a Blank cell. */ public void SetCellValue(String str) { SetCellValue(str == null ? null : new XSSFRichTextString(str)); } /** * Set a string value for the cell. * * @param str value to Set the cell to. For formulas we'll Set the 'pre-Evaluated result string, * for String cells we'll Set its value. For other types we will * change the cell to a string cell and Set its value. * If value is null then we will change the cell to a Blank cell. */ public void SetCellValue(IRichTextString str) { if (str == null || str.String == null) { SetCellType(CellType.Blank); return; } if (str.Length > SpreadsheetVersion.EXCEL2007.MaxTextLength) { throw new ArgumentException("The maximum length of cell contents (text) is 32,767 characters"); } CellType cellType = CellType; switch (cellType) { case CellType.Formula: _cell.v = (str.String); _cell.t= (ST_CellType.str); break; default: if (_cell.t == ST_CellType.inlineStr) { //set the 'pre-Evaluated result _cell.v = str.String; } else { _cell.t = ST_CellType.s; XSSFRichTextString rt = (XSSFRichTextString)str; rt.SetStylesTableReference(_stylesSource); int sRef = _sharedStringSource.AddEntry(rt.GetCTRst()); _cell.v=sRef.ToString(); } break; } } /// <summary> /// Return a formula for the cell, for example, <code>SUM(C4:E4)</code> /// </summary> public String CellFormula { get { // existing behavior - create a new XSSFEvaluationWorkbook for every call return GetCellFormula(null); } set { SetCellFormula(value); } } /** * package/hierarchy use only - reuse an existing evaluation workbook if available for caching * * @param fpb evaluation workbook for reuse, if available, or null to create a new one as needed * @return a formula for the cell * @throws InvalidOperationException if the cell type returned by {@link #getCellType()} is not CELL_TYPE_FORMULA */ protected internal String GetCellFormula(XSSFEvaluationWorkbook fpb) { CellType cellType = CellType; if (cellType != CellType.Formula) throw TypeMismatch(CellType.Formula, cellType, false); CT_CellFormula f = _cell.f; if (IsPartOfArrayFormulaGroup && f == null) { XSSFCell cell = ((XSSFSheet)Sheet).GetFirstCellInArrayFormula(this); return cell.GetCellFormula(fpb); } if (f.t == ST_CellFormulaType.shared) { //return ConvertSharedFormula((int)f.si); return ConvertSharedFormula((int)f.si, fpb == null ? XSSFEvaluationWorkbook.Create(Sheet.Workbook) : fpb); } return f.Value; } /// <summary> /// Creates a non shared formula from the shared formula counterpart /// </summary> /// <param name="si">Shared Group Index</param> /// <param name="fpb"></param> /// <returns>non shared formula created for the given shared formula and this cell</returns> private String ConvertSharedFormula(int si, XSSFEvaluationWorkbook fpb) { XSSFSheet sheet = (XSSFSheet)Sheet; CT_CellFormula f = sheet.GetSharedFormula(si); if (f == null) throw new InvalidOperationException( "Master cell of a shared formula with sid=" + si + " was not found"); String sharedFormula = f.Value; //Range of cells which the shared formula applies to String sharedFormulaRange = f.@ref; CellRangeAddress ref1 = CellRangeAddress.ValueOf(sharedFormulaRange); int sheetIndex = sheet.Workbook.GetSheetIndex(sheet); SharedFormula sf = new SharedFormula(SpreadsheetVersion.EXCEL2007); Ptg[] ptgs = FormulaParser.Parse(sharedFormula, fpb, FormulaType.Cell, sheetIndex, RowIndex); Ptg[] fmla = sf.ConvertSharedFormulas(ptgs, RowIndex - ref1.FirstRow, ColumnIndex - ref1.FirstColumn); return FormulaRenderer.ToFormulaString(fpb, fmla); } /** * Sets formula for this cell. * <p> * Note, this method only Sets the formula string and does not calculate the formula value. * To Set the precalculated value use {@link #setCellValue(double)} or {@link #setCellValue(String)} * </p> * * @param formula the formula to Set, e.g. <code>"SUM(C4:E4)"</code>. * If the argument is <code>null</code> then the current formula is Removed. * @throws NPOI.ss.formula.FormulaParseException if the formula has incorrect syntax or is otherwise invalid * @throws InvalidOperationException if the operation is not allowed, for example, * when the cell is a part of a multi-cell array formula */ public void SetCellFormula(String formula) { if (IsPartOfArrayFormulaGroup) { NotifyArrayFormulaChanging(); } SetFormula(formula, FormulaType.Cell); } internal void SetCellArrayFormula(String formula, CellRangeAddress range) { SetFormula(formula, FormulaType.Array); CT_CellFormula cellFormula = _cell.f; cellFormula.t = (ST_CellFormulaType.array); cellFormula.@ref = (range.FormatAsString()); } private void SetFormula(String formula, FormulaType formulaType) { XSSFWorkbook wb = (XSSFWorkbook)_row.Sheet.Workbook; if (formula == null) { ((XSSFWorkbook)wb).OnDeleteFormula(this); if (_cell.IsSetF()) _cell.unsetF(); return; } if (wb.CellFormulaValidation) { IFormulaParsingWorkbook fpb = XSSFEvaluationWorkbook.Create(wb); //validate through the FormulaParser FormulaParser.Parse(formula, fpb, formulaType, wb.GetSheetIndex(this.Sheet), RowIndex); } CT_CellFormula f = new CT_CellFormula(); f.Value = formula; _cell.f= (f); if (_cell.IsSetV()) _cell.unsetV(); } /// <summary> /// Returns zero-based column index of this cell /// </summary> public int ColumnIndex { get { return this._cellNum; } } /// <summary> /// Returns zero-based row index of a row in the sheet that contains this cell /// </summary> public int RowIndex { get { return _row.RowNum; } } /// <summary> /// Returns an A1 style reference to the location of this cell /// </summary> /// <returns>A1 style reference to the location of this cell</returns> public String GetReference() { String ref1 = _cell.r; if (ref1 == null) { return new CellAddress(this).FormatAsString(); } return ref1; } public CellAddress Address { get { return new CellAddress(this); } } /// <summary> /// Return the cell's style. /// </summary> public ICellStyle CellStyle { get { XSSFCellStyle style = null; if ((null != _stylesSource) && (_stylesSource.NumCellStyles > 0)) { long idx = _cell.IsSetS() ? _cell.s : 0; style = _stylesSource.GetStyleAt((int)idx); } return style; } set { if (value == null) { if (_cell.IsSetS()) _cell.unsetS(); } else { XSSFCellStyle xStyle = (XSSFCellStyle)value; xStyle.VerifyBelongsToStylesSource(_stylesSource); long idx = _stylesSource.PutStyle(xStyle); _cell.s = (uint)idx; } } } private bool IsFormulaCell { get { if (_cell.f != null || ((XSSFSheet)Sheet).IsCellInArrayFormulaContext(this)) { return true; } return false; } } /// <summary> /// Return the cell type. /// </summary> public CellType CellType { get { if (IsFormulaCell) { return CellType.Formula; } return GetBaseCellType(true); } } /// <summary> /// Only valid for formula cells /// </summary> public CellType CachedFormulaResultType { get { if (!IsFormulaCell) { throw new InvalidOperationException("Only formula cells have cached results"); } return GetBaseCellType(false); } } /// <summary> /// Detect cell type based on the "t" attribute of the CT_Cell bean /// </summary> /// <param name="blankCells"></param> /// <returns></returns> private CellType GetBaseCellType(bool blankCells) { switch (_cell.t) { case ST_CellType.b: return CellType.Boolean; case ST_CellType.n: if (!_cell.IsSetV() && blankCells) { // ooxml does have a separate cell type of 'blank'. A blank cell Gets encoded as // (either not present or) a numeric cell with no value Set. // The formula Evaluator (and perhaps other clients of this interface) needs to // distinguish blank values which sometimes Get translated into zero and sometimes // empty string, depending on context return CellType.Blank; } return CellType.Numeric; case ST_CellType.e: return CellType.Error; case ST_CellType.s: // String is in shared strings case ST_CellType.inlineStr: // String is inline in cell case ST_CellType.str: return CellType.String; default: throw new InvalidOperationException("Illegal cell type: " + this._cell.t); } } /// <summary> /// Get the value of the cell as a date. /// </summary> public DateTime DateCellValue { get { if (CellType == CellType.Blank) { return DateTime.MinValue; } double value = NumericCellValue; bool date1904 = Sheet.Workbook.IsDate1904(); return DateUtil.GetJavaDate(value, date1904); } } public void SetCellValue(DateTime? value) { if (value == null) { SetCellType(CellType.Blank); return; } SetCellValue(value.Value); } /// <summary> /// Set a date value for the cell. Excel treats dates as numeric so you will need to format the cell as a date. /// </summary> /// <param name="value">the date value to Set this cell to. For formulas we'll set the precalculated value, /// for numerics we'll Set its value. For other types we will change the cell to a numeric cell and Set its value. </param> public void SetCellValue(DateTime value) { bool date1904 = Sheet.Workbook.IsDate1904(); SetCellValue(DateUtil.GetExcelDate(value, date1904)); } /// <summary> /// Returns the error message, such as #VALUE! /// </summary> public String ErrorCellString { get { CellType cellType = GetBaseCellType(true); if (cellType != CellType.Error) throw TypeMismatch(CellType.Error, cellType, false); return _cell.v; } } /// <summary> /// Get the value of the cell as an error code. /// For strings, numbers, and bools, we throw an exception. /// For blank cells we return a 0. /// </summary> public byte ErrorCellValue { get { String code = this.ErrorCellString; if (code == null) { return 0; } return FormulaError.ForString(code).Code; } } public void SetCellErrorValue(byte errorCode) { FormulaError error = FormulaError.ForInt(errorCode); SetCellErrorValue(error); } /// <summary> /// Set a error value for the cell /// </summary> /// <param name="error">the error value to Set this cell to. /// For formulas we'll Set the precalculated value , for errors we'll set /// its value. For other types we will change the cell to an error cell and Set its value. /// </param> public void SetCellErrorValue(FormulaError error) { _cell.t = (ST_CellType.e); _cell.v = (error.String); } /// <summary> /// Sets this cell as the active cell for the worksheet. /// </summary> public void SetAsActiveCell() { Sheet.ActiveCell = Address; } /// <summary> /// Blanks this cell. Blank cells have no formula or value but may have styling. /// This method erases all the data previously associated with this cell. /// </summary> private void SetBlankInternal() { CT_Cell blank = new CT_Cell(); blank.r = (_cell.r); if (_cell.IsSetS()) blank.s=(_cell.s); _cell.Set(blank); } public void SetBlank() { SetCellType(CellType.Blank); } /// <summary> /// Sets column index of this cell /// </summary> /// <param name="num"></param> internal void SetCellNum(int num) { CheckBounds(num); _cellNum = num; String ref1 = new CellReference(RowIndex, ColumnIndex).FormatAsString(); _cell.r = (ref1); } /// <summary> /// Set the cells type (numeric, formula or string) /// </summary> /// <param name="cellType"></param> public void SetCellType(CellType cellType) { CellType prevType = CellType; if (IsPartOfArrayFormulaGroup) { NotifyArrayFormulaChanging(); } if (prevType == CellType.Formula && cellType != CellType.Formula) { ((XSSFWorkbook)Sheet.Workbook).OnDeleteFormula(this); } switch (cellType) { case CellType.Blank: SetBlankInternal(); break; case CellType.Boolean: String newVal = ConvertCellValueToBoolean() ? TRUE_AS_STRING : FALSE_AS_STRING; _cell.t= (ST_CellType.b); _cell.v= (newVal); break; case CellType.Numeric: _cell.t = (ST_CellType.n); break; case CellType.Error: _cell.t = (ST_CellType.e); break; case CellType.String: if (prevType != CellType.String) { String str = ConvertCellValueToString(); XSSFRichTextString rt = new XSSFRichTextString(str); rt.SetStylesTableReference(_stylesSource); int sRef = _sharedStringSource.AddEntry(rt.GetCTRst()); _cell.v= sRef.ToString(); } _cell.t= (ST_CellType.s); break; case CellType.Formula: if (!_cell.IsSetF()) { CT_CellFormula f = new CT_CellFormula(); f.Value = "0"; _cell.f = (f); if (_cell.IsSetT()) _cell.unsetT(); } break; default: throw new ArgumentException("Illegal cell type: " + cellType); } if (cellType != CellType.Formula && _cell.IsSetF()) { _cell.unsetF(); } } /// <summary> /// Returns a string representation of the cell /// </summary> /// <returns>Formula cells return the formula string, rather than the formula result. /// Dates are displayed in dd-MMM-yyyy format /// Errors are displayed as #ERR&lt;errIdx&gt; /// </returns> public override String ToString() { switch (CellType) { case CellType.Blank: return ""; case CellType.Boolean: return BooleanCellValue ? "TRUE" : "FALSE"; case CellType.Error: return ErrorEval.GetText(ErrorCellValue); case CellType.Formula: return CellFormula; case CellType.Numeric: if (DateUtil.IsCellDateFormatted(this)) { FormatBase sdf = new SimpleDateFormat("dd-MMM-yyyy"); return sdf.Format(DateCellValue, CultureInfo.CurrentCulture); } return NumericCellValue.ToString(); case CellType.String: return RichStringCellValue.ToString(); default: return "Unknown Cell Type: " + CellType; } } /** * Returns the raw, underlying ooxml value for the cell * <p> * If the cell Contains a string, then this value is an index into * the shared string table, pointing to the actual string value. Otherwise, * the value of the cell is expressed directly in this element. Cells Containing formulas express * the last calculated result of the formula in this element. * </p> * * @return the raw cell value as Contained in the underlying CT_Cell bean, * <code>null</code> for blank cells. */ public String GetRawValue() { return _cell.v; } /// <summary> /// Used to help format error messages /// </summary> /// <param name="cellTypeCode"></param> /// <returns></returns> private static String GetCellTypeName(CellType cellTypeCode) { switch (cellTypeCode) { case CellType.Blank: return "blank"; case CellType.String: return "text"; case CellType.Boolean: return "bool"; case CellType.Error: return "error"; case CellType.Numeric: return "numeric"; case CellType.Formula: return "formula"; } return "#unknown cell type (" + cellTypeCode + ")#"; } /** * Used to help format error messages */ private static Exception TypeMismatch(CellType expectedTypeCode, CellType actualTypeCode, bool isFormulaCell) { String msg = "Cannot get a " + GetCellTypeName(expectedTypeCode) + " value from a " + GetCellTypeName(actualTypeCode) + " " + (isFormulaCell ? "formula " : "") + "cell"; return new InvalidOperationException(msg); } /** * @throws RuntimeException if the bounds are exceeded. */ private static void CheckBounds(int cellIndex) { SpreadsheetVersion v = SpreadsheetVersion.EXCEL2007; int maxcol = SpreadsheetVersion.EXCEL2007.LastColumnIndex; if (cellIndex < 0 || cellIndex > maxcol) { throw new ArgumentException("Invalid column index (" + cellIndex + "). Allowable column range for " + v.ToString() + " is (0.." + maxcol + ") or ('A'..'" + v.LastColumnName + "')"); } } /// <summary> /// Returns cell comment associated with this cell /// </summary> public IComment CellComment { get { return Sheet.GetCellComment(new CellAddress(this)); } set { if (value == null) { RemoveCellComment(); return; } value.SetAddress(RowIndex, ColumnIndex); } } /// <summary> /// Removes the comment for this cell, if there is one. /// </summary> public void RemoveCellComment() { IComment comment = this.CellComment; if (comment != null) { CellAddress ref1 = new CellAddress(GetReference()); XSSFSheet sh = (XSSFSheet)Sheet; sh.GetCommentsTable(false).RemoveComment(ref1); sh.GetVMLDrawing(false).RemoveCommentShape(RowIndex, ColumnIndex); } } /// <summary> /// Get or set hyperlink associated with this cell /// If the supplied hyperlink is null on setting, the hyperlink for this cell will be removed. /// </summary> public IHyperlink Hyperlink { get { return ((XSSFSheet)Sheet).GetHyperlink(_row.RowNum, _cellNum); } set { if (value == null) { RemoveHyperlink(); return; } XSSFHyperlink link = (XSSFHyperlink)value; // Assign to us link.SetCellReference(new CellReference(_row.RowNum, _cellNum).FormatAsString()); // Add to the lists ((XSSFSheet)Sheet).AddHyperlink(link); } } /** * Removes the hyperlink for this cell, if there is one. */ public void RemoveHyperlink() { ((XSSFSheet)Sheet).RemoveHyperlink(_row.RowNum, _cellNum); } /** * Returns the xml bean containing information about the cell's location (reference), value, * data type, formatting, and formula * * @return the xml bean containing information about this cell */ internal CT_Cell GetCTCell() { return _cell; } /** * Chooses a new bool value for the cell when its type is changing.<p/> * * Usually the caller is calling SetCellType() with the intention of calling * SetCellValue(bool) straight afterwards. This method only exists to give * the cell a somewhat reasonable value until the SetCellValue() call (if at all). * TODO - perhaps a method like SetCellTypeAndValue(int, Object) should be introduced to avoid this */ private bool ConvertCellValueToBoolean() { CellType cellType = CellType; if (cellType == CellType.Formula) { cellType = GetBaseCellType(false); } switch (cellType) { case CellType.Boolean: return TRUE_AS_STRING.Equals(_cell.v); case CellType.String: int sstIndex = Int32.Parse(_cell.v); XSSFRichTextString rt = new XSSFRichTextString(_sharedStringSource.GetEntryAt(sstIndex)); String text = rt.String; return Boolean.Parse(text); case CellType.Numeric: return Double.Parse(_cell.v, CultureInfo.InvariantCulture) != 0; case CellType.Error: case CellType.Blank: return false; } throw new RuntimeException("Unexpected cell type (" + cellType + ")"); } private String ConvertCellValueToString() { CellType cellType = CellType; switch (cellType) { case CellType.Blank: return ""; case CellType.Boolean: return TRUE_AS_STRING.Equals(_cell.v) ? "TRUE" : "FALSE"; case CellType.String: int sstIndex = Int32.Parse(_cell.v); XSSFRichTextString rt = new XSSFRichTextString(_sharedStringSource.GetEntryAt(sstIndex)); return rt.String; case CellType.Numeric: case CellType.Error: return _cell.v; case CellType.Formula: // should really Evaluate, but HSSFCell can't call HSSFFormulaEvaluator // just use cached formula result instead break; default: throw new InvalidOperationException("Unexpected cell type (" + cellType + ")"); } cellType = GetBaseCellType(false); String textValue = _cell.v; switch (cellType) { case CellType.Boolean: if (TRUE_AS_STRING.Equals(textValue)) { return "TRUE"; } if (FALSE_AS_STRING.Equals(textValue)) { return "FALSE"; } throw new InvalidOperationException("Unexpected bool cached formula value '" + textValue + "'."); case CellType.String: case CellType.Numeric: case CellType.Error: return textValue; } throw new InvalidOperationException("Unexpected formula result type (" + cellType + ")"); } public CellRangeAddress ArrayFormulaRange { get { XSSFCell cell = ((XSSFSheet)Sheet).GetFirstCellInArrayFormula(this); if (cell == null) { throw new InvalidOperationException("Cell " + GetReference() + " is not part of an array formula."); } String formulaRef = cell._cell.f.@ref; return CellRangeAddress.ValueOf(formulaRef); } } public bool IsPartOfArrayFormulaGroup { get { return ((XSSFSheet)Sheet).IsCellInArrayFormulaContext(this); } } /** * The purpose of this method is to validate the cell state prior to modification * * @see #NotifyArrayFormulaChanging() */ internal void NotifyArrayFormulaChanging(String msg) { if (IsPartOfArrayFormulaGroup) { CellRangeAddress cra = this.ArrayFormulaRange; if (cra.NumberOfCells > 1) { throw new InvalidOperationException(msg); } //un-register the Single-cell array formula from the parent XSSFSheet Row.Sheet.RemoveArrayFormula(this); } } /// <summary> /// Called when this cell is modified.The purpose of this method is to validate the cell state prior to modification. /// </summary> /// <exception cref="InvalidOperationException">if modification is not allowed</exception> internal void NotifyArrayFormulaChanging() { CellReference ref1 = new CellReference(this); String msg = "Cell " + ref1.FormatAsString() + " is part of a multi-cell array formula. " + "You cannot change part of an array."; NotifyArrayFormulaChanging(msg); } #region ICell Members public bool IsMergedCell { get { return this.Sheet.IsMergedRegion(new CellRangeAddress(this.RowIndex, this.RowIndex, this.ColumnIndex, this.ColumnIndex)); } } #endregion public ICell CopyCellTo(int targetIndex) { return CellUtil.CopyCell(this.Row, this.ColumnIndex, targetIndex); } public CellType GetCachedFormulaResultTypeEnum() { throw new NotImplementedException(); } } }
36.590389
137
0.492808
[ "Apache-2.0" ]
LiveFly/npoi
ooxml/XSSF/UserModel/XSSFCell.cs
47,970
C#
/* *************************************************************************** * This file is part of SharpNEAT - Evolution of Neural Networks. * * Copyright 2004-2016 Colin Green (sharpneat@gmail.com) * * SharpNEAT is free software; you can redistribute it and/or modify * it under the terms of The MIT License (MIT). * * You should have received a copy of the MIT License * along with SharpNEAT; if not, see https://opensource.org/licenses/MIT. */ using Redzen.Numerics; using SharpNeat.Core; using SharpNeat.Network; using System; using System.Collections.Generic; using System.Diagnostics; namespace SharpNeat.Genomes.Neat { /// <summary> /// A genome class for Neuro Evolution of Augmenting Topologies (NEAT). /// /// Note that neuron genes must be arranged according to the following layout plan. /// Bias - single neuron. Innovation ID = 0 /// Input neurons. /// Output neurons. /// Hidden neurons. /// /// This allows us to add and remove hidden neurons without affecting the position of the bias, /// input and output neurons; This is convenient because bias and input and output neurons are /// fixed, they cannot be added to or removed and so remain constant throughout a given run. In fact they /// are only stored in the same list as hidden nodes as an efficiency measure when producing offspring /// and decoding genomes, otherwise it would probably make sense to store them in read-only lists. /// </summary> public class NeatGenome : IGenome<NeatGenome>, INetworkDefinition { #region Instance Variables NeatGenomeFactory _genomeFactory; readonly uint _id; int _specieIdx; readonly uint _birthGeneration; EvaluationInfo _evalInfo; CoordinateVector _position; object _cachedPhenome; // We ensure that the connectionGenes are sorted by innovation ID at all times. This allows significant optimisations // to be made in crossover and decoding routines. // Neuron genes must also be arranged according to the following layout plan. // Bias - single neuron. Innovation ID = 0 // Input neurons. // Output neurons. // Hidden neurons. readonly NeuronGeneList _neuronGeneList; readonly ConnectionGeneList _connectionGeneList; // For efficiency we store the number of input and output neurons. These two quantities do not change // throughout the life of a genome. Note that inputNeuronCount does NOT include the bias neuron; Use // inputAndBiasNeuronCount. readonly int _inputNeuronCount; readonly int _outputNeuronCount; readonly int _inputAndBiasNeuronCount; readonly int _inputBiasOutputNeuronCount; int _auxStateNeuronCount; // Created in a just-in-time manner and cached for possible re-use. NetworkConnectivityData _networkConnectivityData; #endregion #region Constructors /// <summary> /// Constructs with the provided ID, birth generation and gene lists. /// </summary> public NeatGenome(NeatGenomeFactory genomeFactory, uint id, uint birthGeneration, NeuronGeneList neuronGeneList, ConnectionGeneList connectionGeneList, int inputNeuronCount, int outputNeuronCount, bool rebuildNeuronGeneConnectionInfo) { _genomeFactory = genomeFactory; _id = id; _birthGeneration = birthGeneration; _neuronGeneList = neuronGeneList; _connectionGeneList = connectionGeneList; _inputNeuronCount = inputNeuronCount; _outputNeuronCount = outputNeuronCount; // Precalculate some often used values. _inputAndBiasNeuronCount = inputNeuronCount+1; _inputBiasOutputNeuronCount = _inputAndBiasNeuronCount + outputNeuronCount; // Rebuild per neuron connection info if caller has requested it. if(rebuildNeuronGeneConnectionInfo) { RebuildNeuronGeneConnectionInfo(); } // If we have a factory then create the evaluation info object now, also count the nodes that have auxiliary state. // Otherwise wait until the factory is provided through the property setter. if(null != _genomeFactory) { _evalInfo = new EvaluationInfo(genomeFactory.NeatGenomeParameters.FitnessHistoryLength); _auxStateNeuronCount = CountAuxStateNodes(); } Debug.Assert(PerformIntegrityCheck()); } /// <summary> /// Copy constructor. /// </summary> public NeatGenome(NeatGenome copyFrom, uint id, uint birthGeneration) { _genomeFactory = copyFrom._genomeFactory; _id = id; _birthGeneration = birthGeneration; // These copy constructors make clones of the genes rather than copies of the object references. _neuronGeneList = new NeuronGeneList(copyFrom._neuronGeneList); _connectionGeneList = new ConnectionGeneList(copyFrom._connectionGeneList); // Copy pre-calculated values. _inputNeuronCount = copyFrom._inputNeuronCount; _outputNeuronCount = copyFrom._outputNeuronCount; _auxStateNeuronCount = copyFrom._auxStateNeuronCount; _inputAndBiasNeuronCount = copyFrom._inputAndBiasNeuronCount; _inputBiasOutputNeuronCount = copyFrom._inputBiasOutputNeuronCount; _evalInfo = new EvaluationInfo(copyFrom.EvaluationInfo.FitnessHistoryLength); Debug.Assert(PerformIntegrityCheck()); } #endregion #region IGenome<NeatGenome> Members /// <summary> /// Gets the genome's unique ID. IDs are unique across all genomes created from a single /// IGenomeFactory and all ancestor genomes spawned from those genomes. /// </summary> public uint Id { get { return _id; } } /// <summary> /// Gets or sets a specie index. This is the index of the species that the genome is in. /// Implementing this is required only when using evolution algorithms that speciate genomes. /// </summary> public int SpecieIdx { get { return _specieIdx; } set { _specieIdx = value; } } /// <summary> /// Gets the generation that this genome was born/created in. Used to track genome age. /// </summary> public uint BirthGeneration { get { return _birthGeneration; } } /// <summary> /// Gets evaluation information for the genome, including its fitness. /// </summary> public EvaluationInfo EvaluationInfo { get { return _evalInfo; } } /// <summary> /// Gets a value that indicates the magnitude of a genome's complexity. /// For a NeatGenome we return the number of connection genes since a neural network's /// complexity is approximately proportional to the number of connections - the number of /// neurons is less important and can be viewed as being a limit on the possible number of /// connections. /// </summary> public double Complexity { get { return _connectionGeneList.Count; } } /// <summary> /// Gets a coordinate that represents the genome's position in the search space (also known /// as the genetic encoding space). This allows speciation/clustering algorithms to operate on /// an abstract coordinate data type rather than being coded against specific IGenome types. /// </summary> public CoordinateVector Position { get { if(null == _position) { // Consider each connection gene as a dimension where the innovation ID is the // dimension's ID and the weight is the position within that dimension. // The coordinate elements in the resulting array must be sorted by innovation/dimension ID, // this requirement is met by the connection gene list also requiring to be sorted at all times. ConnectionGeneList list = _connectionGeneList; int count = list.Count; KeyValuePair<ulong,double>[] coordElemArray = new KeyValuePair<ulong,double>[count]; for(int i=0; i<count; i++) { coordElemArray[i] = new KeyValuePair<ulong,double>(list[i].InnovationId, list[i].Weight); } _position = new CoordinateVector(coordElemArray); } return _position; } } /// <summary> /// Gets or sets a cached phenome obtained from decoding the genome. /// Genomes are typically decoded to Phenomes for evaluation. This property allows decoders to /// cache the phenome in order to avoid decoding on each re-evaluation; However, this is optional. /// The phenome in un-typed to prevent the class framework from becoming overly complex. /// </summary> public object CachedPhenome { get { return _cachedPhenome; } set { _cachedPhenome = value; } } /// <summary> /// Asexual reproduction. /// </summary> /// <param name="birthGeneration">The current evolution algorithm generation. /// Assigned to the new genome at its birth generation.</param> public NeatGenome CreateOffspring(uint birthGeneration) { // Make a new genome that is a copy of this one but with a new genome ID. NeatGenome offspring = _genomeFactory.CreateGenomeCopy(this, _genomeFactory.NextGenomeId(), birthGeneration); // Mutate the new genome. offspring.Mutate(); return offspring; } /// <summary> /// Sexual reproduction. /// </summary> /// <param name="parent">The other parent genome (mates with the current genome).</param> /// <param name="birthGeneration">The current evolution algorithm generation. /// Assigned to the new genome at its birth generation.</param> public NeatGenome CreateOffspring(NeatGenome parent, uint birthGeneration) { // NOTE: Feed-forward only networks. Due to how this crossover method works the resulting offspring will never have recurrent // connections if the two parents are feed-forward only, this is because we do not actually mix the connectivity of the two // parents (only the connection weights were there is a match). Therefore any changes to this method must take feed-forward // networks into account. CorrelationResults correlationResults = CorrelateConnectionGeneLists(_connectionGeneList, parent._connectionGeneList); Debug.Assert(correlationResults.PerformIntegrityCheck(), "CorrelationResults failed integrity check."); // Construct a ConnectionGeneListBuilder with its capacity set the maximum number of connections that // could be added to it (all connection genes from both parents). This eliminates the possibility of having to // re-allocate list memory, improving performance at the cost of a little additional allocated memory on average. ConnectionGeneListBuilder connectionListBuilder = new ConnectionGeneListBuilder(_connectionGeneList.Count + parent._connectionGeneList.Count); // Pre-register all of the fixed neurons (bias, inputs and outputs) with the ConnectionGeneListBuilder's // neuron ID dictionary. We do this so that we can use the dictionary later on as a complete list of // all neuron IDs required by the offspring genome - if we didn't do this we might miss some of the fixed neurons // that happen to not be connected to or from. SortedDictionary<uint,NeuronGene> neuronDictionary = connectionListBuilder.NeuronDictionary; for(int i=0; i<_inputBiasOutputNeuronCount; i++) { neuronDictionary.Add(_neuronGeneList[i].InnovationId, _neuronGeneList[i].CreateCopy(false)); } // A variable that stores which parent is fittest, 1 or 2. We pre-calculate this value because this // fitness test needs to be done in subsequent sub-routine calls for each connection gene. int fitSwitch; if(_evalInfo.Fitness > parent._evalInfo.Fitness) { fitSwitch = 1; } else if(_evalInfo.Fitness < parent._evalInfo.Fitness) { fitSwitch = 2; } else { // Select one of the parents at random to be the 'master' genome during crossover. fitSwitch = (_genomeFactory.Rng.NextDouble() < 0.5) ? 1 : 2; } // TODO: Reconsider this approach. // Pre-calculate a flag that indicates if excess and disjoint genes should be copied into the offspring genome. // Excess and disjoint genes are either copied altogether or none at all. bool combineDisjointExcessFlag = _genomeFactory.Rng.NextDouble() < _genomeFactory.NeatGenomeParameters.DisjointExcessGenesRecombinedProbability; // Loop through the items within the CorrelationResults, processing each one in turn. // Where we have a match between parents we select which parent's copy (effectively which connection weight) to // use probabilistically with even chance. // For disjoint and excess genes, if they are on the fittest parent (as indicated by fitSwitch) we always take that gene. // If the disjoint/excess gene is on the least fit parent then we take that gene also but only when // combineDisjointExcessFlag is true. // Loop 1: Get all genes that are present on the fittest parent. // Note. All accepted genes are accumulated within connectionListBuilder. // Note. Any disjoint/excess genes that we wish to select from the least fit parent are stored in a second list for processing later // (this avoids having to do another complete pass through the correlation results). The principle reason for this is handling detection of // cyclic connections when combining two genomes when evolving feed-forward-only networks. Each genome by itself will be acyclic, so can safely // copy all genes from any one parent, but for any genes from the other parent we then need to check each one as we add it to the offspring // genome to check if it would create a cycle. List<CorrelationItem> disjointExcessGeneList = combineDisjointExcessFlag ? new List<CorrelationItem>(correlationResults.CorrelationStatistics.DisjointConnectionGeneCount + correlationResults.CorrelationStatistics.ExcessConnectionGeneCount) : null; foreach(CorrelationItem correlItem in correlationResults.CorrelationItemList) { // Determine which genome to copy from (if any) int selectionSwitch; if(CorrelationItemType.Match == correlItem.CorrelationItemType) { // For matches pick a parent genome at random (they both have the same connection gene, // but with a different connection weight) selectionSwitch = DiscreteDistributionUtils.SampleBinaryDistribution(0.5, _genomeFactory.Rng) ? 1 : 2; } else if(1==fitSwitch && null != correlItem.ConnectionGene1) { // Disjoint/excess gene on the fittest genome (genome #1). selectionSwitch = 1; } else if(2==fitSwitch && null != correlItem.ConnectionGene2) { // Disjoint/excess gene on the fittest genome (genome #2). selectionSwitch = 2; } else { // Disjoint/excess gene on the least fit genome. if(combineDisjointExcessFlag) { // Put to one side for processing later. disjointExcessGeneList.Add(correlItem); } // Skip to next gene. continue; } // Get ref to the selected connection gene and its source target neuron genes. ConnectionGene connectionGene; NeatGenome parentGenome; if(1 == selectionSwitch) { connectionGene = correlItem.ConnectionGene1; parentGenome = this; } else { connectionGene = correlItem.ConnectionGene2; parentGenome = parent; } // Add connection gene to the offspring's genome. For genes from a match we set a flag to force // an override of any existing gene with the same innovation ID (which may have come from a previous disjoint/excess gene). // We prefer matched genes as they will tend to give better fitness to the offspring - this logic if based purely on the // fact that the gene has clearly been replicated at least once before and survived within at least two genomes. connectionListBuilder.TryAddGene(connectionGene, parentGenome, (CorrelationItemType.Match == correlItem.CorrelationItemType)); } // Loop 2: Add disjoint/excess genes from the least fit parent (if any). These may create connectivity cycles, hence we need to test // for this when evolving feed-forward-only networks. if(null != disjointExcessGeneList && 0 != disjointExcessGeneList.Count) { foreach(CorrelationItem correlItem in disjointExcessGeneList) { // Get ref to the selected connection gene and its source target neuron genes. ConnectionGene connectionGene; NeatGenome parentGenome; if(null != correlItem.ConnectionGene1) { connectionGene = correlItem.ConnectionGene1; parentGenome = this; } else { connectionGene = correlItem.ConnectionGene2; parentGenome = parent; } // We are effectively adding connections from one genome to another, as such it is possible to create cyclic connections here. // Thus only add the connection if we allow cyclic connections *or* the connection does not form a cycle. if(!_genomeFactory.NeatGenomeParameters.FeedforwardOnly || !connectionListBuilder.IsConnectionCyclic(connectionGene.SourceNodeId, connectionGene.TargetNodeId)) { // Add connection gene to the offspring's genome. connectionListBuilder.TryAddGene(connectionGene, parentGenome, false); } } } // Extract the connection builders definitive list of neurons into a list. NeuronGeneList neuronGeneList = new NeuronGeneList(connectionListBuilder.NeuronDictionary.Count); foreach(NeuronGene neuronGene in neuronDictionary.Values) { neuronGeneList.Add(neuronGene); } // Note that connectionListBuilder.ConnectionGeneList is already sorted by connection gene innovation ID // because it was generated by passing over the correlation items generated by CorrelateConnectionGeneLists() // - which returns correlation items in order. return _genomeFactory.CreateGenome(_genomeFactory.NextGenomeId(), birthGeneration, neuronGeneList, connectionListBuilder.ConnectionGeneList, _inputNeuronCount, _outputNeuronCount, false); } #endregion #region Properties [NEAT Genome Specific] /// <summary> /// Gets or sets the NeatGenomeFactory associated with the genome. A reference to the factory is /// passed to spawned genomes, this allows all genomes within a population to have access to common /// data such as NeatGenomeParameters and an ID generator. /// Setting the genome factory after construction is allowed in order to resolve chicken-and-egg /// scenarios when loading genomes from storage. /// </summary> public NeatGenomeFactory GenomeFactory { get { return _genomeFactory; } set { if(null != _genomeFactory) { throw new SharpNeatException("NeatGenome already has an assigned GenomeFactory."); } _genomeFactory = value; _evalInfo = new EvaluationInfo(_genomeFactory.NeatGenomeParameters.FitnessHistoryLength); _auxStateNeuronCount = CountAuxStateNodes(); } } /// <summary> /// Gets the genome's list of neuron genes. /// </summary> public NeuronGeneList NeuronGeneList { get { return _neuronGeneList; } } /// <summary> /// Gets the genome's list of connection genes. /// </summary> public ConnectionGeneList ConnectionGeneList { get { return _connectionGeneList; } } /// <summary> /// Gets the number of input neurons represented by the genome. /// </summary> public int InputNeuronCount { get { return _inputNeuronCount; } } /// <summary> /// Gets the number of input and bias neurons represented by the genome. /// </summary> public int InputAndBiasNeuronCount { get { return _inputAndBiasNeuronCount; } } /// <summary> /// Gets the number of output neurons represented by the genome. /// </summary> public int OutputNeuronCount { get { return _outputNeuronCount; } } /// <summary> /// Gets the number total number of neurons represented by the genome. /// </summary> public int InputBiasOutputNeuronCount { get { return _inputBiasOutputNeuronCount; } } #endregion #region Private Methods [Asexual Reproduction / Mutation] private void Mutate() { // If we have fewer than two connections then use an alternative RouletteWheelLayout that avoids // destructive mutations. This prevents the creation of genomes with no connections. DiscreteDistribution rwlInitial = (_connectionGeneList.Count < 2) ? _genomeFactory.NeatGenomeParameters.RouletteWheelLayoutNonDestructive : _genomeFactory.NeatGenomeParameters.RouletteWheelLayout; // Select a type of mutation and attempt to perform it. If that mutation is not possible // then we eliminate that possibility from the roulette wheel and try again until a mutation is successful // or we have no mutation types remaining to try. DiscreteDistribution distCurrent = rwlInitial; bool success = false; bool structureChange = false; for(;;) { int outcome = distCurrent.Sample(_genomeFactory.Rng); switch(outcome) { case 0: Mutate_ConnectionWeights(); // Connection weight mutation is assumed to always succeed - genomes should always have at least one connection to mutate. success = true; break; case 1: success = structureChange = (null != Mutate_AddNode()); break; case 2: success = structureChange = (null != Mutate_AddConnection()); break; case 3: success = Mutate_NodeAuxState(); break; case 4: success = structureChange = (null != Mutate_DeleteConnection()); break; default: throw new SharpNeatException(string.Format("NeatGenome.Mutate(): Unexpected outcome value [{0}]", outcome)); } // Success. Break out of loop. if(success) { if(structureChange) { // Discard any cached connectivity data. It is now invalidated. _networkConnectivityData = null; } break; } // Mutation did not succeed. Remove attempted type of mutation from set of possible outcomes. distCurrent = distCurrent.RemoveOutcome(outcome); if(0 == distCurrent.Probabilities.Length) { // Nothing left to try. Do nothing. return; } } // Mutation succeeded. Check resulting genome. Debug.Assert(PerformIntegrityCheck()); } /// <summary> /// Add a new node to the Genome. We do this by removing a connection at random and inserting a new /// node and two new connections that make the same circuit as the original connection, that is, we split an /// existing connection. This way the new node is integrated into the network from the outset. /// </summary> /// <returns>Returns the added NeuronGene if successful, otherwise null.</returns> private NeuronGene Mutate_AddNode() { if(0 == _connectionGeneList.Count) { // Nodes are added by splitting an existing connection into two and placing a new node // between the two new connections. Since we don't have any connections to split we // indicate failure. return null; } // Select a connection at random, keep a ref to it and delete it from the genome. int connectionToReplaceIdx = _genomeFactory.Rng.Next(_connectionGeneList.Count); ConnectionGene connectionToReplace = _connectionGeneList[connectionToReplaceIdx]; _connectionGeneList.RemoveAt(connectionToReplaceIdx); // Get IDs for the two new connections and a single neuron. This call will check the history // buffer (AddedNeuronBuffer) for matching structures from previously added neurons (for the search as // a whole, not just on this genome). AddedNeuronGeneStruct idStruct; bool reusedIds = Mutate_AddNode_GetIDs(connectionToReplace.InnovationId, out idStruct); // Replace connection with two new connections and a new neuron. The first connection uses the weight // from the replaced connection (so it's functionally the same connection, but the ID is new). Ideally // we want the functionality of the new structure to match as closely as possible the replaced connection, // but that depends on the neuron activation function. As a cheap/quick approximation we make the second // connection's weight full strength (_genomeFactory.NeatGenomeParameters.ConnectionWeightRange). This // maps the range 0..1 being output from the new neuron to something close to 0.5..1.0 when using a unipolar // sigmoid (depending on exact sigmoid function in use). Weaker weights reduce that range, ultimately a zero // weight always gives an output of 0.5 for a unipolar sigmoid. NeuronGene newNeuronGene = _genomeFactory.CreateNeuronGene(idStruct.AddedNeuronId, NodeType.Hidden); ConnectionGene newConnectionGene1 = new ConnectionGene(idStruct.AddedInputConnectionId, connectionToReplace.SourceNodeId, idStruct.AddedNeuronId, connectionToReplace.Weight); ConnectionGene newConnectionGene2 = new ConnectionGene(idStruct.AddedOutputConnectionId, idStruct.AddedNeuronId, connectionToReplace.TargetNodeId, _genomeFactory.NeatGenomeParameters.ConnectionWeightRange); // If we are re-using innovation numbers from elsewhere in the population they are likely to have // lower values than other genes in the current genome. Therefore we need to be careful to ensure the // genes lists remain sorted by innovation ID. The most efficient means of doing this is to insert the new // genes into the correct location (as opposed to adding them to the list ends and re-sorting the lists). if(reusedIds) { _neuronGeneList.InsertIntoPosition(newNeuronGene); _connectionGeneList.InsertIntoPosition(newConnectionGene1); _connectionGeneList.InsertIntoPosition(newConnectionGene2); } else { // The genes have new innovation IDs - so just add them to the ends of the gene lists. _neuronGeneList.Add(newNeuronGene); _connectionGeneList.Add(newConnectionGene1); _connectionGeneList.Add(newConnectionGene2); } // Track connections associated with each neuron. // Original source neuron. NeuronGene srcNeuronGene = _neuronGeneList.GetNeuronById(connectionToReplace.SourceNodeId); srcNeuronGene.TargetNeurons.Remove(connectionToReplace.TargetNodeId); srcNeuronGene.TargetNeurons.Add(newNeuronGene.Id); // Original target neuron. NeuronGene tgtNeuronGene = _neuronGeneList.GetNeuronById(connectionToReplace.TargetNodeId); tgtNeuronGene.SourceNeurons.Remove(connectionToReplace.SourceNodeId); tgtNeuronGene.SourceNeurons.Add(newNeuronGene.Id); // New neuron. newNeuronGene.SourceNeurons.Add(connectionToReplace.SourceNodeId); newNeuronGene.TargetNeurons.Add(connectionToReplace.TargetNodeId); // Track aux state node count and update stats. if(_genomeFactory.ActivationFnLibrary.GetFunction(newNeuronGene.ActivationFnId).AcceptsAuxArgs) { _auxStateNeuronCount++; } _genomeFactory.Stats._mutationCountAddNode++; // Indicate success. return newNeuronGene; } /// <summary> /// Gets innovation IDs for a new neuron and two connections. We add neurons by splitting an existing connection, here we /// check if the connection to be split has previously been split and if so attempt to re-use the IDs assigned during that /// split. /// </summary> /// <param name="connectionToReplaceId">ID of the connection that is being replaced.</param> /// <param name="idStruct">Conveys the required IDs back to the caller.</param> /// <returns>Returns true if the IDs are existing IDs from a matching structure in the history buffer (AddedNeuronBuffer).</returns> private bool Mutate_AddNode_GetIDs(uint connectionToReplaceId, out AddedNeuronGeneStruct idStruct) { bool registerNewStruct = false; if(_genomeFactory.AddedNeuronBuffer.TryGetValue(connectionToReplaceId, out idStruct)) { // Found existing matching structure. // However we can only re-use the IDs from that structure if they aren't already present in the current genome; // this is possible because genes can be acquired from other genomes via sexual reproduction. // Therefore we only re-use IDs if we can re-use all three together, otherwise we aren't assigning the IDs to matching // structures throughout the population, which is the reason for ID re-use. if(_neuronGeneList.BinarySearch(idStruct.AddedNeuronId) < 0 && _connectionGeneList.BinarySearch(idStruct.AddedInputConnectionId) < 0 && _connectionGeneList.BinarySearch(idStruct.AddedOutputConnectionId) < 0) { // Return true to indicate re-use of existing IDs. return true; } } else { // ConnectionID not found. This connectionID has not been split to add a neuron in the past, or at least as far // back as the history buffer goes. Therefore we register the structure with the history buffer. registerNewStruct = true; } // No pre-existing matching structure or if there is we already have some of its genes (from sexual reproduction). // Generate new IDs for this structure. idStruct = new AddedNeuronGeneStruct(_genomeFactory.InnovationIdGenerator); // If the connectionToReplaceId was not found (above) then we register it along with the new structure // it is being replaced with. if(registerNewStruct) { _genomeFactory.AddedNeuronBuffer.Enqueue(connectionToReplaceId, idStruct); } return false; } /// <summary> /// Attempt to perform a connection addition mutation. Returns the added connection gene if successful. /// </summary> private ConnectionGene Mutate_AddConnection() { // We attempt to find a pair of neurons with no connection between them in one or both directions. We disallow multiple // connections between the same two neurons going in the same direction, but we *do* allow connections going // in opposite directions (one connection each way). We also allow a neuron to have a single recurrent connection, // that is, a connection that has the same neuron as its source and target neuron. // ENHANCEMENT: Test connection 'density' and use alternative connection selection method if above some threshold. // Because input/output neurons are fixed (cannot be added to or deleted) and always present (any domain that // doesn't require input/outputs is a bit nonsensical) we always have candidate pairs of neurons to consider // adding connections to, but if all neurons are already fully interconnected then we should handle this case // where there are no possible neuron pairs to add a connection to. To handle this we use a simple strategy // of testing the suitability of randomly selected pairs and after some number of failed tests we bail out // of the routine and perform weight mutation as a last resort - so that we did at least some form of mutation on // the genome. if(_neuronGeneList.Count < 3) { // We should always have at least three neurons - one each of a bias, input and output neuron. return null; } // TODO: Try to improve chance of finding a candidate connection to make. // We have at least 2 neurons, so we have a chance at creating a connection. int neuronCount = _neuronGeneList.Count; int hiddenOutputNeuronCount = neuronCount - _inputAndBiasNeuronCount; int inputBiasHiddenNeuronCount = neuronCount - _outputNeuronCount; // Use slightly different logic when evolving feed-forward only networks. if(_genomeFactory.NeatGenomeParameters.FeedforwardOnly) { // Feed-forward networks. for(int attempts=0; attempts<5; attempts++) { // Select candidate source and target neurons. // Valid source nodes are bias, input and hidden nodes. Output nodes are not source node candidates // for acyclic nets (because that can prevent future connections from targeting the output if it would // create a cycle). int srcNeuronIdx = _genomeFactory.Rng.Next(inputBiasHiddenNeuronCount); if(srcNeuronIdx >= _inputAndBiasNeuronCount) { srcNeuronIdx += _outputNeuronCount; } // Valid target nodes are all hidden and output nodes. // ENHANCEMENT: Devise more efficient strategy. This can still select the same node as source and target (the cyclic connection is tested for below). int tgtNeuronIdx = _inputAndBiasNeuronCount + _genomeFactory.Rng.Next(hiddenOutputNeuronCount-1); if(srcNeuronIdx == tgtNeuronIdx) { // The source neuron was selected. To ensure selections are evenly distributed across all valid targets, this // selection is substituted with the last possible node in the list of possibilities (the last output node). tgtNeuronIdx = neuronCount-1; } // Test if this connection already exists or is recurrent NeuronGene sourceNeuron = _neuronGeneList[srcNeuronIdx]; NeuronGene targetNeuron = _neuronGeneList[tgtNeuronIdx]; if(sourceNeuron.TargetNeurons.Contains(targetNeuron.Id) || IsConnectionCyclic(sourceNeuron, targetNeuron.Id)) { // Try again. continue; } return Mutate_AddConnection_CreateConnection(sourceNeuron, targetNeuron); } } else { // Recurrent networks. for(int attempts=0; attempts<5; attempts++) { // Select candidate source and target neurons. Any neuron can be used as the source. Input neurons // should not be used as a target // Source neuron can by any neuron. Target neuron is any neuron except input neurons. int srcNeuronIdx = _genomeFactory.Rng.Next(neuronCount); int tgtNeuronIdx = _inputAndBiasNeuronCount + _genomeFactory.Rng.Next(hiddenOutputNeuronCount); // Test if this connection already exists. NeuronGene sourceNeuron = _neuronGeneList[srcNeuronIdx]; NeuronGene targetNeuron = _neuronGeneList[tgtNeuronIdx]; if(sourceNeuron.TargetNeurons.Contains(targetNeuron.Id)) { // Try again. continue; } return Mutate_AddConnection_CreateConnection(sourceNeuron, targetNeuron); } } // No valid connection to create was found. // Indicate failure. return null; } /// <summary> /// Tests if adding the specified connection would cause a cyclic pathway in the network connectivity. /// Returns true if the connection would form a cycle. /// </summary> private bool IsConnectionCyclic(NeuronGene sourceNeuron, uint targetNeuronId) { // Quick test. Is connection connecting a neuron to itself. if(sourceNeuron.Id == targetNeuronId) { return true; } // Trace backwards through sourceNeuron's source neurons. If targetNeuron is encountered then it feeds // signals into sourceNeuron already and therefore a new connection between sourceNeuron and targetNeuron // would create a cycle. // Maintain a set of neurons that have been visited. This allows us to avoid unnecessary re-traversal // of the network and detection of cyclic connections. HashSet<uint> visitedNeurons = new HashSet<uint>(); visitedNeurons.Add(sourceNeuron.Id); // This search uses an explicitly created stack instead of function recursion, the logic here is that this // may be more efficient through avoidance of multiple function calls (but not sure). Stack<uint> workStack = new Stack<uint>(); // Push source neuron's sources onto the work stack. We could just push the source neuron but we choose // to cover that test above to avoid the one extra neuronID lookup that would require. foreach(uint neuronId in sourceNeuron.SourceNeurons) { workStack.Push(neuronId); } // While there are neurons to check/traverse. while(0 != workStack.Count) { // Pop a neuron to check from the top of the stack, and then check it. uint currNeuronId = workStack.Pop(); if(visitedNeurons.Contains(currNeuronId)) { // Already visited (via a different route). continue; } if(currNeuronId == targetNeuronId) { // Target neuron already feeds into the source neuron. return true; } // Register visit of this node. visitedNeurons.Add(currNeuronId); // Push the current neuron's source neurons onto the work stack. NeuronGene currNeuron = _neuronGeneList.GetNeuronById(currNeuronId); foreach(uint neuronId in currNeuron.SourceNeurons) { workStack.Push(neuronId); } } // Connection not cyclic. return false; } private ConnectionGene Mutate_AddConnection_CreateConnection(NeuronGene sourceNeuron, NeuronGene targetNeuron) { uint sourceId = sourceNeuron.Id; uint targetId = targetNeuron.Id; // Determine the connection weight. // TODO: Make this behaviour configurable. // 50% of the time use weights very close to zero. double connectionWeight = _genomeFactory.GenerateRandomConnectionWeight(); if(_genomeFactory.Rng.NextBool()) { connectionWeight *= 0.01; } // Check if a matching mutation has already occurred on another genome. // If so then re-use the connection ID. ConnectionEndpointsStruct connectionKey = new ConnectionEndpointsStruct(sourceId, targetId); uint? existingConnectionId; ConnectionGene newConnectionGene; if(_genomeFactory.AddedConnectionBuffer.TryGetValue(connectionKey, out existingConnectionId)) { // Create a new connection, re-using the ID from existingConnectionId, and add it to the Genome. newConnectionGene = new ConnectionGene(existingConnectionId.Value, sourceId, targetId, connectionWeight); // Add the new gene to this genome. We are re-using an ID so we must ensure the connection gene is // inserted into the correct position (sorted by innovation ID). The ID is most likely an older one // with a lower value than recent IDs, and thus it probably doesn't belong on the end of the list. _connectionGeneList.InsertIntoPosition(newConnectionGene); } else { // Create a new connection with a new ID and add it to the Genome. newConnectionGene = new ConnectionGene(_genomeFactory.NextInnovationId(), sourceId, targetId, connectionWeight); // Add the new gene to this genome. We have a new ID so we can safely append the gene to the end // of the list without risk of breaking the innovation ID sort order. _connectionGeneList.Add(newConnectionGene); // Register the new connection with the added connection history buffer. _genomeFactory.AddedConnectionBuffer.Enqueue(new ConnectionEndpointsStruct(sourceId, targetId), newConnectionGene.InnovationId); } // Track connections associated with each neuron. sourceNeuron.TargetNeurons.Add(targetId); targetNeuron.SourceNeurons.Add(sourceId); // Update stats. _genomeFactory.Stats._mutationCountAddConnection++; return newConnectionGene; } /// <summary> /// Mutate a neuron's auxiliary state. Returns true if successful (failure can occur if there are no neuron's with auxiliary state). /// </summary> private bool Mutate_NodeAuxState() { if(_auxStateNeuronCount == 0) { // No nodes with aux state. Indicate failure. return false; } // ENHANCEMENT: Target for performance improvement. // Select neuron to mutate. Depending on the genome type it may be the case that not all genomes have mutable state, hence // we may have to scan for mutable neurons. int auxStateNodeIdx = _genomeFactory.Rng.Next(_auxStateNeuronCount) + 1; IActivationFunctionLibrary fnLib = _genomeFactory.ActivationFnLibrary; NeuronGene gene; if(_auxStateNeuronCount == _neuronGeneList.Count) { gene = _neuronGeneList[auxStateNodeIdx]; } else { // Scan for selected gene. int i=0; for(int j=0; j<auxStateNodeIdx; i++) { if(fnLib.GetFunction(_neuronGeneList[i].ActivationFnId).AcceptsAuxArgs) { j++; } } gene = _neuronGeneList[i-1]; } Debug.Assert(fnLib.GetFunction(gene.ActivationFnId).AcceptsAuxArgs); // Invoke mutation method (specific to each activation function). fnLib.GetFunction(gene.ActivationFnId).MutateAuxArgs(gene.AuxState, _genomeFactory.Rng, _genomeFactory.GaussianSampler, _genomeFactory.NeatGenomeParameters.ConnectionWeightRange); // Indicate success. return true; } /// <summary> /// Attempt to perform a connection deletion mutation. Returns the deleted connection gene if successful. /// </summary> private ConnectionGene Mutate_DeleteConnection() { if(_connectionGeneList.Count < 2) { // Either no connections to delete or only one. Indicate failure. return null; } // Select a connection at random. int connectionToDeleteIdx = _genomeFactory.Rng.Next(_connectionGeneList.Count); ConnectionGene connectionToDelete = _connectionGeneList[connectionToDeleteIdx]; // Delete the connection. _connectionGeneList.RemoveAt(connectionToDeleteIdx); // Track connections associated with each neuron and remove neurons that are no longer connected to anything. // Source neuron. int srcNeuronIdx = _neuronGeneList.BinarySearch(connectionToDelete.SourceNodeId); NeuronGene srcNeuronGene = _neuronGeneList[srcNeuronIdx]; srcNeuronGene.TargetNeurons.Remove(connectionToDelete.TargetNodeId); if(IsNeuronRedundant(srcNeuronGene)) { // Remove neuron. _neuronGeneList.RemoveAt(srcNeuronIdx); // Track aux state node count. if(_genomeFactory.ActivationFnLibrary.GetFunction(srcNeuronGene.ActivationFnId).AcceptsAuxArgs) { _auxStateNeuronCount--; } } // Target neuron. int tgtNeuronIdx = _neuronGeneList.BinarySearch(connectionToDelete.TargetNodeId); NeuronGene tgtNeuronGene = _neuronGeneList[tgtNeuronIdx]; tgtNeuronGene.SourceNeurons.Remove(connectionToDelete.SourceNodeId); // Note. Check that source and target neurons are not the same neuron. if( srcNeuronGene != tgtNeuronGene && IsNeuronRedundant(tgtNeuronGene)) { // Remove neuron. _neuronGeneList.RemoveAt(tgtNeuronIdx); // Track aux state node count. if(_genomeFactory.ActivationFnLibrary.GetFunction(tgtNeuronGene.ActivationFnId).AcceptsAuxArgs) { _auxStateNeuronCount--; } } _genomeFactory.Stats._mutationCountDeleteConnection++; // Indicate success. return connectionToDelete; } private void Mutate_ConnectionWeights() { // Determine the type of weight mutation to perform. ConnectionMutationInfo mutationInfo = _genomeFactory.NeatGenomeParameters.ConnectionMutationInfoList.GetRandomItem(_genomeFactory.Rng); // Get a delegate that performs the mutation specified by mutationInfo. The alternative is to use a switch statement // test perturbance type on each connection weight mutation - which creates a lot of unnecessary branch instructions. MutateWeightMethod mutateWeigthMethod = Mutate_ConnectionWeights_GetMutateWeightMethod(mutationInfo); // Perform mutations of the required type. if(mutationInfo.SelectionType == ConnectionSelectionType.Proportional) { bool mutationOccured=false; int connectionCount = _connectionGeneList.Count; // ENHANCEMENT: The fastest approach here depends on SelectionProportion and the number of connections... // .. implement a simple heuristic. for(int i=0; i<connectionCount; i++) { if(_genomeFactory.Rng.NextDouble() < mutationInfo.SelectionProportion) { _connectionGeneList[i].Weight = mutateWeigthMethod(_connectionGeneList[i].Weight, mutationInfo); mutationOccured = true; } } if(!mutationOccured && 0!=connectionCount) { // Perform at least one mutation. Pick a gene at random. ConnectionGene connectionGene = _connectionGeneList[_genomeFactory.Rng.Next(connectionCount)]; connectionGene.Weight = mutateWeigthMethod(connectionGene.Weight, mutationInfo); } } else // if(mutationInfo.SelectionType==ConnectionSelectionType.FixedQuantity) { // Determine how many mutations to perform. At least one - if there are any genes. int connectionCount = _connectionGeneList.Count; int mutations = Math.Min(connectionCount, mutationInfo.SelectionQuantity); if(0==mutations) { return; } // ENHANCEMENT: If the number of connections is large relative to the number of required mutations, or the // absolute number of connections is small then the current approach is OK. If however the number of required // mutations is large such that the probability of 'hitting' an un-mutated connection is low as the loop progresses, // then we should use a set of non-mutated connections that we removed mutated connections from in each loop. // // The mutation loop. Here we pick an index at random and scan forward from that point // for the first non-mutated gene. This prevents any gene from being mutated more than once without // too much overhead. // Ensure all IsMutated flags are reset prior to entering the loop. Not doing so introduces the // possibility of getting stuck in the inner while loop forever, as well as preventing previously // mutated connections from being mutated again. _connectionGeneList.ResetIsMutatedFlags(); int maxRetries = mutations * 5; for(int i=0, retryCount=0; i<mutations && retryCount < maxRetries; i++) { // Pick an index at random. int index = _genomeFactory.Rng.Next(connectionCount); // Test if the connection has already been mutated. if(_connectionGeneList[index].IsMutated) { retryCount++; continue; } // Mutate the gene at 'index'. _connectionGeneList[index].Weight = mutateWeigthMethod(_connectionGeneList[index].Weight, mutationInfo); _connectionGeneList[index].IsMutated = true; } } _genomeFactory.Stats._mutationCountConnectionWeights++; } delegate double MutateWeightMethod(double weight, ConnectionMutationInfo info); /// <summary> /// Method that returns a delegate to perform connection weight mutation based on the provided ConnectionMutationInfo /// object. Re-using such a delegate obviates the need to test the type of mutation on each weight mutation operation, thus /// eliminating many branch execution operations. /// </summary> private MutateWeightMethod Mutate_ConnectionWeights_GetMutateWeightMethod(ConnectionMutationInfo mutationInfo) { // ENHANCEMENT: Can we use something akin to a closure here to package up mutation params with the delegate code? switch(mutationInfo.PerturbanceType) { case ConnectionPerturbanceType.JiggleUniform: { return delegate(double weight, ConnectionMutationInfo info) { return CapWeight(weight + (((_genomeFactory.Rng.NextDouble()*2.0) - 1.0) * info.PerturbanceMagnitude)); }; } case ConnectionPerturbanceType.JiggleGaussian: { return delegate(double weight, ConnectionMutationInfo info) { return CapWeight(weight + _genomeFactory.SampleGaussianDistribution(0, info.Sigma)); }; } case ConnectionPerturbanceType.Reset: { return delegate { return _genomeFactory.GenerateRandomConnectionWeight(); }; } } throw new SharpNeatException("Unexpected ConnectionPerturbanceType"); } private double CapWeight(double weight) { double weightRange = _genomeFactory.NeatGenomeParameters.ConnectionWeightRange; if(weight > weightRange) { weight = weightRange; } else if(weight < -weightRange) { weight = -weightRange; } return weight; } /// <summary> /// Redundant neurons are hidden neurons with no connections attached to them. /// </summary> private bool IsNeuronRedundant(NeuronGene neuronGene) { if(neuronGene.NodeType != NodeType.Hidden) { return false; } return (0 == (neuronGene.SourceNeurons.Count + neuronGene.TargetNeurons.Count)); } #endregion #region Private Methods [Genome Comparison] /// <summary> /// Correlates the ConnectionGenes from two distinct genomes based upon gene innovation numbers. /// </summary> private static CorrelationResults CorrelateConnectionGeneLists(ConnectionGeneList list1, ConnectionGeneList list2) { // If none of the connections match up then the number of correlation items will be the sum of the two // connections list counts.. CorrelationResults correlationResults = new CorrelationResults(list1.Count + list2.Count); //----- Test for special cases. int list1Count = list1.Count; int list2Count = list2.Count; if(0 == list1Count && 0 == list2Count) { // Both lists are empty! return correlationResults; } if(0 == list1Count) { // All list2 genes are excess. correlationResults.CorrelationStatistics.ExcessConnectionGeneCount = list2Count; foreach(ConnectionGene connectionGene in list2) { correlationResults.CorrelationItemList.Add(new CorrelationItem(CorrelationItemType.Excess, null, connectionGene)); } return correlationResults; } if(0 == list2Count) { // All list1 genes are excess. correlationResults.CorrelationStatistics.ExcessConnectionGeneCount = list1Count; foreach(ConnectionGene connectionGene in list1) { correlationResults.CorrelationItemList.Add(new CorrelationItem(CorrelationItemType.Excess, connectionGene, null)); } return correlationResults; } //----- Both connection genes lists contain genes - compare their contents. int list1Idx=0; int list2Idx=0; ConnectionGene connectionGene1 = list1[list1Idx]; ConnectionGene connectionGene2 = list2[list2Idx]; for(;;) { if(connectionGene2.InnovationId < connectionGene1.InnovationId) { // connectionGene2 is disjoint. correlationResults.CorrelationItemList.Add(new CorrelationItem(CorrelationItemType.Disjoint, null, connectionGene2)); correlationResults.CorrelationStatistics.DisjointConnectionGeneCount++; // Move to the next gene in list2. list2Idx++; } else if(connectionGene1.InnovationId == connectionGene2.InnovationId) { correlationResults.CorrelationItemList.Add(new CorrelationItem(CorrelationItemType.Match, connectionGene1, connectionGene2)); correlationResults.CorrelationStatistics.ConnectionWeightDelta += Math.Abs(connectionGene1.Weight - connectionGene2.Weight); correlationResults.CorrelationStatistics.MatchingGeneCount++; // Move to the next gene in both lists. list1Idx++; list2Idx++; } else // (connectionGene2.InnovationId > connectionGene1.InnovationId) { // connectionGene1 is disjoint. correlationResults.CorrelationItemList.Add(new CorrelationItem(CorrelationItemType.Disjoint, connectionGene1, null)); correlationResults.CorrelationStatistics.DisjointConnectionGeneCount++; // Move to the next gene in list1. list1Idx++; } // Check if we have reached the end of one (or both) of the lists. If we have reached the end of both then // although we enter the first 'if' block it doesn't matter because the contained loop is not entered if both // lists have been exhausted. if(list1Count == list1Idx) { // All remaining list2 genes are excess. for(; list2Idx < list2Count; list2Idx++) { correlationResults.CorrelationItemList.Add(new CorrelationItem(CorrelationItemType.Excess, null, list2[list2Idx])); correlationResults.CorrelationStatistics.ExcessConnectionGeneCount++; } return correlationResults; } if(list2Count == list2Idx) { // All remaining list1 genes are excess. for(; list1Idx < list1Count; list1Idx++) { correlationResults.CorrelationItemList.Add(new CorrelationItem(CorrelationItemType.Excess, list1[list1Idx], null)); correlationResults.CorrelationStatistics.ExcessConnectionGeneCount++; } return correlationResults; } connectionGene1 = list1[list1Idx]; connectionGene2 = list2[list2Idx]; } } #endregion #region Private Methods [Initialisation] private int CountAuxStateNodes() { IActivationFunctionLibrary fnLib = _genomeFactory.ActivationFnLibrary; int auxNodeCount = 0; int nodeCount = _neuronGeneList.Count; for(int i=0; i<nodeCount; i++) { if(fnLib.GetFunction(_neuronGeneList[i].ActivationFnId).AcceptsAuxArgs) { auxNodeCount++; } } return auxNodeCount; } /// <summary> /// Rebuild the connection info on each neuron gene. This info is created by genome factories and maintained during evolution, /// but requires building after loading genomes from storage. /// </summary> private void RebuildNeuronGeneConnectionInfo() { // Ensure data is cleared down. int nCount = _neuronGeneList.Count; for(int i=0; i<nCount; i++) { NeuronGene nGene = _neuronGeneList[i]; nGene.SourceNeurons.Clear(); nGene.TargetNeurons.Clear(); } // Loop connections and register them with neuron genes. int cCount = _connectionGeneList.Count; for(int i=0; i<cCount; i++) { ConnectionGene cGene = _connectionGeneList[i]; NeuronGene srcNeuronGene = _neuronGeneList.GetNeuronById(cGene.SourceNodeId); NeuronGene tgtNeuronGene = _neuronGeneList.GetNeuronById(cGene.TargetNodeId); srcNeuronGene.TargetNeurons.Add(cGene.TargetNodeId); tgtNeuronGene.SourceNeurons.Add(cGene.SourceNodeId); } } #endregion #region Private Methods [Debug Code / Integrity Checking] /// <summary> /// Performs an integrity check on the genome's internal data. /// Returns true if OK. /// </summary> public bool PerformIntegrityCheck() { // Check genome class type (can only do this if we have a genome factory). if(null != _genomeFactory && !_genomeFactory.CheckGenomeType(this)) { Debug.WriteLine($"Invalid genome class type [{this.GetType().Name}]"); return false; } // Check neuron genes. int count = _neuronGeneList.Count; // We will always have at least a bias and an output. if(count < 2) { Debug.WriteLine($"NeuronGeneList has less than the minimum number of neuron genes [{count}]"); return false; } // Check bias neuron. if(NodeType.Bias != _neuronGeneList[0].NodeType) { Debug.WriteLine("Missing bias gene"); return false; } if(0u != _neuronGeneList[0].InnovationId) { Debug.WriteLine($"Bias neuron ID != 0. [{_neuronGeneList[0].InnovationId}]"); return false; } // Check input neurons. uint prevId = 0u; int idx = 1; for(int i=0; i<_inputNeuronCount; i++, idx++) { if(NodeType.Input != _neuronGeneList[idx].NodeType) { Debug.WriteLine($"Invalid neuron gene type. Expected Input, got [{_neuronGeneList[idx].NodeType}]"); return false; } if(_neuronGeneList[idx].InnovationId <= prevId) { Debug.WriteLine("Input neuron gene is out of order and/or a duplicate."); return false; } prevId = _neuronGeneList[idx].InnovationId; } // Check output neurons. for(int i=0; i<_outputNeuronCount; i++, idx++) { if(NodeType.Output != _neuronGeneList[idx].NodeType) { Debug.WriteLine($"Invalid neuron gene type. Expected Output, got [{_neuronGeneList[idx].NodeType}]"); return false; } if(_neuronGeneList[idx].InnovationId <= prevId) { Debug.WriteLine("Output neuron gene is out of order and/or a duplicate."); return false; } prevId = _neuronGeneList[idx].InnovationId; } // Check hidden neurons. // All remaining neurons should be hidden neurons. for(; idx<count; idx++) { if(NodeType.Hidden != _neuronGeneList[idx].NodeType) { Debug.WriteLine($"Invalid neuron gene type. Expected Hidden, got [{_neuronGeneList[idx].NodeType}]"); return false; } if(_neuronGeneList[idx].InnovationId <= prevId) { Debug.WriteLine("Hidden neuron gene is out of order and/or a duplicate."); return false; } prevId = _neuronGeneList[idx].InnovationId; } // Count nodes with aux state (can only do this if we have a genome factory). if(null != _genomeFactory) { IActivationFunctionLibrary fnLib = _genomeFactory.ActivationFnLibrary; int auxStateNodeCount = 0; for(int i=0; i<count; i++) { if(fnLib.GetFunction(_neuronGeneList[i].ActivationFnId).AcceptsAuxArgs) { auxStateNodeCount++; } } if(_auxStateNeuronCount != auxStateNodeCount) { Debug.WriteLine("Aux state neuron count is incorrect."); return false; } } // Check connection genes. count = _connectionGeneList.Count; if(0 == count) { // At least one connection is required. // (A) Connectionless genomes are pointless and // (B) Connections form the basis for defining a genome's position in the encoding space. // Without a position speciation will be sub-optimal and may fail (depending on the speciation strategy). Debug.WriteLine("Zero connection genes."); return false; } Dictionary<ConnectionEndpointsStruct, object> endpointDict = new Dictionary<ConnectionEndpointsStruct,object>(count); // Initialise with the first connection's details. ConnectionGene connectionGene = _connectionGeneList[0]; prevId = connectionGene.InnovationId; endpointDict.Add(new ConnectionEndpointsStruct(connectionGene.SourceNodeId, connectionGene.TargetNodeId), null); // Loop over remaining connections. for(int i=1; i<count; i++) { connectionGene = _connectionGeneList[i]; if(connectionGene.InnovationId <= prevId) { Debug.WriteLine("Connection gene is out of order and/or a duplicate."); return false; } ConnectionEndpointsStruct key = new ConnectionEndpointsStruct(connectionGene.SourceNodeId, connectionGene.TargetNodeId); if(endpointDict.ContainsKey(key)) { Debug.WriteLine("Connection gene error. A connection between the specified endpoints already exists."); return false; } endpointDict.Add(key, null); prevId = connectionGene.InnovationId; } // Check each neuron gene's list of source and target neurons. // Init connection info per neuron. int nCount = _neuronGeneList.Count; Dictionary<uint,NeuronConnectionInfo> conInfoByNeuronId = new Dictionary<uint,NeuronConnectionInfo>(count); for(int i=0; i<nCount; i++) { NeuronConnectionInfo conInfo = new NeuronConnectionInfo(); conInfo._srcNeurons = new HashSet<uint>(); conInfo._tgtNeurons = new HashSet<uint>(); conInfoByNeuronId.Add(_neuronGeneList[i].Id, conInfo); } // Compile connectivity info. int cCount = _connectionGeneList.Count; for(int i=0; i<cCount; i++) { ConnectionGene cGene = _connectionGeneList[i]; conInfoByNeuronId[cGene.SourceNodeId]._tgtNeurons.Add(cGene.TargetNodeId); conInfoByNeuronId[cGene.TargetNodeId]._srcNeurons.Add(cGene.SourceNodeId); } // Compare connectivity info with that recorded in each NeuronGene. for(int i=0; i<nCount; i++) { NeuronGene nGene = _neuronGeneList[i]; NeuronConnectionInfo conInfo = conInfoByNeuronId[nGene.Id]; // Check source node count. if(nGene.SourceNeurons.Count != conInfo._srcNeurons.Count) { Debug.WriteLine("NeuronGene has incorrect number of source neurons recorded."); return false; } // Check target node count. if(nGene.TargetNeurons.Count != conInfo._tgtNeurons.Count) { Debug.WriteLine("NeuronGene has incorrect number of target neurons recorded."); return false; } // Check that the source node IDs match up. foreach(uint srcNeuronId in nGene.SourceNeurons) { if(!conInfo._srcNeurons.Contains(srcNeuronId)) { Debug.WriteLine("NeuronGene has incorrect list of source neurons recorded."); return false; } } // Check that the target node IDs match up. foreach(uint tgtNeuronId in nGene.TargetNeurons) { if(!conInfo._tgtNeurons.Contains(tgtNeuronId)) { Debug.WriteLine("NeuronGene has incorrect list of target neurons recorded."); return false; } } } // Check that network is acyclic if we are evolving feed-forward only networks // (can only do this if we have a genome factory). if(null != _genomeFactory && _genomeFactory.NeatGenomeParameters.FeedforwardOnly) { if(CyclicNetworkTest.IsNetworkCyclic(this)) { Debug.WriteLine("Feed-forward only network has one or more cyclic paths."); return false; } } return true; } #endregion #region Inner Classes /// <summary> /// Holds sets of source and target neurons for a given neuron. /// </summary> struct NeuronConnectionInfo { /// <summary> /// Gets a set of IDs for the source neurons that directly connect into a given neuron. /// </summary> public HashSet<uint> _srcNeurons; /// <summary> /// Gets a set of IDs for the target neurons that a given neuron directly connects out to. /// </summary> public HashSet<uint> _tgtNeurons; } #endregion #region INetworkDefinition Members /// <summary> /// Gets the number of input nodes. This does not include the bias node which is always present. /// </summary> public int InputNodeCount { get { return _inputNeuronCount; } } /// <summary> /// Gets the number of output nodes. /// </summary> public int OutputNodeCount { get { return _outputNeuronCount; } } /// <summary> /// Gets the network's activation function library. The activation function at each node is /// represented by an integer ID, which refers to a function in this activation function library. /// </summary> public IActivationFunctionLibrary ActivationFnLibrary { get { return _genomeFactory.ActivationFnLibrary; } } /// <summary> /// Gets a bool flag that indicates if the network is acyclic. /// </summary> public bool IsAcyclic { get { return _genomeFactory.NeatGenomeParameters.FeedforwardOnly; } } /// <summary> /// Gets the list of network nodes. /// </summary> public INodeList NodeList { get { return _neuronGeneList; } } /// <summary> /// Gets the list of network connections. /// </summary> public IConnectionList ConnectionList { get { return _connectionGeneList; } } /// <summary> /// Gets NetworkConnectivityData for the network. /// </summary> public NetworkConnectivityData GetConnectivityData() { if(null != _networkConnectivityData) { // Return cached data. return _networkConnectivityData; } int nodeCount = _neuronGeneList.Count; NodeConnectivityData[] nodeConnectivityDataArr = new NodeConnectivityData[nodeCount]; Dictionary<uint,NodeConnectivityData> nodeConnectivityDataById = new Dictionary<uint,NodeConnectivityData>(nodeCount); // NeatGenome(s) have connectivity data pre-calculated, as such we point to this data rather than copying or // rebuilding it. Essentially NetworkConnectivityData becomes a useful general-purpose layer over the connectivity data. for(int i=0; i<nodeCount; i++) { NeuronGene neuronGene = _neuronGeneList[i]; NodeConnectivityData ncd = new NodeConnectivityData(neuronGene.Id, neuronGene.SourceNeurons, neuronGene.TargetNeurons); nodeConnectivityDataArr[i] = ncd; nodeConnectivityDataById.Add(neuronGene.Id, ncd); } _networkConnectivityData = new NetworkConnectivityData(nodeConnectivityDataArr, nodeConnectivityDataById); return _networkConnectivityData; } #endregion } }
50.081581
260
0.582313
[ "MIT" ]
AlexLeung/TradingNEAT
src/SharpNeatLib/Genomes/Neat/NeatGenome.cs
78,578
C#
using Northwind.Entity.Base; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Northwind.Entity.Dto { public class DtoOrderDetail:DtoBase { public DtoOrderDetail() { } public int OrderId { get; set; } public int ProductId { get; set; } public decimal UnitPrice { get; set; } public short Quantity { get; set; } public float Discount { get; set; } } }
24.45
46
0.658487
[ "MIT" ]
142-Bupa-Acibadem-FullStack-Bootcamp/week-5-assignment-1-YTeyfik
Northwind.Entity/Dto/DtoOrderDetail.cs
491
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.DataBoxEdge { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// UsersOperations operations. /// </summary> internal partial class UsersOperations : IServiceOperations<DataBoxEdgeManagementClient>, IUsersOperations { /// <summary> /// Initializes a new instance of the UsersOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal UsersOperations(DataBoxEdgeManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the DataBoxEdgeManagementClient /// </summary> public DataBoxEdgeManagementClient Client { get; private set; } /// <summary> /// Gets all the users registered on a Data Box Edge/Data Box Gateway device. /// </summary> /// <param name='deviceName'> /// The device name. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='filter'> /// Specify $filter='UserType eq &lt;type&gt;' to filter on user type property /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<User>>> ListByDataBoxEdgeDeviceWithHttpMessagesAsync(string deviceName, string resourceGroupName, string filter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (deviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "deviceName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("deviceName", deviceName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("filter", filter); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByDataBoxEdgeDevice", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/users").ToString(); _url = _url.Replace("{deviceName}", System.Uri.EscapeDataString(deviceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (filter != null) { _queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<User>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<User>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the properties of the specified user. /// </summary> /// <param name='deviceName'> /// The device name. /// </param> /// <param name='name'> /// The user name. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<User>> GetWithHttpMessagesAsync(string deviceName, string name, string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (deviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "deviceName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("deviceName", deviceName); tracingParameters.Add("name", name); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/users/{name}").ToString(); _url = _url.Replace("{deviceName}", System.Uri.EscapeDataString(deviceName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<User>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<User>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates a new user or updates an existing user's information on a Data Box /// Edge/Data Box Gateway device. /// </summary> /// <param name='deviceName'> /// The device name. /// </param> /// <param name='name'> /// The user name. /// </param> /// <param name='user'> /// The user details. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<User>> CreateOrUpdateWithHttpMessagesAsync(string deviceName, string name, User user, string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<User> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(deviceName, name, user, resourceGroupName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes the user on a databox edge/gateway device. /// </summary> /// <param name='deviceName'> /// The device name. /// </param> /// <param name='name'> /// The user name. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string deviceName, string name, string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(deviceName, name, resourceGroupName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates a new user or updates an existing user's information on a Data Box /// Edge/Data Box Gateway device. /// </summary> /// <param name='deviceName'> /// The device name. /// </param> /// <param name='name'> /// The user name. /// </param> /// <param name='user'> /// The user details. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<User>> BeginCreateOrUpdateWithHttpMessagesAsync(string deviceName, string name, User user, string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (deviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "deviceName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (user == null) { throw new ValidationException(ValidationRules.CannotBeNull, "user"); } if (user != null) { user.Validate(); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("deviceName", deviceName); tracingParameters.Add("name", name); tracingParameters.Add("user", user); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/users/{name}").ToString(); _url = _url.Replace("{deviceName}", System.Uri.EscapeDataString(deviceName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(user != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(user, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<User>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<User>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the user on a databox edge/gateway device. /// </summary> /// <param name='deviceName'> /// The device name. /// </param> /// <param name='name'> /// The user name. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string deviceName, string name, string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (deviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "deviceName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("deviceName", deviceName); tracingParameters.Add("name", name); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/users/{name}").ToString(); _url = _url.Replace("{deviceName}", System.Uri.EscapeDataString(deviceName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the users registered on a Data Box Edge/Data Box Gateway device. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<User>>> ListByDataBoxEdgeDeviceNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByDataBoxEdgeDeviceNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<User>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<User>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
45.738854
306
0.562198
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/databoxedge/Microsoft.Azure.Management.DataBoxEdge/src/Generated/UsersOperations.cs
50,267
C#
/* * Written by James Leahy. (c) 2018 DeFunc Art. * https://github.com/defuncart/ */ #if UNITY_EDITOR using DeFuncArt.UI; using UnityEditor; using UnityEditor.UI; using UnityEngine; /// <summary>Included in the DeFuncArtEditor namespace.</summary> namespace DeFuncArtEditor { /// <summary>Custom Editor which subclasses of DAButton can extend from.</summary> public abstract class DAButtonSubclassEditor : DAButtonEditor { /// <summary>An array of property names.</summary> protected abstract string[] propertyNames { get; } /// <summary>An array of properties.</summary> protected SerializedProperty[] properties; /// <summary>Callback when script was enabled.</summary> protected override void OnEnable() { //firstly call base implementation base.OnEnable(); //then get references to the class's properties properties = new SerializedProperty[propertyNames.Length]; for(int i=0; i < properties.Length; i++) { properties[i] = serializedObject.FindProperty(propertyNames[i]); } } /// <summary>Callback to draw the inspector.</summary> public override void OnInspectorGUI() { //draw base properties and update the serialized object base.OnInspectorGUI(); serializedObject.Update(); //draw properties for(int i=0; i < properties.Length; i++) { EditorGUILayout.PropertyField(properties[i], true); } //apply any changes to the serialized object serializedObject.ApplyModifiedProperties(); } } } #endif
27.611111
83
0.720993
[ "MIT" ]
defuncart/game-in-a-week
SultansGems/Assets/Imported/DeFuncArt/Editor/CustomUI/Buttons/DAButtonSubclassEditor.cs
1,493
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.Runtime.InteropServices; using Xunit; namespace System.SpanTests { public static partial class SpanTests { [Fact] public static void FillEmpty() { var span = Span<byte>.Empty; span.Fill(1); } [Fact] public static void FillByteLonger() { const byte fill = 5; var expected = new byte[2048]; for (int i = 0; i < expected.Length; i++) { expected[i] = fill; } var actual = new byte[2048]; var span = new Span<byte>(actual); span.Fill(fill); Assert.Equal<byte>(expected, actual); } [Fact] public static void FillByteUnaligned() { const byte fill = 5; const int length = 32; var expectedFull = new byte[length]; for (int i = 0; i < length; i++) { expectedFull[i] = fill; } var actualFull = new byte[length]; var start = 1; var expectedSpan = new Span<byte>(expectedFull, start, length - start - 1); var actualSpan = new Span<byte>(actualFull, start, length - start - 1); actualSpan.Fill(fill); var actual = actualSpan.ToArray(); var expected = expectedSpan.ToArray(); Assert.Equal<byte>(expected, actual); Assert.Equal(0, actualFull[0]); Assert.Equal(0, actualFull[length - 1]); } [Fact] public static void FillValueTypeWithoutReferences() { const byte fill = 5; for (int length = 0; length < 32; length++) { var expectedFull = new int[length]; var actualFull = new int[length]; for (int i = 0; i < length; i++) { expectedFull[i] = fill; actualFull[i] = i; } var span = new Span<int>(actualFull); span.Fill(fill); Assert.Equal<int>(expectedFull, actualFull); } } [Fact] public static void FillReferenceType() { string[] actual = { "a", "b", "c" }; string[] expected = { "d", "d", "d" }; var span = new Span<string>(actual); span.Fill("d"); Assert.Equal<string>(expected, actual); } [Fact] public static void FillValueTypeWithReferences() { TestValueTypeWithReference[] actual = { new TestValueTypeWithReference() { I = 1, S = "a" }, new TestValueTypeWithReference() { I = 2, S = "b" }, new TestValueTypeWithReference() { I = 3, S = "c" } }; TestValueTypeWithReference[] expected = { new TestValueTypeWithReference() { I = 5, S = "d" }, new TestValueTypeWithReference() { I = 5, S = "d" }, new TestValueTypeWithReference() { I = 5, S = "d" } }; var span = new Span<TestValueTypeWithReference>(actual); span.Fill(new TestValueTypeWithReference() { I = 5, S = "d" }); Assert.Equal<TestValueTypeWithReference>(expected, actual); } [Fact] public static unsafe void FillNativeBytes() { // Arrange int length = 50; byte* ptr = null; try { ptr = (byte*)Marshal.AllocHGlobal((IntPtr)50); } // Skipping test if Out-of-Memory, since this test can only be run, if there is enough memory catch (OutOfMemoryException) { Console.WriteLine( $"Span.Fill test {nameof(FillNativeBytes)} skipped due to {nameof(OutOfMemoryException)}."); return; } try { byte initial = 1; for (int i = 0; i < length; i++) { *(ptr + i) = initial; } const byte fill = 5; var span = new Span<byte>(ptr, length); // Act span.Fill(fill); // Assert using custom code for perf and to avoid allocating extra memory for (int i = 0; i < length; i++) { var actual = *(ptr + i); Assert.Equal(fill, actual); } } finally { Marshal.FreeHGlobal(new IntPtr(ptr)); } } } }
32.210526
112
0.473243
[ "MIT" ]
Acidburn0zzz/corefx
src/System.Memory/tests/Span/Fill.cs
4,896
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bubbles : Projectile { public override void Shoot(GameObject shooter) { base.Shoot(shooter); } protected override void OnTriggerEnter(Collider other) { // If this hits a projectile, destroy both projectiles if(other.CompareTag("Projectile")) { Destroy(other); Destroy(gameObject); } base.OnTriggerEnter(other); } }
22
62
0.634387
[ "MIT" ]
DaemonUmbra/NHTI-Capstone
Assets/Scripts/Bubbles.cs
508
C#
using System; using System.Windows.Forms; namespace FC_Killer { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1(args)); } } }
19.5
59
0.653846
[ "MIT" ]
coenvdwel/fckiller
FC Killer/Program.cs
392
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\MethodRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The type WorkbookFunctionsChiSq_InvRequest. /// </summary> public partial class WorkbookFunctionsChiSq_InvRequest : BaseRequest, IWorkbookFunctionsChiSq_InvRequest { /// <summary> /// Constructs a new WorkbookFunctionsChiSq_InvRequest. /// </summary> public WorkbookFunctionsChiSq_InvRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { this.ContentType = "application/json"; this.RequestBody = new WorkbookFunctionsChiSq_InvRequestBody(); } /// <summary> /// Gets the request body. /// </summary> public WorkbookFunctionsChiSq_InvRequestBody RequestBody { get; private set; } /// <summary> /// Issues the POST request. /// </summary> public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync() { return this.PostAsync(CancellationToken.None); } /// <summary> /// Issues the POST request. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await for async call.</returns> public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync( CancellationToken cancellationToken) { this.Method = "POST"; return this.SendAsync<WorkbookFunctionResult>(this.RequestBody, cancellationToken); } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookFunctionsChiSq_InvRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookFunctionsChiSq_InvRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } } }
35.425287
153
0.586632
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/WorkbookFunctionsChiSq_InvRequest.cs
3,082
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Globalization; using Microsoft.ML.Runtime.CommandLine; using Microsoft.ML.Runtime.Data; using Microsoft.ML.Runtime.EntryPoints; using Microsoft.ML.Runtime.Internal.Calibration; using Microsoft.ML.Runtime.Internal.Internallearn; using Microsoft.ML.Runtime.Internal.Utilities; using Microsoft.ML.Runtime.Numeric; using Microsoft.ML.Runtime.Training; namespace Microsoft.ML.Runtime.Learners { using Float = System.Single; public abstract class OnlineLinearArguments : LearnerInputBaseWithLabel { [Argument(ArgumentType.AtMostOnce, HelpText = "Number of iterations", ShortName = "iter", SortOrder = 50)] [TGUI(Label = "Number of Iterations", Description = "Number of training iterations through data", SuggestedSweeps = "1,10,100")] [TlcModule.SweepableLongParamAttribute("NumIterations", 1, 100, stepSize: 10, isLogScale: true)] public int NumIterations = 1; [Argument(ArgumentType.AtMostOnce, HelpText = "Initial Weights and bias, comma-separated", ShortName = "initweights")] [TGUI(NoSweep = true)] public string InitialWeights = null; [Argument(ArgumentType.AtMostOnce, HelpText = "Init weights diameter", ShortName = "initwts", SortOrder = 140)] [TGUI(Label = "Initial Weights Scale", SuggestedSweeps = "0,0.1,0.5,1")] [TlcModule.SweepableFloatParamAttribute("InitWtsDiameter", 0.0f, 1.0f, numSteps: 5)] public Float InitWtsDiameter = 0; [Argument(ArgumentType.AtMostOnce, HelpText = "Whether to shuffle for each training iteration", ShortName = "shuf")] [TlcModule.SweepableDiscreteParamAttribute("Shuffle", new object[] { false, true })] public bool Shuffle = true; [Argument(ArgumentType.AtMostOnce, HelpText = "Size of cache when trained in Scope", ShortName = "cache")] public int StreamingCacheSize = 1000000; } public abstract class OnlineLinearTrainer<TArguments, TPredictor> : TrainerBase<TPredictor> where TArguments : OnlineLinearArguments where TPredictor : IPredictorProducing<Float> { protected readonly TArguments Args; // Initialized by InitCore protected int NumFeatures; // Current iteration state protected int Iteration; protected long NumIterExamples; protected long NumBad; // Current weights and bias. The weights vector is considered to be scaled by // weightsScale. Storing this separately allows us to avoid the overhead of // an explicit scaling, which many learning algorithms will attempt to do on // each update. Bias is not subject to the weights scale. protected VBuffer<Float> Weights; protected Float WeightsScale; protected Float Bias; // Our tolerance for the error induced by the weight scale may depend on our precision. private const Float _maxWeightScale = 1 << 10; // Exponent ranges 127 to -128, tolerate 10 being cut off that. private const Float _minWeightScale = 1 / _maxWeightScale; protected const string UserErrorPositive = "must be positive"; protected const string UserErrorNonNegative = "must be non-negative"; public override TrainerInfo Info { get; } protected virtual bool NeedCalibration => false; protected OnlineLinearTrainer(TArguments args, IHostEnvironment env, string name) : base(env, name) { Contracts.CheckValue(args, nameof(args)); Contracts.CheckUserArg(args.NumIterations > 0, nameof(args.NumIterations), UserErrorPositive); Contracts.CheckUserArg(args.InitWtsDiameter >= 0, nameof(args.InitWtsDiameter), UserErrorNonNegative); Contracts.CheckUserArg(args.StreamingCacheSize > 0, nameof(args.StreamingCacheSize), UserErrorPositive); Args = args; // REVIEW: Caching could be false for one iteration, if we got around the whole shuffling issue. Info = new TrainerInfo(calibration: NeedCalibration, supportIncrementalTrain: true); } /// <summary> /// Propagates the <see cref="WeightsScale"/> to the <see cref="Weights"/> vector. /// </summary> protected void ScaleWeights() { if (WeightsScale != 1) { VectorUtils.ScaleBy(ref Weights, WeightsScale); WeightsScale = 1; } } /// <summary> /// Conditionally propagates the <see cref="WeightsScale"/> to the <see cref="Weights"/> vector /// when it reaches a scale where additions to weights would start dropping too much precision. /// ("Too much" is mostly empirically defined.) /// </summary> protected void ScaleWeightsIfNeeded() { Float absWeightsScale = Math.Abs(WeightsScale); if (absWeightsScale < _minWeightScale || absWeightsScale > _maxWeightScale) ScaleWeights(); } public override TPredictor Train(TrainContext context) { Host.CheckValue(context, nameof(context)); var initPredictor = context.InitialPredictor; var initLinearPred = initPredictor as LinearPredictor ?? (initPredictor as CalibratedPredictorBase)?.SubPredictor as LinearPredictor; Host.CheckParam(initPredictor == null || initLinearPred != null, nameof(context), "Not a linear predictor."); var data = context.TrainingSet; data.CheckFeatureFloatVector(out int numFeatures); CheckLabel(data); using (var ch = Host.Start("Training")) { InitCore(ch, numFeatures, initLinearPred); // InitCore should set the number of features field. Contracts.Assert(NumFeatures > 0); TrainCore(ch, data); if (NumBad > 0) { ch.Warning( "Skipped {0} instances with missing features during training (over {1} iterations; {2} inst/iter)", NumBad, Args.NumIterations, NumBad / Args.NumIterations); } Contracts.Assert(WeightsScale == 1); Float maxNorm = Math.Max(VectorUtils.MaxNorm(ref Weights), Math.Abs(Bias)); Contracts.Check(FloatUtils.IsFinite(maxNorm), "The weights/bias contain invalid values (NaN or Infinite). Potential causes: high learning rates, no normalization, high initial weights, etc."); ch.Done(); } return CreatePredictor(); } protected abstract TPredictor CreatePredictor(); protected abstract void CheckLabel(RoleMappedData data); protected virtual void TrainCore(IChannel ch, RoleMappedData data) { bool shuffle = Args.Shuffle; if (shuffle && !data.Data.CanShuffle) { ch.Warning("Training data does not support shuffling, so ignoring request to shuffle"); shuffle = false; } var rand = shuffle ? Host.Rand : null; var cursorFactory = new FloatLabelCursor.Factory(data, CursOpt.Label | CursOpt.Features | CursOpt.Weight); while (Iteration < Args.NumIterations) { BeginIteration(ch); using (var cursor = cursorFactory.Create(rand)) { while (cursor.MoveNext()) ProcessDataInstance(ch, ref cursor.Features, cursor.Label, cursor.Weight); NumBad += cursor.BadFeaturesRowCount; } FinishIteration(ch); } // #if OLD_TRACING // REVIEW: How should this be ported? Console.WriteLine(); // #endif } protected virtual void InitCore(IChannel ch, int numFeatures, LinearPredictor predictor) { Contracts.Check(numFeatures > 0, "Can't train with zero features!"); Contracts.Check(NumFeatures == 0, "Can't re-use trainer!"); Contracts.Assert(Iteration == 0); Contracts.Assert(Bias == 0); ch.Trace("{0} Initializing {1} on {2} features", DateTime.UtcNow, Name, numFeatures); NumFeatures = numFeatures; // We want a dense vector, to prevent memory creation during training // unless we have a lot of features. // REVIEW: make a setting if (predictor != null) { predictor.GetFeatureWeights(ref Weights); VBufferUtils.Densify(ref Weights); Bias = predictor.Bias; } else if (!string.IsNullOrWhiteSpace(Args.InitialWeights)) { ch.Info("Initializing weights and bias to " + Args.InitialWeights); string[] weightStr = Args.InitialWeights.Split(','); if (weightStr.Length != NumFeatures + 1) { throw Contracts.Except( "Could not initialize weights from 'initialWeights': expecting {0} values to initialize {1} weights and the intercept", NumFeatures + 1, NumFeatures); } Weights = VBufferUtils.CreateDense<Float>(NumFeatures); for (int i = 0; i < NumFeatures; i++) Weights.Values[i] = Float.Parse(weightStr[i], CultureInfo.InvariantCulture); Bias = Float.Parse(weightStr[NumFeatures], CultureInfo.InvariantCulture); } else if (Args.InitWtsDiameter > 0) { Weights = VBufferUtils.CreateDense<Float>(NumFeatures); for (int i = 0; i < NumFeatures; i++) Weights.Values[i] = Args.InitWtsDiameter * (Host.Rand.NextSingle() - (Float)0.5); Bias = Args.InitWtsDiameter * (Host.Rand.NextSingle() - (Float)0.5); } else if (NumFeatures <= 1000) Weights = VBufferUtils.CreateDense<Float>(NumFeatures); else Weights = VBufferUtils.CreateEmpty<Float>(NumFeatures); WeightsScale = 1; } protected virtual void BeginIteration(IChannel ch) { Iteration++; NumIterExamples = 0; ch.Trace("{0} Starting training iteration {1}", DateTime.UtcNow, Iteration); // #if OLD_TRACING // REVIEW: How should this be ported? if (Iteration % 20 == 0) { Console.Write('.'); if (Iteration % 1000 == 0) Console.WriteLine(" {0} \t{1}", Iteration, DateTime.UtcNow); } // #endif } protected virtual void FinishIteration(IChannel ch) { Contracts.Check(NumIterExamples > 0, NoTrainingInstancesMessage); ch.Trace("{0} Finished training iteration {1}; iterated over {2} examples.", DateTime.UtcNow, Iteration, NumIterExamples); ScaleWeights(); #if OLD_TRACING // REVIEW: How should this be ported? if (DebugLevel > 3) PrintWeightsHistogram(); #endif } #if OLD_TRACING // REVIEW: How should this be ported? protected virtual void PrintWeightsHistogram() { // Weights is scaled by weightsScale, but bias is not. Also, the scale term // in the histogram function is the inverse. PrintWeightsHistogram(ref _weights, _bias * _weightsScale, 1 / _weightsScale); } /// <summary> /// print the weights as an ASCII histogram /// </summary> protected void PrintWeightsHistogram(ref VBuffer<Float> weightVector, Float bias, Float scale) { Float min = Float.MaxValue; Float max = Float.MinValue; foreach (var iv in weightVector.Items()) { var v = iv.Value; if (v != 0) { if (min > v) min = v; if (max < v) max = v; } } if (min > bias) min = bias; if (max < bias) max = bias; int numTicks = 50; Float tick = (max - min) / numTicks; if (scale != 1) { min /= scale; max /= scale; tick /= scale; } Host.StdOut.WriteLine(" WEIGHTS HISTOGRAM"); Host.StdOut.Write("\t\t\t" + @" {0:G2} ", min); for (int i = 0; i < numTicks; i = i + 5) Host.StdOut.Write(@" {0:G2} ", min + i * tick); Host.StdOut.WriteLine(); foreach (var iv in weightVector.Items()) { if (iv.Value == 0) continue; Host.StdOut.Write(" " + iv.Key + "\t"); Float weight = iv.Value / scale; Host.StdOut.Write(@" {0,5:G3} " + "\t|", weight); for (int j = 0; j < (weight - min) / tick; j++) Host.StdOut.Write("="); Host.StdOut.WriteLine(); } bias /= scale; Host.StdOut.Write(" BIAS\t\t\t\t" + @" {0:G3} " + "\t|", bias); for (int i = 0; i < (bias - min) / tick; i++) Host.StdOut.Write("="); Host.StdOut.WriteLine(); } #endif /// <summary> /// This should be overridden by derived classes. This implementation simply increments /// _numIterExamples and dumps debug information to the console. /// </summary> protected virtual void ProcessDataInstance(IChannel ch, ref VBuffer<Float> feat, Float label, Float weight) { Contracts.Assert(FloatUtils.IsFinite(feat.Values, feat.Count)); ++NumIterExamples; #if OLD_TRACING // REVIEW: How should this be ported? if (DebugLevel > 2) { Vector features = instance.Features; Host.StdOut.Write("Instance has label {0} and {1} features:", instance.Label, features.Length); for (int i = 0; i < features.Length; i++) { Host.StdOut.Write('\t'); Host.StdOut.Write(features[i]); } Host.StdOut.WriteLine(); } if (DebugLevel > 1) { if (_numIterExamples % 5000 == 0) { Host.StdOut.Write('.'); if (_numIterExamples % 500000 == 0) { Host.StdOut.Write(" "); Host.StdOut.Write(_numIterExamples); if (_numIterExamples % 5000000 == 0) { Host.StdOut.Write(" "); Host.StdOut.Write(DateTime.UtcNow); } Host.StdOut.WriteLine(); } } } #endif } /// <summary> /// Return the raw margin from the decision hyperplane /// </summary> protected Float CurrentMargin(ref VBuffer<Float> feat) { return Bias + VectorUtils.DotProduct(ref feat, ref Weights) * WeightsScale; } protected virtual Float Margin(ref VBuffer<Float> feat) { return CurrentMargin(ref feat); } } }
41.27013
166
0.564667
[ "MIT" ]
JeataekRyu/machinelearning
src/Microsoft.ML.StandardLearners/Standard/Online/OnlineLinear.cs
15,889
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ETModel { public static class SeatIndexTool { public static int GetLastSeatIndex(int currSeatIndexint, int maxSeatIndex) { if (currSeatIndexint > 0) { return currSeatIndexint-1; } else { return maxSeatIndex; } } public static int GetNextSeatIndex(int currSeatIndexint, int maxSeatIndex) { if (currSeatIndexint >= maxSeatIndex) { return 0; } else { return currSeatIndexint + 1; } } //根据服务索引 和用户所处索引 和房间人数 获得客户端位置位置索引 0:下 1:右 2:上 3:左 public static int GetClientSeatIndex(int serverSeatIndex, int serverUserSeatIndex, int roomNumber) { if(serverSeatIndex== serverUserSeatIndex) { return 0; } if(roomNumber==4) { if (serverSeatIndex > serverUserSeatIndex) { return serverSeatIndex - serverUserSeatIndex; } else { return roomNumber - (serverUserSeatIndex - serverSeatIndex); } } else if(roomNumber==3) { if (serverSeatIndex == GetNextSeatIndex(serverUserSeatIndex, 2)) { return 1; } else { return 3; } } else if (roomNumber == 2) { return 2; } Log.Error("获取客户端索引错误 人数:" + roomNumber + " 用户索引:" + serverUserSeatIndex + " 玩家索引:" + serverSeatIndex); return 0; } } }
27.75
116
0.449449
[ "MIT" ]
594270461/fivestar
Unity/Assets/Model/GameGather/Tools/SeatIndexTool.cs
2,104
C#
using Com.Game.Data; using Com.Game.Manager; using Com.Game.Module; using System; using System.Collections.Generic; using UnityEngine; namespace MobaFrame.SkillAction { public class DamageDataManager : Singleton<DamageDataManager> { private Dictionary<int, DamageData> _dataVos = new Dictionary<int, DamageData>(); private bool isParseTable; public void ParseTables() { if (!this.isParseTable) { Dictionary<string, object> dicByType = BaseDataMgr.instance.GetDicByType<SysSkillDamageVo>(); if (dicByType == null) { Debug.LogError("==> SysSkillDamageVo is NULL !!"); return; } this.isParseTable = true; this._dataVos.Clear(); Dictionary<string, object>.Enumerator enumerator = dicByType.GetEnumerator(); while (enumerator.MoveNext()) { KeyValuePair<string, object> current = enumerator.Current; string key = current.Key; KeyValuePair<string, object> current2 = enumerator.Current; SysSkillDamageVo damage_vo = current2.Value as SysSkillDamageVo; DamageData value = new DamageData(key, damage_vo); this._dataVos.Add(int.Parse(key), value); } } } public DamageData GetVo(int id) { if (this._dataVos.ContainsKey(id)) { return this._dataVos[id]; } return null; } public void Clear() { this._dataVos.Clear(); } } }
25.035714
98
0.666191
[ "MIT" ]
corefan/mobahero_src
MobaFrame.SkillAction/DamageDataManager.cs
1,402
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // // Generated with CoreBot .NET Template version __vX.X.X__ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Integration.AspNet.Core; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using CoreBot.Bots; using CoreBot.Dialogs; namespace CoreBot { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddNewtonsoftJson(); // Create the Bot Framework Adapter with error handling enabled. services.AddSingleton<IBotFrameworkHttpAdapter, AdapterWithErrorHandler>(); // Create the storage we'll be using for User and Conversation state. (Memory is great for testing purposes.) services.AddSingleton<IStorage, MemoryStorage>(); // Create the User state. (Used in this bot's Dialog implementation.) services.AddSingleton<UserState>(); // Create the Conversation state. (Used by the Dialog system itself.) services.AddSingleton<ConversationState>(); // Register LUIS recognizer services.AddSingleton<FlightBookingRecognizer>(); // Register the BookingDialog. services.AddSingleton<BookingDialog>(); // The MainDialog that will be run by the bot. services.AddSingleton<MainDialog>(); // Create the bot as a transient. In this case the ASP Controller is expecting an IBot. services.AddTransient<IBot, DialogAndWelcomeBot<MainDialog>>(); } // 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.UseDefaultFiles() .UseStaticFiles() .UseWebSockets() .UseRouting() .UseAuthorization() .UseEndpoints(endpoints => { endpoints.MapControllers(); }); // app.UseHttpsRedirection(); } } }
34.944444
121
0.637122
[ "MIT" ]
AdsTable/BotBuilder-Samples
generators/dotnet-templates/Microsoft.BotFramework.CSharp.CoreBot/content/CoreBot/Startup.cs
2,516
C#
namespace KorneiDontsov.Sql.Migrations { using System; using System.Threading; using System.Threading.Tasks; class DbMigrationState: IDbMigrationState { public TaskCompletionSource<DbMigrationResult> whenCompleted { get; } = new TaskCompletionSource<DbMigrationResult>(TaskCreationOptions.RunContinuationsAsynchronously); /// <inheritdoc /> public ValueTask<DbMigrationResult> WhenCompleted (CancellationToken cancellationToken = default) { static async ValueTask<T> WithCancellation<T> (Task<T> task, CancellationToken ct) { var awaitedTask = await Task.WhenAny(task, Task.Delay(Timeout.Infinite, ct)); if(awaitedTask == task) return await task; else { await awaitedTask; throw new OperationCanceledException(ct); } } if(whenCompleted.Task.IsCompleted || ! cancellationToken.CanBeCanceled) return new ValueTask<DbMigrationResult>(whenCompleted.Task); else if(cancellationToken.IsCancellationRequested) return new ValueTask<DbMigrationResult>(Task.FromCanceled<DbMigrationResult>(cancellationToken)); else return WithCancellation(whenCompleted.Task, cancellationToken); } } }
37.225806
101
0.771231
[ "MIT" ]
prachikatre005/KorneiDontsov.Sql
src/libs/KorneiDontsov.Sql/impl/migrations/DbMigrationState.cs
1,156
C#
 namespace CyPhyPET { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics.Contracts; using System.IO; using CyPhy = ISIS.GME.Dsml.CyPhyML.Interfaces; using CyPhyClasses = ISIS.GME.Dsml.CyPhyML.Classes; using CyPhyCOMInterfaces; using System.Text.RegularExpressions; using System.Diagnostics; using CyPhyGUIs; using GME.MGA; using Newtonsoft.Json; using System.Globalization; using AVM.DDP; using System.Security; using System.Runtime.InteropServices; using static AVM.DDP.PETConfig; public class PET { //public static GME.CSharp.GMEConsole GMEConsole { get; set; } public CyPhyGUIs.SmartLogger Logger { get; set; } public bool Success = false; private enum DriverType { None, PCC, Optimizer, ParameterStudy }; private DriverType theDriver; private CyPhy.ParametricExploration pet; private MgaFCO rootPET; public string outputDirectory { get; set; } private string testBenchOutputDir; public static readonly ISet<string> testbenchtypes = GetDerivedTypeNames(typeof(CyPhy.TestBenchType)); public static readonly ISet<string> petWrapperTypes = GetDerivedTypeNames(typeof(CyPhy.ParametricTestBench)); public Dictionary<string, string> PCCPropertyInputDistributions { get; set; } private PETConfig _config; public PETConfig config { get { return _config; } set { _config = value; components = _config.components; drivers = _config.drivers; subProblems = _config.subProblems; } } public Dictionary<string, Component> components; public Dictionary<string, Driver> drivers; public Dictionary<string, SubProblem> subProblems; private SubProblem _subProblem; public SubProblem subProblem { get { return _subProblem; } set { _subProblem = value; components = subProblem.components; drivers = subProblem.drivers; subProblems = subProblem.subProblems; } } public static IEnumerable<IMgaObject> getAncestors(IMgaFCO fco, IMgaObject stopAt = null) { if (fco.ParentModel != null) { IMgaModel parent = fco.ParentModel; while (parent != null && (stopAt == null || parent.ID != stopAt.ID)) { yield return parent; if (parent.ParentModel == null) { break; } parent = parent.ParentModel; } fco = parent; } IMgaFolder folder = fco.ParentFolder; while (folder != null && (stopAt == null || folder.ID != stopAt.ID)) { yield return folder; folder = folder.ParentFolder; } } public static IEnumerable<IMgaObject> getAncestorsAndSelf(IMgaFCO fco, IMgaObject stopAt = null) { yield return fco; foreach (var parent in getAncestors(fco, stopAt)) { yield return parent; } } public PET(MgaFCO rootPET, MgaFCO currentFCO, CyPhyGUIs.SmartLogger logger) { this.Logger = logger; this.pet = CyPhyClasses.ParametricExploration.Cast(currentFCO); this.rootPET = rootPET; } public void Initialize() { // Determine type of driver of the Parametric Exploration if (this.pet.Children.PCCDriverCollection.Count() == 1) { this.theDriver = DriverType.PCC; } else if (this.pet.Children.OptimizerCollection.Count() == 1) { this.theDriver = DriverType.Optimizer; var optimizer = this.pet.Children.OptimizerCollection.FirstOrDefault(); var config = AddConfigurationForMDAODriver(optimizer); config.type = "optimizer"; config.details["OptimizationFunction"] = optimizer.Attributes.OptimizationFunction.ToString(); if (optimizer.Attributes.OptimizationFunction == CyPhyClasses.Optimizer.AttributesClass.OptimizationFunction_enum.Custom) { config.details["OptimizationClass"] = optimizer.Attributes.CustomOptimizer; } foreach (var intermediateVar in optimizer.Children.IntermediateVariableCollection) { var sourcePath = GetSourcePath(null, (MgaFCO)intermediateVar.Impl); if (sourcePath != null) { var intermVar = new PETConfig.Parameter(); intermVar.source = sourcePath; setUnit(intermediateVar.Referred.unit, intermVar); checkUnitMatchesSource(intermediateVar); config.intermediateVariables.Add(intermediateVar.Name, intermVar); } } foreach (var constraint in optimizer.Children.OptimizerConstraintCollection) { var sourcePath = GetSourcePath(null, (MgaFCO)constraint.Impl); if (sourcePath != null) { var cons = new PETConfig.Constraint(); cons.source = sourcePath; if (!string.IsNullOrWhiteSpace(constraint.Attributes.MinValue)) { double minValue; if (double.TryParse(constraint.Attributes.MinValue, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out minValue)) { cons.RangeMin = minValue; } else { throw new ApplicationException(String.Format("Cannot parse Constraint MinValue '{0}'", constraint.Attributes.MinValue)); } } else { cons.RangeMin = null; } if (!string.IsNullOrWhiteSpace(constraint.Attributes.MaxValue)) { double maxValue; if (double.TryParse(constraint.Attributes.MaxValue, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out maxValue)) { cons.RangeMax = maxValue; } else { throw new ApplicationException(String.Format("Cannot parse Constraint MaxValue '{0}'", constraint.Attributes.MaxValue)); } } else { cons.RangeMax = null; } config.constraints.Add(constraint.Name, cons); } } } else if (this.pet.Children.ParameterStudyCollection.Count() == 1) { this.theDriver = DriverType.ParameterStudy; var parameterStudy = this.pet.Children.ParameterStudyCollection.FirstOrDefault(); var config = AddConfigurationForMDAODriver(parameterStudy); config.type = "parameterStudy"; bool hasDesignVariables = parameterStudy.Children.DesignVariableCollection.Count() > 0; if (hasDesignVariables == false) { config.details["DOEType"] = "Uniform"; } Dictionary<string, object> assignment; try { // FIXME: do this in another thread assignment = getPythonAssignment(parameterStudy.Attributes.Code); } catch (JsonException e) { throw new ApplicationException("Error parsing " + parameterStudy.Impl.ToMgaHyperLink(Logger.Traceability) + " Code", e); } long num_samples; long num_levels; object num_samplesObj; object num_levelsObj; if (parameterStudy.Attributes.DOEType == CyPhyClasses.ParameterStudy.AttributesClass.DOEType_enum.CSV_File) { object filename; if (assignment.TryGetValue("filename", out filename) == false || filename is string == false) { throw new ApplicationException("For CSV File input, you must specify filename=r'file.csv' in the ParameterStudy's Code attribute"); } var projectDir = Path.GetDirectoryName(Path.GetFullPath(parameterStudy.Impl.Project.ProjectConnStr.Substring("MGA=".Length))); string basename = Path.GetFileName((string)filename); try { File.Copy(Path.Combine(projectDir, (string)filename), Path.Combine(outputDirectory, basename)); } catch (IOException e) { throw new ApplicationException(String.Format("Could not copy '{0}': {1}", filename, e.Message), e); } if (basename == "output.csv") { throw new ApplicationException("CSV File input filename must not be 'output.csv'"); } if (basename != (string)filename) { var code = config.details["Code"].ToString(); var basenameEscaped = escapePythonString(basename); code += String.Format("\nfilename = u'{0}'\n", basenameEscaped); config.details["Code"] = code; } } else if (parameterStudy.Attributes.DOEType == CyPhyClasses.ParameterStudy.AttributesClass.DOEType_enum.Full_Factorial) { if (assignment.TryGetValue("num_levels", out num_levelsObj)) { if (num_levelsObj is long) { num_levels = (long)num_levelsObj; } else { throw new ApplicationException("num_levels must be an integer"); } } // Legacy support for num_samples assignment in code block. else if (assignment.TryGetValue("num_samples", out num_samplesObj)) { if (num_samplesObj is long) { num_samples = (long)num_samplesObj; } else { throw new ApplicationException("num_samples must be an integer"); } config.details["Code"] = "num_levels = " + num_samples.ToString(); } else if (hasDesignVariables == false) { config.details["Code"] = "num_samples = 1"; config.details["DOEType"] = "Uniform"; } else { throw new ApplicationException("num_levels must be specified in the Code attribute of a Full Factorial Parameter Study Driver"); } } else { if (assignment.TryGetValue("num_samples", out num_samplesObj)) { if (num_samplesObj is long) { num_samples = (long)num_samplesObj; } else { throw new ApplicationException("num_samples must be an integer"); } if (parameterStudy.Attributes.DOEType == CyPhyClasses.ParameterStudy.AttributesClass.DOEType_enum.Opt_Latin_Hypercube) { if (num_samples < 2) { throw new ApplicationException("num_samples must be >= 2 when using Optimized Latin Hypercube"); } } } else if (hasDesignVariables == false) { config.details["Code"] = "num_samples = 1"; config.details["DOEType"] = "Uniform"; } else { throw new ApplicationException("num_samples must be specified in the Code attribute of the Parameter Study"); } } } } public static string escapePythonString(string value) { return Regex.Replace(value, "('|[^ -~])", m => String.Format("\\u{0:X4}", (int)m.Groups[0].Value[0])); } public static Dictionary<string, object> getPythonAssignment(string code) { using (Process getParamsAndUnknowns = new Process()) { getParamsAndUnknowns.StartInfo = new ProcessStartInfo(META.VersionInfo.PythonVEnvExe) { CreateNoWindow = true, UseShellExecute = false, RedirectStandardError = true, RedirectStandardOutput = true, RedirectStandardInput = true, Arguments = "-E -c \"import sys, json;" + "assignment = {};" + "eval(compile(sys.stdin.read().decode('utf8'), '<driver Code>', 'exec'), globals(), assignment);" + "print(json.dumps(assignment))\"" }; getParamsAndUnknowns.Start(); StreamWriter utf8Writer = new StreamWriter(getParamsAndUnknowns.StandardInput.BaseStream, new UTF8Encoding(false)); utf8Writer.Write(code); utf8Writer.Close(); // n.b. assume buffers will not fill up and deadlock us string stdout = getParamsAndUnknowns.StandardOutput.ReadToEnd(); string stderr = getParamsAndUnknowns.StandardError.ReadToEnd(); getParamsAndUnknowns.WaitForExit(); getParamsAndUnknowns.StandardOutput.Close(); getParamsAndUnknowns.StandardError.Close(); if (getParamsAndUnknowns.ExitCode != 0) { throw new ApplicationException(stderr); } return Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(stdout.Replace("\r", "").Split('\n').Last(line => string.IsNullOrWhiteSpace(line) == false)); } } private PETConfig.Driver AddConfigurationForMDAODriver(CyPhy.MDAODriver driver) { var config = new PETConfig.Driver() { designVariables = new Dictionary<string, PETConfig.DesignVariable>(), objectives = new Dictionary<string, PETConfig.Parameter>(), constraints = new Dictionary<string, PETConfig.Constraint>(), intermediateVariables = new Dictionary<string, PETConfig.Parameter>(), details = new Dictionary<string, object>() }; this.drivers.Add(driver.Name, config); foreach (var designVariable in driver.Children.DesignVariableCollection) { var configVariable = new PETConfig.DesignVariable(); setUnit(designVariable.Referred.unit, configVariable); ParseDesignVariableRange(designVariable.Attributes.Range, configVariable); config.designVariables.Add(designVariable.Name, configVariable); } foreach (var objective in driver.Children.ObjectiveCollection) { var sourcePath = GetSourcePath(null, (MgaFCO)objective.Impl); if (sourcePath != null) { var configParameter = new PETConfig.Parameter() { source = sourcePath }; config.objectives.Add(objective.Name, configParameter); setUnit(objective.Referred.unit, configParameter); checkUnitMatchesSource(objective); } } foreach (MgaAttribute attribute in ((MgaFCO)driver.Impl).Attributes) { config.details.Add(attribute.Meta.Name, attribute.StringValue); } return config; } public static double nextafter(double value, double direction) { if (Double.IsInfinity(value) || Double.IsNaN(value)) { return value; } if (value == direction) { return value; } int dir = value > direction ? 1 : -1; long bits = BitConverter.DoubleToInt64Bits(value); if (value > 0) { return BitConverter.Int64BitsToDouble(bits - dir); } else if (value < 0) { return BitConverter.Int64BitsToDouble(bits + dir); } else { return -1 * dir * double.Epsilon; } } public static void ParseDesignVariableRange(string range, DesignVariable configVariable) { var parseErrorMessage = String.Format("Cannot parse Design Variable Range '{0}'. ", range) + "Double ranges are specified by an un-quoted value or two un-quoted values separated by commas. " + "Enumerations are specified by one double-quoted value or two or more double-quoted values separated by semicolons. " + "E.g.: '2.0,2.5' or '\"Low\";\"Medium\";\"High\"'"; var oneValue = new System.Text.RegularExpressions.Regex( // start with previous match. match number or string "\\G(" + // number: // TODO: scientific notation? // TODO: a la NumberStyles.AllowThousands? "[+-]?(?:\\d*[.])?\\d+" + "|" + // string: match \ escape sequence, or anything but \ or " "\"(?:\\\\(?:\\\\|\"|/|b|f|n|r|t|u\\d{4})|[^\\\\\"])*\"" + // match ends with ; or end of string ")(?:;|$)"); /* Print(oneValue.Matches("12;")); Print(oneValue.Matches("12.2;")); Print(oneValue.Matches("\"\"")); Print(oneValue.Matches("\";asdf;asd\"")); Print(oneValue.Matches("\"\\\"\"")); // \" Print(oneValue.Matches("\"\\\\\"")); // \\ Print(oneValue.Matches("\"\\n\"")); // \n Print(oneValue.Matches("\"\\n\";\"\";\"asdf\"")); Print(oneValue.Matches("\"\\\"")); // \ => false Print(oneValue.Matches("\"\"\"")); // " => false */ MatchCollection matches = oneValue.Matches(range); if (matches.Count > 0) { var items = matches.Cast<Match>().Select(x => x.Groups[1].Value).Select(x => x[0] == '"' ? (string)JsonConvert.DeserializeObject(x) : (object)Double.Parse(x, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture) ).ToList(); var last = matches.Cast<Match>().Last(); if (last.Index + last.Length != range.Length) { throw new ApplicationException(parseErrorMessage); } // special-case: a single number produces a double range if (matches.Count == 1 && matches[0].Groups[1].Value[0] != '"') { configVariable.RangeMin = (double)items[0]; configVariable.RangeMax = (double)items[0]; } else { configVariable.items = items; configVariable.type = "enum"; } } else if (range.Contains(",")) { var range_split = range.Split(new char[] { ',' }); if (range_split.Length != 2) { throw new ApplicationException(parseErrorMessage); } string lower = range_split[0]; string upper = range_split[1]; bool lowerExcluded = false; bool upperExcluded = false; if (lower[0] == '(') { lowerExcluded = true; lower = lower.Substring(1); } else if (lower[0] == '[') { lowerExcluded = false; lower = lower.Substring(1); } if (upper.Last() == ')') { upperExcluded = true; upper = upper.Substring(0, upper.Length - 1); } else if (upper.Last() == ']') { upperExcluded = false; upper = upper.Substring(0, upper.Length - 1); } double rangeMin, rangeMax; if (!Double.TryParse(lower, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out rangeMin)) { throw new ApplicationException(String.Format("Could not parse min range value '{0}'", lower)); } if (!Double.TryParse(upper, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out rangeMax)) { throw new ApplicationException(String.Format("Could not parse min range value '{0}'", upper)); } configVariable.RangeMin = rangeMin; configVariable.RangeMax = rangeMax; if (lowerExcluded) { configVariable.RangeMin = nextafter((double)configVariable.RangeMin, Double.PositiveInfinity); } if (upperExcluded) { configVariable.RangeMax = nextafter((double)configVariable.RangeMax, Double.NegativeInfinity); } if (configVariable.RangeMin > configVariable.RangeMax) { throw new ApplicationException(String.Format("Invalid Design Variable Range '{0}'. ", range)); } } else { throw new ApplicationException(parseErrorMessage); } } [DllImport("kernel32.dll", SetLastError = true)] static extern bool SetDllDirectory(string lpPathName); [DllImport("CyPhyFormulaEvaluator.dll", CallingConvention=CallingConvention.Cdecl)] static extern bool AreUnitsEqual(IMgaFCO fco1, IMgaFCO fco2); private void checkUnitMatchesSource(ISIS.GME.Common.Interfaces.Reference objective) { var mgaObjective = (MgaReference)objective.Impl; foreach (MgaConnPoint connPoint in mgaObjective.PartOfConns) { if (connPoint.ConnRole != "dst") { continue; } var src = ((MgaSimpleConnection)connPoint.Owner).Src; if (src is MgaReference) { var metric = (MgaReference)src; if (metric.Referred == null || mgaObjective.Referred == null) { continue; } if (metric.Referred.ID != mgaObjective.Referred.ID) { foreach (var path in new string[] { Path.Combine(META.VersionInfo.MetaPath, "bin"), Path.Combine(META.VersionInfo.MetaPath, "src", "bin") }) { if (File.Exists(Path.Combine(path, "CyPhyFormulaEvaluator.dll"))) { SetDllDirectory(path); } } if (AreUnitsEqual(metric.Referred, mgaObjective.Referred) == false) { Logger.WriteFailed(String.Format("Unit for <a href=\"mga:{0}\">{1}</a> must match unit for <a href=\"mga:{2}\">{3}</a>", metric.getTracedObjectOrSelf(Logger.Traceability).ID, SecurityElement.Escape(metric.Name), objective.Impl.getTracedObjectOrSelf(Logger.Traceability).ID, SecurityElement.Escape(objective.Name))); throw new ApplicationException(); } } } } } public void GenerateCode(CyPhy.TestBenchRef testBenchRef, string testBenchOutputDir) { var testBench = testBenchRef.Referred.TestBenchType; this.testBenchOutputDir = testBenchOutputDir; var config = new PETConfig.Component() { parameters = new Dictionary<string, PETConfig.Parameter>(), unknowns = new Dictionary<string, PETConfig.Parameter>(), details = new Dictionary<string, object>() }; config.details["directory"] = testBenchOutputDir; this.components.Add(testBenchRef.Name, config); foreach (var parameter in testBench.Children.ParameterCollection.Select(parameter => new { fco = parameter.Impl, unit = parameter.Referred.unit }). Concat(testBench.Children.FileInputCollection.Select(fileInput => new { fco = fileInput.Impl, unit = (CyPhy.unit)null })) ) { var sourcePath = GetSourcePath((MgaReference)testBenchRef.Impl, (MgaFCO)parameter.fco); if (sourcePath != null) { var configParameter = new PETConfig.Parameter() { source = sourcePath }; config.parameters.Add(parameter.fco.Name, configParameter); setUnit(parameter.unit, configParameter); } } foreach (var metric in testBench.Children.MetricCollection) { var configParameter = new PETConfig.Parameter(); config.unknowns.Add(metric.Name, configParameter); setUnit(metric.Referred.unit, configParameter); } foreach (var fileOutput in testBench.Children.FileOutputCollection) { var configParameter = new PETConfig.Parameter(); config.unknowns.Add(fileOutput.Name, configParameter); } if (testBench is CyPhy.TestBench) { var interpreterProgID = Rules.Global.GetTasksFromTestBench(testBench as CyPhy.TestBench); if (interpreterProgID.OfType<CyPhy.Task>().Select(task => task.Attributes.COMName).Contains("MGA.Interpreter.CyPhyFormulaEvaluator")) { // FIXME: does this still work this.SimpleCalculation((CyPhy.TestBench)testBench); } } } public Dictionary<CyPhy.unit, List<Action<string>>> unitsToSet = new Dictionary<CyPhy.unit, List<Action<string>>>(); private void setUnit(CyPhy.unit unit, Action<string> action) { if (unit == null) { return; } List<Action<string>> setters; if (unitsToSet.TryGetValue(unit, out setters) == false) { setters = new List<Action<string>>(); unitsToSet[unit] = setters; } setters.Add(action); } private void setUnit(CyPhy.unit unit, PETConfig.Parameter configParameter) { setUnit(unit, units => configParameter.units = units); } private void setUnit(CyPhy.unit unit, PETConfig.DesignVariable designVariable) { setUnit(unit, units => designVariable.units = units); } private string[] GetSourcePath(MgaReference refe, MgaFCO port) { IEnumerable<MgaConnPoint> sources; if (refe != null) { sources = port.PartOfConns.Cast<MgaConnPoint>().Where(cp => cp.References != null && cp.References.Count > 0 && cp.References[1].ID == refe.ID && cp.ConnRole == "dst"); } else { sources = port.PartOfConns.Cast<MgaConnPoint>().Where(cp => (cp.References == null || cp.References.Count == 0) && cp.ConnRole == "dst"); } sources = sources.Where(s => getAncestors(s.Owner).Select(x => x.ID).Contains(rootPET.ID)); if (sources.Count() == 0) { return null; } var source = (MgaSimpleConnection)sources.First().Owner; // top-level ParametricExploration: ignore top-level ProblemInput and ProblemOutputs if (config != null && source.Src.ParentModel.ID == pet.ID && (source.Src.Meta.Name == typeof(CyPhy.ProblemInput).Name || source.Src.Meta.Name == typeof(CyPhy.ProblemOutput).Name)) { return GetSourcePath(null, source.Src); } string parentName; if (source.SrcReferences != null && source.SrcReferences.Count > 0) { parentName = source.SrcReferences[1].Name; } else { if (pet.ID == source.Src.ParentModel.ID) { return new string[] { source.Src.Name }; } parentName = source.Src.ParentModel.Name; } var sourcePath = new string[] { parentName, source.Src.Name }; return sourcePath; MgaModel parent; if (source.SrcReferences != null && source.SrcReferences.Count > 0) { parent = (MgaModel)source.SrcReferences[1]; } else { parent = source.Src.ParentModel; } List<string> path = new List<string>(); while (parent.ID != pet.ID) { path.Add(parent.Name); parent = parent.ParentModel; } path.Reverse(); path.Add(source.Src.Name); return path.ToArray(); } public void GenerateDriverCode() { // Generate Driver if (this.theDriver == DriverType.PCC) { // this.Label = " && PCC" + JobManager.Job.LabelVersion; // TODO convert this to code in python -m run_mdao this.GeneratePCCScripts(); } else if (this.theDriver == DriverType.Optimizer) { } else if (this.theDriver == DriverType.ParameterStudy) { if (this.pet.Children.ParameterStudyCollection.First().Attributes.SurrogateType != CyPhyClasses.ParameterStudy.AttributesClass.SurrogateType_enum.None) { throw new ApplicationException("Surrogates are not supported"); } } if (unitsToSet.Count > 0) { var cyPhyPython = (IMgaComponentEx)Activator.CreateInstance(Type.GetTypeFromProgID("MGA.Interpreter.CyPhyPython")); // cyPhyPython.ComponentParameter["script_file"] = Path.Combine(META.VersionInfo.MetaPath, "bin", "CyPhyPET_unit_setter.py"); cyPhyPython.ComponentParameter["script_file"] = "CyPhyPET_unit_setter.py"; var fcos = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); int i = 0; foreach (var unit in unitsToSet.Keys) { // fcos.Append((MgaFCO)unit.Impl); cyPhyPython.ComponentParameter[String.Format("unit_id_{0}", i)] = unit.Impl.ID; i++; } cyPhyPython.InvokeEx(pet.Impl.Project, (MgaFCO)pet.Impl, fcos, 128); i = 0; foreach (var unit in unitsToSet.Keys) { foreach (var action in unitsToSet[unit]) { var value = (string)cyPhyPython.ComponentParameter[String.Format("unit_id_{0}_ret", i)]; if (value == "") { value = null; } action(value); } i++; } } } # region DriverTypes /// <summary> /// Generates PCC scripts /// </summary> private PCC.RootObject GeneratePCCScripts() { var pccDriverCfgFile = "PCCDriverconfigs.json"; var PCCDriver = this.pet.Children.PCCDriverCollection.FirstOrDefault(); var upMethod = PCCDriver.Attributes.PCC_UP_Methods; int upMethodNum; switch (upMethod) { case CyPhyClasses.PCCDriver.AttributesClass.PCC_UP_Methods_enum.Monte_Carlo_Simulation__UP_MCS_: upMethodNum = 1; break; case CyPhyClasses.PCCDriver.AttributesClass.PCC_UP_Methods_enum.Taylor_Series_Approximation__UP_TS_: upMethodNum = 2; break; case CyPhyClasses.PCCDriver.AttributesClass.PCC_UP_Methods_enum.Most_Probable_Point_Method__UP_MPP_: this.Logger.WriteWarning("The output from Most Probable Point Method is not compatible with the project analyzer Dashboard."); upMethodNum = 3; break; case CyPhyClasses.PCCDriver.AttributesClass.PCC_UP_Methods_enum.Full_Factorial_Numerical_Integration__UP_FFNI_: upMethodNum = 4; break; case CyPhyClasses.PCCDriver.AttributesClass.PCC_UP_Methods_enum.Univariate_Dimension_Reduction_Method__UP_UDR_: upMethodNum = 5; break; case CyPhyClasses.PCCDriver.AttributesClass.PCC_UP_Methods_enum.Polynomial_Chaos_Expansion__UP_PCE_: this.Logger.WriteWarning("The output from Polynomial Chaos Expansion is not compatible with the project analyzer Dashboard."); this.Logger.WriteWarning("Trying to display such data might require a refresh in order to view other data again."); upMethodNum = 6; break; default: upMethodNum = 0; break; } var saMethod = PCCDriver.Attributes.PCC_SA_Methods; int saMethodNum; switch (saMethod) { case CyPhyClasses.PCCDriver.AttributesClass.PCC_SA_Methods_enum.Sobol_method__SA_SOBOL_: saMethodNum = 7; break; case CyPhyClasses.PCCDriver.AttributesClass.PCC_SA_Methods_enum.FAST_method__SA_FAST_: saMethodNum = 9; break; case CyPhyClasses.PCCDriver.AttributesClass.PCC_SA_Methods_enum.EFAST_method__SA_EFAST_: saMethodNum = 10; break; default: saMethodNum = 0; break; } // Generate input config file for OSU code var pccConfig = this.BuildUpPCCConfiguration(PCCDriver.Name, PCCDriver, upMethodNum, saMethodNum); List<string> objectives = new List<string>(); List<string> designVariabels = new List<string>(); foreach (var item in pccConfig.Configurations.Configuration.PCCInputArguments.PCCMetrics) { objectives.Add("TestBench." + item.TestBenchMetricName); } foreach (var item in pccConfig.Configurations.Configuration.PCCInputArguments.StochasticInputs.InputDistributions) { designVariabels.Add("TestBench." + item.TestBenchParameterNames.FirstOrDefault()); } // Add registry defied inputdistributions for Properties in Components var PCCPropertyInputs = TryToObtainDyanmicsProperties(); foreach (var pccProperty in PCCPropertyInputs) { this.Logger.WriteDebug("Adding Property Input Distribution, Name : {0}, Distribution : {1}", pccProperty.Name, pccProperty.Distribution); // TODO: Can multiple testbench names be handled correctly? For now only use the first. var testBenchParameterName = pccProperty.TestBenchParameterNames.FirstOrDefault(); pccProperty.TestBenchParameterNames.Clear(); pccProperty.TestBenchParameterNames.Add(testBenchParameterName); this.PCCPropertyInputDistributions.Add(pccProperty.Name, testBenchParameterName); pccConfig.Configurations.Configuration.PCCInputArguments.StochasticInputs.InputDistributions.Add(pccProperty); } PETConfig.Driver driver = new PETConfig.Driver() { type = "PCCDriver", details = new Dictionary<string, object>(), designVariables = new Dictionary<string, PETConfig.DesignVariable>(), constraints = new Dictionary<string, PETConfig.Constraint>(), intermediateVariables = new Dictionary<string, PETConfig.Parameter>(), objectives = new Dictionary<string, PETConfig.Parameter>(), }; this.config.drivers.Add(PCCDriver.Name, driver); driver.details["Configurations"] = pccConfig.Configurations; foreach (var designVariable in PCCDriver.Children.PCCParameterCollection) { var configVariable = new PETConfig.DesignVariable(); driver.designVariables.Add(designVariable.Name, configVariable); } foreach (var objective in PCCDriver.Children.PCCOutputCollection) { var sourcePath = GetSourcePath(null, (MgaFCO)objective.Impl); if (sourcePath != null) { driver.objectives.Add(objective.Name, new PETConfig.Parameter() { source = sourcePath }); } } return pccConfig; } #endregion #region TestBenchTypes private void SimpleCalculation(CyPhy.TestBench testBench) { this.Logger.WriteWarning("Formula has limited support. You may experience issues during the execution."); Directory.CreateDirectory(Path.Combine(outputDirectory, "scripts")); using (StreamWriter writer = new StreamWriter(Path.Combine(outputDirectory, "scripts", "test_bench.py"))) { Templates.TestBenchExecutors.Formula simpleCalc = new Templates.TestBenchExecutors.Formula() { testBench = testBench }; writer.WriteLine(simpleCalc.TransformText()); } using (StreamWriter writer = new StreamWriter(Path.Combine(outputDirectory, "scripts", "driver_runner.py"))) { writer.WriteLine(CyPhyPET.Properties.Resources.driver_runner_simpleCalc); } } #endregion # region HelperMethods private PCC.RootObject BuildUpPCCConfiguration(string driverName, CyPhy.PCCDriver PCCDriver, int upMethodNum, int saMethodNum) { PCC.RootObject rootConfig = new PCC.RootObject(); PCC.Configurations configs = new PCC.Configurations(); configs.Configuration = new PCC.Configuration(); configs.Configuration.Parts = new List<PCC.Part>(); PCC.Part part = new PCC.Part(); PCC.PCCInputArguments pccInputArgs = new PCC.PCCInputArguments(); part.ModelConfigFileName = "test_bench_model_config.json"; part.ToolConfigFileName = "test_bench_tool_config.json"; configs.Configuration.Parts.Add(part); configs.Configuration.Name = driverName; configs.Configuration.ID = PCCDriver.ID; configs.Configuration.PCCInputArguments = new PCC.PCCInputArguments(); pccInputArgs = configs.Configuration.PCCInputArguments; pccInputArgs.InputIDs = new List<string>(); pccInputArgs.OutputIDs = new List<string>(); pccInputArgs.StochasticInputs = new PCC.StochasticInputs(); pccInputArgs.StochasticInputs.InputDistributions = new List<PCCInputDistribution>(); pccInputArgs.PCCMetrics = new List<PCC.PCCMetric>(); foreach (var item in PCCDriver.Children.PCCParameterCollection) { //pccInputArgs.InputIDs.Add(item.ID); PCCInputDistribution inputDist = new PCCInputDistribution(); if (item is CyPhy.PCCParameterNormal) { inputDist.Distribution = "NORM"; inputDist.Param1 = (item as CyPhy.PCCParameterNormal).Attributes.Mean; inputDist.Param2 = (item as CyPhy.PCCParameterNormal).Attributes.StandardDeviation; } else if (item is CyPhy.PCCParameterUniform) { inputDist.Distribution = "UNIF"; inputDist.Param1 = (item as CyPhy.PCCParameterUniform).Attributes.LowLimit; inputDist.Param2 = (item as CyPhy.PCCParameterUniform).Attributes.HighLimit; } else if (item is CyPhy.PCCParameterLNormal) { inputDist.Distribution = "LNORM"; inputDist.Param1 = (item as CyPhy.PCCParameterLNormal).Attributes.Shape; inputDist.Param2 = (item as CyPhy.PCCParameterLNormal).Attributes.LogScale; } else if (item is CyPhy.PCCParameterBeta) { inputDist.Distribution = "BETA"; inputDist.Param1 = (item as CyPhy.PCCParameterBeta).Attributes.Shape1; inputDist.Param2 = (item as CyPhy.PCCParameterBeta).Attributes.Shape2; inputDist.Param3 = (item as CyPhy.PCCParameterBeta).Attributes.LowLimit; inputDist.Param4 = (item as CyPhy.PCCParameterBeta).Attributes.HighLimit; } foreach (var driveParameter in item.DstConnections.DriveParameterCollection) { inputDist.TestBenchParameterNames.Add(driveParameter.DstEnd.Name); } //inputDist.ID = inputDist.ID == null ? item.ID : inputDist.ID; inputDist.ID = item.ID; inputDist.Name = item.Name; pccInputArgs.StochasticInputs.InputDistributions.Add(inputDist); } pccInputArgs.StochasticInputs.InputDistributions = pccInputArgs.StochasticInputs.InputDistributions.OrderBy(p => p.TestBenchParameterNames.FirstOrDefault()).ToList(); foreach (var item in pccInputArgs.StochasticInputs.InputDistributions) { pccInputArgs.InputIDs.Add(item.ID); } foreach (var item in PCCDriver.Children.PCCOutputCollection) { //pccInputArgs.OutputIDs.Add(item.ID); if (item.Attributes.TargetPCCValue == 0) { this.Logger.WriteWarning("TargetPCCValue is set to zero. Is this correct?"); } var pccMetric = new PCC.PCCMetric(); pccMetric.ID = item.ID; var sourcePath = GetSourcePath(null, (MgaFCO) item.Impl); pccMetric.TestBenchMetricName = sourcePath[1]; pccMetric.Name = sourcePath[0] + "." + pccMetric.TestBenchMetricName; pccMetric.PCC_Spec = item.Attributes.TargetPCCValue; // Could this ever present a problem? var metricLimits = new PCC.Limits(); double dMin = double.NegativeInfinity; double dMax = double.PositiveInfinity; if (double.TryParse(item.Attributes.MinValue, out dMin) == false) { // using min infinity this.Logger.WriteWarning("MinValue must be 'Infinity,' '-Infinity,' or a double."); } if (double.TryParse(item.Attributes.MaxValue, out dMax) == false) { // using max infinity this.Logger.WriteWarning("MaxValue must be 'Infinity,' '-Infinity,' or a double."); } metricLimits.Min = dMin; metricLimits.Max = dMax; metricLimits.op = null; // "min/max/avg/none"; // metricLimits.minrange = null; // "value or n/a"; // TODO: add these 3 attributes to the PCCOutput component in CyPhy metricLimits.maxrange = null; //"value or n/a"; // pccMetric.Limits = metricLimits; pccInputArgs.PCCMetrics.Add(pccMetric); } pccInputArgs.PCCMetrics = pccInputArgs.PCCMetrics.OrderBy(m => m.TestBenchMetricName).ToList(); foreach (var item in pccInputArgs.PCCMetrics) { pccInputArgs.OutputIDs.Add(item.ID); } pccInputArgs.Methods = new List<int>(); if (upMethodNum > 0) { pccInputArgs.Methods.Add(upMethodNum); } if (saMethodNum > 0) { pccInputArgs.Methods.Add(saMethodNum); } rootConfig = new PCC.RootObject() { Configurations = configs }; return rootConfig; } private List<PCCInputDistribution> TryToObtainDyanmicsProperties() { var results = new List<PCCInputDistribution>(); if (testBenchOutputDir != null) { var jsonFile = Path.Combine(this.outputDirectory, this.testBenchOutputDir, "CyPhy", "PCCProperties.json"); if (File.Exists(jsonFile)) { this.Logger.WriteInfo("Found defined PCC-Properties for the DynamicTestBench."); results = Newtonsoft.Json.JsonConvert.DeserializeObject<List<PCCInputDistribution>>(File.ReadAllText(jsonFile)); } } return results; } public void GenerateCode(CyPhy.ExcelWrapper excel) { if (excel.Attributes.ExcelFilename == "") { throw new ApplicationException(String.Format("ExcelWrapper {0} must specify Excel Filename", excel.Name)); } var config = GenerateCode((CyPhy.ParametricTestBench)excel); var projectDir = Path.GetDirectoryName(Path.GetFullPath(excel.Impl.Project.ProjectConnStr.Substring("MGA=".Length))); config.details = new Dictionary<string, object>() { // TODO: maybe generate a relative path instead of making absolute here {"excelFile", Path.Combine(projectDir, excel.Attributes.ExcelFilename)}, }; config.type = "excel_wrapper.excel_wrapper.ExcelWrapper"; var inputs = excel.Children.ParameterCollection.Select(fco => fco.Name).ToList(); var outputs = excel.Children.MetricCollection.Select(fco => fco.Name).ToList(); HashSet<string> xlInputs = new HashSet<string>(); HashSet<string> xlOutputs = new HashSet<string>(); Dictionary<string, ExcelInterop.ExcelType> types = new Dictionary<string, ExcelInterop.ExcelType>(); Dictionary<string, List<int>> dimensions = new Dictionary<string, List<int>>(); ExcelInterop.GetExcelInputsAndOutputs((string)config.details["excelFile"], (string name, string refersTo, ExcelInterop.ExcelType type, List<int> dims) => { outputs.Remove(name); types[name] = type; dimensions[name] = dims; }, (string name, string refersTo, string value, ExcelInterop.ExcelType type, List<int> dims) => { inputs.Remove(name); types[name] = type; dimensions[name] = dims; }, () => { }); config.details["varFile"] = generateXLFileJson(excel, types, dimensions); if (inputs.Count > 0) { throw new ApplicationException(String.Format("ExcelWrapper {0} has inputs {1} that are not in the Excel file", excel.Name, String.Join(",", inputs.ToArray()))); } if (outputs.Count > 0) { throw new ApplicationException(String.Format("ExcelWrapper {0} has outputs {1} that are not in the Excel file", excel.Name, String.Join(",", outputs.ToArray()))); } } public void GenerateCode(CyPhy.PythonWrapper python) { var config = GenerateCode((CyPhy.ParametricTestBench)python); var projectDir = Path.GetDirectoryName(Path.GetFullPath(python.Impl.Project.ProjectConnStr.Substring("MGA=".Length))); System.Uri pyFileUri = new Uri(Path.Combine(projectDir, python.Attributes.PyFilename)); System.Uri outputUri = new Uri(this.outputDirectory + "\\"); string pyFilename = Uri.UnescapeDataString(outputUri.MakeRelativeUri(pyFileUri).ToString()); // n.b. keep forward slashes config.details = new Dictionary<string, object>() { {"filename", pyFilename} }; config.type = "run_mdao.python_component.PythonComponent"; } public void GenerateCode(CyPhy.AnalysisBlock analysisBlock) { var config = GenerateCode((CyPhy.ParametricTestBench)analysisBlock); var projectDir = Path.GetDirectoryName(Path.GetFullPath(analysisBlock.Impl.Project.ProjectConnStr.Substring("MGA=".Length))); System.Uri pyFileUri = new Uri(Path.Combine(projectDir, analysisBlock.Attributes.PyFilename)); System.Uri outputUri = new Uri(this.outputDirectory + "\\"); string pyFilename = Uri.UnescapeDataString(outputUri.MakeRelativeUri(pyFileUri).ToString()); // n.b. keep forward slashes config.details = new Dictionary<string, object>() { {"filename", pyFilename}, {"kwargs", CyPhyPETInterpreter.GetConfigurationParameters(analysisBlock)}, }; config.type = "run_mdao.python_component.PythonComponent"; } public void GenerateCode(CyPhy.MATLABWrapper matlab) { var config = GenerateCode((CyPhy.ParametricTestBench)matlab); var projectDir = Path.GetDirectoryName(Path.GetFullPath(matlab.Impl.Project.ProjectConnStr.Substring("MGA=".Length))); config.details = new Dictionary<string, object>() { // TODO: maybe generate a relative path instead of making absolute here {"mFile", Path.Combine(projectDir, matlab.Attributes.MFilename)}, }; config.type = "matlab_wrapper.MatlabWrapper"; } private void CopyFiles(CyPhy.ParametricTestBench wrapper) { var projectDir = Path.GetDirectoryName(Path.GetFullPath(wrapper.Impl.Project.ProjectConnStr.Substring("MGA=".Length))); CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI.CopyFiles(wrapper.Children.CopyFilesCollection, projectDir, this.outputDirectory); } public PETConfig.Component GenerateCode(CyPhy.Constants constants) { // Get a new config var config = new PETConfig.Component() { parameters = new Dictionary<string, PETConfig.Parameter>(), unknowns = new Dictionary<string, PETConfig.Parameter>(), type = "IndepVarComp" }; foreach (var metric in constants.Children.MetricCollection) { var configParameter = new PETConfig.Parameter(); Exception ex = null; try { configParameter.value = Newtonsoft.Json.Linq.JToken.Parse(metric.Attributes.Value); } catch (JsonReaderException jre) { ex = jre; } catch (System.FormatException fe) { ex = fe; } if (ex != null) { String msg = "Failed to parse the Value for the Metric " + "<a href=\"mga:{1}\">{0}</a> in <a href=\"mga:{3}\">{2}</a> as JSON. " + "If this was intended to be a String, surround it in quotes."; if (metric.Attributes.Value.Equals("true", StringComparison.InvariantCultureIgnoreCase) || metric.Attributes.Value.Equals("false", StringComparison.InvariantCultureIgnoreCase)) { msg += " Use 'false' or 'true' for boolean values."; } this.Logger.WriteError(String.Format(msg, metric.Name, metric.ID, constants.Name, constants.ID)); throw ex; } config.unknowns.Add(metric.Name, configParameter); setUnit(metric.Referred.unit, configParameter); } this.components.Add(constants.Name, config); return config; } internal void GenerateInputsAndOutputs() { if (this.config != null) { return; } foreach (var input in pet.Children.ProblemInputCollection) { var problemInput = new SubProblem.ProblemInput() { //outerSource = //innerSource = value = input.Attributes.Value }; var sources = ((MgaFCO)input.Impl).PartOfConns.Cast<MgaConnPoint>().Where(cp => (cp.References == null || cp.References.Count == 0) && cp.ConnRole == "dst"); foreach (var connPoint in sources) { var source = (MgaSimpleConnection)connPoint.Owner; IMgaFCO parent; if (source.SrcReferences != null && source.SrcReferences.Count > 0) { parent = source.SrcReferences[1]; } else { parent = source.Src.ParentModel; } var gparent = parent.ParentModel; // var ggparent = parent == null ? null : parent.ParentModel; if (gparent != null && gparent.ID == pet.ID) { problemInput.innerSource = new string[] { parent.Name, source.Src.Name }; } else { if (parent.ID == this.pet.ParentContainer.ID) { problemInput.outerSource = new string[] { source.Src.Name }; } else { problemInput.outerSource = new string[] { parent.Name, source.Src.Name }; } } } List<MgaFCO> realSources = GetTransitiveSources((MgaFCO)input.Impl, new HashSet<string>() { typeof(CyPhy.Metric).Name, typeof(CyPhy.FileOutput).Name, // not a "real" source: typeof(CyPhy.ProblemOutput) typeof(CyPhy.DesignVariable).Name, typeof(CyPhy.PCCParameterLNormal).Name, typeof(CyPhy.PCCParameterNormal).Name, typeof(CyPhy.PCCParameterUniform).Name, typeof(CyPhy.PCCParameterBeta).Name }); var driverTypes = new HashSet<string>() { typeof(CyPhy.DesignVariable).Name, typeof(CyPhy.PCCParameterLNormal).Name, typeof(CyPhy.PCCParameterNormal).Name, typeof(CyPhy.PCCParameterUniform).Name, typeof(CyPhy.PCCParameterBeta).Name }; var desVarSources = realSources.Where(s => driverTypes.Contains(s.Meta.Name)); if (desVarSources.Count() > 0) { var desVar = desVarSources.First(); if (desVar.Meta.Name == typeof(CyPhy.DesignVariable).Name) { SetProblemInputValueFromDesignVariable(problemInput, desVar); } else { SetProblemInputValueFromPCCParameter(problemInput, desVar); } } else { if (realSources.Count > 1) { // should be unreachable because checker should detect this error throw new ApplicationException(String.Format("Error: {0} has more than one source", input.Name)); } MgaFCO realSource = realSources.FirstOrDefault(); MgaModel realSourceParent = realSource?.ParentModel; if (problemInput.value == "") { if (realSource == null) { throw new ApplicationException(String.Format("Error: <a href=\"mga:{0}\">{1}</a> must specify a JSON Value", input.Impl.getTracedObjectOrSelf(Logger.Traceability).ID, SecurityElement.Escape(input.Name))); } if (testbenchtypes.Contains(realSourceParent.Meta.Name)) { // FIXME is this right? problemInput.value = "0.0"; problemInput.pass_by_obj = true; } else if (realSource.Meta.Name == typeof(CyPhy.Metric).Name) { string value = CyPhyClasses.Metric.Cast(realSource).Attributes.Value; // FIXME: move this to the checker if (value == "") { throw new ApplicationException(String.Format("Error: <a href=\"mga:{0}\">{1}</a> must specify a JSON Value", realSource.getTracedObjectOrSelf(Logger.Traceability).ID, SecurityElement.Escape(realSource.Name))); } // problemInput.value gets eval()ed in Python if (realSourceParent.Meta.Name == typeof(CyPhy.PythonWrapper).Name || realSourceParent.Meta.Name == typeof(CyPhy.AnalysisBlock).Name || realSourceParent.Meta.Name == typeof(CyPhy.ExcelWrapper).Name || realSourceParent.Meta.Name == typeof(CyPhy.MATLABWrapper).Name) { problemInput.value = value; } else { // problemInput.value = String.Format("u'{0}'", escapePythonString((string)configDesignVariable.items[0])); Newtonsoft.Json.Linq.JToken parsedValue; try { parsedValue = Newtonsoft.Json.Linq.JToken.Parse(CyPhyClasses.Metric.Cast(realSource).Attributes.Value); } catch (JsonException e) { throw new ApplicationException(String.Format("Error: <a href=\"mga:{0}\">{1}</a> must specify a valid JSON Value", realSource.getTracedObjectOrSelf(Logger.Traceability).ID, SecurityElement.Escape(realSource.Name)), e); } Func<Newtonsoft.Json.Linq.JToken, string> convertValueToPythonString = null; convertValueToPythonString = v => { if (v is Newtonsoft.Json.Linq.JValue) { var jvalue = (Newtonsoft.Json.Linq.JValue)v; switch (jvalue.Type) { case Newtonsoft.Json.Linq.JTokenType.Boolean: return ((bool)jvalue) ? "True" : "False"; case Newtonsoft.Json.Linq.JTokenType.Integer: return jvalue.ToString(); case Newtonsoft.Json.Linq.JTokenType.None: case Newtonsoft.Json.Linq.JTokenType.Null: return "None"; case Newtonsoft.Json.Linq.JTokenType.Float: return FormatDoubleForPython((double)jvalue); case Newtonsoft.Json.Linq.JTokenType.String: return String.Format("u'{0}'", escapePythonString((string)jvalue)); } return jvalue.ToString(); } if (v is Newtonsoft.Json.Linq.JArray) { var jarray = (Newtonsoft.Json.Linq.JArray)v; StringBuilder ret = new StringBuilder(); ret.Append("["); foreach (Newtonsoft.Json.Linq.JToken token in jarray) { ret.Append(convertValueToPythonString(token)); ret.Append(", "); } ret.Append("]"); return ret.ToString(); } if (v is Newtonsoft.Json.Linq.JObject) { var jobject = (Newtonsoft.Json.Linq.JObject)v; StringBuilder ret = new StringBuilder(); ret.Append("{"); foreach (KeyValuePair<string, Newtonsoft.Json.Linq.JToken> entry in jobject) { ret.Append(String.Format("u'{0}'", escapePythonString(entry.Key))); ret.Append(": "); ret.Append(convertValueToPythonString(entry.Value)); ret.Append(", "); } ret.Append("}"); return ret.ToString(); } throw new ApplicationException(String.Format("Unknown type in {0}", value)); }; problemInput.value = convertValueToPythonString(parsedValue); } } } string kind = realSourceParent?.Meta?.Name; if (kind == null) { problemInput.pass_by_obj = false; } else if (testbenchtypes.Contains(kind)) { problemInput.pass_by_obj = true; } else if (kind == typeof(CyPhy.ExcelWrapper).Name || kind == typeof(CyPhy.MATLABWrapper).Name) { problemInput.pass_by_obj = false; } else { string pbo = realSource.GetRegistryValueDisp("pass_by_obj") ?? "False"; problemInput.pass_by_obj = true.ToString().Equals(pbo, StringComparison.InvariantCultureIgnoreCase); } } subProblem.problemInputs.Add(input.Name, problemInput); } foreach (var output in pet.Children.ProblemOutputCollection) { subProblem.problemOutputs.Add(output.Name, GetSourcePath(null, (MgaFCO)output.Impl)); } } private static void SetProblemInputValueFromDesignVariable(SubProblem.ProblemInput problemInput, MgaFCO desVar) { var configDesignVariable = new DesignVariable(); ParseDesignVariableRange(CyPhyClasses.DesignVariable.Cast(desVar).Attributes.Range, configDesignVariable); if (configDesignVariable.items != null) { if (configDesignVariable.items[0] is string) { problemInput.value = String.Format("u'{0}'", escapePythonString((string)configDesignVariable.items[0])); problemInput.pass_by_obj = true; } else { problemInput.value = FormatDoubleForPython((double)configDesignVariable.items[0]); problemInput.pass_by_obj = false; } } else { problemInput.value = FormatDoubleForPython((double)(configDesignVariable.RangeMin + (configDesignVariable.RangeMax - configDesignVariable.RangeMin) / 2)); problemInput.pass_by_obj = false; } } private static void SetProblemInputValueFromPCCParameter(SubProblem.ProblemInput problemInput, MgaFCO param) { string kind = param.Meta.Name; if (kind == typeof(CyPhy.PCCParameterBeta).Name) { var beta = CyPhyClasses.PCCParameterBeta.Cast(param); problemInput.value = FormatDoubleForPython(beta.Attributes.HighLimit); } else if (kind == typeof(CyPhy.PCCParameterBeta).Name) { var lnormal = CyPhyClasses.PCCParameterLNormal.Cast(param); problemInput.value = FormatDoubleForPython(lnormal.Attributes.LogScale); } else if (kind == typeof(CyPhy.PCCParameterNormal).Name) { var normal = CyPhyClasses.PCCParameterNormal.Cast(param); problemInput.value = FormatDoubleForPython(normal.Attributes.Mean); } else if (kind == typeof(CyPhy.PCCParameterUniform).Name) { var beta = CyPhyClasses.PCCParameterUniform.Cast(param); problemInput.value = FormatDoubleForPython(beta.Attributes.LowLimit); } } private static string FormatDoubleForPython(double v) { if (Double.IsNaN(v)) { return "float(\"nan\")"; } // (0.0).ToString returns 0, which Python parses as int if (v == Math.Floor(v)) { return v.ToString() + ".0"; } if (Double.IsPositiveInfinity(v)) { return "float(\"inf\")"; } if (Double.IsNegativeInfinity(v)) { return "float(\"-inf\")"; } // G17 ensures enough precision to parse the same value return v.ToString("G17", CultureInfo.InvariantCulture); } private static ISet<string> GetDerivedTypeNames(Type type) { HashSet<string> ret = new HashSet<string>(); foreach (Type t in type.Assembly.GetExportedTypes()) { if (type.IsAssignableFrom(t)) { ret.Add(t.Name); } } return ret; } public static List<MgaFCO> GetTransitiveSources(MgaFCO fco, ISet<string> stopKinds) { List<MgaFCO> ret = new List<MgaFCO>(); Queue<MgaFCO> q = new Queue<MgaFCO>(); q.Enqueue(fco); while (q.Count > 0) { fco = q.Dequeue(); foreach (MgaConnPoint cp in fco.PartOfConns) { // FIXME: don't go above top-level PET if (cp.ConnRole == "dst") { fco = ((MgaSimpleConnection)cp.Owner).Src; if (stopKinds.Contains(fco.Meta.Name)) { ret.Add(fco); } else { q.Enqueue(fco); } } } } return ret; } public PETConfig.Component GenerateCode(CyPhy.ParametricTestBench excel) { var config = new PETConfig.Component() { parameters = new Dictionary<string, PETConfig.Parameter>(), unknowns = new Dictionary<string, PETConfig.Parameter>(), }; foreach (var parameter in excel.Children.ParameterCollection.Select(parameter => new { fco = (ISIS.GME.Common.Interfaces.FCO)parameter, unit = parameter.Referred.unit }). Concat(excel.Children.FileInputCollection.Select(fileInput => new { fco = (ISIS.GME.Common.Interfaces.FCO)fileInput, unit = (CyPhy.unit)null })) ) { var sourcePath = GetSourcePath(null, (MgaFCO)parameter.fco.Impl); if (sourcePath != null) { var configParameter = new PETConfig.Parameter() { source = sourcePath, }; config.parameters.Add(parameter.fco.Name, configParameter); setUnit(parameter.unit, configParameter); } } foreach (var metric in excel.Children.MetricCollection) { var configParameter = new PETConfig.Parameter() { }; config.unknowns.Add(metric.Name, configParameter); setUnit(metric.Referred.unit, configParameter); } foreach (var fileOutput in excel.Children.FileOutputCollection) { config.unknowns.Add(fileOutput.Name, new PETConfig.Parameter()); } this.components.Add(excel.Name, config); CopyFiles(excel); return config; } private string generateXLFileJson(CyPhy.ExcelWrapper excel, Dictionary<string, ExcelInterop.ExcelType> types, Dictionary<string, List<int>> dimensions) { List<Dictionary<string, object>> params_ = new List<Dictionary<string, object>>(); foreach (var param in excel.Children.ParameterCollection) { ExcelInterop.ExcelType type = types[param.Name]; List<int> dims = dimensions[param.Name]; var details = new Dictionary<string, object>() { {"name", param.Name }, {"type", type.ToString() }, {"desc", param.Attributes.Description }, // TODO sheet, row, column, units }; if (type == ExcelInterop.ExcelType.Float) { double val = 0.0; Double.TryParse(param.Attributes.Value, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out val); details["val"] = val; } else if (type == ExcelInterop.ExcelType.Str) { details["val"] = param.Attributes.Value; } if (type == ExcelInterop.ExcelType.FloatArray || type == ExcelInterop.ExcelType.StrArray) { details["dims"] = dims; } params_.Add(details); } List<Dictionary<string, object>> metrics = new List<Dictionary<string, object>>(); foreach (var metric in excel.Children.MetricCollection) { ExcelInterop.ExcelType type = types[metric.Name]; List<int> dims = dimensions[metric.Name]; var details = new Dictionary<string, object>() { {"name", metric.Name }, {"type", type.ToString() }, {"desc", metric.Attributes.Description }, // TODO sheet, row, column, units }; if (type == ExcelInterop.ExcelType.Float) { double val = 0.0; Double.TryParse(metric.Attributes.Value, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out val); details["val"] = val; } else if (type == ExcelInterop.ExcelType.Str) { details["val"] = metric.Attributes.Value; } if (type == ExcelInterop.ExcelType.FloatArray || type == ExcelInterop.ExcelType.StrArray) { details["dims"] = dims; } metrics.Add(details); } var macros = new List<string>(); if (string.IsNullOrEmpty(excel.Attributes.Macro) == false) { macros.Add(excel.Attributes.Macro); } Dictionary<string, object> varFile = new Dictionary<string, object>() { {"unknowns", metrics}, {"params", params_}, {"macros", macros } }; var filename = Path.Combine(this.outputDirectory, excel.Name + ".json"); File.WriteAllText(filename, JsonConvert.SerializeObject(varFile, Formatting.Indented)); return Path.GetFileName(filename); } #endregion } public static class Extensions { public static IEnumerable<IMgaObject> getTracedObjectOrSelf(this IEnumerable<IMgaObject> enumerable, CyPhyCOMInterfaces.IMgaTraceability traceability) { foreach (var obj in enumerable) { string originalID; if (traceability != null && traceability.TryGetMappedObject(obj.ID, out originalID)) { yield return obj.Project.GetObjectByID(originalID); } else { yield return obj; } } } public static IMgaObject getTracedObjectOrSelf(this IMgaObject obj, CyPhyCOMInterfaces.IMgaTraceability traceability) { string originalID; if (traceability != null && traceability.TryGetMappedObject(obj.ID, out originalID)) { return obj.Project.GetObjectByID(originalID); } else { return obj; } } } }
46.209529
191
0.495397
[ "MIT" ]
lefevre-fraser/openmeta-mms
src/CyPhyPET/PET.cs
80,499
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.ContractsLight; using System.Linq; using System.Threading; using BuildXL.Utilities; using BuildXL.FrontEnd.Script; using BuildXL.FrontEnd.Script.Evaluator; using VSCode.DebugAdapter; using VSCode.DebugProtocol; #pragma warning disable SA1649 // File name must match first type name namespace BuildXL.FrontEnd.Script.Debugger { /// <summary> /// A tuple class comprised of Breakpoint and its affiliated node. /// </summary> internal sealed class BreakpointRecord { /// <summary> /// The breakpoint. /// </summary> internal IBreakpoint Breakpoint { get; } /// <summary> /// The node affiliated with this breakpoint. Will be null the first time we hit it. /// </summary> internal Node Node { get; set; } internal BreakpointRecord(ISourceBreakpoint sbp) { Breakpoint = new Breakpoint(true, sbp.Line); } } /// <summary> /// Static factory for creating breakpoint stores. /// </summary> public static class BreakpointStoreFactory { /// <summary>Creates and returns a new instance of a <see cref="IMasterStore"/></summary> public static IMasterStore CreateMaster() => new MasterStoreWithLocking(); /// <summary>Creates and returns a new instance of a <see cref="IBreakpointStore"/></summary> public static IBreakpointStore CreateProxy(IMasterStore master) => new ReadOnlyProxyStore(master); // =========================================================================================================== // == Shared pure static methods for internal (within this file) use. // =========================================================================================================== internal static IBreakpoint SearchRecords(IReadOnlyList<BreakpointRecord> breakpointsForSource, Node node) { // 1) Check if the specified line is set with a BP. BreakpointRecord record = breakpointsForSource.FirstOrDefault(bp => bp.Breakpoint.Line == node.Location.Line); if (record == null) { return null; } // 2) Check if a node is affiliated with this BP. if (record.Node != null) { if (record.Node == node) { // We hit both same line and same node. // (This happens during a recursive call or in a loop) return record.Breakpoint; } else { // We hit the same line, but not same node. return null; } } else { // This is the first time we hit this line. Associate the node with this BP. record.Node = node; return record.Breakpoint; } } internal static IReadOnlyList<BreakpointRecord> UpdateBreakpointRecords(IReadOnlyList<ISourceBreakpoint> newBreakpoints, IReadOnlyList<BreakpointRecord> currentBreakpoints) { Contract.Requires(newBreakpoints != null); Contract.Ensures(Contract.Result<IReadOnlyList<BreakpointRecord>>() != null); Contract.Ensures(Contract.Result<IReadOnlyList<BreakpointRecord>>().Count == newBreakpoints.Count); // convert to BreakpointRecord var breakpoints = newBreakpoints.Select(b => new BreakpointRecord(b)).ToArray(); // if 0 breakpoints given --> return early if (breakpoints.Length == 0) { return breakpoints; } if (currentBreakpoints != null) { // If we already have any breakpoint in this file, try to preserve their // node affinity if they also appear in the new breakpoint list. // Get nodes currently associated with each breakpoint var currentBreakpointSet = new Dictionary<int, Node>(); foreach (var bpr in currentBreakpoints) { if (bpr.Node != null) { currentBreakpointSet[bpr.Breakpoint.Line] = bpr.Node; } } // Store them in the new breakpoint if line number matches foreach (var bpr in breakpoints) { Node node; if (currentBreakpointSet.TryGetValue(bpr.Breakpoint.Line, out node)) { bpr.Node = node; } } } return breakpoints; } // =========================================================================================================== // == Private Implementations of interfaces declared above (IBreakpointStore, IMasterStore). // =========================================================================================================== /// <summary> /// Super slow. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1812:InternalClassNeverInstantiated")] private sealed class MasterStoreWithConcurrentDictionary : IMasterStore { private int m_version; /// <summary> /// Maps a source path to a list of <code cref="IBreakpoint"/>s. /// </summary> private readonly ConcurrentDictionary<AbsolutePath, IReadOnlyList<BreakpointRecord>> m_breakpoints; /// <inheritdoc/> public int Version => Volatile.Read(ref m_version); /// <summary>Constructor. Creates a new store with <see cref="Version"/> set to 1.</summary> internal MasterStoreWithConcurrentDictionary() { m_version = 0; m_breakpoints = new ConcurrentDictionary<AbsolutePath, IReadOnlyList<BreakpointRecord>>(); } /// <inheritdoc/> public bool IsEmpty => m_breakpoints.IsEmpty; /// <inheritdoc/> public IReadOnlyList<IBreakpoint> Set(AbsolutePath source, IReadOnlyList<ISourceBreakpoint> sourceBreakpoints) { IncrementVersion(); // remove existing breakpoints IReadOnlyList<BreakpointRecord> currentRecords; var breakpointsForSourceExisted = m_breakpoints.TryRemove(source, out currentRecords); var records = UpdateBreakpointRecords(sourceBreakpoints, breakpointsForSourceExisted ? currentRecords : null); // if 0 breakpoints given --> already removed from dictionary, so just return if (records.Count == 0) { return new IBreakpoint[0]; } else { m_breakpoints[source] = records; return records.Select(b => b.Breakpoint).ToArray(); } } /// <inheritdoc/> public void Clear() { IncrementVersion(); m_breakpoints.Clear(); } /// <inheritdoc/> public IBreakpoint Find(AbsolutePath source, Node node) { IReadOnlyList<BreakpointRecord> breakpointsForSource; return m_breakpoints.TryGetValue(source, out breakpointsForSource) ? SearchRecords(breakpointsForSource, node) : null; } /// <summary> /// Returns a clone of this store which is not thread-safe and implements not locking. /// </summary> public IBreakpointStore Clone() { var dict = m_breakpoints.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); return new DictBackedReadOnlyStore(Version, dict); } private void IncrementVersion() { Interlocked.Increment(ref m_version); } object ICloneable.Clone() => Clone(); } /// <summary> /// Thread-safe implementation of <see cref="IMasterStore"/> that uses locking. /// </summary> private sealed class MasterStoreWithLocking : IMasterStore { private int m_version; /// <summary> /// Maps a source path to a list of <code cref="IBreakpoint"/>s. /// </summary> // (TODO: consider using AbsolutePath as key) private readonly IDictionary<AbsolutePath, IReadOnlyList<BreakpointRecord>> m_breakpoints; /// <inheritdoc/> public int Version => m_version; /// <summary>Constructor. Creates a new store with <see cref="Version"/> set to 1.</summary> public MasterStoreWithLocking() { m_version = 0; m_breakpoints = new Dictionary<AbsolutePath, IReadOnlyList<BreakpointRecord>>(); } /// <inheritdoc/> public bool IsEmpty => m_breakpoints.Count == 0; /// <inheritdoc/> public IReadOnlyList<IBreakpoint> Set(AbsolutePath source, IReadOnlyList<ISourceBreakpoint> sourceBreakpoints) { lock (this) { IncrementVersion(); var currentBreakpoints = m_breakpoints.ContainsKey(source) ? m_breakpoints[source] : null; var records = UpdateBreakpointRecords(sourceBreakpoints, currentBreakpoints); // if 0 breakpoints given --> already removed from dictionary, so just return if (records.Count == 0) { m_breakpoints.Remove(source); return new IBreakpoint[0]; } else { m_breakpoints[source] = records; return records.Select(b => b.Breakpoint).ToArray(); } } } /// <inheritdoc/> public void Clear() { lock (this) { IncrementVersion(); m_breakpoints.Clear(); } } /// <inheritdoc/> public IBreakpoint Find(AbsolutePath source, Node node) { lock (this) { IReadOnlyList<BreakpointRecord> breakpointsForSource; return m_breakpoints.TryGetValue(source, out breakpointsForSource) ? SearchRecords(breakpointsForSource, node) : null; } } /// <summary> /// Returns a clone of this store which is not thread-safe and implements not locking. /// </summary> public IBreakpointStore Clone() { lock (this) { var dict = m_breakpoints.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); return new DictBackedReadOnlyStore(Version, dict); } } object ICloneable.Clone() => Clone(); private void IncrementVersion() { Interlocked.Increment(ref m_version); } } /// <summary> /// A simple dictionary-backed, non-thread-safe implementation of <see cref="IBreakpointStore"/>. /// </summary> private sealed class DictBackedReadOnlyStore : IBreakpointStore { private readonly int m_version; private readonly IDictionary<AbsolutePath, IReadOnlyList<BreakpointRecord>> m_dict; /// <inheritdoc/> public int Version => m_version; /// <inheritdoc/> public bool IsEmpty => m_dict.Count == 0; /// <inheritdoc/> public IBreakpoint Find(AbsolutePath source, Node node) { IReadOnlyList<BreakpointRecord> breakpointsForSource; return m_dict.TryGetValue(source, out breakpointsForSource) ? SearchRecords(breakpointsForSource, node) : null; } internal DictBackedReadOnlyStore(int version, IDictionary<AbsolutePath, IReadOnlyList<BreakpointRecord>> dict) { m_version = version; m_dict = dict; } } /// <summary> /// An implementation of <see cref="IBreakpointStore"/> that has two different backing breakpoint /// stores: one thread-safe master, and one simple proxy store. All reads are performed from the /// proxy store, as long as its version is the same as that of the master store; when the versions /// are not the same, the proxy store is overwritten with a clone of the master. /// </summary> /// <remarks> /// The motivation behind this implementation is to be able to do locking-free reads. /// </remarks> private sealed class ReadOnlyProxyStore : IBreakpointStore { private readonly IMasterStore m_master; private IBreakpointStore m_proxy; internal ReadOnlyProxyStore(IMasterStore master) { m_master = master; m_proxy = master.Clone(); } /// <inheritdoc/> public int Version => m_proxy.Version; /// <inheritdoc/> public bool IsEmpty { get { UpdateProxy(); return m_proxy.IsEmpty; } } /// <inheritdoc/> public IBreakpoint Find(AbsolutePath source, Node node) { UpdateProxy(); return m_proxy.Find(source, node); } private void UpdateProxy() { if (m_proxy.Version != m_master.Version) { m_proxy = m_master.Clone(); } } } } }
38.492386
181
0.50389
[ "MIT" ]
MatisseHack/BuildXL
Public/Src/IDE/Debugger/BreakpointStore.cs
15,166
C#
namespace PddOpenSdk.Models.Response.Refund; public partial class GetRefundListIncrementResponse : PddResponseModel { /// <summary> /// 售后增量订单列表对象 /// </summary> [JsonPropertyName("refund_increment_get_response")] public RefundIncrementGetResponseResponse RefundIncrementGetResponse { get; set; } public partial class RefundIncrementGetResponseResponse : PddResponseModel { /// <summary> /// 售后列表对象 /// </summary> [JsonPropertyName("refund_list")] public List<RefundListResponse> RefundList { get; set; } /// <summary> /// 返回的售后订单列表总数 /// </summary> [JsonPropertyName("total_count")] public int? TotalCount { get; set; } public partial class RefundListResponse : PddResponseModel { /// <summary> /// 极速退款状态,"1":有极速退款资格,"2":极速退款失败, "3" 表示极速退款成功,其他表示非极速退款 /// </summary> [JsonPropertyName("speed_refund_status")] public string SpeedRefundStatus { get; set; } /// <summary> /// 售后原因 /// </summary> [JsonPropertyName("after_sale_reason")] public string AfterSaleReason { get; set; } /// <summary> /// 售后状态 0:无售后 2:买家申请退款,待商家处理 3:退货退款,待商家处理 4:商家同意退款,退款中 5:平台同意退款,退款中 6:驳回退款,待买家处理 7:已同意退货退款,待用户发货 8:平台处理中 9:平台拒绝退款,退款关闭 10:退款成功 11:买家撤销 12:买家逾期未处理,退款失败 13:买家逾期,超过有效期 14:换货补寄待商家处理 15:换货补寄待用户处理 16:换货补寄成功 17:换货补寄失败 18:换货补寄待用户确认完成 21:待商家同意维修 22:待用户确认发货 24:维修关闭 25:维修成功 27:待用户确认收货 31:已同意拒收退款,待用户拒收 32:补寄待商家发货 /// </summary> [JsonPropertyName("after_sales_status")] public int? AfterSalesStatus { get; set; } /// <summary> /// 售后类型 /// </summary> [JsonPropertyName("after_sales_type")] public int? AfterSalesType { get; set; } /// <summary> /// 成团时间 /// </summary> [JsonPropertyName("confirm_time")] public string ConfirmTime { get; set; } /// <summary> /// 创建时间 /// </summary> [JsonPropertyName("created_time")] public string CreatedTime { get; set; } /// <summary> /// 订单折扣金额(元) /// </summary> [JsonPropertyName("discount_amount")] public string DiscountAmount { get; set; } /// <summary> /// 商品图片 /// </summary> [JsonPropertyName("good_image")] public string GoodImage { get; set; } /// <summary> /// 商品编码 /// </summary> [JsonPropertyName("goods_id")] public long? GoodsId { get; set; } /// <summary> /// 商品名称 /// </summary> [JsonPropertyName("goods_name")] public string GoodsName { get; set; } /// <summary> /// 商品数量 /// </summary> [JsonPropertyName("goods_number")] public string GoodsNumber { get; set; } /// <summary> /// 商品单价 /// </summary> [JsonPropertyName("goods_price")] public string GoodsPrice { get; set; } /// <summary> /// 售后编号 /// </summary> [JsonPropertyName("id")] public long? Id { get; set; } /// <summary> /// 订单金额(元) /// </summary> [JsonPropertyName("order_amount")] public string OrderAmount { get; set; } /// <summary> /// 订单编号 /// </summary> [JsonPropertyName("order_sn")] public string OrderSn { get; set; } /// <summary> /// 商家外部编码(商品) /// </summary> [JsonPropertyName("outer_goods_id")] public string OuterGoodsId { get; set; } /// <summary> /// 商家外部编码(sku) /// </summary> [JsonPropertyName("outer_id")] public string OuterId { get; set; } /// <summary> /// 退款金额(元) /// </summary> [JsonPropertyName("refund_amount")] public string RefundAmount { get; set; } /// <summary> /// 商品规格ID /// </summary> [JsonPropertyName("sku_id")] public string SkuId { get; set; } /// <summary> /// 快递运单号 /// </summary> [JsonPropertyName("tracking_number")] public string TrackingNumber { get; set; } /// <summary> /// 更新时间 /// </summary> [JsonPropertyName("updated_time")] public string UpdatedTime { get; set; } /// <summary> /// 极速退款标志位 1:极速退款,0:非极速退款 /// </summary> [JsonPropertyName("speed_refund_flag")] public int? SpeedRefundFlag { get; set; } /// <summary> /// 退货物流公司名称 /// </summary> [JsonPropertyName("shipping_name")] public string ShippingName { get; set; } /// <summary> /// 0-未勾选 1-消费者选择的收货状态为未收到货 2-消费者选择的收货状态为已收到货 /// </summary> [JsonPropertyName("user_shipping_status")] public string UserShippingStatus { get; set; } /// <summary> /// 1纠纷退款 0非纠纷退款 /// </summary> [JsonPropertyName("dispute_refund_status")] public int? DisputeRefundStatus { get; set; } } } }
30.84153
315
0.490787
[ "Apache-2.0" ]
niltor/open-pdd-net-sdk
PddOpenSdk/PddOpenSdk/Models/Response/Refund/GetRefundListIncrementResponse.cs
6,578
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Collections.Generic; using System.Diagnostics; using Roslyn.Utilities; using Word = System.UInt64; namespace Microsoft.CodeAnalysis { [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal struct BitVector : IEquatable<BitVector> { private const Word ZeroWord = 0; private const int Log2BitsPerWord = 6; public const int BitsPerWord = 1 << Log2BitsPerWord; // Cannot expose the following two field publicly because this structure is mutable // and might become not null/empty, unless we restrict access to it. private static Word[] s_emptyArray => Array.Empty<Word>(); private static readonly BitVector s_nullValue = default; private static readonly BitVector s_emptyValue = new BitVector(0, s_emptyArray, 0); private Word _bits0; private Word[] _bits; private int _capacity; private BitVector(Word bits0, Word[] bits, int capacity) { int requiredWords = WordsForCapacity(capacity); Debug.Assert(requiredWords == 0 || requiredWords <= bits.Length); _bits0 = bits0; _bits = bits; _capacity = capacity; Check(); } public bool Equals(BitVector other) { // Bit arrays only equal if their underlying sets are of the same size return _capacity == other._capacity // and have the same set of bits set && _bits0 == other._bits0 && _bits.AsSpan().SequenceEqual(other._bits.AsSpan()); } public override bool Equals(object? obj) { return obj is BitVector other && Equals(other); } public static bool operator ==(BitVector left, BitVector right) { return left.Equals(right); } public static bool operator !=(BitVector left, BitVector right) { return !left.Equals(right); } public override int GetHashCode() { int bitsHash = _bits0.GetHashCode(); if (_bits != null) { for (int i = 0; i < _bits.Length; i++) { bitsHash = Hash.Combine(_bits[i].GetHashCode(), bitsHash); } } return Hash.Combine(_capacity, bitsHash); } private static int WordsForCapacity(int capacity) { if (capacity <= 0) return 0; int lastIndex = (capacity - 1) >> Log2BitsPerWord; return lastIndex; } public int Capacity => _capacity; [Conditional("DEBUG_BITARRAY")] private void Check() { Debug.Assert(_capacity == 0 || WordsForCapacity(_capacity) <= _bits.Length); } public void EnsureCapacity(int newCapacity) { if (newCapacity > _capacity) { int requiredWords = WordsForCapacity(newCapacity); if (requiredWords > _bits.Length) Array.Resize(ref _bits, requiredWords); _capacity = newCapacity; Check(); } Check(); } public IEnumerable<Word> Words() { if (_capacity > 0) { yield return _bits0; } for (int i = 0, n = _bits?.Length ?? 0; i < n; i++) { yield return _bits![i]; } } public IEnumerable<int> TrueBits() { Check(); if (_bits0 != 0) { for (int bit = 0; bit < BitsPerWord; bit++) { Word mask = ((Word)1) << bit; if ((_bits0 & mask) != 0) { if (bit >= _capacity) yield break; yield return bit; } } } for (int i = 0; i < _bits.Length; i++) { Word w = _bits[i]; if (w != 0) { for (int b = 0; b < BitsPerWord; b++) { Word mask = ((Word)1) << b; if ((w & mask) != 0) { int bit = ((i + 1) << Log2BitsPerWord) | b; if (bit >= _capacity) yield break; yield return bit; } } } } } /// <summary> /// Create BitArray with at least the specified number of bits. /// </summary> public static BitVector Create(int capacity) { int requiredWords = WordsForCapacity(capacity); Word[] bits = (requiredWords == 0) ? s_emptyArray : new Word[requiredWords]; return new BitVector(0, bits, capacity); } /// <summary> /// return a bit array with all bits set from index 0 through bitCount-1 /// </summary> /// <param name="capacity"></param> /// <returns></returns> public static BitVector AllSet(int capacity) { if (capacity == 0) { return Empty; } int requiredWords = WordsForCapacity(capacity); Word[] bits = (requiredWords == 0) ? s_emptyArray : new Word[requiredWords]; int lastWord = requiredWords - 1; Word bits0 = ~ZeroWord; for (int j = 0; j < lastWord; j++) bits[j] = ~ZeroWord; int numTrailingBits = capacity & ((BitsPerWord) - 1); if (numTrailingBits > 0) { Debug.Assert(numTrailingBits <= BitsPerWord); Word lastBits = ~((~ZeroWord) << numTrailingBits); if (lastWord < 0) { bits0 = lastBits; } else { bits[lastWord] = lastBits; } } else if (requiredWords > 0) { bits[lastWord] = ~ZeroWord; } return new BitVector(bits0, bits, capacity); } /// <summary> /// Make a copy of a bit array. /// </summary> /// <returns></returns> public BitVector Clone() { Word[] newBits; if (_bits is null || _bits.Length == 0) { newBits = s_emptyArray; } else { newBits = (Word[])_bits.Clone(); } return new BitVector(_bits0, newBits, _capacity); } /// <summary> /// Invert all the bits in the vector. /// </summary> public void Invert() { _bits0 = ~_bits0; if (!(_bits is null)) { for (int i = 0; i < _bits.Length; i++) { _bits[i] = ~_bits[i]; } } } /// <summary> /// Is the given bit array null? /// </summary> public bool IsNull { get { return _bits == null; } } public static BitVector Null => s_nullValue; public static BitVector Empty => s_emptyValue; /// <summary> /// Modify this bit vector by bitwise AND-ing each element with the other bit vector. /// For the purposes of the intersection, any bits beyond the current length will be treated as zeroes. /// Return true if any changes were made to the bits of this bit vector. /// </summary> public bool IntersectWith(in BitVector other) { bool anyChanged = false; int otherLength = other._bits.Length; var thisBits = _bits; int thisLength = thisBits.Length; if (otherLength > thisLength) otherLength = thisLength; // intersect the inline portion { var oldV = _bits0; var newV = oldV & other._bits0; if (newV != oldV) { _bits0 = newV; anyChanged = true; } } // intersect up to their common length. for (int i = 0; i < otherLength; i++) { var oldV = thisBits[i]; var newV = oldV & other._bits[i]; if (newV != oldV) { thisBits[i] = newV; anyChanged = true; } } // treat the other bit array as being extended with zeroes for (int i = otherLength; i < thisLength; i++) { if (thisBits[i] != 0) { thisBits[i] = 0; anyChanged = true; } } Check(); return anyChanged; } /// <summary> /// Modify this bit vector by '|'ing each element with the other bit vector. /// </summary> /// <returns> /// True if any bits were set as a result of the union. /// </returns> public bool UnionWith(in BitVector other) { bool anyChanged = false; if (other._capacity > _capacity) EnsureCapacity(other._capacity); Word oldbits = _bits0; _bits0 |= other._bits0; if (oldbits != _bits0) anyChanged = true; for (int i = 0; i < other._bits.Length; i++) { oldbits = _bits[i]; _bits[i] |= other._bits[i]; if (_bits[i] != oldbits) anyChanged = true; } Check(); return anyChanged; } public bool this[int index] { get { if (index < 0) throw new IndexOutOfRangeException(); if (index >= _capacity) return false; int i = (index >> Log2BitsPerWord) - 1; var word = (i < 0) ? _bits0 : _bits[i]; return IsTrue(word, index); } set { if (index < 0) throw new IndexOutOfRangeException(); if (index >= _capacity) EnsureCapacity(index + 1); int i = (index >> Log2BitsPerWord) - 1; int b = index & (BitsPerWord - 1); Word mask = ((Word)1) << b; if (i < 0) { if (value) _bits0 |= mask; else _bits0 &= ~mask; } else { if (value) _bits[i] |= mask; else _bits[i] &= ~mask; } } } public void Clear() { _bits0 = 0; if (_bits != null) Array.Clear(_bits, 0, _bits.Length); } public static bool IsTrue(Word word, int index) { int b = index & (BitsPerWord - 1); Word mask = ((Word)1) << b; return (word & mask) != 0; } public static int WordsRequired(int capacity) { if (capacity <= 0) return 0; return WordsForCapacity(capacity) + 1; } internal string GetDebuggerDisplay() { var value = new char[_capacity]; for (int i = 0; i < _capacity; i++) { value[_capacity - i - 1] = this[i] ? '1' : '0'; } return new string(value); } } }
30.02445
111
0.446173
[ "MIT" ]
06needhamt/roslyn
src/Compilers/Core/Portable/Collections/BitVector.cs
12,282
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spinner : MonoBehaviour { [SerializeField] float xAngle = 0; [SerializeField] float yAngle = 1; [SerializeField] float zAngle = 0; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { transform.Rotate(xAngle,yAngle,zAngle); } }
20.318182
52
0.653244
[ "MIT" ]
CallMeCody/obstacle-course
Obstacle Course/Assets/Scripts/Spinner.cs
447
C#
// Copyright © 2018 Wave Engine S.L. All rights reserved. Use is subject to license terms. #region Using Statements using System; using System.Runtime.Serialization; using WaveEngine.Common.Math; using WaveEngine.Framework; #endregion namespace WaveEngine.Networking.Components { /// <summary> /// Provides an abstraction to track changes on a <see cref="Vector3"/> property contained on a /// <see cref="NetworkPropertiesTable"/>. A <see cref="NetworkPropertiesTable"/> component is needed in the same /// entity or any of its parents /// </summary> /// <typeparam name="K">The type of the property key. Must be <see cref="byte"/> or <see cref="Enum"/></typeparam> [DataContract] [AllowMultipleInstances] public abstract class NetworkVector3PropertySync<K> : NetworkPropertySync<K, Vector3> where K : struct, IConvertible { #region Private Methods /// <inheritdoc /> protected override Vector3 ReadValue(NetworkPropertiesTable propertiesTable) { return propertiesTable.GetVector3(this.propertyKey); } /// <inheritdoc /> protected override void WriteValue(NetworkPropertiesTable propertiesTable, Vector3 value) { propertiesTable.Set(this.propertyKey, value); } #endregion } }
33.45
118
0.681614
[ "MIT" ]
WaveEngine/Extensions
WaveEngine.Networking/Shared/Components/Synchronization/NetworkVector3PropertySync`1.cs
1,341
C#