commit
stringlengths
40
40
subject
stringlengths
4
1.73k
repos
stringlengths
5
127k
old_file
stringlengths
2
751
new_file
stringlengths
2
751
new_contents
stringlengths
1
8.98k
old_contents
stringlengths
0
6.59k
license
stringclasses
13 values
lang
stringclasses
23 values
b2933231cd05f46f1adfc319ddb25980136466d6
Add summary notes to properties on DayEntry
ithielnor/harvest.net
Harvest.Net/Models/DayEntry.cs
Harvest.Net/Models/DayEntry.cs
using RestSharp.Serializers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Harvest.Net.Models { [SerializeAs(Name = "day-entry")] public class DayEntry : Harvest.Net.Models.IModel { public long Id { get; set; } public DateTime UpdatedAt { get; set; } public DateTime CreatedAt { get; set; } public string Notes { get; set; } public DateTime SpentAt { get; set; } public decimal Hours { get; set; } public int UserId { get; set; } public int ProjectId { get; set; } public int TaskId { get; set; } public bool AdjustmentRecord { get; set; } public bool IsBilled { get; set; } public bool IsClosed { get; set; } /// <summary> /// Only supplied by the Daily resource /// </summary> public DateTime? TimerStartedAt { get; set; } /// <summary> /// Only supplied by the Daily resource /// </summary> public DateTime? StartedAt { get; set; } /// <summary> /// Only supplied by the Daily resource /// </summary> public DateTime? EndedAt { get; set; } /// <summary> /// Only supplied by the Daily resource /// </summary> public string Task { get; set; } /// <summary> /// Only supplied by the Daily resource /// </summary> public string Project { get; set; } } }
using RestSharp.Serializers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Harvest.Net.Models { [SerializeAs(Name = "day-entry")] public class DayEntry : Harvest.Net.Models.IModel { public long Id { get; set; } public DateTime UpdatedAt { get; set; } public DateTime CreatedAt { get; set; } public string Notes { get; set; } public DateTime SpentAt { get; set; } public decimal Hours { get; set; } public int UserId { get; set; } public int ProjectId { get; set; } public int TaskId { get; set; } public bool AdjustmentRecord { get; set; } public bool IsBilled { get; set; } public bool IsClosed { get; set; } // These fields are only present when loaded from the Daily resource public DateTime? TimerStartedAt { get; set; } public DateTime? StartedAt { get; set; } public DateTime? EndedAt { get; set; } public string Task { get; set; } public string Project { get; set; } } }
mit
C#
6093d5c24b812b2f09d0956d868e7353433d1ef1
Fix app bar bug
zumicts/Audiotica
Apps/Audiotica.WindowsPhone/View/CollectionAlbumPage.xaml.cs
Apps/Audiotica.WindowsPhone/View/CollectionAlbumPage.xaml.cs
#region using Windows.UI.StartScreen; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Audiotica.ViewModel; using GalaSoft.MvvmLight.Messaging; #endregion namespace Audiotica.View { public sealed partial class CollectionAlbumPage { public CollectionAlbumPage() { InitializeComponent(); Bar = BottomAppBar; BottomAppBar = null; } public override void NavigatedTo(object e) { base.NavigatedTo(e); var id = e as int?; if (id == null) return; var msg = new GenericMessage<int>((int)id); Messenger.Default.Send(msg, "album-coll-detail-id"); ToggleAppBarButton(SecondaryTile.Exists("album." + Vm.Album.Id)); } private CollectionAlbumViewModel Vm { get { return DataContext as CollectionAlbumViewModel; } } private void ToggleAppBarButton(bool isPinned) { if (!isPinned) { PinUnpinAppBarButton.Label = "Pin"; PinUnpinAppBarButton.Icon = new SymbolIcon(Symbol.Pin); } else { PinUnpinAppBarButton.Label = "Unpin"; PinUnpinAppBarButton.Icon = new SymbolIcon(Symbol.UnPin); } } private async void PinUnpinAppBarButton_OnClick(object sender, RoutedEventArgs e) { ToggleAppBarButton(await CollectionHelper.PinToggleAsync(Vm.Album)); } } }
#region using Windows.UI.StartScreen; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Audiotica.ViewModel; using GalaSoft.MvvmLight.Messaging; #endregion namespace Audiotica.View { public sealed partial class CollectionAlbumPage { public CollectionAlbumPage() { InitializeComponent(); } public override void NavigatedTo(object e) { base.NavigatedTo(e); var id = e as int?; if (id == null) return; var msg = new GenericMessage<int>((int)id); Messenger.Default.Send(msg, "album-coll-detail-id"); ToggleAppBarButton(SecondaryTile.Exists("album." + Vm.Album.Id)); } private CollectionAlbumViewModel Vm { get { return DataContext as CollectionAlbumViewModel; } } private void ToggleAppBarButton(bool isPinned) { if (!isPinned) { PinUnpinAppBarButton.Label = "Pin"; PinUnpinAppBarButton.Icon = new SymbolIcon(Symbol.Pin); } else { PinUnpinAppBarButton.Label = "Unpin"; PinUnpinAppBarButton.Icon = new SymbolIcon(Symbol.UnPin); } } private async void PinUnpinAppBarButton_OnClick(object sender, RoutedEventArgs e) { ToggleAppBarButton(await CollectionHelper.PinToggleAsync(Vm.Album)); } } }
apache-2.0
C#
235d113973e6985e68e350d97d9e3c2510f83e1c
Update assertion error message
lordmilko/PrtgAPI,lordmilko/PrtgAPI
PrtgAPI.Tests.UnitTests/ObjectTests/SensorTests.cs
PrtgAPI.Tests.UnitTests/ObjectTests/SensorTests.cs
using System.Collections; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using PrtgAPI.Tests.UnitTests.ObjectTests.Items; using PrtgAPI.Tests.UnitTests.ObjectTests.Responses; namespace PrtgAPI.Tests.UnitTests.ObjectTests { [TestClass] public class SensorTests : ObjectTests<Sensor, SensorItem, SensorResponse> { [TestMethod] public void Sensor_CanDeserialize() => Object_CanDeserialize(); [TestMethod] public void Sensor_AllFields_HaveValues() { Object_AllFields_HaveValues(prop => { if (prop.Name == nameof(Sensor.BaseType)) //As Sensor is the default value of BaseType, we cannot verify whether the value was actually set return true; return false; }); } [TestMethod] public void Sensor_Async_Ordered_FastestToSlowest() { var count = 2000; var perPage = 500; var pages = count/perPage; var client = Initialize_Client_WithItems(Enumerable.Range(0, count).Select(i => GetItem()).ToArray()); var results = client.GetSensorsAsync().Select(i => i.Id).ToList(); Assert.IsTrue(results.Count == count, $"Expected {count} results but got {results.Count} instead."); for (int pageNum = pages; pageNum > 0; pageNum--) { var r = results.Skip((pages - pageNum)*perPage).Take(perPage).ToList(); Assert.IsTrue(r.TrueForAll(item => item == pageNum)); } } protected override List<Sensor> GetObjects(PrtgClient client) => client.GetSensors(); protected override SensorItem GetItem() => new SensorItem(); protected override SensorResponse GetResponse(SensorItem[] items) => new SensorResponse(items); } }
using System.Collections; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using PrtgAPI.Tests.UnitTests.ObjectTests.Items; using PrtgAPI.Tests.UnitTests.ObjectTests.Responses; namespace PrtgAPI.Tests.UnitTests.ObjectTests { [TestClass] public class SensorTests : ObjectTests<Sensor, SensorItem, SensorResponse> { [TestMethod] public void Sensor_CanDeserialize() => Object_CanDeserialize(); [TestMethod] public void Sensor_AllFields_HaveValues() { Object_AllFields_HaveValues(prop => { if (prop.Name == nameof(Sensor.BaseType)) //As Sensor is the default value of BaseType, we cannot verify whether the value was actually set return true; return false; }); } [TestMethod] public void Sensor_Async_Ordered_FastestToSlowest() { var count = 2000; var perPage = 500; var pages = count/perPage; var client = Initialize_Client_WithItems(Enumerable.Range(0, count).Select(i => GetItem()).ToArray()); var results = client.GetSensorsAsync().Select(i => i.Id).ToList(); Assert.IsTrue(results.Count == count); for (int pageNum = pages; pageNum > 0; pageNum--) { var r = results.Skip((pages - pageNum)*perPage).Take(perPage).ToList(); Assert.IsTrue(r.TrueForAll(item => item == pageNum)); } } protected override List<Sensor> GetObjects(PrtgClient client) => client.GetSensors(); protected override SensorItem GetItem() => new SensorItem(); protected override SensorResponse GetResponse(SensorItem[] items) => new SensorResponse(items); } }
mit
C#
448f66ea7f46e0dc78297fd6fc2fee11dcfd1c52
Implement analyzing skeleton
occar421/OpenTKAnalyzer
src/OpenTKAnalyzer/OpenTKAnalyzer/OpenTK/RotationValueOpenTKMathAnalyzer.cs
src/OpenTKAnalyzer/OpenTKAnalyzer/OpenTK/RotationValueOpenTKMathAnalyzer.cs
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace OpenTKAnalyzer.OpenTK { [DiagnosticAnalyzer(LanguageNames.CSharp)] class RotationValueOpenTKMathAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "RotatinoValueOpenTKMath"; private const string Title = "Rotation value(OpenTK Math)"; private const string MessageFormat = "{0} accepts {1} values."; private const string Description = "Warm on literal in argument seems invalid style(radian or degree)."; private const string Category = "OpenTKAnalyzer:OpenTK"; private const string RadianString = "radian"; private const string DegreeString = "degree"; internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor( id: DiagnosticId, title: Title, messageFormat: MessageFormat, category: Category, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.InvocationExpression); } private static void Analyze(SyntaxNodeAnalysisContext context) { var invotation = context.Node as InvocationExpressionSyntax; // MathHelper if (invotation.GetFirstToken().ValueText == "MathHelper") { switch (invotation.Expression.GetLastToken().ValueText) { default: break; } return; } // Matrix2, Matrix3x4 etc... if (invotation.GetFirstToken().ValueText.StartsWith("Matrix")) { switch (invotation.Expression.GetLastToken().ValueText) { default: break; } return; } } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace OpenTKAnalyzer.OpenTK { [DiagnosticAnalyzer(LanguageNames.CSharp)] class RotationValueOpenTKMathAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "RotatinoValueOpenTKMath"; private const string Title = "Rotation value(OpenTK Math)"; private const string MessageFormat = "{0} accepts {1} values."; private const string Description = "Warm on literal in argument seems invalid style(radian or degree)."; private const string Category = "OpenTKAnalyzer:OpenTK"; private const string RadianString = "radian"; private const string DegreeString = "degree"; internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor( id: DiagnosticId, title: Title, messageFormat: MessageFormat, category: Category, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.InvocationExpression); } private static void Analyze(SyntaxNodeAnalysisContext context) { var invotation = context.Node as InvocationExpressionSyntax; // TODO: check method name and literal on argument } } }
mit
C#
2317e38cbd3083912619eff1cfba381ea8fe63ae
Update main.cs
eightyeight/vlrtt,eightyeight/vlrtt
modules/stateMachine/main.cs
modules/stateMachine/main.cs
function StateMachine::onEvent(%this, %event) { // See if there's a transition callback ssociated with this event. %script = "on" @ %event; if(%this.isMethod(%script)) { %this.call(%script); } // Figure out the new state to transition to. %newState = %this.transition[%this.state, %event]; // If it doesn't exist, see if there's a wildcard transition for this event. if(%newState $= "") { %newState = %this.transition["*", %event]; } // Apply the state change. if(%newState !$= "") { // Callback for leaving the current state. %script = "leave" @ %this.state; if(%this.isMethod(%script)) { %this.call(%script); } // Change the state! %this.state = %newState; // Callback upon entering the new state. %script = "enter" @ %this.state; if(%this.isMethod(%script)) { %this.call(%script); } } return %this; }
function StateMachine::onEvent(%this, %event) { // See if there's a transition callback ssociated with this event. %script = "on" @ %event; if(%this.isMethod(%script)) { %this.call(%script); } // Figure out the new state to transition to. %trans = %this.transition[%this.state, %event]; // If it doesn't exist, see if there's a wildcard transition for this event. if(%trans $= "") { %trans = %this.transition["*", %event]; } // Apply the state change. if(%trans !$= "") { // Callback for leaving the current state. %script = "leave" @ %this.state; if(%this.isMethod(%script)) { %this.call(%script); } // Change the state! %this.state = %trans; // Callback upon entering the new state. %script = "enter" @ %this.state; if(%this.isMethod(%script)) { %this.call(%script); } } return %this; }
mit
C#
2cad479e1bb7f2abd174b89e187dd9def1965067
Improve InvokerCOMException class design
NetOfficeFw/NetOffice
Source/NetOffice/Exceptions/InvokerCOMException.cs
Source/NetOffice/Exceptions/InvokerCOMException.cs
using System; namespace NetOffice.Exceptions { /// <summary> /// Indicates a failed invoke operation. /// </summary> public abstract class InvokerCOMException : NetOfficeCOMException { /// <summary> /// Creates an instance of the InvokerCOMException class. /// </summary> /// <param name="message">the message that indicates the reason for the exception</param> /// <param name="innerException">inner exception</param> protected InvokerCOMException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Creates an instance of the InvokerCOMException class. /// </summary> /// <param name="innerException">inner exception</param> protected InvokerCOMException(Exception innerException) : base(innerException?.Message ?? "Failed to invoke property.", innerException) { } } }
using System; namespace NetOffice.Exceptions { /// <summary> /// Indicates a failed invoke operation /// </summary> public abstract class InvokerCOMException : NetOfficeCOMException { /// <summary> /// Creates an instance of the class /// </summary> /// <param name="message">the message that indicates the reason for the exception</param> /// <param name="innerException">inner exception</param> public InvokerCOMException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Creates an instance of the class /// </summary> /// <param name="innerException">inner exception</param> public InvokerCOMException(Exception innerException) : base(null != innerException ? innerException.Message : "Failed to invoke property.", innerException) { } } }
mit
C#
f9464773543dee7bcde5be46b61a4d3efe1c5ad7
correct test
OlegKleyman/Omego.Selenium
tests/unit/Omego.Selenium.Tests.Unit/Extensions/WebDriverExtensionsTests.cs
tests/unit/Omego.Selenium.Tests.Unit/Extensions/WebDriverExtensionsTests.cs
namespace Omego.Selenium.Tests.Unit.Extensions { using System; using System.Collections.Generic; using System.Drawing.Imaging; using FluentAssertions; using NSubstitute; using Selenium.Extensions; using OpenQA.Selenium; using Xunit; public class WebDriverExtensionsTests { [CLSCompliant(false)] [Theory] [MemberData( nameof(WebDriverExtensionsTestData.SaveScreenshotAsShouldThrowArgumentNullExceptionWhenRequiredArgumentsAreNullCases), null, MemberType = typeof(WebDriverExtensionsTestData))] public void SaveScreenshotAsShouldThrowArgumentNullExceptionWhenRequiredArgumentsAreNull(IWebDriver driver) { Action saveScreenshotAs = () => driver.SaveScreenshotAs(1, new ImageTarget("", "file", ImageFormat.Bmp)); saveScreenshotAs.ShouldThrowExactly<ArgumentNullException>().And.ParamName.ShouldBeEquivalentTo("driver"); } [Fact] public void SaveScreenshotAsShouldThrowExceptionWhenTimeLimitIsReached() { var driver = Substitute.For<IMockWebDriver>(); driver.GetScreenshot().Returns(new Screenshot("")); Action saveScreenshotAs = () => driver.SaveScreenshotAs(500, new ImageTarget("", "test.bmp", ImageFormat.Bmp)); saveScreenshotAs.ShouldThrow<TimeoutException>() .Which.Message.Should() .MatchRegex(@"Unable to get screenshot after trying for 50\dms."); } private class WebDriverExtensionsTestData { public static IEnumerable<object[]> SaveScreenshotAsShouldThrowArgumentNullExceptionWhenRequiredArgumentsAreNullCases => new List<object[]> { new object[] { null } }; } public interface IMockWebDriver : IWebDriver, ITakesScreenshot { } } }
namespace Omego.Selenium.Tests.Unit.Extensions { using System; using System.Collections.Generic; using System.Drawing.Imaging; using FluentAssertions; using NSubstitute; using Selenium.Extensions; using OpenQA.Selenium; using Xunit; public class WebDriverExtensionsTests { [CLSCompliant(false)] [Theory] [MemberData( nameof(WebDriverExtensionsTestData.SaveScreenshotAsShouldThrowArgumentNullExceptionWhenRequiredArgumentsAreNullCases), null, MemberType = typeof(WebDriverExtensionsTestData))] public void SaveScreenshotAsShouldThrowArgumentNullExceptionWhenRequiredArgumentsAreNull(IWebDriver driver) { Action saveScreenshotAs = () => driver.SaveScreenshotAs(1, new ImageTarget("", "", ImageFormat.Bmp)); saveScreenshotAs.ShouldThrowExactly<ArgumentNullException>().And.ParamName.ShouldBeEquivalentTo("driver"); } [Fact] public void SaveScreenshotAsShouldThrowExceptionWhenTimeLimitIsReached() { var driver = Substitute.For<IMockWebDriver>(); driver.GetScreenshot().Returns(new Screenshot("")); Action saveScreenshotAs = () => driver.SaveScreenshotAs(500, new ImageTarget("", "test.bmp", ImageFormat.Bmp)); saveScreenshotAs.ShouldThrow<TimeoutException>() .Which.Message.Should() .MatchRegex(@"Unable to get screenshot after trying for 50\dms."); } private class WebDriverExtensionsTestData { public static IEnumerable<object[]> SaveScreenshotAsShouldThrowArgumentNullExceptionWhenRequiredArgumentsAreNullCases => new List<object[]> { new object[] { null } }; } public interface IMockWebDriver : IWebDriver, ITakesScreenshot { } } }
unlicense
C#
806d109a8ccf9a4c5c919f180ad5a97eb912ac24
Fix failing tests on Travis
plivo/plivo-dotnet,plivo/plivo-dotnet
tests/Plivo.Test/TestSignature.cs
tests/Plivo.Test/TestSignature.cs
using System; using NUnit.Framework; namespace Plivo.Test { [TestFixture] public class TestSignature { [Test] public void TestSignatureV2Pass() { string url = "https://answer.url"; string nonce = "12345"; string signature = "ehV3IKhLysWBxC1sy8INm0qGoQYdYsHwuoKjsX7FsXc="; string authToken = "my_auth_token"; Assert.True(Utilities.XPlivoSignatureV2.VerifySignature(url, nonce, signature, authToken)); } [Test] public void TestSignatureV2Fail() { string url = "https://answer.url"; string nonce = "12345"; string signature = "ehV3IKhLysWBxC1sy8INm0qGoQYdYsHwuoKjsX7FsXc="; string authToken = "my_auth_tokens"; Assert.False(Utilities.XPlivoSignatureV2.VerifySignature(url, nonce, signature, authToken)); } } }
using System; using NUnit.Framework; namespace Plivo.Test { [TestFixture] public class TestSignature { [Test] public void TestSignatureV2Pass() { string url = "https://answer.url"; string nonce = "12345"; string signature = "ehV3IKhLysWBxC1sy8INm0qGoQYdYsHwuoKjsX7FsXc="; string authToken = "my_auth_token"; Assert.Equals(Utilities.XPlivoSignatureV2.VerifySignature(url, nonce, signature, authToken), true); } [Test] public void TestSignatureV2Fail() { string url = "https://answer.url"; string nonce = "12345"; string signature = "ehV3IKhLysWBxC1sy8INm0qGoQYdYsHwuoKjsX7FsXc="; string authToken = "my_auth_tokens"; Assert.Equals(Utilities.XPlivoSignatureV2.VerifySignature(url, nonce, signature, authToken), false); } } }
mit
C#
7abe566c0f574183bd5d74fd206063cf911cf23d
Make ExtraCC and ExtraEmail optional - fixes #385
Didux/MvvmCross-Plugins,MatthewSannes/MvvmCross-Plugins,lothrop/MvvmCross-Plugins,martijn00/MvvmCross-Plugins
Cirrious/Email/Cirrious.MvvmCross.Plugins.Email.Droid/MvxComposeEmailTask.cs
Cirrious/Email/Cirrious.MvvmCross.Plugins.Email.Droid/MvxComposeEmailTask.cs
// MvxComposeEmailTask.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 Android.Content; using Cirrious.CrossCore.Droid.Platform; namespace Cirrious.MvvmCross.Plugins.Email.Droid { public class MvxComposeEmailTask : MvxAndroidTask , IMvxComposeEmailTask { public void ComposeEmail(string to, string cc, string subject, string body, bool isHtml) { var emailIntent = new Intent(global::Android.Content.Intent.ActionSend); if (!string.IsNullOrEmpty(to)) emailIntent.PutExtra(global::Android.Content.Intent.ExtraEmail, to); if (!string.IsNullOrEmpty(cc)) emailIntent.PutExtra(global::Android.Content.Intent.ExtraCc, cc); emailIntent.PutExtra(global::Android.Content.Intent.ExtraSubject, subject ?? string.Empty); emailIntent.SetType(isHtml ? "text/html" : "text/plain"); emailIntent.PutExtra(global::Android.Content.Intent.ExtraText, body ?? string.Empty); StartActivity(emailIntent); } } }
// MvxComposeEmailTask.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 Android.Content; using Cirrious.CrossCore.Droid.Platform; namespace Cirrious.MvvmCross.Plugins.Email.Droid { public class MvxComposeEmailTask : MvxAndroidTask , IMvxComposeEmailTask { public void ComposeEmail(string to, string cc, string subject, string body, bool isHtml) { var emailIntent = new Intent(global::Android.Content.Intent.ActionSend); var toList = new[] {to ?? string.Empty}; var ccList = new[] {cc ?? string.Empty}; ; emailIntent.PutExtra(global::Android.Content.Intent.ExtraEmail, toList); emailIntent.PutExtra(global::Android.Content.Intent.ExtraCc, ccList); emailIntent.PutExtra(global::Android.Content.Intent.ExtraSubject, subject ?? string.Empty); if (isHtml) emailIntent.SetType("text/html"); else emailIntent.SetType("text/plain"); emailIntent.PutExtra(global::Android.Content.Intent.ExtraText, body ?? string.Empty); StartActivity(emailIntent); } } }
mit
C#
269ce605a289cb866ab211c9a9a22f28fd83e19b
rename user management to users
neurral/enterprise,neurral/enterprise,neurral/enterprise,neurral/enterprise
Enterprise/Enterprise.Web/Modules/Administration/AdministrationNavigation.cs
Enterprise/Enterprise.Web/Modules/Administration/AdministrationNavigation.cs
using Serenity.Navigation; using Administration = Enterprise.Administration.Pages; [assembly: NavigationMenu(1000, "Administration", icon: "fa-gear")] [assembly: NavigationLink(1000, "Administration/Roles", typeof(Administration.RoleController), icon: "icon-lock")] [assembly: NavigationLink(1000, "Administration/Users", typeof(Administration.UserController), icon: "icon-people")] //[assembly: NavigationLink(1000, "Administration/Languages", typeof(Administration.LanguageController), icon: "icon-bubbles")] //[assembly: NavigationLink(1000, "Administration/Translations", typeof(Administration.TranslationController), icon: "icon-speech")] [assembly: NavigationMenu(1000, "Administration/Security", icon: "fa-shield")] [assembly: NavigationLink(1000, "Administration/Security/Exceptions Log", url: "~/errorlog.axd", permission: Enterprise.Administration.Keys.Security.Access, icon: "icon-ban", Target = "_blank")]
using Serenity.Navigation; using Administration = Enterprise.Administration.Pages; [assembly: NavigationMenu(1000, "Administration", icon: "fa-gear")] [assembly: NavigationLink(1000, "Administration/Roles", typeof(Administration.RoleController), icon: "icon-lock")] [assembly: NavigationLink(1000, "Administration/User Management", typeof(Administration.UserController), icon: "icon-people")] //[assembly: NavigationLink(1000, "Administration/Languages", typeof(Administration.LanguageController), icon: "icon-bubbles")] //[assembly: NavigationLink(1000, "Administration/Translations", typeof(Administration.TranslationController), icon: "icon-speech")] [assembly: NavigationMenu(1000, "Administration/Security", icon: "fa-shield")] [assembly: NavigationLink(1000, "Administration/Security/Exceptions Log", url: "~/errorlog.axd", permission: Enterprise.Administration.Keys.Security.Access, icon: "icon-ban", Target = "_blank")]
mit
C#
5d0ae85a61dc5d20117e77f24950ccc8ac079c0e
Update IComparisonOperators.cs
Flepper/flepper,Flepper/flepper
Flepper.QueryBuilder/Operators/Comparison/Interfaces/IComparisonOperators.cs
Flepper.QueryBuilder/Operators/Comparison/Interfaces/IComparisonOperators.cs
namespace Flepper.QueryBuilder { /// <summary> /// Comparison Operator Interface /// </summary> public interface IComparisonOperators : IQueryCommand { /// <summary> /// Equal Comparison Operator Contract /// </summary> /// <param name="value">Value used to compare</param> /// <returns></returns> IComparisonOperators EqualTo(object value); /// <summary> /// Greater Than Comparison Operator Contract /// </summary> /// <param name="value">Value used to compare</param> /// <returns></returns> IComparisonOperators GreaterThan(int value); /// <summary> /// Less Than Comparison Operator Contract /// </summary> /// <param name="value">Value used to compare</param> /// <returns></returns> IComparisonOperators LessThan(int value); /// <summary> /// Greater Than Or Equal Comparison Operator Contract /// </summary> /// <param name="value">Value used to compare</param> /// <returns></returns> IComparisonOperators GreaterThanOrEqualTo(int value); /// <summary> /// Less Than Or Equal Comparison Operator Contract /// </summary> /// <param name="value">Value used to compare</param> /// <returns></returns> IComparisonOperators LessThanOrEqualTo(int value); /// <summary> /// Not equal Comparison Operator Contract /// </summary> /// <param name="value">Value used to compare</param> /// <returns></returns> IComparisonOperators NotEqualTo(object value); } }
namespace Flepper.QueryBuilder { /// <summary> /// Comparison Operator Interface /// </summary> public interface IComparisonOperators : IQueryCommand { /// <summary> /// Equal Comparison Operator Contract /// </summary> /// <param name="value">Value</param> /// <returns></returns> IComparisonOperators EqualTo(object value); /// <summary> /// Greater Than Comparison Operator Contract /// </summary> /// <param name="value">Value</param> /// <returns></returns> IComparisonOperators GreaterThan(int value); /// <summary> /// Less Than Comparison Operator Contract /// </summary> /// <param name="value">Value</param> /// <returns></returns> IComparisonOperators LessThan(int value); /// <summary> /// Greater Than Or Equal Comparison Operator Contract /// </summary> /// <param name="value">Value</param> /// <returns></returns> IComparisonOperators GreaterThanOrEqualTo(int value); /// <summary> /// Less Than Or Equal Comparison Operator Contract /// </summary> /// <param name="value">Value</param> /// <returns></returns> IComparisonOperators LessThanOrEqualTo(int value); /// <summary> /// Not equal Comparison Operator Contract /// </summary> /// <param name="value">Value</param> /// <returns></returns> IComparisonOperators NotEqualTo(object value); } }
mit
C#
b196dd9e3d7a9afb3401530669bbc8681ad8c503
Fix horizontal scroll for Virtual list
Silphid/Silphid.Unity,Silphid/Silphid.Unity
Sources/Silphid.Showzup/Sources/Controls/ListLayouts/HorizontalListLayout.cs
Sources/Silphid.Showzup/Sources/Controls/ListLayouts/HorizontalListLayout.cs
using Silphid.Extensions; using UnityEngine; namespace Silphid.Showzup.ListLayouts { public class HorizontalListLayout : ListLayout { public float HorizontalSpacing; public float ItemWidth; protected float ItemOffsetX => ItemWidth + HorizontalSpacing; private Rect VisibleRect = new Rect(); public override Rect GetItemRect(int index, Vector2 viewportSize) => new Rect( FirstItemPosition + new Vector2(ItemOffsetX * index, 0), new Vector2(ItemWidth, viewportSize.y - (Padding.top + Padding.bottom))); public override Vector2 GetContainerSize(int count, Vector2 viewportSize) => new Vector2( Padding.left + ItemWidth * count + HorizontalSpacing * (count - 1).AtLeast(0) + Padding.right, viewportSize.y); public override IndexRange GetVisibleIndexRange(Rect visibleRect) { VisibleRect.Set(visibleRect.x*-1, visibleRect.y, visibleRect.width, visibleRect.height); return new IndexRange( ((VisibleRect.xMin - FirstItemPosition.x) / ItemOffsetX).FloorInt(), ((VisibleRect.xMax - FirstItemPosition.x) / ItemOffsetX).FloorInt() + 1); } } }
using Silphid.Extensions; using UnityEngine; namespace Silphid.Showzup.ListLayouts { public class HorizontalListLayout : ListLayout { public float HorizontalSpacing; public float ItemWidth; protected float ItemOffsetX => ItemWidth + HorizontalSpacing; public override Rect GetItemRect(int index, Vector2 viewportSize) => new Rect( FirstItemPosition + new Vector2(ItemOffsetX * index, 0), new Vector2(ItemWidth, viewportSize.y - (Padding.top + Padding.bottom))); public override Vector2 GetContainerSize(int count, Vector2 viewportSize) => new Vector2( Padding.left + ItemWidth * count + HorizontalSpacing * (count - 1).AtLeast(0) + Padding.right, viewportSize.y); public override IndexRange GetVisibleIndexRange(Rect rect) => new IndexRange( ((rect.xMin - FirstItemPosition.x) / ItemOffsetX).FloorInt(), ((rect.xMax - FirstItemPosition.x) / ItemOffsetX).FloorInt() + 1); } }
mit
C#
8d1b3e53e631512588b549fe0a0dbd86c2445564
Fix redundancy
PKI-InVivo/reactive-domain
src/ReactiveDomain.Foundation.Tests/Logging/with_message_logging_disabled.cs
src/ReactiveDomain.Foundation.Tests/Logging/with_message_logging_disabled.cs
using System; using System.Threading; using EventStore.ClientAPI; using ReactiveDomain.Foundation.EventStore; using ReactiveDomain.Messaging.Testing; namespace ReactiveDomain.Foundation.Tests.Logging { // ReSharper disable once InconsistentNaming public abstract class with_message_logging_disabled : CommandBusSpecification { private readonly IEventStoreConnection _connection; protected with_message_logging_disabled(IEventStoreConnection connection) { _connection = connection; } //protected member Logging class that inherits from QueuedSubscriber protected EventStoreMessageLogger Logging; protected string StreamName = $"LogTest-{Guid.NewGuid():N}"; protected EventStoreRepository Repo; protected IStreamNameBuilder StreamNameBuilder; protected EventStoreCatchupStreamSubscriber Subscriber; protected override void Given() { StreamNameBuilder = new PrefixedCamelCaseStreamNameBuilder("UnitTest"); Repo = new EventStoreRepository(StreamNameBuilder, _connection); // ctor defaults to disabled Logging = new EventStoreMessageLogger(Bus, _connection, StreamName); Subscriber = new EventStoreCatchupStreamSubscriber(_connection); Thread.Sleep(1000); } } }
using System; using System.Threading; using EventStore.ClientAPI; using ReactiveDomain.Foundation.EventStore; using ReactiveDomain.Messaging.Testing; namespace ReactiveDomain.Foundation.Tests.Logging { // ReSharper disable once InconsistentNaming public abstract class with_message_logging_disabled : CommandBusSpecification { private readonly IEventStoreConnection _connection; protected with_message_logging_disabled(IEventStoreConnection connection) { _connection = connection; } //protected member Logging class that inherits from QueuedSubscriber protected EventStoreMessageLogger Logging; protected string StreamName = $"LogTest-{Guid.NewGuid():N}"; protected EventStoreRepository Repo; protected IStreamNameBuilder StreamNameBuilder; protected EventStoreCatchupStreamSubscriber Subscriber; protected override void Given() { StreamNameBuilder = new PrefixedCamelCaseStreamNameBuilder("UnitTest"); Repo = new EventStoreRepository(new PrefixedCamelCaseStreamNameBuilder("UnitTest"),_connection); // ctor defaults to disabled Logging = new EventStoreMessageLogger(Bus, _connection, StreamName); Subscriber = new EventStoreCatchupStreamSubscriber(_connection); Thread.Sleep(1000); } } }
mit
C#
24d9cdad023c8f2c07161d605f545d43202e5208
Fix bug with test cases not working with different timezone
stranne/Vasttrafik.NET,stranne/Vasttrafik.NET
src/Stranne.VasttrafikNET.Tests/JsonParsing/HistoricalAvailabilityJsonTest.cs
src/Stranne.VasttrafikNET.Tests/JsonParsing/HistoricalAvailabilityJsonTest.cs
using System; using System.Collections.Generic; using Stranne.VasttrafikNET.ApiModels.CommuterParking; using Stranne.VasttrafikNET.Tests.Json; using Xunit; namespace Stranne.VasttrafikNET.Tests.JsonParsing { public class HistoricalAvailabilityJsonTest : BaseJsonTest { protected override string Json => HistoricalAvailabilityJson.Json; public static TheoryData TestParameters => new TheoryData<string, object> { { "", 5 }, { "[0].DateTime", TimeZoneInfo.ConvertTime(new DateTime(2016, 8, 1, 8, 0, 0), TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time")) }, { "[0].FreeSpaces",79 }, { "[1].DateTime", TimeZoneInfo.ConvertTime(new DateTime(2016, 8, 1, 8, 15, 0), TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time")) }, { "[1].FreeSpaces", 78 }, { "[2].DateTime", TimeZoneInfo.ConvertTime(new DateTime(2016, 8, 1, 8, 30, 0), TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time")) }, { "[2].FreeSpaces", 71 }, { "[3].DateTime", TimeZoneInfo.ConvertTime(new DateTime(2016, 8, 1, 8, 45, 0), TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time")) }, { "[3].FreeSpaces", 70 }, { "[4].DateTime", TimeZoneInfo.ConvertTime(new DateTime(2016, 8, 1, 9, 0, 0), TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time")) }, { "[4].FreeSpaces", 67 } }; [Theory, MemberData(nameof(TestParameters))] public void HistoricalAvailabilityJsonParsing(string property, object expected) { TestValue<IEnumerable<HistoricalAvailability>>(property, expected); } } }
using System; using System.Collections.Generic; using Stranne.VasttrafikNET.ApiModels.CommuterParking; using Stranne.VasttrafikNET.Tests.Json; using Xunit; namespace Stranne.VasttrafikNET.Tests.JsonParsing { public class HistoricalAvailabilityJsonTest : BaseJsonTest { protected override string Json => HistoricalAvailabilityJson.Json; public static TheoryData TestParameters => new TheoryData<string, object> { { "", 5 }, { "[0].DateTime", new DateTime(2016, 8, 1, 8, 0, 0) }, { "[0].FreeSpaces",79 }, { "[1].DateTime", new DateTime(2016, 8, 1, 8, 15, 0) }, { "[1].FreeSpaces", 78 }, { "[2].DateTime", new DateTime(2016, 8, 1, 8, 30, 0) }, { "[2].FreeSpaces", 71 }, { "[3].DateTime", new DateTime(2016, 8, 1, 8, 45, 0) }, { "[3].FreeSpaces", 70 }, { "[4].DateTime", new DateTime(2016, 8, 1, 9, 0, 0) }, { "[4].FreeSpaces", 67 } }; [Theory, MemberData(nameof(TestParameters))] public void HistoricalAvailabilityJsonParsing(string property, object expected) { TestValue<IEnumerable<HistoricalAvailability>>(property, expected); } } }
mit
C#
f3e62680640e9aa130cc3ebe7db8073ce43ffca9
Make polymorphic schema generation opt-in
domaindrivendev/Ahoy,domaindrivendev/Ahoy,domaindrivendev/Ahoy,domaindrivendev/Swashbuckle.AspNetCore,domaindrivendev/Swashbuckle.AspNetCore,domaindrivendev/Swashbuckle.AspNetCore
src/Swashbuckle.AspNetCore.SwaggerGen/SchemaGen/PolymorphicSchemaGenerator.cs
src/Swashbuckle.AspNetCore.SwaggerGen/SchemaGen/PolymorphicSchemaGenerator.cs
using System; using System.Linq; using Microsoft.OpenApi.Models; using Newtonsoft.Json.Serialization; namespace Swashbuckle.AspNetCore.SwaggerGen { public class PolymorphicSchemaGenerator : ChainableSchemaGenerator { public PolymorphicSchemaGenerator( SchemaGeneratorOptions options, ISchemaGenerator rootGenerator, IContractResolver contractResolver) : base(options, rootGenerator, contractResolver) { } protected override bool CanGenerateSchemaFor(Type type) { return (Options.GeneratePolymorphicSchemas && Options.SubTypesResolver(type).Any()); } protected override OpenApiSchema GenerateSchemaFor(Type type, SchemaRepository schemaRepository) { var subTypes = Options.SubTypesResolver(type); return new OpenApiSchema { OneOf = subTypes .Select(subType => RootGenerator.GenerateSchema(subType, schemaRepository)) .ToList() }; } } }
using System; using System.Linq; using Microsoft.OpenApi.Models; using Newtonsoft.Json.Serialization; namespace Swashbuckle.AspNetCore.SwaggerGen { public class PolymorphicSchemaGenerator : ChainableSchemaGenerator { public PolymorphicSchemaGenerator( SchemaGeneratorOptions options, ISchemaGenerator rootGenerator, IContractResolver contractResolver) : base(options, rootGenerator, contractResolver) { } protected override bool CanGenerateSchemaFor(Type type) { var subTypes = Options.SubTypesResolver(type); return subTypes.Any(); } protected override OpenApiSchema GenerateSchemaFor(Type type, SchemaRepository schemaRepository) { var subTypes = Options.SubTypesResolver(type); return new OpenApiSchema { OneOf = subTypes .Select(subType => RootGenerator.GenerateSchema(subType, schemaRepository)) .ToList() }; } } }
mit
C#
cf53811cc70a3adf00b4456770be715ef82acaa0
update to unity web request
iBicha/ChromeAppBuilder,iBicha/ChromeAppBuilder,iBicha/ChromeAppBuilder
Assets/ChromeAppBuilder/Scripts/WebRequest.cs
Assets/ChromeAppBuilder/Scripts/WebRequest.cs
/*This is a helper class to wrap around the WWW class and the coroutine system * so it can be called without a MonoBehaviour or a game object * basically we will create one, and destroy it when we're done. * Of course other solutions exists, but this is a way to use unity's stock option. * Note that this can be replaced with the newer UnityWebRequest * https://docs.unity3d.com/Manual/UnityWebRequest.html */ using UnityEngine; using System.Collections; using System; using System.Collections.Generic; using UnityEngine.Networking; public class WebRequest : MonoBehaviour { public static void Get(string url, Action<DownloadHandler> callback, Dictionary<string, string> headers = null) { GameObject go = new GameObject("{WebRequest}"); WebRequest req = go.AddComponent<WebRequest>(); req.OnResponse = callback; req.uRequest = UnityWebRequest.Get(url); if (headers != null) { foreach (string header in headers.Keys) { req.uRequest.SetRequestHeader(header, headers[header]); } } req.Send(); } public static void GetTexture(string url, Action<DownloadHandler> callback, Dictionary<string, string> headers = null) { GameObject go = new GameObject("{WebRequest}"); WebRequest req = go.AddComponent<WebRequest>(); req.OnResponse = callback; req.uRequest = new UnityWebRequest(url, UnityWebRequest.kHttpVerbGET, new DownloadHandlerTexture(), null); if (headers != null) { foreach (string header in headers.Keys) { req.uRequest.SetRequestHeader(header, headers[header]); } } req.Send(); } public static void Post(string url, Dictionary<string, string> formFields, Action<DownloadHandler> callback, Dictionary<string, string> headers = null) { GameObject go = new GameObject("{WebRequest}"); WebRequest req = go.AddComponent<WebRequest>(); req.OnResponse = callback; req.uRequest = UnityWebRequest.Post(url, formFields); if (headers != null) { foreach (string header in headers.Keys) { req.uRequest.SetRequestHeader(header, headers[header]); } } req.Send(); } private UnityWebRequest uRequest; private Action<DownloadHandler> OnResponse; private void Send() { Destroy(gameObject, 30); //30 seconds timeout StartCoroutine(GetResponse()); } private IEnumerator GetResponse() { yield return uRequest.Send(); Action<DownloadHandler> handler = OnResponse; if (handler != null) { handler(uRequest.downloadHandler); } Destroy(gameObject); } }
/*This is a helper class to wrap around the WWW class and the coroutine system * so it can be called without a MonoBehaviour or a game object * basically we will create one, and destroy it when we're done. * Of course other solutions exists, but this is a way to use unity's stock option. * Note that this can be replaced with the newer UnityWebRequest * https://docs.unity3d.com/Manual/UnityWebRequest.html */ using UnityEngine; using System.Collections; using System; using System.Collections.Generic; using UnityEngine.Networking; public class WebRequest : MonoBehaviour { public static void Get(string url, Action<DownloadHandler> callback, Dictionary<string, string> headers=null){ GameObject go = new GameObject ("{WebRequest}"); WebRequest req = go.AddComponent<WebRequest> (); req.OnResponse = callback; req.uRequest = UnityWebRequest.Get (url); if(headers != null) { foreach (string header in headers.Keys) { req.uRequest.SetRequestHeader (header, headers [header]); } } req.Send(); } UnityWebRequest uRequest; private Action<DownloadHandler> OnResponse; private void Send () { Destroy (gameObject, 30); //30 seconds timeout StartCoroutine (GetResponse()); } private IEnumerator GetResponse(){ yield return uRequest.Send(); Action<DownloadHandler> handler = OnResponse; if (handler != null) { handler (uRequest.downloadHandler); } Destroy (gameObject); } }
mit
C#
632a751458abb2e0e8f193d5faf881e7d068d85f
Allow AvroExtractor to handle empty files
Azure/usql
Examples/DataFormats/Microsoft.Analytics.Samples.Formats/Avro/AvroExtractor.cs
Examples/DataFormats/Microsoft.Analytics.Samples.Formats/Avro/AvroExtractor.cs
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // using System.Collections.Generic; using Microsoft.Analytics.Interfaces; using Microsoft.Hadoop.Avro; using Microsoft.Hadoop.Avro.Container; namespace Microsoft.Analytics.Samples.Formats.Avro { [SqlUserDefinedExtractor(AtomicFileProcessing = true)] public class AvroExtractor : IExtractor { private string avroSchema; public AvroExtractor(string avroSchema) { this.avroSchema = avroSchema; } public override IEnumerable<IRow> Extract(IUnstructuredReader input, IUpdatableRow output) { if (input.Length == 0) { yield break; } var serializer = AvroSerializer.CreateGeneric(avroSchema); using (var genericReader = AvroContainer.CreateGenericReader(input.BaseStream)) { using (var reader = new SequentialReader<dynamic>(genericReader)) { foreach (var obj in reader.Objects) { foreach (var column in output.Schema) { output.Set(column.Name, obj[column.Name]); } yield return output.AsReadOnly(); } } } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // using System.Collections.Generic; using Microsoft.Analytics.Interfaces; using Microsoft.Hadoop.Avro; using Microsoft.Hadoop.Avro.Container; namespace Microsoft.Analytics.Samples.Formats.Avro { [SqlUserDefinedExtractor(AtomicFileProcessing = true)] public class AvroExtractor : IExtractor { private string avroSchema; public AvroExtractor(string avroSchema) { this.avroSchema = avroSchema; } public override IEnumerable<IRow> Extract(IUnstructuredReader input, IUpdatableRow output) { var serializer = AvroSerializer.CreateGeneric(avroSchema); using (var genericReader = AvroContainer.CreateGenericReader(input.BaseStream)) { using (var reader = new SequentialReader<dynamic>(genericReader)) { foreach (var obj in reader.Objects) { foreach (var column in output.Schema) { output.Set(column.Name, obj[column.Name]); } yield return output.AsReadOnly(); } } } } } }
mit
C#
767ef576718da58c8a888e2c28edea4d4ac9b061
Use the new form of the binding function in the bytecode solver
Logicalshift/Reason
LogicalShift.Reason/Solvers/ClauseCompiler.cs
LogicalShift.Reason/Solvers/ClauseCompiler.cs
using LogicalShift.Reason.Api; using System; using System.Collections.Generic; using System.Linq; namespace LogicalShift.Reason.Solvers { /// <summary> /// Methods for compiling clauses to a bytecode program /// </summary> public static class ClauseCompiler { /// <summary> /// Compiles a clause to a bytecode program /// </summary> public static void Compile(this IClause clause, ByteCodeProgram program) { var unifier = new ByteCodeUnifier(program); // Get the assignments for this clause var allPredicates = new[] { clause.Implies }.Concat(clause.If).ToArray(); var assignmentList = allPredicates .Select(predicate => new { Assignments = PredicateAssignmentList.FromPredicate(predicate), UnificationKey = predicate.UnificationKey }) .ToArray(); // Allocate space for the arguments and any permanent variables var permanentVariables = PermanentVariableAssignments.PermanentVariables(assignmentList.Select(assign => assign.Assignments)); if (permanentVariables.Count > 0) { program.Write(Operation.Allocate, permanentVariables.Count); } // Unify with the predicate first unifier.ProgramUnifier.Bind(assignmentList[0].Assignments.Assignments, permanentVariables); unifier.ProgramUnifier.Compile(assignmentList[0].Assignments.Assignments); // Call the clauses foreach (var assignment in assignmentList.Skip(1)) { unifier.QueryUnifier.Bind(assignment.Assignments.Assignments, permanentVariables); unifier.QueryUnifier.Compile(assignment.Assignments.Assignments); program.Write(Operation.Call, assignment.UnificationKey); } // Deallocate any permanent variables that we might have found if (permanentVariables.Count > 0) { program.Write(Operation.Deallocate); } } } }
using LogicalShift.Reason.Api; using System; using System.Collections.Generic; using System.Linq; namespace LogicalShift.Reason.Solvers { /// <summary> /// Methods for compiling clauses to a bytecode program /// </summary> public static class ClauseCompiler { /// <summary> /// Compiles a clause to a bytecode program /// </summary> public static void Compile(this IClause clause, ByteCodeProgram program) { var unifier = new ByteCodeUnifier(program); // Get the assignments for this clause var allPredicates = new[] { clause.Implies }.Concat(clause.If).ToArray(); var assignmentList = allPredicates .Select(predicate => new { Assignments = PredicateAssignmentList.FromPredicate(predicate), UnificationKey = predicate.UnificationKey }) .ToArray(); // Allocate space for the arguments and any permanent variables var permanentVariables = PermanentVariableAssignments.PermanentVariables(assignmentList.Select(assign => assign.Assignments)); if (permanentVariables.Count > 0) { program.Write(Operation.Allocate, permanentVariables.Count); } // Unify with the predicate first unifier.ProgramUnifier.Bind(assignmentList[0].Assignments.Assignments); unifier.ProgramUnifier.Compile(assignmentList[0].Assignments.Assignments); // Call the clauses foreach (var assignment in assignmentList.Skip(1)) { unifier.QueryUnifier.Bind(assignment.Assignments.Assignments); unifier.QueryUnifier.Compile(assignment.Assignments.Assignments); program.Write(Operation.Call, assignment.UnificationKey); } // Deallocate any permanent variables that we might have found if (permanentVariables.Count > 0) { program.Write(Operation.Deallocate); } } } }
apache-2.0
C#
76dad08d8831564be883adda2498e014b9494c31
Update server.cs
ahmedkhaled4d/Dot-NET-Projects,ahmedkhaled4d/C-Projects,ahmedkhaled4d/Dot-NET-Projects
client-server/server.cs
client-server/server.cs
using System; using System.Threading; using System.Net; using System.Net.Sockets; using System.Text; namespace server { public class server { ManualResetEvent tcpClientConnected = new ManualResetEvent(false); void ProcessIncomingData(object obj) { TcpClient client = (TcpClient)obj; StringBuilder sb = new StringBuilder(); // comment streaming here using (NetworkStream stream = client.GetStream()) { int i; while ((i = stream.ReadByte()) != 0) { sb.Append((char)i); } string reply = "ack: " + sb.ToString() + '\0'; stream.Write(Encoding.ASCII.GetBytes(reply), 0, reply.Length); } Console.WriteLine(sb.ToString()); } void ProcessIncomingConnection(IAsyncResult ar) { TcpListener listener = (TcpListener)ar.AsyncState; TcpClient client = listener.EndAcceptTcpClient(ar); ThreadPool.QueueUserWorkItem(ProcessIncomingData, client); tcpClientConnected.Set(); } public void start() { IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5000); TcpListener listener = new TcpListener(endpoint); listener.Start(); while (true) { tcpClientConnected.Reset(); listener.BeginAcceptTcpClient(new AsyncCallback(ProcessIncomingConnection), listener); tcpClientConnected.WaitOne(); } } } class Program { static void Main(string[] args) { server s = new server(); s.start(); } } }
using System; using System.Threading; using System.Net; using System.Net.Sockets; using System.Text; namespace server { public class server { ManualResetEvent tcpClientConnected = new ManualResetEvent(false); void ProcessIncomingData(object obj) { TcpClient client = (TcpClient)obj; StringBuilder sb = new StringBuilder(); using (NetworkStream stream = client.GetStream()) { int i; while ((i = stream.ReadByte()) != 0) { sb.Append((char)i); } string reply = "ack: " + sb.ToString() + '\0'; stream.Write(Encoding.ASCII.GetBytes(reply), 0, reply.Length); } Console.WriteLine(sb.ToString()); } void ProcessIncomingConnection(IAsyncResult ar) { TcpListener listener = (TcpListener)ar.AsyncState; TcpClient client = listener.EndAcceptTcpClient(ar); ThreadPool.QueueUserWorkItem(ProcessIncomingData, client); tcpClientConnected.Set(); } public void start() { IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5000); TcpListener listener = new TcpListener(endpoint); listener.Start(); while (true) { tcpClientConnected.Reset(); listener.BeginAcceptTcpClient(new AsyncCallback(ProcessIncomingConnection), listener); tcpClientConnected.WaitOne(); } } } class Program { static void Main(string[] args) { server s = new server(); s.start(); } } }
mit
C#
a09b5b37b13c5f6e750e1b5dc8894b65a93c79ac
bump version
alecgorge/adzerk-dot-net
Adzerk.Api/Properties/AssemblyInfo.cs
Adzerk.Api/Properties/AssemblyInfo.cs
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("Adzerk.Api")] [assembly: AssemblyDescription("Unofficial Adzerk API client.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Stack Exchange")] [assembly: AssemblyProduct("Adzerk.Api")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("d05e1e25-d95d-43d6-a74b-3cb38492fa7e")] // 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("0.0.0.20")] [assembly: AssemblyFileVersion("0.0.0.20")]
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("Adzerk.Api")] [assembly: AssemblyDescription("Unofficial Adzerk API client.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Stack Exchange")] [assembly: AssemblyProduct("Adzerk.Api")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("d05e1e25-d95d-43d6-a74b-3cb38492fa7e")] // 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("0.0.0.18")] [assembly: AssemblyFileVersion("0.0.0.18")]
mit
C#
7885ac02e00a50f7b4fd1c1c4190c7ce7404d2e4
Fix voice delay double serialization
Barleytree/NitoriWare,NitorInc/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare
Assets/Scripts/Microgame/Microgame.cs
Assets/Scripts/Microgame/Microgame.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; using UnityEngine.Events; using System.Linq; #if UNITY_EDITOR using UnityEditor; #endif [CreateAssetMenu(menuName = "Microgame/Normal")] public class Microgame : ScriptableObject { public string microgameId => name; [SerializeField] private ControlScheme _controlScheme; public ControlScheme controlScheme => _controlScheme; public enum ControlScheme { Key, Mouse } [SerializeField] private bool _hideCursor; public bool hideCursorDefault => _hideCursor; [SerializeField] private CursorLockMode _cursorLockState = CursorLockMode.None; public CursorLockMode cursorLockStateDefault => _cursorLockState; [SerializeField] private Duration _duration; public Duration duration => _duration; public enum Duration { Short8Beats, Long16Beats } public bool canEndEarly => _duration == Duration.Long16Beats; [SerializeField] private string _command; public string commandDefault => _command; [SerializeField] private AnimatorOverrideController _commandAnimatorOveride; public AnimatorOverrideController CommandAnimatorOverrideDefault => _commandAnimatorOveride; [SerializeField] private bool _defaultVictory; public bool defaultVictory => _defaultVictory; [SerializeField] private float _victoryVoiceDelay; public float VictoryVoiceDelayDefault => VictoryVoiceDelayDefault; [SerializeField] private float _failureVoiceDelay; public float FailureVoiceDelayDefault => FailureVoiceDelayDefault; [SerializeField] private AudioClip _musicClip; public AudioClip MusicClipDefault => _musicClip; public virtual AudioClip[] GetAllPossibleMusicClips() => new AudioClip[] { _musicClip }; [SerializeField] private Milestone _milestone = Milestone.Unfinished; public Milestone milestone => _milestone; public enum Milestone { Unfinished, StageReady, Finished } [Header("Credits order is Art, Code, Music:")] [SerializeField] private string[] _credits = { "", "", "" }; public string[] credits => _credits; public virtual float getDurationInBeats() => (duration == Duration.Long16Beats) ? 16f : 8f; public bool isBossMicrogame() => GetType() == typeof(MicrogameBoss) || GetType().IsSubclassOf(typeof(MicrogameBoss)); public virtual MicrogameSession CreateSession(StageController player, int difficulty, bool debugMode = false) => new MicrogameSession(this, player, difficulty, debugMode); public MicrogameSession CreateDebugSession(int difficulty) => CreateSession(null, difficulty, true); // For debug mode purposes public virtual bool SceneDeterminesDifficulty => true; public virtual int GetDifficultyFromScene(string sceneName) => int.Parse(sceneName.Last().ToString()); }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; using UnityEngine.Events; using System.Linq; #if UNITY_EDITOR using UnityEditor; #endif [CreateAssetMenu(menuName = "Microgame/Normal")] public class Microgame : ScriptableObject { public string microgameId => name; [SerializeField] private ControlScheme _controlScheme; public ControlScheme controlScheme => _controlScheme; public enum ControlScheme { Key, Mouse } [SerializeField] private bool _hideCursor; public bool hideCursorDefault => _hideCursor; [SerializeField] private CursorLockMode _cursorLockState = CursorLockMode.None; public CursorLockMode cursorLockStateDefault => _cursorLockState; [SerializeField] private Duration _duration; public Duration duration => _duration; public enum Duration { Short8Beats, Long16Beats } public bool canEndEarly => _duration == Duration.Long16Beats; [SerializeField] private string _command; public string commandDefault => _command; [SerializeField] private AnimatorOverrideController _commandAnimatorOveride; public AnimatorOverrideController CommandAnimatorOverrideDefault => _commandAnimatorOveride; [SerializeField] private bool _defaultVictory; public bool defaultVictory => _defaultVictory; [SerializeField] private float _victoryVoiceDelay; public float VictoryVoiceDelayDefault; [SerializeField] private float _failureVoiceDelay; public float FailureVoiceDelayDefault; [SerializeField] private AudioClip _musicClip; public AudioClip MusicClipDefault => _musicClip; public virtual AudioClip[] GetAllPossibleMusicClips() => new AudioClip[] { _musicClip }; [SerializeField] private Milestone _milestone = Milestone.Unfinished; public Milestone milestone => _milestone; public enum Milestone { Unfinished, StageReady, Finished } [Header("Credits order is Art, Code, Music:")] [SerializeField] private string[] _credits = { "", "", "" }; public string[] credits => _credits; public virtual float getDurationInBeats() => (duration == Duration.Long16Beats) ? 16f : 8f; public bool isBossMicrogame() => GetType() == typeof(MicrogameBoss) || GetType().IsSubclassOf(typeof(MicrogameBoss)); public virtual MicrogameSession CreateSession(StageController player, int difficulty, bool debugMode = false) => new MicrogameSession(this, player, difficulty, debugMode); public MicrogameSession CreateDebugSession(int difficulty) => CreateSession(null, difficulty, true); // For debug mode purposes public virtual bool SceneDeterminesDifficulty => true; public virtual int GetDifficultyFromScene(string sceneName) => int.Parse(sceneName.Last().ToString()); }
mit
C#
55998f25b99f37b569024df119e52350a5244f8d
Fix LinkedIn claims, add linkedIn locality claim support
brockallen/BrockAllen.OAuth2,hattonpoint/BrockAllen.OAuth2
BrockAllen.OAuth2/LinkedInProvider.cs
BrockAllen.OAuth2/LinkedInProvider.cs
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; namespace BrockAllen.OAuth2 { class LinkedInProvider : Provider { public LinkedInProvider(string clientID, string clientSecret, string scope) : base(ProviderType.LinkedIn, "https://www.linkedin.com/uas/oauth2/authorization", "https://www.linkedin.com/uas/oauth2/accessToken", "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address,picture-url,formatted-name,location:(country:(code)),public-profile-url)", clientID, clientSecret, "oauth2_access_token", new NameValueCollection(){ { "format", "json" } }) { if (scope == null) { Scope = "r_fullprofile r_emailaddress"; } else { Scope = scope; } } protected override IEnumerable<Claim> GetClaimsFromProfile(Dictionary<string, object> profile) { var claims = base.GetClaimsFromProfile(profile).ToList(); var localityClaim = claims.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Locality)); var location = Newtonsoft.Json.JsonConvert.DeserializeObject<LinkedInLocation>(localityClaim.Value); claims.Remove(localityClaim); localityClaim = new Claim(localityClaim.Type, location.Country.Code); claims.Add(localityClaim); return claims; } static Dictionary<string, string> supportedClaimTypes = new Dictionary<string, string>(); static LinkedInProvider() { supportedClaimTypes.Add("id", ClaimTypes.NameIdentifier); supportedClaimTypes.Add("formattedName", ClaimTypes.Name); supportedClaimTypes.Add("emailAddress", ClaimTypes.Email); supportedClaimTypes.Add("firstName", ClaimTypes.GivenName); supportedClaimTypes.Add("lastName", ClaimTypes.Surname); supportedClaimTypes.Add("publicProfileUrl", ClaimTypes.Webpage); supportedClaimTypes.Add("location", ClaimTypes.Locality); supportedClaimTypes.Add("pictureUrl", ClaimTypes.UserData); } internal override Dictionary<string, string> SupportedClaimTypes { get { return supportedClaimTypes; } } private class LinkedInLocation { [JsonProperty("country")] public LinkedInCountry Country { get; set; } } private class LinkedInCountry { [JsonProperty("code")] public string Code { get; set; } } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; namespace BrockAllen.OAuth2 { class LinkedInProvider : Provider { public LinkedInProvider(string clientID, string clientSecret, string scope) : base(ProviderType.LinkedIn, "https://www.linkedin.com/uas/oauth2/authorization", "https://www.linkedin.com/uas/oauth2/accessToken", "https://api.linkedin.com/v1/people/~", clientID, clientSecret, "oauth2_access_token", new NameValueCollection(){ { "format", "json" } }) { if (scope == null) { Scope = "r_basicprofile r_emailaddress"; } else { Scope = scope; } } static Dictionary<string, string> supportedClaimTypes = new Dictionary<string, string>(); static LinkedInProvider() { supportedClaimTypes.Add("id", ClaimTypes.NameIdentifier); supportedClaimTypes.Add("formatted-name", ClaimTypes.Name); supportedClaimTypes.Add("email", ClaimTypes.Email); supportedClaimTypes.Add("first-name", ClaimTypes.GivenName); supportedClaimTypes.Add("last-name", ClaimTypes.Surname); supportedClaimTypes.Add("public-profile-url", ClaimTypes.Webpage); supportedClaimTypes.Add("location:(country:(code))", ClaimTypes.Locality); supportedClaimTypes.Add("picture-url", ClaimTypes.UserData); } internal override Dictionary<string, string> SupportedClaimTypes { get { return supportedClaimTypes; } } } }
bsd-3-clause
C#
cad97086ab05ee357a7f9f58727cb1281f654718
Add HttpClient to GetToolConsumerProfileAsync convenience method to make it easier to call from an integration test.
andyfmiller/LtiLibrary
LtiLibrary.NetCore/Profiles/ToolConsumerProfileClient.cs
LtiLibrary.NetCore/Profiles/ToolConsumerProfileClient.cs
using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using LtiLibrary.NetCore.Common; using LtiLibrary.NetCore.Extensions; namespace LtiLibrary.NetCore.Profiles { public static class ToolConsumerProfileClient { /// <summary> /// Get a ToolConsumerProfile from the service endpoint. /// </summary> /// <param name="client">The HttpClient to use for the request.</param> /// <param name="serviceUrl">The full URL of the ToolConsumerProfile service.</param> /// <returns>A <see cref="ToolConsumerProfileResponse"/> which includes both the HTTP status code /// and the <see cref="ToolConsumerProfile"/> if the HTTP status is a success code.</returns> public static async Task<ToolConsumerProfileResponse> GetToolConsumerProfileAsync(HttpClient client, string serviceUrl) { var profileResponse = new ToolConsumerProfileResponse(); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(LtiConstants.ToolConsumerProfileMediaType)); using (var response = await client.GetAsync(serviceUrl)) { profileResponse.StatusCode = response.StatusCode; if (response.IsSuccessStatusCode) { profileResponse.ToolConsumerProfile = await response.Content.ReadJsonAsObjectAsync<ToolConsumerProfile>(); profileResponse.ContentType = response.Content.Headers.ContentType.MediaType; } return profileResponse; } } } }
using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using LtiLibrary.NetCore.Common; using LtiLibrary.NetCore.Extensions; namespace LtiLibrary.NetCore.Profiles { public static class ToolConsumerProfileClient { /// <summary> /// Get a ToolConsumerProfile from the service endpoint. /// </summary> /// <param name="serviceUrl">The full URL of the ToolConsumerProfile service.</param> /// <returns>A <see cref="ToolConsumerProfileResponse"/> which includes both the HTTP status code /// and the <see cref="ToolConsumerProfile"/> if the HTTP status is a success code.</returns> public static async Task<ToolConsumerProfileResponse> GetToolConsumerProfileAsync(string serviceUrl) { var profileResponse = new ToolConsumerProfileResponse(); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(LtiConstants.ToolConsumerProfileMediaType)); var response = await client.GetAsync(serviceUrl); profileResponse.StatusCode = response.StatusCode; if (response.IsSuccessStatusCode) { profileResponse.ToolConsumerProfile = await response.Content.ReadJsonAsObjectAsync<ToolConsumerProfile>(); } } return profileResponse; } } }
apache-2.0
C#
82b999307bd1b516056ed43be1c6bed7388999af
Update version to 1.3
CryptonZylog/carbonator,lhoworko/carbonator
Carbonator/Properties/AssemblyInfo.cs
Carbonator/Properties/AssemblyInfo.cs
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("Carbonator")] [assembly: AssemblyDescription("Collects performance counter metrics and reports them to Graphite/Carbon server")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Carbonator")] [assembly: AssemblyCopyright("Copyright © Crypton Technologies 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("a92aff8a-bbd6-4d7d-8ba2-4d4b1c7c2f33")] // 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.3.*")] [assembly: AssemblyFileVersion("1.3.0.0")]
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("Carbonator")] [assembly: AssemblyDescription("Collects performance counter metrics and reports them to Graphite/Carbon server")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Carbonator")] [assembly: AssemblyCopyright("Copyright © Crypton Technologies 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("a92aff8a-bbd6-4d7d-8ba2-4d4b1c7c2f33")] // 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.2.0.0")] [assembly: AssemblyFileVersion("1.2.0.0")]
mit
C#
68126fda3f6f28e7de91d884e55a3ddd64ebf35c
Add asteroid to store
gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer
Client/Systems/Asteroid/AsteroidEvents.cs
Client/Systems/Asteroid/AsteroidEvents.cs
using LunaClient.Base; using LunaClient.Systems.Lock; using LunaClient.Systems.SettingsSys; using LunaClient.Systems.VesselProtoSys; using LunaClient.VesselStore; using System; namespace LunaClient.Systems.Asteroid { public class AsteroidEventHandler : SubSystem<AsteroidSystem> { public void OnAsteroidSpawned(Vessel asteroid) { if (LockSystem.LockQuery.AsteroidLockBelongsToPlayer(SettingsSystem.CurrentSettings.PlayerName)) { if (System.GetAsteroidCount() <= SettingsSystem.ServerSettings.MaxNumberOfAsteroids) { System.ServerAsteroids.Add(asteroid.id.ToString()); SystemsContainer.Get<VesselProtoSystem>().MessageSender.SendVesselMessage(asteroid, true); VesselsProtoStore.AddVesselToDictionary(asteroid); } else { LunaLog.Log($"[LMP]: Killing non-server asteroid {asteroid.id}"); TryKillAsteroid(asteroid); } } else { LunaLog.Log($"[LMP]: Killing non-server asteroid {asteroid.id}, we don't own the asteroid lock"); TryKillAsteroid(asteroid); } } private static void TryKillAsteroid(Vessel asteroid) { try { asteroid.Die(); } catch (Exception) { // ignored } } } }
using LunaClient.Base; using LunaClient.Systems.Lock; using LunaClient.Systems.SettingsSys; using LunaClient.Systems.VesselProtoSys; using System; namespace LunaClient.Systems.Asteroid { public class AsteroidEventHandler : SubSystem<AsteroidSystem> { public void OnAsteroidSpawned(Vessel asteroid) { if (LockSystem.LockQuery.AsteroidLockBelongsToPlayer(SettingsSystem.CurrentSettings.PlayerName)) { if (System.GetAsteroidCount() <= SettingsSystem.ServerSettings.MaxNumberOfAsteroids) { System.ServerAsteroids.Add(asteroid.id.ToString()); SystemsContainer.Get<VesselProtoSystem>().MessageSender.SendVesselMessage(asteroid, true); } else { LunaLog.Log($"[LMP]: Killing non-server asteroid {asteroid.id}"); TryKillAsteroid(asteroid); } } else { LunaLog.Log($"[LMP]: Killing non-server asteroid {asteroid.id}, we don't own the asteroid lock"); TryKillAsteroid(asteroid); } } private static void TryKillAsteroid(Vessel asteroid) { try { asteroid.Die(); } catch (Exception) { // ignored } } } }
mit
C#
f31a405c5e9cfc0e1e4afda854d8749872c7bbef
update test env
qiniu/csharp-sdk
src/QiniuTests/TestEnv.cs
src/QiniuTests/TestEnv.cs
namespace Qiniu.Tests { public class TestEnv { public string AccessKey; public string SecretKey; public string Bucket; public string Domain; public string LocalFile; public TestEnv() { string isTravisTest = System.Environment.GetEnvironmentVariable("isTravisTest"); if (!string.IsNullOrEmpty(isTravisTest) && isTravisTest.Equals("true")) { this.AccessKey = System.Environment.GetEnvironmentVariable("QINIU_ACCESS_KEY"); this.SecretKey = System.Environment.GetEnvironmentVariable("QINIU_SECRET_KEY"); this.Bucket = System.Environment.GetEnvironmentVariable("QINIU_TEST_BUCKET"); this.Domain = System.Environment.GetEnvironmentVariable("QINIU_TEST_DOMAIN"); this.LocalFile = System.Environment.GetEnvironmentVariable("QINIU_LOCAL_FILE"); } else { this.AccessKey = ""; this.SecretKey = ""; this.Bucket = "csharpsdk"; this.Domain = "csharpsdk.qiniudn.com"; this.LocalFile = "E:\\VSProjects\\csharp-sdk\\tools\\files\\test.jpg"; } } } }
namespace Qiniu.Tests { public class TestEnv { public string AccessKey; public string SecretKey; public string Bucket; public string Domain; public string LocalFile; public TestEnv() { string isTravisTest = System.Environment.GetEnvironmentVariable("isTravisTest"); if (!string.IsNullOrEmpty(isTravisTest) && isTravisTest.Equals("true")) { this.AccessKey = System.Environment.GetEnvironmentVariable("QINIU_ACCESS_KEY"); this.SecretKey = System.Environment.GetEnvironmentVariable("QINIU_SECRET_KEY"); this.Bucket = System.Environment.GetEnvironmentVariable("QINIU_TEST_BUCKET"); this.Domain = System.Environment.GetEnvironmentVariable("QINIU_TEST_DOMAIN"); this.LocalFile = System.Environment.GetEnvironmentVariable("QINIU_LOCAL_FILE"); } else { this.AccessKey = "QWYn5TFQsLLU1pL5MFEmX3s5DmHdUThav9WyOWOm"; this.SecretKey = "Bxckh6FA-Fbs9Yt3i3cbKVK22UPBmAOHJcL95pGz"; this.Bucket = "csharpsdk"; this.Domain = "csharpsdk.qiniudn.com"; this.LocalFile = "E:\\VSProjects\\csharp-sdk\\tools\\files\\test.jpg"; } } } }
mit
C#
07fc5372ed8e28eae1bd0806af6adeca5db0f48a
Update PermissionState
one-signal/OneSignal-Xamarin-SDK,one-signal/OneSignal-Xamarin-SDK
Com.OneSignal.Core/PermissionState.cs
Com.OneSignal.Core/PermissionState.cs
using System; using System.Collections.Generic; namespace Com.OneSignal.Core { /// <summary> /// Status of ability to send push notification as determined by the current user /// </summary> public enum NotificationPermission { /// <summary>The user has not yet made a choice regarding whether your app can show notifications.</summary> NotDetermined, /// <summary>The application is not authorized to post user notifications.</summary> Denied, /// <summary>The application is authorized to post user notifications.</summary> Authorized, /// <summary>The application is only authorized to post Provisional notifications (direct to history)</summary> Provisional, /// <summary>The application is authorized to send notifications for 8 hours. Only used by App Clips.</summary> Ephemeral } [Serializable] public sealed class PermissionState { public bool hasPrompted; public NotificationPermission status; public bool provisional; } }
using System; using System.Collections.Generic; namespace Com.OneSignal.Core { public class PermissionState { readonly bool hasPrompted = false; readonly bool provisional = false; NotificationPermission status; //public PermissionState(Dictionary<string, dynamic> json) { // //if (json.ContainsKey("status")) { // // status = json["status"]; // //} // //else if (json.ContainsKey("enabled")) { // // bool enabled = json["enabled"]; // // status = enabled // // ? NotificationPermission.AUTHORIZED // // : NotificationPermission.DENIED; // //} // // if (json.ContainsKey("provisional")) { // // provisional = json["provisional"]; // // } // // else { // // provisional = false; // // } // // if (json.ContainsKey("hasPrompted")) { // // hasPrompted = json["hasPrompted"]; // // } // // else { // // hasPrompted = false; // // } // //} // //public PermissionState(bool areNotificationsEnabled) { // // if (areNotificationsEnabled) { // // status = NotificationPermission.AUTHORIZED; // // } // // else { // // status = NotificationPermission.DENIED; // // } //} //string jsonRepresentation() { // return ""; //} } public enum NotificationPermission { NOTDETERMINED, DENIED, AUTHORIZED, PROVISIONAL }; }
mit
C#
369db139c1f2a442b7b352ba0d67b4219a574134
bump version to 0.2
danbarua/Cedar.EventStore,damianh/SqlStreamStore,SQLStreamStore/SQLStreamStore,SQLStreamStore/SQLStreamStore,damianh/Cedar.EventStore
src/SharedAssemblyInfo.cs
src/SharedAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyProduct("SqlStreamStore")] [assembly: AssemblyCopyright("Copyright Damian Hickey & Contributors 2015 - 2016")] [assembly: AssemblyVersion("0.2.0.0")] [assembly: AssemblyFileVersion("0.2.0.0")]
using System.Reflection; [assembly: AssemblyProduct("SqlStreamStore")] [assembly: AssemblyCopyright("Copyright Damian Hickey & Contributors 2015 - 2016")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
mit
C#
6054aad2b157b4cdbf3ea70d6f21d085e951f3ed
Fix URL to test & character.
cube-soft/Cube.Forms,cube-soft/Cube.Forms,cube-soft/Cube.Core,cube-soft/Cube.Core
Demo/Sources/Interactions/Behaviors/ShowVersionBehavior.cs
Demo/Sources/Interactions/Behaviors/ShowVersionBehavior.cs
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using System; using System.Drawing; using System.Globalization; using Cube.Forms.Behaviors; using Cube.Mixin.Assembly; using Cube.Mixin.Uri; namespace Cube.Forms.Demo { /* --------------------------------------------------------------------- */ /// /// ShowVersionBehavior /// /// <summary> /// Represents the behavior to show a version dialog. /// </summary> /// /* --------------------------------------------------------------------- */ public sealed class ShowVersionBehavior : MessageBehaviorBase<AboutMessage> { #region Constructors /* --------------------------------------------------------------------- */ /// /// ShowVersionBehavior /// /// <summary> /// Initializes a new instance of the ShowVersionBehavior class /// with the specified arguments. /// </summary> /// /// <param name="view">View object.</param> /// <param name="aggregator">Aggregator object.</param> /// /* --------------------------------------------------------------------- */ public ShowVersionBehavior(WindowBase view, IAggregator aggregator) : base(aggregator) { _icon = view.Icon; _text = view.Text; } #endregion #region Implementations /* --------------------------------------------------------------------- */ /// /// Invoke /// /// <summary> /// Invokes the action. /// </summary> /// /* --------------------------------------------------------------------- */ protected override void Invoke(AboutMessage message) { using var view = new VersionWindow(message.Value) { Icon = _icon, Text = _text, Uri = new Uri("https://www.cube-soft.jp") .With(GetType().Assembly) .With("lang", CultureInfo.CurrentCulture.Name), }; _ = view.ShowDialog(); } #endregion #region Fields private readonly Icon _icon; private readonly string _text; #endregion } }
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using System.Drawing; using Cube.Forms.Behaviors; namespace Cube.Forms.Demo { /* --------------------------------------------------------------------- */ /// /// ShowVersionBehavior /// /// <summary> /// Represents the behavior to show a version dialog. /// </summary> /// /* --------------------------------------------------------------------- */ public sealed class ShowVersionBehavior : MessageBehaviorBase<AboutMessage> { #region Constructors /* --------------------------------------------------------------------- */ /// /// ShowVersionBehavior /// /// <summary> /// Initializes a new instance of the ShowVersionBehavior class /// with the specified arguments. /// </summary> /// /// <param name="view">View object.</param> /// <param name="aggregator">Aggregator object.</param> /// /* --------------------------------------------------------------------- */ public ShowVersionBehavior(WindowBase view, IAggregator aggregator) : base(aggregator) { _icon = view.Icon; _text = view.Text; } #endregion #region Implementations /* --------------------------------------------------------------------- */ /// /// Invoke /// /// <summary> /// Invokes the action. /// </summary> /// /* --------------------------------------------------------------------- */ protected override void Invoke(AboutMessage message) { using var view = new VersionWindow(message.Value) { Icon = _icon, Text = _text, Uri = new("https://www.cube-soft.jp"), }; _ = view.ShowDialog(); } #endregion #region Fields private readonly Icon _icon; private readonly string _text; #endregion } }
apache-2.0
C#
86fcd6e32232ec160e604224b5564ba33d3d9bef
use durationExpression
MehdyKarimpour/extensions,AlejandroCano/extensions,MehdyKarimpour/extensions,signumsoftware/extensions,AlejandroCano/extensions,signumsoftware/framework,signumsoftware/framework,signumsoftware/extensions
Signum.Entities.Extensions/RestLog/RestLog.cs
Signum.Entities.Extensions/RestLog/RestLog.cs
using Signum.Entities; using Signum.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using Signum.Entities.Basics; using static System.Int32; namespace Signum.Entities.RestLog { [Serializable, EntityKind(EntityKind.System, EntityData.Transactional)] public class RestLogEntity : Entity { [NotNullable, SqlDbType(Size = MaxValue)] public string Url { get; set; } public DateTime StartDate { get; set; } [NotNullable, SqlDbType(Size = MaxValue)] public string RequestBody { get; set; } [NotNullable, PreserveOrder] [NotNullValidator, NoRepeatValidator] public MList<QueryStringValue> QueryString { get; set; } = new MList<QueryStringValue>(); public Lite<IUserEntity> User { get; set; } [NotNullable, SqlDbType(Size = 100)] public string Controller { get; set; } [NotNullable, SqlDbType(Size = 100)] public string Action { get; set; } public Lite<ExceptionEntity> Exception { get; set; } [SqlDbType(Size = MaxValue)] public string ResponseBody { get; set; } public DateTime EndDate { get; set; } static Expression<Func<RestLogEntity, double?>> DurationExpression = log => (double?)(log.EndDate - log.StartDate).TotalMilliseconds; [Unit("ms"), ExpressionField("DurationExpression")] public double? Duration { get { return DurationExpression.Evaluate(this); } } } [Serializable] public class QueryStringValue : EmbeddedEntity { [NotNullable, SqlDbType(Size = MaxValue)] public string Key { get; set; } [SqlDbType(Size = MaxValue)] public string Value { get; set; } } }
using Signum.Entities; using Signum.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using Signum.Entities.Basics; using static System.Int32; namespace Signum.Entities.RestLog { [Serializable, EntityKind(EntityKind.System, EntityData.Transactional)] public class RestLogEntity : Entity { [NotNullable, SqlDbType(Size = MaxValue)] public string Url { get; set; } public DateTime StartDate { get; set; } [NotNullable, SqlDbType(Size = MaxValue)] public string RequestBody { get; set; } [NotNullable, PreserveOrder] [NotNullValidator, NoRepeatValidator] public MList<QueryStringValue> QueryString { get; set; } = new MList<QueryStringValue>(); public Lite<IUserEntity> User { get; set; } [NotNullable, SqlDbType(Size = 100)] public string Controller { get; set; } [NotNullable, SqlDbType(Size = 100)] public string Action { get; set; } public Lite<ExceptionEntity> Exception { get; set; } [SqlDbType(Size = MaxValue)] public string ResponseBody { get; set; } public DateTime EndDate { get; set; } static Expression<Func<RestLogEntity, double?>> DurationExpression = log => (double?)(log.EndDate - log.StartDate).TotalMilliseconds; [Unit("ms")] public double? Duration { get { return DurationExpression.Evaluate(this); } } } [Serializable] public class QueryStringValue : EmbeddedEntity { [NotNullable, SqlDbType(Size = MaxValue)] public string Key { get; set; } [SqlDbType(Size = MaxValue)] public string Value { get; set; } } }
mit
C#
5aef145649d95eb00dd0ca183d1e3d55ac9cd565
Make ResolveEventArgs.Name not nullable (dotnet/corefx#41415)
krk/coreclr,poizan42/coreclr,cshung/coreclr,krk/coreclr,cshung/coreclr,krk/coreclr,cshung/coreclr,poizan42/coreclr,krk/coreclr,cshung/coreclr,poizan42/coreclr,krk/coreclr,cshung/coreclr,cshung/coreclr,poizan42/coreclr,poizan42/coreclr,poizan42/coreclr,krk/coreclr
src/System.Private.CoreLib/shared/System/ResolveEventArgs.cs
src/System.Private.CoreLib/shared/System/ResolveEventArgs.cs
// 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.Reflection; namespace System { public class ResolveEventArgs : EventArgs { public ResolveEventArgs(string name) { Name = name; } public ResolveEventArgs(string name, Assembly? requestingAssembly) { Name = name; RequestingAssembly = requestingAssembly; } public string Name { get; } public Assembly? RequestingAssembly { get; } } }
// 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.Reflection; namespace System { public class ResolveEventArgs : EventArgs { public ResolveEventArgs(string? name) { Name = name; } public ResolveEventArgs(string? name, Assembly? requestingAssembly) { Name = name; RequestingAssembly = requestingAssembly; } public string? Name { get; } public Assembly? RequestingAssembly { get; } } }
mit
C#
735464e9e3393cd96d91240998e396d240961647
Update to 0.0.4
superkarn/RatanaLibrary
src/RatanaLibrary.Common/Properties/AssemblyInfo.cs
src/RatanaLibrary.Common/Properties/AssemblyInfo.cs
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("RatanaLibrary.Common")] [assembly: AssemblyDescription("A general library for personal projects.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Karn Ratana")] [assembly: AssemblyProduct("RatanaLibrary.Common")] [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("67bc7fc7-1bd7-46f8-8e7b-96a3c12b35ad")] // 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("0.0.4.0")] [assembly: AssemblyFileVersion("0.0.4.0")]
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("RatanaLibrary.Common")] [assembly: AssemblyDescription("A general library for personal projects.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Karn Ratana")] [assembly: AssemblyProduct("RatanaLibrary.Common")] [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("67bc7fc7-1bd7-46f8-8e7b-96a3c12b35ad")] // 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("0.0.3.0")] [assembly: AssemblyFileVersion("0.0.3.0")]
apache-2.0
C#
a83bf3316926fbd7bc3360dcd7a79a1333066886
Fix typo in method header
rapidcore/rapidcore,rapidcore/rapidcore
src/core/main/Network/UriWithHostnameToUriWithIp.cs
src/core/main/Network/UriWithHostnameToUriWithIp.cs
using System; using System.Threading.Tasks; namespace RapidCore.Network { public class UriWithHostnameToUriWithIp { private readonly HostnameToIpResolver resolver; public UriWithHostnameToUriWithIp(HostnameToIpResolver resolver) { this.resolver = resolver; } protected UriWithHostnameToUriWithIp() { // To allow mocking } /// <summary> /// This method takes in a uri that contains a hostname, resolves the ip and returns the correspoding uri with the ip injected /// /// I.e mongodb://my-mongo-server:27017 => mongodb://10.1.1.42:27017 /// /// This is to workaround this bug in dotnet core: /// https://github.com/dotnet/corefx/issues/8768 /// </summary> /// <param name="uriString">The uri with a hostname to fix</param> /// <returns>The patched uri with an ip instead of a hostname</returns> public virtual async Task<string> ConvertAsync(string uriString) { if (!uriString.Contains("://")) { uriString = $"fakeit://{uriString}"; } var uri = new Uri(uriString); var ipaddr = await resolver.ResolveToIpv4Async(uri.DnsSafeHost); return uri.OriginalString.Replace(uri.Host, ipaddr).Replace("fakeit://", string.Empty); } /// <summary> /// Synchronously convert a uri that contains a hostname, resolves the ip and returns the correspoding uri with the ip injected /// /// I.e mongodb://my-mongo-server:27017 => mongodb://10.1.1.42:27017 /// /// This is to workaround this bug in dotnet core: /// https://github.com/dotnet/corefx/issues/8768 /// </summary> /// <param name="uriString">The uri with a hostname to fix</param> /// <returns>The patched uri with an ip instead of a hostname</returns> public virtual string Convert(string uriString) { return ConvertAsync(uriString).Result; } } }
using System; using System.Threading.Tasks; namespace RapidCore.Network { public class UriWithHostnameToUriWithIp { private readonly HostnameToIpResolver resolver; public UriWithHostnameToUriWithIp(HostnameToIpResolver resolver) { this.resolver = resolver; } protected UriWithHostnameToUriWithIp() { // To allow mocking } /// <summary> /// This method takes in a uri that contains a hostname, resolves the ip and returns the correspoding uri with the ip injected /// /// I.e mongodb://my-mongo-server:27017 => mongodb://10.1.1.42:27017 /// /// This is to workaround this bug in dotnet core: /// https://github.com/dotnet/corefx/issues/8768 /// </summary> /// <param name="uriString">The uri with a hostname to fix</param> /// <returns>The patched uri with an ip instead of a hostname</returns> public virtual async Task<string> ConvertAsync(string uriString) { if (!uriString.Contains("://")) { uriString = $"fakeit://{uriString}"; } var uri = new Uri(uriString); var ipaddr = await resolver.ResolveToIpv4Async(uri.DnsSafeHost); return uri.OriginalString.Replace(uri.Host, ipaddr).Replace("fakeit://", string.Empty); } /// <summary> /// Synchronously convert a uri that contains a hostname, resolves the ip and returns the correspoding uri with the ip injected /// /// I.e mongodb://my-mongo-server:27017 => mongodb://10.1.1.42:27017 /// /// This is to workaround this bug in dotnet core: /// https://github.com/dotnet/corefx/issues/8768 /// </summary> /// <param name="uriString">The uri with a hostname to fix</param> /// <returns>The patched uri with an ip instead of a hostname</return> public virtual string Convert(string uriString) { return ConvertAsync(uriString).Result; } } }
mit
C#
9ecd71fef48ac20e5ff72c89a66a974e1d8f8628
implement GetContext support
Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek
services/api/Tweek.ApiService.NetCore/Controllers/ContextController.cs
services/api/Tweek.ApiService.NetCore/Controllers/ContextController.cs
using Engine.DataTypes; using Engine.Drivers.Context; using FSharpUtils.Newtonsoft; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Tweek.ApiService.NetCore.Security; namespace Tweek.ApiService.NetCore.Controllers { [Route("api/v1/context")] public class ContextController : Controller { private readonly IContextDriver _contextDriver; private readonly JsonSerializer _serializer; private readonly CheckWriteContextAccess _checkAccess; public ContextController(IContextDriver contextDriver, JsonSerializer serializer, CheckWriteContextAccess checkAccess) { _contextDriver = contextDriver; _serializer = serializer; _checkAccess =checkAccess; } [HttpPost("{identityType}/{*identityId}")] public async Task<ActionResult> AppendContext([FromRoute] string identityType, [FromRoute] string identityId) { if (!_checkAccess(User, new Identity(identityType, identityId))) return Forbid(); Dictionary<string, JsonValue> data; using (var txtReader = new StreamReader(HttpContext.Request.Body)) using (var jsonReader = new JsonTextReader(txtReader)) { data = _serializer.Deserialize<Dictionary<string,JsonValue>>(jsonReader); } var identity = new Identity(identityType, identityId); await _contextDriver.AppendContext(identity, data); return Ok(); } [HttpDelete("{identityType}/{identityId}/{*prop}")] public async Task<ActionResult> DeleteFromContext([FromRoute] string identityType, [FromRoute] string identityId, [FromRoute] string prop) { if (!_checkAccess(User, new Identity(identityType, identityId))) return Forbid(); var identity = new Identity(identityType, identityId); await _contextDriver.RemoveFromContext(identity, prop); return Ok(); } [HttpGet("{identityType}/{identityId}")] public async Task<ActionResult> GetContext([FromRoute] string identityType, [FromRoute] string identityId) { Identity identity = new Identity(identityType, identityId); if (!_checkAccess(User, identity)) return Forbid(); var contextData = await _contextDriver.GetContext(identity); return Json(contextData); } } }
using Engine.DataTypes; using Engine.Drivers.Context; using FSharpUtils.Newtonsoft; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Tweek.ApiService.NetCore.Security; namespace Tweek.ApiService.NetCore.Controllers { [Route("api/v1/context")] public class ContextController : Controller { private readonly IContextDriver _contextDriver; private readonly JsonSerializer _serializer; private readonly CheckWriteContextAccess _checkAccess; public ContextController(IContextDriver contextDriver, JsonSerializer serializer, CheckWriteContextAccess checkAccess) { _contextDriver = contextDriver; _serializer = serializer; _checkAccess =checkAccess; } [HttpPost("{identityType}/{*identityId}")] public async Task<ActionResult> AppendContext([FromRoute] string identityType, [FromRoute] string identityId) { if (!_checkAccess(User, new Identity(identityType, identityId))) return Forbid(); Dictionary<string, JsonValue> data; using (var txtReader = new StreamReader(HttpContext.Request.Body)) using (var jsonReader = new JsonTextReader(txtReader)) { data = _serializer.Deserialize<Dictionary<string,JsonValue>>(jsonReader); } var identity = new Identity(identityType, identityId); await _contextDriver.AppendContext(identity, data); return Ok(); } [HttpDelete("{identityType}/{identityId}/{*prop}")] public async Task<ActionResult> DeleteFromContext([FromRoute] string identityType, [FromRoute] string identityId, [FromRoute] string prop) { if (!_checkAccess(User, new Identity(identityType, identityId))) return Forbid(); var identity = new Identity(identityType, identityId); await _contextDriver.RemoveFromContext(identity, prop); return Ok(); } } }
mit
C#
47e846eff7909ba211244eec35d82a65fca17a21
Use property initializers for 'PersistedCityBudgetConfiguration'.
Miragecoder/Urbanization,Miragecoder/Urbanization,Miragecoder/Urbanization
src/Mirage.Urbanization.Simulation/PersistedCityBudgetConfiguration.cs
src/Mirage.Urbanization.Simulation/PersistedCityBudgetConfiguration.cs
using System; namespace Mirage.Urbanization.Simulation { public class PersistedCityBudgetConfiguration : ICityBudgetConfiguration { public decimal ResidentialTaxRate { get; set; } = 0.7M; public decimal CommercialTaxRate { get; set; } = 0.7M; public decimal IndustrialTaxRate { get; set; } = 0.7M; public decimal PoliceServiceRate { get; set; } = 1M; public decimal FireDepartmentServiceRate { get; set; } = 1M; public decimal RoadInfrastructureServiceRate { get; set; } = 1M; public decimal RailroadInfrastructureServiceRate { get; set; } = 1M; } }
namespace Mirage.Urbanization.Simulation { public class PersistedCityBudgetConfiguration : ICityBudgetConfiguration { public decimal ResidentialTaxRate { get; set; } public decimal CommercialTaxRate { get; set; } public decimal IndustrialTaxRate { get; set; } public decimal PoliceServiceRate { get; set; } public decimal FireDepartmentServiceRate { get; set; } public decimal RoadInfrastructureServiceRate { get; set; } public decimal RailroadInfrastructureServiceRate { get; set; } public static PersistedCityBudgetConfiguration GetDefaultBudget() { return new PersistedCityBudgetConfiguration { ResidentialTaxRate = 0.07M, CommercialTaxRate = 0.07M, IndustrialTaxRate = 0.07M, RoadInfrastructureServiceRate = 1M, RailroadInfrastructureServiceRate = 1M, PoliceServiceRate = 1M, FireDepartmentServiceRate = 1M }; } } }
mit
C#
5a190d7cd7464c2c50bb80563982d6e208fc8edf
Add Good Night
promusic1974/TestingGitPlamen
HiGitPlamen/HiGitPlamen/Program.cs
HiGitPlamen/HiGitPlamen/Program.cs
using System; namespace HiGitPlamen { class Program { static void Main() { Console.WriteLine("Git,hello!"); Console.WriteLine("Plamen Git"); Console.WriteLine("Good Night"); } } }
using System; namespace HiGitPlamen { class Program { static void Main() { Console.WriteLine("Git,hello!"); Console.WriteLine("Plamen Git"); } } }
mit
C#
486efb8499fa8a0d47281291601458515c9b8e0c
handle null values
Pondidum/Magistrate,Pondidum/Magistrate,Pondidum/Magistrate,Pondidum/Magistrate
Magistrate/Domain/UserKeyConverter.cs
Magistrate/Domain/UserKeyConverter.cs
using System; using Newtonsoft.Json; namespace Magistrate.Domain { public class UserKeyConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(value.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var value = Convert.ToString(reader.Value); return string.IsNullOrWhiteSpace(value) ? null : new UserKey(value); } public override bool CanConvert(Type objectType) { return objectType == typeof(UserKey); } public override bool CanRead => true; public override bool CanWrite => true; } }
using System; using Newtonsoft.Json; namespace Magistrate.Domain { public class UserKeyConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(value.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return new UserKey(Convert.ToString(reader.Value)); } public override bool CanConvert(Type objectType) { return objectType == typeof(UserKey); } public override bool CanRead => true; public override bool CanWrite => true; } }
lgpl-2.1
C#
8928ae3e45ede49931cac0fbf413fcf0b927510f
Remove unused functions (that generate by unity :p)
insthync/LiteNetLibManager,insthync/LiteNetLibManager
Scripts/Events/LiteNetLibLoadSceneEvent.cs
Scripts/Events/LiteNetLibLoadSceneEvent.cs
using UnityEngine.Events; [System.Serializable] public class LiteNetLibLoadSceneEvent : UnityEvent<string, bool, float> { }
using UnityEngine.Events; [System.Serializable] public class LiteNetLibLoadSceneEvent : UnityEvent<string, bool, float> { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
mit
C#
8c7c4f0ffc434d8a9b7d2138dd84e3238c1a283b
Add Mission tracking to data model
iamdavidfrancis/AFO2015,iamdavidfrancis/AFO2015
Orlandia2015/Models/OrlandiaModels.cs
Orlandia2015/Models/OrlandiaModels.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity; namespace Orlandia2015.Models { public class Player { [Key] public Guid uPlayerID { get; set; } public Guid uFactionID { get; set; } public string sName { get; set; } public Guid uRankID { get; set; } public int iPoints { get; set; } public int iMissionsCompleted { get; set; } public virtual ICollection<PlayerAchievements> Achievements { get; set; } public virtual ICollection<PlayerMission> Missions { get; set; } public virtual Faction Faction { get; set; } public virtual Rank Rank { get; set; } } public class Faction { [Key] public Guid uFactionID { get; set; } public string sName { get; set; } [ConcurrencyCheck] public int iPoints { get; set; } } public class Achievement { [Key] public Guid uAchievementID { get; set; } public string sName { get; set; } public int iSortOrder { get; set; } } public class PlayerAchievements { [Key] public Guid uPlayerAchievementID { get; set; } [ForeignKey("Player")] public Guid uPlayerID { get; set; } [ForeignKey("Achievement")] public Guid uAchievementID { get; set; } public virtual Player Player { get; set; } public virtual Achievement Achievement { get; set; } } public class Rank { [Key] public Guid uRankID { get; set; } public Guid uFactionID { get; set; } public byte iRankNumber { get; set; } public short iRankPoints { get; set; } public string sRankName { get; set; } } public class Mission { [Key] public Guid uMissionID { get; set; } public string sMissionName { get; set; } public int iMissionPoints { get; set; } public bool bIsMissionQuest { get; set; } } public class PlayerMission { [ForeignKey("Player")] public Guid uPlayerID { get; set; } [ForeignKey("Mission")] public Guid uMissionID { get; set; } [Key] public Guid uPlayerMissionID { get; set; } public virtual Player Player { get; set; } public virtual Mission Mission { get; set; } } public class OrlandiaDbContext : DbContext { public DbSet<Player> Players { get; set; } public DbSet<Faction> Factions { get; set; } public DbSet<Achievement> Achievements { get; set; } public DbSet<Rank> Ranks { get; set; } public DbSet<Mission> Missions { get; set; } public DbSet<PlayerMission> PlayerMissions { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity; namespace Orlandia2015.Models { public class Player { [Key] public Guid uPlayerID { get; set; } public Guid uFactionID { get; set; } public string sName { get; set; } public Guid uRankID { get; set; } public int iPoints { get; set; } public int iMissionsCompleted { get; set; } public virtual ICollection<PlayerAchievements> Achievements { get; set; } public virtual Faction Faction { get; set; } public virtual Rank Rank { get; set; } } public class Faction { [Key] public Guid uFactionID { get; set; } public string sName { get; set; } [ConcurrencyCheck] public int iPoints { get; set; } } public class Achievement { [Key] public Guid uAchievementID { get; set; } public string sName { get; set; } public int iSortOrder { get; set; } } public class PlayerAchievements { [Key] public Guid uPlayerAchievementID { get; set; } [ForeignKey("Player")] public Guid uPlayerID { get; set; } [ForeignKey("Achievement")] public Guid uAchievementID { get; set; } public virtual Player Player { get; set; } public virtual Achievement Achievement { get; set; } } public class Rank { [Key] public Guid uRankID { get; set; } public Guid uFactionID { get; set; } public byte iRankNumber { get; set; } public short iRankPoints { get; set; } public string sRankName { get; set; } } public class OrlandiaDbContext : DbContext { public DbSet<Player> Players { get; set; } public DbSet<Faction> Factions { get; set; } public DbSet<Achievement> Achievements { get; set; } public DbSet<Rank> Ranks { get; set; } } }
apache-2.0
C#
3eb644d67ab9cfffe276a69c2909b91498d5669d
add Unregister and WipeContainer methods
aloisdeniel/Mvvmicro
Sources/Mvvmicro/Dependencies/Container.cs
Sources/Mvvmicro/Dependencies/Container.cs
namespace Mvvmicro { using System; using System.Collections.Generic; public class Container : IContainer { #region Default private static Lazy<IContainer> instance = new Lazy<IContainer>(() => new Container()); /// <summary> /// Gets the default container. /// </summary> /// <value>The default.</value> public static IContainer Default => instance.Value; #endregion #region Fields private Dictionary<Type, object> instances = new Dictionary<Type, object>(); private Dictionary<Type, Tuple<bool, Func<object>>> factories = new Dictionary<Type, Tuple<bool, Func<object>>>(); #endregion #region Methods public T Get<T>() { var factory = this.factories[typeof(T)]; if (factory.Item1) { if (instances.TryGetValue(typeof(T), out object instance)) { return (T)instance; } var newInstance = factory.Item2(); instances[typeof(T)] = newInstance; return (T)newInstance; } return (T)factory.Item2(); } public void Register<T>(Func<IContainer, T> factory, bool isInstance = false) { this.factories[typeof(T)] = new Tuple<bool, Func<object>>(isInstance, () => factory(this)); } public bool IsRegistered<T>() => factories.ContainsKey(typeof(T)); public void Unregister<T>() { if (this.IsRegistered<T>()) { instances[typeof(T)] = null; factories[typeof(T)] = null; } } public void WipeContainer() { this.instances = new Dictionary<Type, object>(); this.factories = new Dictionary<Type, Tuple<bool, Func<object>>>(); } public T New<T>() => (T)this.factories[typeof(T)].Item2(); #endregion } }
namespace Mvvmicro { using System; using System.Collections.Generic; public class Container : IContainer { #region Default private static Lazy<IContainer> instance = new Lazy<IContainer>(() => new Container()); /// <summary> /// Gets the default container. /// </summary> /// <value>The default.</value> public static IContainer Default => instance.Value; #endregion #region Fields private Dictionary<Type, object> instances = new Dictionary<Type, object>(); private Dictionary<Type, Tuple<bool, Func<object>>> factories = new Dictionary<Type, Tuple<bool, Func<object>>>(); #endregion #region Methods public T Get<T>() { var factory = this.factories[typeof(T)]; if (factory.Item1) { if (instances.TryGetValue(typeof(T), out object instance)) { return (T)instance; } var newInstance = factory.Item2(); instances[typeof(T)] = newInstance; return (T)newInstance; } return (T)factory.Item2(); } public void Register<T>(Func<IContainer, T> factory, bool isInstance = false) { this.factories[typeof(T)] = new Tuple<bool, Func<object>>(isInstance, () => factory(this)); } public bool IsRegistered<T>() => factories.ContainsKey(typeof(T)); public T New<T>() => (T)this.factories[typeof(T)].Item2(); #endregion } }
mit
C#
674aa3518b6fcc8b2b0cec446462b462568636cd
Fix mock authentication wrapper implementation
ginach/onedrive-sdk-csharp,OneDrive/onedrive-sdk-csharp
tests/Test.OneDriveSdk.WinRT/Mocks/MockAuthenticationContextWrapper.cs
tests/Test.OneDriveSdk.WinRT/Mocks/MockAuthenticationContextWrapper.cs
// ------------------------------------------------------------------------------ // Copyright (c) 2015 Microsoft Corporation // // 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. // ------------------------------------------------------------------------------ namespace Test.OneDriveSdk.WinRT.Mocks { using System; using System.Threading.Tasks; using Microsoft.OneDrive.Sdk; using Microsoft.IdentityModel.Clients.ActiveDirectory; public class MockAuthenticationContextWrapper : IAuthenticationContextWrapper { public delegate IAuthenticationResult AuthenticationResultCallback( string resource, string clientId, Uri redirectUri, UserIdentifier userIdentifier); public delegate IAuthenticationResult AuthenticationResultByRefreshTokenCallback( string refreshToken, string clientId, string resource); public delegate IAuthenticationResult AuthenticationResultSilentCallback( string resource, string clientId, UserIdentifier userIdentifier); public AuthenticationResultCallback AcquireTokenAsyncCallback { get; set; } public AuthenticationResultByRefreshTokenCallback AcquireTokenByRefreshTokenAsyncCallback { get; set; } public AuthenticationResultSilentCallback AcquireTokenSilentAsyncCallback { get; set; } public Task<IAuthenticationResult> AcquireTokenAsync( string resource, string clientId, Uri redirectUri, PromptBehavior promptBehavior, UserIdentifier userIdentifier) { return Task.FromResult(this.AcquireTokenAsyncCallback(resource, clientId, redirectUri, userIdentifier)); } public Task<IAuthenticationResult> AcquireTokenSilentAsync(string resource, string clientId, UserIdentifier userIdentifier) { return Task.FromResult(this.AcquireTokenSilentAsyncCallback(resource, clientId, userIdentifier)); } public Task<IAuthenticationResult> AcquireTokenByRefreshTokenAsync(string refreshToken, string clientId, string resource) { return Task.FromResult(this.AcquireTokenByRefreshTokenAsyncCallback(refreshToken, clientId, resource)); } } }
// ------------------------------------------------------------------------------ // Copyright (c) 2015 Microsoft Corporation // // 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. // ------------------------------------------------------------------------------ namespace Test.OneDriveSdk.WinRT.Mocks { using System; using System.Threading.Tasks; using Microsoft.OneDrive.Sdk; using Microsoft.IdentityModel.Clients.ActiveDirectory; public class MockAuthenticationContextWrapper : IAuthenticationContextWrapper { public delegate IAuthenticationResult AuthenticationResultCallback( string resource, string clientId, Uri redirectUri, UserIdentifier userIdentifier); public delegate IAuthenticationResult AuthenticationResultSilentCallback( string resource, string clientId, UserIdentifier userIdentifier); public AuthenticationResultCallback AcquireTokenAsyncCallback { get; set; } public AuthenticationResultSilentCallback AcquireTokenSilentAsyncCallback { get; set; } public Task<IAuthenticationResult> AcquireTokenAsync( string resource, string clientId, Uri redirectUri, PromptBehavior promptBehavior, UserIdentifier userIdentifier) { return Task.FromResult(this.AcquireTokenAsyncCallback(resource, clientId, redirectUri, userIdentifier)); } public Task<IAuthenticationResult> AcquireTokenSilentAsync(string resource, string clientId, UserIdentifier userIdentifier) { return Task.FromResult(this.AcquireTokenSilentAsyncCallback(resource, clientId, userIdentifier)); } } }
mit
C#
d5f77b5215f22e64b6ab3d0cc402bd4097d3b232
Remove unnecessary usings
mmitche/xunit-performance,Microsoft/xunit-performance,pharring/xunit-performance,Microsoft/xunit-performance,visia/xunit-performance,ianhays/xunit-performance,ericeil/xunit-performance
xunit.performance/MathExtensions.cs
xunit.performance/MathExtensions.cs
using MathNet.Numerics.Statistics; using System; namespace Microsoft.Xunit.Performance.Analysis { public static class MathExtensions { public static double MarginOfError(this RunningStatistics stats, double confidence) { if (stats.Count < 2) return double.NaN; var stderr = stats.StandardDeviation / Math.Sqrt(stats.Count); var t = MathNet.Numerics.ExcelFunctions.TInv(1.0 - confidence, (int)stats.Count - 1); var mean = stats.Mean; var interval = t * stderr; return interval / mean; } } }
using MathNet.Numerics.Statistics; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Xunit.Performance.Analysis { public static class MathExtensions { public static double MarginOfError(this RunningStatistics stats, double confidence) { if (stats.Count < 2) return double.NaN; var stderr = stats.StandardDeviation / Math.Sqrt(stats.Count); var t = MathNet.Numerics.ExcelFunctions.TInv(1.0 - confidence, (int)stats.Count - 1); var mean = stats.Mean; var interval = t * stderr; return interval / mean; } } }
mit
C#
8d5e2c00758c9846473af4ccd348113a85a46344
Update HeightCalculatorFromBones.cs
cwesnow/Net_Fiddle
2017oct/HeightCalculatorFromBones.cs
2017oct/HeightCalculatorFromBones.cs
// Original Source Information // Author: GitGub on Reddit // Link: https://www.reddit.com/r/learnprogramming/comments/77a49n/c_help_refactoring_an_ugly_method_with_lots_of_if/ // Refactored using .NET Fiddle - https://dotnetfiddle.net/F8UcJW using System; public class Program { static Random random = new Random(); enum Bones { Femur, Tibia, Humerus, Radius } enum Gender { Male, Female} public static void Main() { for(int x = 0; x < 5; x++) { // Get Randome Values float length = randomLength(); Bones bone = randomBone(); Gender gender = randomGender(); int age = randomAge(); // Result Console.WriteLine("\nGender: {0}\nAge: {1}\nBone: {2}\nLength: {3}\nHeight: {4}", gender, age, bone, length, calculateHeight(bone, length, gender, age)); } } private static float calculateHeight(Bones bone, float boneLength, Gender gender, int age) { float height = 0; switch(bone) { case Bones.Femur: height = (gender == Gender.Male) ? 69.089f + (2.238f * boneLength) - age * 0.06f : 61.412f + (2.317f * boneLength) - age * 0.06f; break; case Bones.Tibia: height = (gender == Gender.Male) ? 81.688f + (2.392f * boneLength) - age * 0.06f : 72.572f + (2.533f * boneLength) - age * 0.06f; break; case Bones.Humerus: height = (gender == Gender.Male) ? 73.570f + (2.970f * boneLength) - age * 0.06f : 64.977f + (3.144f * boneLength) - age * 0.06f; break; case Bones.Radius: height = (gender == Gender.Male) ? 80.405f + (3.650f * boneLength) - age * 0.06f : 73.502f + (3.876f * boneLength) - age * 0.06f; break; default: break; } return height; } private static float randomLength() { return (float)random.NextDouble()*3; } private static Bones randomBone() { return (Bones)random.Next(1,4); } private static Gender randomGender() { return (Gender)random.Next(0,2); } // 1,2 & 0,1 always gave the same gender private static int randomAge() { return random.Next(16, 99); } }
// Original Source Information // Author: GitGub on Reddit // Link: https://www.reddit.com/r/learnprogramming/comments/77a49n/c_help_refactoring_an_ugly_method_with_lots_of_if/ // Refactored using .NET Fiddle - https://dotnetfiddle.net/F8UcJW using System; public class Program { static Random random = new Random(); enum Bones { Femur, Tibia, Humerus, Radius } enum Gender { Male, Female} public static void Main() { for(int x = 0; x < 5; x++) { // Get Randome Values float length = randomLength(); Bones bone = randomBone(); Gender gender = randomGender(); int age = randomAge(); // Result Console.WriteLine("\nGender: {0}\nAge: {1}\nBone: {2}\nLength: {3}\nHeight: {4}", gender, age, bone, length, calculateHeight(bone, length, gender, age)); } } private static float calculateHeight(Bones bone, float boneLength, Gender gender, int age) { float height = 0; switch(bone) { case Bones.Femur: height = (gender == Gender.Male) ? 69.089f + (2.238f * boneLength) - age * 0.06f : 61.412f + (2.317f * boneLength) - age * 0.06f; break; case Bones.Tibia: height = (gender == Gender.Male) ? 81.688f + (2.392f * boneLength) - age * 0.06f : 72.572f + (2.533f * boneLength) - age * 0.06f; break; case Bones.Humerus: height = (gender == Gender.Male) ? height = 73.570f + (2.970f * boneLength) - age * 0.06f : 64.977f + (3.144f * boneLength) - age * 0.06f; break; case Bones.Radius: height = (gender == Gender.Male) ? 80.405f + (3.650f * boneLength) - age * 0.06f : 73.502f + (3.876f * boneLength) - age * 0.06f; break; default: break; } return height; } private static float randomLength() { return (float)random.NextDouble()*3; } private static Bones randomBone() { return (Bones)random.Next(1,4); } private static Gender randomGender() { return (Gender)random.Next(0,2); } // 1,2 & 0,1 always gave the same gender private static int randomAge() { return random.Next(16, 99); } }
mit
C#
f6c65a10950435d4bd61f2483003ff1d1f7949a3
Fix the build
grantcolley/origin
Projects/DevelopmentInProgress.AuthorisationManager/Model/UserEntity.cs
Projects/DevelopmentInProgress.AuthorisationManager/Model/UserEntity.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DevelopmentInProgress.AuthorisationManager.Model { class UserEntity { } }
=using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DevelopmentInProgress.AuthorisationManager.Model { class UserEntity { } }
apache-2.0
C#
8e05667cced410dcdd16485e8201bdf79b060c7d
Rewrite Action Attack erased by mistake
allmonty/BrokenShield,allmonty/BrokenShield
Assets/Scripts/Enemy/Action_Attack.cs
Assets/Scripts/Enemy/Action_Attack.cs
using UnityEngine; [CreateAssetMenu (menuName = "AI/Actions/Enemy_Attack")] public class Action_Attack : Action { [SerializeField] float staminaRequired = 2f; [SerializeField] float attackDelay = 1f; [SerializeField] float attackDuration = 1f; [SerializeField] float attackDamage = 1f; [SerializeField] float attackRange = 2f; float timer; public override void Init(StateController controller) { Debug.Log("ATTACK STATAE"); timer = attackDelay; return; } public override void Act(StateController controller) { attackRoutine(controller as Enemy_StateController); } private void attackRoutine(Enemy_StateController controller) { Vector3 targetPosition = controller.chaseTarget.transform.position; float distanceFromTarget = getDistanceFromTarget(targetPosition, controller); bool hasStamina = controller.characterStatus.stamina.isEnough(staminaRequired); if(hasStamina) { if(timer >= attackDelay) { timer = attackDelay; controller.characterStatus.stamina.decrease(staminaRequired); performAttack(controller, attackDamage, attackDuration); timer = 0f; } else { timer += Time.deltaTime; } } else { timer = attackDelay; } } private void performAttack(Enemy_StateController controller, float attackDamage, float attackDuration) { controller.anim.SetTrigger("AttackState"); controller.attackHandler.damage = attackDamage; controller.attackHandler.duration = attackDuration; controller.attackHandler.hitBox.enabled = true; } private float getDistanceFromTarget(Vector3 targetPosition, Enemy_StateController controller) { Vector3 originPosition = controller.eyes.position; Vector3 originToTargetVector = targetPosition - originPosition; float distanceFromTarget = originToTargetVector.magnitude; return distanceFromTarget; } }
using UnityEngine; [CreateAssetMenu (menuName = "AI/Actions/Enemy_Attack")] public class Action_Attack : Action { public override void Init(StateController controller) { return; } public override void Act(StateController controller) { } }
apache-2.0
C#
6e1499dc99035e210e761a16f6a7706cfef43c4f
edit reset cone position
ChristianHemann/HTW_Motorsport_Simulator
Assets/Scripts/UnityInterface/Cone.cs
Assets/Scripts/UnityInterface/Cone.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace UnityInterface { public class Cone : MonoBehaviour { private Vector3 _normalPosition; void Start() { _normalPosition = transform.position; } void OnCollisionEnter() //nachschauen ob die function wirklich so heißt { //setze timer und rufe function ResetCone nach x sekunden auf } void ResetCone() { transform.position = _normalPosition; } //der code ist zum position des autos setzen; löschen sobald benutzt //this.transform.position = OverallCarOutput.LastCalculation.Position.ToUnityVector3(); //this.transform.rotation = Quaternion.Euler(OverallCarOutput.LastCalculation.Direction.ToUnityVector3()); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace UnityInterface { public class Cone : MonoBehaviour { } }
bsd-2-clause
C#
cfab44b9d87f8a307ce613c811e1ceb0448e1662
バージョン番号更新。
YKSoftware/YKToolkit.Controls
YKToolkit.Controls/Properties/AssemblyInfo.cs
YKToolkit.Controls/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; [assembly: AssemblyTitle("YKToolkit.Controls")] #if NET4 [assembly: AssemblyDescription(".NET Framework 4.0 用 の WPF カスタムコントロールライブラリです。")] #else [assembly: AssemblyDescription("WPF カスタムコントロールライブラリです。")] #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("YKSoftware")] [assembly: AssemblyProduct("YKToolkit.Controls")] [assembly: AssemblyCopyright("Copyright © 2015 YKSoftware")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly:ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)] [assembly: AssemblyVersion("2.4.5.0")]
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; [assembly: AssemblyTitle("YKToolkit.Controls")] #if NET4 [assembly: AssemblyDescription(".NET Framework 4.0 用 の WPF カスタムコントロールライブラリです。")] #else [assembly: AssemblyDescription("WPF カスタムコントロールライブラリです。")] #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("YKSoftware")] [assembly: AssemblyProduct("YKToolkit.Controls")] [assembly: AssemblyCopyright("Copyright © 2015 YKSoftware")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly:ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)] [assembly: AssemblyVersion("2.4.4.5")]
mit
C#
fcf60135b5eb85d6cce1bf198ef22f0a400269e0
Modify assembly info
Blue0500/JoshuaKearney.Measurements
JoshuaKearney.Measurements/JoshuaKearney.Measurements/Properties/AssemblyInfo.cs
JoshuaKearney.Measurements/JoshuaKearney.Measurements/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; // 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("JoshuaKearney.Measurements")] [assembly: AssemblyDescription("A simple liblrary for representing units in a type safe way")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Josh Kearney")] [assembly: AssemblyProduct("JoshuaKearney.Measurements")] [assembly: AssemblyCopyright("Copyright © 2016 Josh Kearney")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // 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("2.0.3.0")] [assembly: AssemblyFileVersion("2.0.3.0")]
using System.Reflection; using System.Resources; // 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("JoshuaKearney.Measurements")] [assembly: AssemblyDescription("A simple liblrary for representing units in a type safe way")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Josh Kearney")] [assembly: AssemblyProduct("JoshuaKearney.Measurements")] [assembly: AssemblyCopyright("Copyright © 2016 Josh Kearney")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // 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("2.0.2.0")] [assembly: AssemblyFileVersion("2.0.2.0")]
mit
C#
c63d213a6289dfbdaba22cd47065cc2a8fd5825c
Fix crash when items are added from non-WPF main thread
GeorgeHahn/SOVND
SOVND.Client/Util/ChannelDirectory.cs
SOVND.Client/Util/ChannelDirectory.cs
using System.Collections.ObjectModel; using System.Linq; using SOVND.Lib.Models; namespace SOVND.Client.Util { public class ChannelDirectory { private readonly SyncHolder _sync; public ObservableCollection<Channel> channels = new ObservableCollection<Channel>(); public ChannelDirectory(SyncHolder sync) { _sync = sync; } public bool AddChannel(Channel channel) { if (channels.Where(x => x.Name == channel.Name).Count() > 0) return false; if (_sync.sync != null) _sync.sync.Send((x) => channels.Add(channel), null); else channels.Add(channel); return true; } } }
using System.Collections.ObjectModel; using System.Linq; using SOVND.Lib.Models; namespace SOVND.Client.Util { public class ChannelDirectory { public ObservableCollection<Channel> channels = new ObservableCollection<Channel>(); public bool AddChannel(Channel channel) { if (channels.Where(x => x.Name == channel.Name).Count() > 0) return false; channels.Add(channel); return true; } } }
epl-1.0
C#
b03bca8cf8088f775a0d1cbf3af60ba11ae687ec
build 0.0.10
rachmann/qboAccess,rachmann/qboAccess,rachmann/qboAccess
src/Global/GlobalAssemblyInfo.cs
src/Global/GlobalAssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.InteropServices; [ assembly : ComVisible( false ) ] [ assembly : AssemblyProduct( "QuickBooksOnlineAccess" ) ] [ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ] [ assembly : AssemblyCopyright( "Copyright (C) 2014 Agile Harbor, LLC" ) ] [ assembly : AssemblyDescription( "QuickBooksOnline webservices API wrapper." ) ] [ assembly : AssemblyTrademark( "" ) ] [ assembly : AssemblyCulture( "" ) ] [ assembly : CLSCompliant( false ) ] // 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.*")] // Keep in track with CA API version [ assembly : AssemblyVersion( "0.0.10.0" ) ]
using System; using System.Reflection; using System.Runtime.InteropServices; [ assembly : ComVisible( false ) ] [ assembly : AssemblyProduct( "QuickBooksOnlineAccess" ) ] [ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ] [ assembly : AssemblyCopyright( "Copyright (C) 2014 Agile Harbor, LLC" ) ] [ assembly : AssemblyDescription( "QuickBooksOnline webservices API wrapper." ) ] [ assembly : AssemblyTrademark( "" ) ] [ assembly : AssemblyCulture( "" ) ] [ assembly : CLSCompliant( false ) ] // 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.*")] // Keep in track with CA API version [ assembly : AssemblyVersion( "0.0.9.0" ) ]
bsd-3-clause
C#
9b489896767e32a710b3f471b72b30c7ef944b8e
Edit IdentificationCode Id to Guid
KristianMariyanov/VotingSystem,KristianMariyanov/VotingSystem,KristianMariyanov/VotingSystem
VotingSystem.Models/IdentificationCode.cs
VotingSystem.Models/IdentificationCode.cs
namespace VotingSystem.Models { using System; using System.ComponentModel.DataAnnotations; public class IdentificationCode { public IdentificationCode() { this.Id = Guid.NewGuid(); } [Key] public Guid Id { get; set; } public int? PollId { get; set; } public virtual Poll Poll { get; set; } public int? VoteId { get; set; } public virtual Vote Vote { get; set; } [Required] public bool Used { get; set; } } }
namespace VotingSystem.Models { using System.ComponentModel.DataAnnotations; public class IdentificationCode { [Key] public int Id { get; set; } public int? PollId { get; set; } public virtual Poll Poll { get; set; } public int? VoteId { get; set; } public virtual Vote Vote { get; set; } [Required] public bool Used { get; set; } } }
mit
C#
1a00fce5a8bedf7d0e9553b284a2ec84127f197f
Remove Drawable.PaintHandler.
bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,PowerOfCode/Eto,l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,l8s/Eto,PowerOfCode/Eto,l8s/Eto
Source/Eto/Forms/Controls/Drawable.cs
Source/Eto/Forms/Controls/Drawable.cs
using System; using Eto.Drawing; namespace Eto.Forms { public partial interface IDrawable : IControl { void Create (); void Update (Rectangle rect); bool CanFocus { get; set; } } public class PaintEventArgs : EventArgs { Graphics graphics; Rectangle clipRectangle; public PaintEventArgs (Graphics graphics,Rectangle clipRectangle) { this.clipRectangle = clipRectangle; this.graphics = graphics; } public Graphics Graphics { get { return graphics; } } public Rectangle ClipRectangle { get { return clipRectangle; } } } public delegate void PaintEventHandler (object sender, PaintEventArgs pe); public partial class Drawable : Control { IDrawable handler; public event PaintEventHandler Paint; public Drawable () : this(Generator.Current) { } public Drawable (Generator g) : this(g, typeof(IDrawable)) { } protected Drawable (Generator generator, Type type, bool initialize = true) : base (generator, type, false) { handler = (IDrawable)Handler; handler.Create (); if (initialize) Initialize (); } public Drawable(Generator g, IDrawable handler) : base(g, handler) { this.handler = handler; } public virtual void OnPaint (PaintEventArgs pe) { if (Paint != null) Paint (this, pe); } public bool CanFocus { get { return handler.CanFocus; } set { handler.CanFocus = value; } } public void Update (Rectangle rect) { handler.Update (rect); } } }
using System; using Eto.Drawing; namespace Eto.Forms { public partial interface IDrawable : IControl { void Create (); void Update (Rectangle rect); bool CanFocus { get; set; } } public class PaintEventArgs : EventArgs { Graphics graphics; Rectangle clipRectangle; public PaintEventArgs (Graphics graphics,Rectangle clipRectangle) { this.clipRectangle = clipRectangle; this.graphics = graphics; } public Graphics Graphics { get { return graphics; } } public Rectangle ClipRectangle { get { return clipRectangle; } } } public delegate void PaintEventHandler (object sender, PaintEventArgs pe); public partial class Drawable : Control { IDrawable handler; public event PaintEventHandler Paint; public PaintEventHandler PaintHandler { get; set; } public Drawable () : this(Generator.Current) { } public Drawable (Generator g) : this(g, typeof(IDrawable)) { } protected Drawable (Generator generator, Type type, bool initialize = true) : base (generator, type, false) { handler = (IDrawable)Handler; handler.Create (); if (initialize) Initialize (); } public Drawable(Generator g, IDrawable handler) : base(g, handler) { this.handler = handler; } public virtual void OnPaint (PaintEventArgs pe) { if (Paint != null) Paint (this, pe); if (PaintHandler != null) PaintHandler(this, pe); } public bool CanFocus { get { return handler.CanFocus; } set { handler.CanFocus = value; } } public void Update (Rectangle rect) { handler.Update (rect); } } }
bsd-3-clause
C#
55f0022a59523187fa5d26f008f40b69954002ba
Disable Clear of oderbys
sdanyliv/linq2db,MaceWindu/linq2db,linq2db/linq2db,genusP/linq2db,sdanyliv/linq2db,inickvel/linq2db,linq2db/linq2db,AK107/linq2db,LinqToDB4iSeries/linq2db,MaceWindu/linq2db,enginekit/linq2db,lvaleriu/linq2db,lvaleriu/linq2db,AK107/linq2db,genusP/linq2db,jogibear9988/linq2db,ronnyek/linq2db,LinqToDB4iSeries/linq2db,jogibear9988/linq2db
Source/Linq/Builder/OrderByBuilder.cs
Source/Linq/Builder/OrderByBuilder.cs
using System; using System.Linq; using System.Linq.Expressions; namespace LinqToDB.Linq.Builder { using Common; using LinqToDB.Expressions; class OrderByBuilder : MethodCallBuilder { protected override bool CanBuildMethodCall(ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo) { if (!methodCall.IsQueryable("OrderBy", "OrderByDescending", "ThenBy", "ThenByDescending")) return false; var body = ((LambdaExpression)methodCall.Arguments[1].Unwrap()).Body.Unwrap(); if (body.NodeType == ExpressionType.MemberInit) { var mi = (MemberInitExpression)body; bool throwExpr; if (mi.NewExpression.Arguments.Count > 0 || mi.Bindings.Count == 0) throwExpr = true; else throwExpr = mi.Bindings.Any(b => b.BindingType != MemberBindingType.Assignment); if (throwExpr) throw new NotSupportedException("Explicit construction of entity type '{0}' in order by is not allowed.".Args(body.Type)); } return true; } protected override IBuildContext BuildMethodCall(ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo) { var sequence = builder.BuildSequence(new BuildInfo(buildInfo, methodCall.Arguments[0])); if (sequence.SelectQuery.Select.TakeValue != null || sequence.SelectQuery.Select.SkipValue != null || sequence.SelectQuery.Select.IsDistinct && !builder.DataContextInfo.SqlProviderFlags.IsDistinctOrderBySupported) sequence = new SubQueryContext(sequence); var lambda = (LambdaExpression)methodCall.Arguments[1].Unwrap(); var sparent = sequence.Parent; var order = new ExpressionContext(buildInfo.Parent, sequence, lambda); var body = lambda.Body.Unwrap(); var sql = builder.ConvertExpressions(order, body, ConvertFlags.Key); builder.ReplaceParent(order, sparent); //if (!methodCall.Method.Name.StartsWith("Then")) // sequence.SelectQuery.OrderBy.Items.Clear(); foreach (var expr in sql) { var e = builder.ConvertSearchCondition(sequence, expr.Sql); sequence.SelectQuery.OrderBy.Expr(e, methodCall.Method.Name.EndsWith("Descending")); } return sequence; } protected override SequenceConvertInfo Convert( ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo, ParameterExpression param) { return null; } } }
using System; using System.Linq; using System.Linq.Expressions; namespace LinqToDB.Linq.Builder { using Common; using LinqToDB.Expressions; class OrderByBuilder : MethodCallBuilder { protected override bool CanBuildMethodCall(ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo) { if (!methodCall.IsQueryable("OrderBy", "OrderByDescending", "ThenBy", "ThenByDescending")) return false; var body = ((LambdaExpression)methodCall.Arguments[1].Unwrap()).Body.Unwrap(); if (body.NodeType == ExpressionType.MemberInit) { var mi = (MemberInitExpression)body; bool throwExpr; if (mi.NewExpression.Arguments.Count > 0 || mi.Bindings.Count == 0) throwExpr = true; else throwExpr = mi.Bindings.Any(b => b.BindingType != MemberBindingType.Assignment); if (throwExpr) throw new NotSupportedException("Explicit construction of entity type '{0}' in order by is not allowed.".Args(body.Type)); } return true; } protected override IBuildContext BuildMethodCall(ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo) { var sequence = builder.BuildSequence(new BuildInfo(buildInfo, methodCall.Arguments[0])); if (sequence.SelectQuery.Select.TakeValue != null || sequence.SelectQuery.Select.SkipValue != null || sequence.SelectQuery.Select.IsDistinct && !builder.DataContextInfo.SqlProviderFlags.IsDistinctOrderBySupported) sequence = new SubQueryContext(sequence); var lambda = (LambdaExpression)methodCall.Arguments[1].Unwrap(); var sparent = sequence.Parent; var order = new ExpressionContext(buildInfo.Parent, sequence, lambda); var body = lambda.Body.Unwrap(); var sql = builder.ConvertExpressions(order, body, ConvertFlags.Key); builder.ReplaceParent(order, sparent); if (!methodCall.Method.Name.StartsWith("Then")) sequence.SelectQuery.OrderBy.Items.Clear(); foreach (var expr in sql) { var e = builder.ConvertSearchCondition(sequence, expr.Sql); sequence.SelectQuery.OrderBy.Expr(e, methodCall.Method.Name.EndsWith("Descending")); } return sequence; } protected override SequenceConvertInfo Convert( ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo, ParameterExpression param) { return null; } } }
mit
C#
fa0af247a2325a9219d1549a6bc112744e386c0b
Rename previously unknown GAF field
MHeasell/Mappy,MHeasell/Mappy
TAUtil/Gaf/Structures/GafFrameData.cs
TAUtil/Gaf/Structures/GafFrameData.cs
namespace TAUtil.Gaf.Structures { using System.IO; public struct GafFrameData { public ushort Width; public ushort Height; public ushort XPos; public ushort YPos; public byte TransparencyIndex; public bool Compressed; public ushort FramePointers; public uint Unknown2; public uint PtrFrameData; public uint Unknown3; public static void Read(BinaryReader b, ref GafFrameData e) { e.Width = b.ReadUInt16(); e.Height = b.ReadUInt16(); e.XPos = b.ReadUInt16(); e.YPos = b.ReadUInt16(); e.TransparencyIndex = b.ReadByte(); e.Compressed = b.ReadBoolean(); e.FramePointers = b.ReadUInt16(); e.Unknown2 = b.ReadUInt32(); e.PtrFrameData = b.ReadUInt32(); e.Unknown3 = b.ReadUInt32(); } } }
namespace TAUtil.Gaf.Structures { using System.IO; public struct GafFrameData { public ushort Width; public ushort Height; public ushort XPos; public ushort YPos; public byte Unknown1; public bool Compressed; public ushort FramePointers; public uint Unknown2; public uint PtrFrameData; public uint Unknown3; public static void Read(BinaryReader b, ref GafFrameData e) { e.Width = b.ReadUInt16(); e.Height = b.ReadUInt16(); e.XPos = b.ReadUInt16(); e.YPos = b.ReadUInt16(); e.Unknown1 = b.ReadByte(); e.Compressed = b.ReadBoolean(); e.FramePointers = b.ReadUInt16(); e.Unknown2 = b.ReadUInt32(); e.PtrFrameData = b.ReadUInt32(); e.Unknown3 = b.ReadUInt32(); } } }
mit
C#
6a61b311863d829837fdb918588c08b18d4d3746
Change Assembly version to 2.3.
yolanother/DockPanelSuite
WinFormsUI/Properties/AssemblyInfo.cs
WinFormsUI/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; [assembly: AssemblyTitle("DockPanel Suite for .Net 2.0")] [assembly: AssemblyDescription(".Net Docking Library for Windows Forms")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Weifen Luo")] [assembly: AssemblyProduct("DockPanel Suite")] [assembly: AssemblyCopyright("Copyright © Weifen Luo 2007")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: Guid("9d690ef9-ce19-4c69-874c-e24d8eb36aff")] [assembly: AssemblyVersion("2.3.*")] [assembly: AssemblyFileVersion("2.3.0.0")] [module: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "namespace", Target = "WeifenLuo.WinFormsUI.Docking", MessageId = "Weifen")] [module: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "namespace", Target = "WeifenLuo.WinFormsUI.Docking", MessageId = "Luo")] [module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Weifen")] [module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Luo")] [module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Dockable")]
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; [assembly: AssemblyTitle("DockPanel Suite for .Net 2.0")] [assembly: AssemblyDescription(".Net Docking Library for Windows Forms")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Weifen Luo")] [assembly: AssemblyProduct("DockPanel Suite")] [assembly: AssemblyCopyright("Copyright © Weifen Luo 2007")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: Guid("9d690ef9-ce19-4c69-874c-e24d8eb36aff")] [assembly: AssemblyVersion("2.2.*")] [assembly: AssemblyFileVersion("2.2.0.0")] [module: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "namespace", Target = "WeifenLuo.WinFormsUI.Docking", MessageId = "Weifen")] [module: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "namespace", Target = "WeifenLuo.WinFormsUI.Docking", MessageId = "Luo")] [module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Weifen")] [module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Luo")] [module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Dockable")]
mit
C#
3b62e4d0b0acb083e8d3350714c1aaff1fa8c2b1
Add Safeguards for modules throwing exceptions causing the bot to crash
Luke-Wolf/wolfybot
WolfyBot.Core/BotController.cs
WolfyBot.Core/BotController.cs
// // Copyright 2014 luke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.Design; namespace WolfyBot.Core { public class BotController { public BotController (List<IBotCommand> commands) { if (commands.Count == 0) { throw new NotSupportedException (); } _commands = commands; foreach (var item in _commands) { item.ScriptMessage += new EventHandler<IRCMessage> (ScriptMessageHandler); } } protected virtual void OnMessageSent (IRCMessage e) { EventHandler<IRCMessage> handler = MessageSent; if (handler != null) { handler (this, e); } } public void ReceiveMessageHandler (Object sender, IRCMessage e) { foreach (var item in _commands) { if (item.CommandWords.Contains (e.Command)) { //If a command script is listening for a command as opposed to parameters //or trailing parameters invoke it if (item.ParameterWords.Count == 0 && item.TrailingParameterWords.Count == 0) { try { item.Execute (sender, e); } catch (Exception ex) { Console.WriteLine (ex.Message); } //if a command script is looking for parameters but not trailing parameters //invoke it } else if (item.ParameterWords.Count > 0 && item.TrailingParameterWords.Count == 0) { foreach (var item2 in item.ParameterWords) { if (e.Parameters.Contains (item2)) { try { item.Execute (sender, e); } catch (Exception ex) { Console.WriteLine (ex.Message); } } } //if a command script is looking for words in a trailing parameter //invoke it. } else if (item.TrailingParameterWords.Count > 0) { foreach (var item3 in item.TrailingParameterWords) { if (e.TrailingParameters.Contains (item3)) { try { item.Execute (sender, e); } catch (Exception ex) { Console.WriteLine (ex.Message); } } } } } } } public void ScriptMessageHandler (Object sender, IRCMessage e) { OnMessageSent (e); } public event EventHandler<IRCMessage> MessageSent; List<IBotCommand> _commands; } }
// // Copyright 2014 luke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.Design; namespace WolfyBot.Core { public class BotController { public BotController (List<IBotCommand> commands) { if (commands.Count == 0) { throw new NotSupportedException (); } _commands = commands; foreach (var item in _commands) { item.ScriptMessage += new EventHandler<IRCMessage> (ScriptMessageHandler); } } protected virtual void OnMessageSent (IRCMessage e) { EventHandler<IRCMessage> handler = MessageSent; if (handler != null) { handler (this, e); } } public void ReceiveMessageHandler (Object sender, IRCMessage e) { foreach (var item in _commands) { if (item.CommandWords.Contains (e.Command)) { //If a command script is listening for a command as opposed to parameters //or trailing parameters invoke it if (item.ParameterWords.Count == 0 && item.TrailingParameterWords.Count == 0) { item.Execute (sender, e); //if a command script is looking for parameters but not trailing parameters //invoke it } else if (item.ParameterWords.Count > 0 && item.TrailingParameterWords.Count == 0) { foreach (var item2 in item.ParameterWords) { if (e.Parameters.Contains (item2)) { item.Execute (sender, e); } } //if a command script is looking for words in a trailing parameter //invoke it. } else if (item.TrailingParameterWords.Count > 0) { foreach (var item3 in item.TrailingParameterWords) { if (e.TrailingParameters.Contains (item3)) { item.Execute (sender, e); } } } } } } public void ScriptMessageHandler (Object sender, IRCMessage e) { OnMessageSent (e); } public event EventHandler<IRCMessage> MessageSent; List<IBotCommand> _commands; } }
apache-2.0
C#
b6239ebcd52f22d9698a86a33ec053fdb8e3eb3c
Fix CloudFoundry Configuration sample
SteelToeOSS/Samples,SteelToeOSS/Samples,SteelToeOSS/Samples,SteelToeOSS/Samples
Configuration/src/AspDotNetCore/SimpleCloudFoundry/Program.cs
Configuration/src/AspDotNetCore/SimpleCloudFoundry/Program.cs
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Logging; using Pivotal.Extensions.Configuration.ConfigServer; namespace SimpleCloudFoundry { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseCloudFoundryHosting() .AddConfigServer(new LoggerFactory().AddConsole(LogLevel.Trace)) .UseStartup<Startup>() .Build(); } }
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Logging; using Pivotal.Extensions.Configuration.ConfigServer; namespace SimpleCloudFoundry { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseCloudFoundryHosting() .ConfigureAppConfiguration(b => b.AddConfigServer(new LoggerFactory().AddConsole(LogLevel.Trace))) .UseStartup<Startup>() .Build(); } }
apache-2.0
C#
76847705e7ecc1e0d75d4cbaf66ca3117d75abdf
fix descriptorbuilder test paths
Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen
Dashen.Tests/Infrastructure/Spark/DescriptorBuilderTests.cs
Dashen.Tests/Infrastructure/Spark/DescriptorBuilderTests.cs
using Dashen.Endpoints.Index; using Dashen.Endpoints.Stats; using Dashen.Infrastructure.Spark; using NSubstitute; using Shouldly; using Spark; using Spark.FileSystem; using Xunit; namespace Dashen.Tests.Infrastructure.Spark { public class DescriptorBuilderTests { private readonly IViewFolder _viewFolder; private readonly DescriptorBuilder _builder; public DescriptorBuilderTests() { _viewFolder = Substitute.For<IViewFolder>(); var engine = Substitute.For<ISparkViewEngine>(); engine.ViewFolder.Returns(_viewFolder); _builder = new DescriptorBuilder(engine); } private void HasTemplate(string path) { _viewFolder.HasView(path).Returns(true); } [Fact] public void When_loading_a_normal_view_and_there_is_no_application_view() { HasTemplate("Dashen\\Endpoints\\Index\\Index.spark"); var descriptor = _builder.Build(typeof(IndexViewModel)); descriptor.Templates.ShouldBe(new[] { "Dashen\\Endpoints\\Index\\Index.spark" }, ignoreOrder: true); } [Fact] public void When_loading_normal_view_and_there_is_an_application_view() { HasTemplate("Dashen\\Endpoints\\Index\\Index.spark"); HasTemplate("Dashen\\Views\\Application.spark"); var descriptor = _builder.Build(typeof(IndexViewModel)); descriptor.Templates.ShouldBe(new[] { "Dashen\\Endpoints\\Index\\Index.spark", "Dashen\\Views\\Application.spark" }, ignoreOrder: true); } [Fact] public void When_loading_a_shared_view_and_there_is_no_application_view() { HasTemplate("Dashen\\Endpoints\\Index\\Index.spark"); HasTemplate("Dashen\\Views\\TextControl.spark"); var descriptor = _builder.Build(typeof(TextControlViewModel)); descriptor.Templates.ShouldBe(new[] { "Dashen\\Views\\TextControl.spark" }, ignoreOrder: true); } [Fact] public void When_loading_a_shared_view_and_there_is_an_application_view() { HasTemplate("Dashen\\Endpoints\\Index\\Index.spark"); HasTemplate("Dashen\\Views\\Application.spark"); HasTemplate("Dashen\\Views\\TextControl.spark"); var descriptor = _builder.Build(typeof(TextControlViewModel)); descriptor.Templates.ShouldBe(new[] { "Dashen\\Views\\TextControl.spark" }, ignoreOrder: true); } } }
using Dashen.Endpoints.Index; using Dashen.Endpoints.Stats; using Dashen.Infrastructure.Spark; using NSubstitute; using Shouldly; using Spark; using Spark.FileSystem; using Xunit; namespace Dashen.Tests.Infrastructure.Spark { public class DescriptorBuilderTests { private readonly IViewFolder _viewFolder; private readonly DescriptorBuilder _builder; public DescriptorBuilderTests() { _viewFolder = Substitute.For<IViewFolder>(); var engine = Substitute.For<ISparkViewEngine>(); engine.ViewFolder.Returns(_viewFolder); _builder = new DescriptorBuilder(engine); } private void HasTemplate(string path) { _viewFolder.HasView(path).Returns(true); } [Fact] public void When_loading_a_normal_view_and_there_is_no_application_view() { HasTemplate("Endpoints\\Index\\Index.spark"); var descriptor = _builder.Build(typeof(IndexViewModel)); descriptor.Templates.ShouldBe(new[] { "Endpoints\\Index\\Index.spark" }, ignoreOrder: true); } [Fact] public void When_loading_normal_view_and_there_is_an_application_view() { HasTemplate("Endpoints\\Index\\Index.spark"); HasTemplate("Views\\Application.spark"); var descriptor = _builder.Build(typeof(IndexViewModel)); descriptor.Templates.ShouldBe(new[] { "Endpoints\\Index\\Index.spark", "Views\\Application.spark" }, ignoreOrder: true); } [Fact] public void When_loading_a_shared_view_and_there_is_no_application_view() { HasTemplate("Endpoints\\Index\\Index.spark"); HasTemplate("Views\\TextControl.spark"); var descriptor = _builder.Build(typeof(TextControlViewModel)); descriptor.Templates.ShouldBe(new[] { "Views\\TextControl.spark" }, ignoreOrder: true); } [Fact] public void When_loading_a_shared_view_and_there_is_an_application_view() { HasTemplate("Endpoints\\Index\\Index.spark"); HasTemplate("Views\\Application.spark"); HasTemplate("Views\\TextControl.spark"); var descriptor = _builder.Build(typeof(TextControlViewModel)); descriptor.Templates.ShouldBe(new[] { "Views\\TextControl.spark" }, ignoreOrder: true); } } }
lgpl-2.1
C#
13c4520c80af22bfa58916919f2e0eda9e0ae509
Add ThrowsWithMessage() overload with format string
whampson/cascara,whampson/bft-spec
Cascara.Tests/Src/AssertExtension.cs
Cascara.Tests/Src/AssertExtension.cs
using System; using Xunit; namespace Cascara.Tests { public class AssertExtension : Assert { public static T ThrowsWithMessage<T>(Func<object> testCode, string message) where T : Exception { var ex = Assert.Throws<T>(testCode); Assert.Equal(ex.Message, message); return ex; } public static T ThrowsWithMessage<T>(Func<object> testCode, string fmt, params object[] args) where T : Exception { string message = string.Format(fmt, args); var ex = Assert.Throws<T>(testCode); Assert.Equal(ex.Message, message); return ex; } } }
using System; using Xunit; namespace Cascara.Tests { public class AssertExtension : Assert { public static T ThrowsWithMessage<T>(Func<object> testCode, string message) where T : Exception { var ex = Assert.Throws<T>(testCode); Assert.Equal(ex.Message, message); return ex; } } }
mit
C#
e9b12a47c37a18766910f3678ef6206db301f1f7
Tag version 0.2.0.0.
AeonLucid/POGOLib,m5219/POGOLib
POGOLib/Properties/AssemblyInfo.cs
POGOLib/Properties/AssemblyInfo.cs
using System.Reflection; 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("POGOLib.Official")] [assembly: AssemblyDescription("A community driven PokémonGo API Library written in C#.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("AeonLucid")] [assembly: AssemblyProduct("POGOLib.Official")] [assembly: AssemblyCopyright("Copyright © AeonLucid 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3ba89dfb-a162-420a-9ded-daa211e52ad2")] // 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("0.2.0.0")] [assembly: AssemblyFileVersion("0.2.0.0")]
using System.Reflection; 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("POGOLib.Official")] [assembly: AssemblyDescription("A community driven PokémonGo API Library written in C#.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("AeonLucid")] [assembly: AssemblyProduct("POGOLib.Official")] [assembly: AssemblyCopyright("Copyright © AeonLucid 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3ba89dfb-a162-420a-9ded-daa211e52ad2")] // 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("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
mit
C#
d11595e09ca6265037e2358dcd6ca8148b73724e
Rename test feature class for hostname tests
junderhill/Foggle
Foggle.Tests/EnableByHostnameTests.cs
Foggle.Tests/EnableByHostnameTests.cs
using System; using Moq; using Xunit; using Should; namespace Foggle { public class EnableByHostnameTests { [Fact] public void IsEnabled_ClassMarkedWithFoggleByHostName_TrysToGetListOfHostname() { var mockConfig = new Mock<IConfigWrapper>(); Feature.configurationWrapper = mockConfig.Object; Feature.IsEnabled<TestHostnameFeature>().ShouldBeFalse(); mockConfig.Verify(x => x.GetApplicationSetting(It.Is<string>(s => s.EndsWith("Hostnames")))); } [Fact] public void IsEnabled_ClassMarkedWithFoggleByHostName_GetsCurrentHostname() { var mockConfig = new Mock<IConfigWrapper>(); Feature.configurationWrapper = mockConfig.Object; Feature.IsEnabled<TestHostnameFeature>(); mockConfig.Verify(x => x.GetCurrentHostname(), Times.Once); } [Fact] public void IsEnabledByHostName_HostnameInList_ReturnsTrue() { var mockConfig = new Mock<IConfigWrapper>(); Feature.configurationWrapper = mockConfig.Object; Feature.IsEnabled<TestHostnameFeature>(); mockConfig.Verify(x => x.GetCurrentHostname(), Times.Once); } [FoggleByHostname] class TestHostnameFeature : FoggleFeature { } } }
using System; using Moq; using Xunit; using Should; namespace Foggle { public class EnableByHostnameTests { [Fact] public void IsEnabled_ClassMarkedWithFoggleByHostName_TrysToGetListOfHostname() { var mockConfig = new Mock<IConfigWrapper>(); Feature.configurationWrapper = mockConfig.Object; Feature.IsEnabled<TestFeature>().ShouldBeFalse(); mockConfig.Verify(x => x.GetApplicationSetting(It.Is<string>(s => s.EndsWith("Hostnames")))); } [Fact] public void IsEnabled_ClassMarkedWithFoggleByHostName_GetsCurrentHostname() { var mockConfig = new Mock<IConfigWrapper>(); Feature.configurationWrapper = mockConfig.Object; Feature.IsEnabled<TestFeature>(); mockConfig.Verify(x => x.GetCurrentHostname(), Times.Once); } [Fact] public void IsEnabledByHostName_HostnameInList_ReturnsTrue() { var mockConfig = new Mock<IConfigWrapper>(); Feature.configurationWrapper = mockConfig.Object; Feature.IsEnabled<TestFeature>(); mockConfig.Verify(x => x.GetCurrentHostname(), Times.Once); } [FoggleByHostname] class TestFeature : FoggleFeature { } } }
mit
C#
2fa5b9df828b74abf9c9fe8935c8d270628d8f4a
Change log time format to formal one
SaladLab/Unity3D.IncrementalCompiler,SaladbowlCreative/Unity3D.IncrementalCompiler
extra/UniversalCompiler/Logger.cs
extra/UniversalCompiler/Logger.cs
using System; using System.IO; using System.Text; using System.Threading; internal class Logger : IDisposable { private enum LoggingMethod { Immediate, Retained, /* - Immediate Every message will be written to the log file right away in real time. - Retained All the messages will be retained in a temporary storage and flushed to disk only when the Logger object is disposed. This solves the log file sharing problem when Unity launched two compilation processes simultaneously, that can happen and happens in case of Assembly-CSharp.dll and Assembly-CSharp-Editor-firstpass.dll as they do not reference one another. */ } private const string LOG_FILENAME = "./Temp/UniversalCompiler.txt"; private const int MAXIMUM_FILE_AGE_IN_MINUTES = 5; private readonly Mutex mutex; private readonly LoggingMethod loggingMethod; private readonly StringBuilder pendingLines; public Logger() { mutex = new Mutex(true, "smcs"); if (mutex.WaitOne(0)) // check if no other process is owning the mutex { loggingMethod = LoggingMethod.Immediate; DeleteLogFileIfTooOld(); } else { pendingLines = new StringBuilder(); loggingMethod = LoggingMethod.Retained; } } public void Dispose() { mutex.WaitOne(); // make sure we own the mutex now, so no other process is writing to the file if (loggingMethod == LoggingMethod.Retained) { DeleteLogFileIfTooOld(); File.AppendAllText(LOG_FILENAME, pendingLines.ToString()); } mutex.ReleaseMutex(); } private void DeleteLogFileIfTooOld() { var lastWriteTime = new FileInfo(LOG_FILENAME).LastWriteTimeUtc; if (DateTime.UtcNow - lastWriteTime > TimeSpan.FromMinutes(MAXIMUM_FILE_AGE_IN_MINUTES)) { File.Delete(LOG_FILENAME); } } public void AppendHeader() { var dateTimeString = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"); var middleLine = "*" + new string(' ', 78) + "*"; int index = (80 - dateTimeString.Length) / 2; middleLine = middleLine.Remove(index, dateTimeString.Length).Insert(index, dateTimeString); Append(new string('*', 80)); Append(middleLine); Append(new string('*', 80)); } public void Append(string message) { if (loggingMethod == LoggingMethod.Immediate) { File.AppendAllText(LOG_FILENAME, message + Environment.NewLine); } else { pendingLines.AppendLine(message); } } }
using System; using System.IO; using System.Text; using System.Threading; internal class Logger : IDisposable { private enum LoggingMethod { Immediate, Retained, /* - Immediate Every message will be written to the log file right away in real time. - Retained All the messages will be retained in a temporary storage and flushed to disk only when the Logger object is disposed. This solves the log file sharing problem when Unity launched two compilation processes simultaneously, that can happen and happens in case of Assembly-CSharp.dll and Assembly-CSharp-Editor-firstpass.dll as they do not reference one another. */ } private const string LOG_FILENAME = "./Temp/UniversalCompiler.txt"; private const int MAXIMUM_FILE_AGE_IN_MINUTES = 5; private readonly Mutex mutex; private readonly LoggingMethod loggingMethod; private readonly StringBuilder pendingLines; public Logger() { mutex = new Mutex(true, "smcs"); if (mutex.WaitOne(0)) // check if no other process is owning the mutex { loggingMethod = LoggingMethod.Immediate; DeleteLogFileIfTooOld(); } else { pendingLines = new StringBuilder(); loggingMethod = LoggingMethod.Retained; } } public void Dispose() { mutex.WaitOne(); // make sure we own the mutex now, so no other process is writing to the file if (loggingMethod == LoggingMethod.Retained) { DeleteLogFileIfTooOld(); File.AppendAllText(LOG_FILENAME, pendingLines.ToString()); } mutex.ReleaseMutex(); } private void DeleteLogFileIfTooOld() { var lastWriteTime = new FileInfo(LOG_FILENAME).LastWriteTimeUtc; if (DateTime.UtcNow - lastWriteTime > TimeSpan.FromMinutes(MAXIMUM_FILE_AGE_IN_MINUTES)) { File.Delete(LOG_FILENAME); } } public void AppendHeader() { var dateTimeString = DateTime.Now.ToString("F"); var middleLine = "*" + new string(' ', 78) + "*"; int index = (80 - dateTimeString.Length) / 2; middleLine = middleLine.Remove(index, dateTimeString.Length).Insert(index, dateTimeString); Append(new string('*', 80)); Append(middleLine); Append(new string('*', 80)); } public void Append(string message) { if (loggingMethod == LoggingMethod.Immediate) { File.AppendAllText(LOG_FILENAME, message + Environment.NewLine); } else { pendingLines.AppendLine(message); } } }
mit
C#
c5a7d18a79c793b2137f967f93ae8539eef68b87
Tweak indentation.
ejball/XmlDocMarkdown
src/XmlDocMarkdown/CommonArgs.cs
src/XmlDocMarkdown/CommonArgs.cs
using ArgsReading; using XmlDocMarkdown.Core; namespace XmlDocMarkdown { internal static class CommonArgs { public static string ReadSettingsOption(this ArgsReader args) { return args.ReadOption("settings"); } public static string ReadSourceOption(this ArgsReader args) { return args.ReadOption("source"); } public static string ReadNamespaceOption(this ArgsReader args) { return args.ReadOption("namespace"); } public static XmlDocVisibilityLevel? ReadVisibilityOption(this ArgsReader args) { string visibility = args.ReadOption("visibility"); switch (visibility) { case "public": return XmlDocVisibilityLevel.Public; case "protected": return XmlDocVisibilityLevel.Protected; case "internal": return XmlDocVisibilityLevel.Internal; case "private": return XmlDocVisibilityLevel.Private; case null: return null; default: throw new ArgsReaderException($"Unknown visibility option: {visibility}"); } } public static bool ReadObsoleteFlag(this ArgsReader args) { return args.ReadFlag("obsolete"); } public static bool ReadCleanFlag(this ArgsReader args) { return args.ReadFlag("clean"); } public static bool ReadDryRunFlag(this ArgsReader args) { return args.ReadFlag("dryrun"); } public static bool ReadHelpFlag(this ArgsReader args) { return args.ReadFlag("help|h|?"); } public static bool ReadQuietFlag(this ArgsReader args) { return args.ReadFlag("quiet"); } public static bool ReadVerifyFlag(this ArgsReader args) { return args.ReadFlag("verify"); } public static string ReadNewLineOption(this ArgsReader args) { string value = args.ReadOption("newline"); if (value == null) return null; switch (value) { case "auto": return null; case "lf": return "\n"; case "crlf": return "\r\n"; default: throw new ArgsReaderException($"Invalid new line '{value}'. (Should be 'auto', 'lf', or 'crlf'.)"); } } } }
using ArgsReading; using XmlDocMarkdown.Core; namespace XmlDocMarkdown { internal static class CommonArgs { public static string ReadSettingsOption(this ArgsReader args) { return args.ReadOption("settings"); } public static string ReadSourceOption(this ArgsReader args) { return args.ReadOption("source"); } public static string ReadNamespaceOption(this ArgsReader args) { return args.ReadOption("namespace"); } public static XmlDocVisibilityLevel? ReadVisibilityOption(this ArgsReader args) { string visibility = args.ReadOption("visibility"); switch (visibility) { case "public": return XmlDocVisibilityLevel.Public; case "protected": return XmlDocVisibilityLevel.Protected; case "internal": return XmlDocVisibilityLevel.Internal; case "private": return XmlDocVisibilityLevel.Private; case null: return null; default: throw new ArgsReaderException($"Unknown visibility option: {visibility}"); } } public static bool ReadObsoleteFlag(this ArgsReader args) { return args.ReadFlag("obsolete"); } public static bool ReadCleanFlag(this ArgsReader args) { return args.ReadFlag("clean"); } public static bool ReadDryRunFlag(this ArgsReader args) { return args.ReadFlag("dryrun"); } public static bool ReadHelpFlag(this ArgsReader args) { return args.ReadFlag("help|h|?"); } public static bool ReadQuietFlag(this ArgsReader args) { return args.ReadFlag("quiet"); } public static bool ReadVerifyFlag(this ArgsReader args) { return args.ReadFlag("verify"); } public static string ReadNewLineOption(this ArgsReader args) { string value = args.ReadOption("newline"); if (value == null) return null; switch (value) { case "auto": return null; case "lf": return "\n"; case "crlf": return "\r\n"; default: throw new ArgsReaderException($"Invalid new line '{value}'. (Should be 'auto', 'lf', or 'crlf'.)"); } } } }
mit
C#
57a25b5b95478e2285d45f634b3dde7bfc80cfd4
Add logical operations to NuGit operations
macro187/produce
produce/Modules/NuGitModule.cs
produce/Modules/NuGitModule.cs
using MacroDiagnostics; using MacroExceptions; using MacroGuards; namespace produce { public class NuGitModule : Module { public override void Attach(ProduceRepository repository, Graph graph) { Guard.NotNull(repository, nameof(repository)); Guard.NotNull(graph, nameof(graph)); var nugitRestore = graph.Command("nugit-restore", _ => Restore(repository)); graph.Dependency(nugitRestore, graph.Command("restore")); var nugitUpdate = graph.Command("nugit-update", _ => Update(repository)); graph.Dependency(nugitUpdate, graph.Command("update")); } static void Restore(ProduceRepository repository) { using (LogicalOperation.Start("Restoring NuGit dependencies")) if (ProcessExtensions.Execute(true, true, repository.Path, "cmd", "/c", "nugit", "restore") != 0) throw new UserException("nugit failed"); } static void Update(ProduceRepository repository) { using (LogicalOperation.Start("Updating NuGit dependencies")) if (ProcessExtensions.Execute(true, true, repository.Path, "cmd", "/c", "nugit", "update") != 0) throw new UserException("nugit failed"); } } }
using MacroDiagnostics; using MacroExceptions; using MacroGuards; namespace produce { public class NuGitModule : Module { public override void Attach(ProduceRepository repository, Graph graph) { Guard.NotNull(repository, nameof(repository)); Guard.NotNull(graph, nameof(graph)); var nugitRestore = graph.Command("nugit-restore", _ => Restore(repository)); graph.Dependency(nugitRestore, graph.Command("restore")); var nugitUpdate = graph.Command("nugit-update", _ => Update(repository)); graph.Dependency(nugitUpdate, graph.Command("update")); } static void Restore(ProduceRepository repository) { if (ProcessExtensions.Execute(true, true, repository.Path, "cmd", "/c", "nugit", "restore") != 0) throw new UserException("nugit failed"); } static void Update(ProduceRepository repository) { if (ProcessExtensions.Execute(true, true, repository.Path, "cmd", "/c", "nugit", "update") != 0) throw new UserException("nugit failed"); } } }
mit
C#
a9d82421ea5055ef400a40fadfb03573dcb88334
Add missing attribute to mouse effect
CoraleStudios/Colore,WolfspiritM/Colore
Corale.Colore/Razer/Mouse/Effects/SpectrumCycling.cs
Corale.Colore/Razer/Mouse/Effects/SpectrumCycling.cs
// --------------------------------------------------------------------------------------- // <copyright file="SpectrumCycling.cs" company="Corale"> // Copyright © 2015 by Adam Hellberg and Brandon Scott. // // 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. // // Disclaimer: Corale and/or Colore is in no way affiliated with Razer and/or any // of its employees and/or licensors. Corale, Adam Hellberg, and/or Brandon Scott // do not take responsibility for any harm caused, direct or indirect, to any // Razer peripherals via the use of Colore. // // "Razer" is a trademark of Razer USA Ltd. // </copyright> // --------------------------------------------------------------------------------------- namespace Corale.Colore.Razer.Mouse.Effects { using Corale.Colore.Annotations; /// <summary> /// Spectrum cycling effect. /// </summary> public struct SpectrumCycling { /// <summary> /// The LED on which to apply the effect. /// </summary> [UsedImplicitly] public Led Led; /// <summary> /// Initializes a new instance of the <see cref="SpectrumCycling" /> struct. /// </summary> /// <param name="led">The LED on which to apply the effect.</param> public SpectrumCycling(Led led) { Led = led; } } }
// --------------------------------------------------------------------------------------- // <copyright file="SpectrumCycling.cs" company="Corale"> // Copyright © 2015 by Adam Hellberg and Brandon Scott. // // 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. // // Disclaimer: Corale and/or Colore is in no way affiliated with Razer and/or any // of its employees and/or licensors. Corale, Adam Hellberg, and/or Brandon Scott // do not take responsibility for any harm caused, direct or indirect, to any // Razer peripherals via the use of Colore. // // "Razer" is a trademark of Razer USA Ltd. // </copyright> // --------------------------------------------------------------------------------------- namespace Corale.Colore.Razer.Mouse.Effects { /// <summary> /// Spectrum cycling effect. /// </summary> public struct SpectrumCycling { /// <summary> /// The LED on which to apply the effect. /// </summary> public Led Led; /// <summary> /// Initializes a new instance of the <see cref="SpectrumCycling" /> struct. /// </summary> /// <param name="led">The LED on which to apply the effect.</param> public SpectrumCycling(Led led) { Led = led; } } }
mit
C#
d423afb9e3ff440e2577e7984a88818ac16dab15
Improve code
sakapon/Tools-2017
EpidemicSimulator/EpidemicSimulator/MainViewModel.cs
EpidemicSimulator/EpidemicSimulator/MainViewModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using Reactive.Bindings; namespace EpidemicSimulator { public class MainViewModel { const int PopulationBarWidth = 800; public AppModel AppModel { get; } = new AppModel(); public ReadOnlyReactiveProperty<byte[]> PopulationImage { get; } public ReadOnlyReactiveProperty<PopulationSummary> PopulationSummary { get; } public ReadOnlyReactiveProperty<PopulationLayout> PopulationLayout { get; } public MainViewModel() { PopulationImage = AppModel.InfectionSnapshot.Select(DataModelHelper.GetBitmapBinary).ToReadOnlyReactiveProperty(); PopulationSummary = AppModel.InfectionSnapshot.Select(DataModelHelper.ToSummary).ToReadOnlyReactiveProperty(); PopulationLayout = PopulationSummary.Select(ToLayout).ToReadOnlyReactiveProperty(); } static PopulationLayout ToLayout(PopulationSummary s) { var width_i = (int)Math.Round(PopulationBarWidth * ((double)s.Infectious / s.Total), MidpointRounding.AwayFromZero); var width_r = (int)Math.Round(PopulationBarWidth * ((double)s.Recovered / s.Total), MidpointRounding.AwayFromZero); return new PopulationLayout { SusceptibleWidth = PopulationBarWidth - width_i - width_r, InfectiousWidth = width_i, RecoveredWidth = width_r, }; } } public struct PopulationLayout { public int SusceptibleWidth { get; set; } public int InfectiousWidth { get; set; } public int RecoveredWidth { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using Reactive.Bindings; namespace EpidemicSimulator { public class MainViewModel { const int PopulationBarWidth = 800; public AppModel AppModel { get; } = new AppModel(); public ReadOnlyReactiveProperty<byte[]> PopulationImage { get; } public ReadOnlyReactiveProperty<PopulationSummary> PopulationSummary { get; } public ReadOnlyReactiveProperty<PopulationLayout> PopulationLayout { get; } public MainViewModel() { PopulationImage = AppModel.InfectionSnapshot.Select(DataModelHelper.GetBitmapBinary).ToReadOnlyReactiveProperty(); PopulationSummary = AppModel.InfectionSnapshot.Select(DataModelHelper.ToSummary).ToReadOnlyReactiveProperty(); PopulationLayout = PopulationSummary.Select(ToLayout).ToReadOnlyReactiveProperty(); } static PopulationLayout ToLayout(PopulationSummary s) { var width_s = (int)Math.Round(PopulationBarWidth * ((double)s.Susceptible / s.Total), MidpointRounding.AwayFromZero); var width_i = (int)Math.Round(PopulationBarWidth * ((double)s.Infectious / s.Total), MidpointRounding.AwayFromZero); return new PopulationLayout { SusceptibleWidth = width_s, InfectiousWidth = width_i, RecoveredWidth = PopulationBarWidth - width_s - width_i, }; } } public struct PopulationLayout { public int SusceptibleWidth { get; set; } public int InfectiousWidth { get; set; } public int RecoveredWidth { get; set; } } }
mit
C#
1b317bdee49b6483f50b4297bf9c3f3bcf183a66
Simplify handler
einaregilsson/ChordImageGenerator,einaregilsson/ChordImageGenerator,einaregilsson/ChordImageGenerator
ChordHandler.ashx.cs
ChordHandler.ashx.cs
/* * Chord Image Generator * http://einaregilsson.com/chord-image-generator/ * * Copyright (C) 2009-2012 Einar Egilsson [einar@einaregilsson.com] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Text.RegularExpressions; using System.Web; namespace EinarEgilsson.Chords { /// <summary> /// HTTP Handler that interprets the url and saves a generated /// image to the response stream. /// </summary> public class ChordHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { var request = context.Request; var response = context.Response; var chordName = Regex.Match(request.FilePath, @"^/(.*)\.png$").Groups[1].Value; var qs = request.QueryString; var pos = qs["pos"] ?? qs["p"] ?? "000000"; var fingers = qs["fingers"] ?? qs["f"] ?? "------"; var size = qs["size"] ?? qs["s"] ?? "1"; using (var img = new ChordBoxImage(chordName, pos, fingers, size)) { response.ContentType = "image/png"; response.ExpiresAbsolute = DateTime.Now.AddDays(7); img.Save(context.Response.OutputStream); } } public bool IsReusable { get { return true; } } } }
/* * Chord Image Generator * http://einaregilsson.com/chord-image-generator/ * * Copyright (C) 2009-2012 Einar Egilsson [einar@einaregilsson.com] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Text.RegularExpressions; using System.Web; namespace EinarEgilsson.Chords { /// <summary> /// HTTP Handler that interprets the url and saves a generated /// image to the response stream. /// </summary> public class ChordHandler : IHttpHandler { private string Get(HttpContext context, string key) { return context.Request.QueryString[key] ?? context.Request.QueryString[key.Substring(0,1)]; } public void ProcessRequest(HttpContext context) { //Important to use .RawUrl, since that hasn't been set to chord.ashx string chordName = Regex.Replace(context.Request.AppRelativeCurrentExecutionFilePath, "^~/|/$", ""); chordName = Regex.Replace(chordName, @"\.png$", "", RegexOptions.IgnoreCase); string pos = Get(context, "pos") ?? "000000"; string fingers = Get(context, "fingers") ?? "------"; string size = Get(context, "size") ?? "1"; using (var img = new ChordBoxImage(chordName, pos, fingers, size)) { context.Response.ContentType = "image/png"; context.Response.ExpiresAbsolute = DateTime.Now.AddDays(7); img.Save(context.Response.OutputStream); } } public bool IsReusable { get { return true; } } } }
mit
C#
151703e593ea0869bce3a9ea1b3ab1aab7978bc7
Update ViewTestPage.xaml.cs
thehunte199/mAppQuiz
mAppQuiz/mAppQuiz/ContentPages/ViewTestPage.xaml.cs
mAppQuiz/mAppQuiz/ContentPages/ViewTestPage.xaml.cs
using mAppQuiz.Data; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace mAppQuiz.ContentPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ViewTestPage : ContentPage { public Test CurrentTest { get; set; } //need to access test grades somehow public ViewTestPage (Test selectedTest) { InitializeComponent (); this.BindingContext = selectedTest; CurrentTest = selectedTest; } private async void TakeTest(object sender, EventArgs e) { Page InProgressTest = (Page)new TakeTestPage(CurrentTest.Questions); await Navigation.PushAsync(InProgressTest); } } }
using mAppQuiz.Data; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace mAppQuiz.ContentPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ViewTestPage : ContentPage { public Test CurrentTest { get; set; } //need to access test grades somehow public ViewTestPage (Test selectedTest) { InitializeComponent (); CurrentTest = selectedTest; } private async void TakeTest(object sender, EventArgs e) { Page InProgressTest = (Page)new TakeTestPage(CurrentTest.Questions); await Navigation.PushAsync(InProgressTest); } } }
mit
C#
e431246903b6f88721ee23f68aa7020245b34be8
update assemply to 1.0.0.7
rocker8942/Utility
Utility/Properties/AssemblyInfo.cs
Utility/Properties/AssemblyInfo.cs
using System.Reflection; 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("Utility")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Utility")] [assembly: AssemblyCopyright("Copyright © Microsoft 2013")] [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("9670546d-3d79-4655-89d6-93e5d82e28a8")] // 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.7")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; 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("Utility")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Utility")] [assembly: AssemblyCopyright("Copyright © Microsoft 2013")] [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("9670546d-3d79-4655-89d6-93e5d82e28a8")] // 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")]
mit
C#
e2c8688d1d075ac92a8e8fc8f175b6189676028b
Fix issue where alpaca editor fields where not loaded when using IIS virtual directories
sachatrauwaen/openform,sachatrauwaen/openform,sachatrauwaen/openform
EditSettings.ascx.cs
EditSettings.ascx.cs
#region Copyright // // Copyright (c) 2015 // by Satrabel // #endregion #region Using Statements using System; using DotNetNuke.Entities.Modules; using DotNetNuke.Common; using DotNetNuke.Framework.JavaScriptLibraries; using DotNetNuke.Framework; using Satrabel.OpenContent.Components; using Satrabel.OpenForm.Components; using Satrabel.OpenContent.Components.Alpaca; using System.IO; #endregion namespace Satrabel.OpenForm { public partial class EditSettings : PortalModuleBase { #region Event Handlers protected override void OnInit(EventArgs e) { base.OnInit(e); hlCancel.NavigateUrl = Globals.NavigateURL(); //ServicesFramework.Instance.RequestAjaxScriptSupport(); //ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); AlpacaEngine alpaca = new AlpacaEngine(Page, ModuleContext, "DesktopModules/OpenForm", "settings"); alpaca.RegisterAll(); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!Page.IsPostBack) { hlTemplateExchange.NavigateUrl = EditUrl("ShareTemplate"); var scriptFileSetting = Settings["template"] as string; scriptList.Items.AddRange(OpenFormUtils.GetTemplatesFiles(PortalSettings, ModuleId, scriptFileSetting).ToArray()); } } protected void cmdSave_Click(object sender, EventArgs e) { ModuleController mc = new ModuleController(); mc.UpdateModuleSetting(ModuleId, "template", scriptList.SelectedValue); mc.UpdateModuleSetting(ModuleId, "data", HiddenField.Value); Response.Redirect(Globals.NavigateURL(), true); //DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, "Update Successful", DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.GreenSuccess); } protected void cmdCancel_Click(object sender, EventArgs e) { } #endregion } }
#region Copyright // // Copyright (c) 2015 // by Satrabel // #endregion #region Using Statements using System; using DotNetNuke.Entities.Modules; using DotNetNuke.Common; using DotNetNuke.Framework.JavaScriptLibraries; using DotNetNuke.Framework; using Satrabel.OpenContent.Components; using Satrabel.OpenForm.Components; using Satrabel.OpenContent.Components.Alpaca; using System.IO; #endregion namespace Satrabel.OpenForm { public partial class EditSettings : PortalModuleBase { #region Event Handlers protected override void OnInit(EventArgs e) { base.OnInit(e); hlCancel.NavigateUrl = Globals.NavigateURL(); //ServicesFramework.Instance.RequestAjaxScriptSupport(); //ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); AlpacaEngine alpaca = new AlpacaEngine(Page, ModuleContext); alpaca.VirtualDirectory = "/DesktopModules/OpenForm"; alpaca.Prefix = "settings"; alpaca.RegisterAll(); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!Page.IsPostBack) { hlTemplateExchange.NavigateUrl = EditUrl("ShareTemplate"); var scriptFileSetting = Settings["template"] as string; scriptList.Items.AddRange(OpenFormUtils.GetTemplatesFiles(PortalSettings, ModuleId, scriptFileSetting).ToArray()); } } protected void cmdSave_Click(object sender, EventArgs e) { ModuleController mc = new ModuleController(); mc.UpdateModuleSetting(ModuleId, "template", scriptList.SelectedValue); mc.UpdateModuleSetting(ModuleId, "data", HiddenField.Value); Response.Redirect(Globals.NavigateURL(), true); //DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, "Update Successful", DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.GreenSuccess); } protected void cmdCancel_Click(object sender, EventArgs e) { } #endregion } }
mit
C#
a3702c486ff4cab83239b79e0cc6b372098a5682
Fix CA1416 warning for GettextCatalog alls
mrward/monodevelop-nuget-extensions,mrward/monodevelop-nuget-extensions
src/MonoDevelop.PackageManagement.Extensions/Properties/AssemblyInfo.cs
src/MonoDevelop.PackageManagement.Extensions/Properties/AssemblyInfo.cs
// // AssemblyInfo.cs // // Author: // Matt Ward <matt.ward@xamarin.com> // // Copyright (c) 2014 Xamarin Inc. (http://xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("MonoDevelop.PackageManagement.Extensions")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("Xamarin Inc. (http://xamarin.com)")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // Need to fix CA1416 build warning. // This call site is reachable on all platforms. 'NSLayoutConstraint.Active' is only supported on: 'ios' 10.0 and later, // 'maccatalyst' 10.0 and later, 'macOS/OSX' 10.14 and later, 'tvos' 10.0 and later. (CA1416)) // https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1416 [assembly: SupportedOSPlatform ("macos10.15")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("0.27")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
// // AssemblyInfo.cs // // Author: // Matt Ward <matt.ward@xamarin.com> // // Copyright (c) 2014 Xamarin Inc. (http://xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("MonoDevelop.PackageManagement.Extensions")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("Xamarin Inc. (http://xamarin.com)")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("0.27")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
mit
C#
a48c1550021436fb9a33ef5d670d23828560feda
Update DeleteNotificationConfigSnippets.g.cs (#1151)
GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples
securitycenter/api/src/DeleteNotificationConfigSnippets.g.cs
securitycenter/api/src/DeleteNotificationConfigSnippets.g.cs
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // [START scc_delete_notification_config] using Google.Cloud.SecurityCenter.V1; using System; /// <summary>Snippet for DeleteNotificationConfig</summary> public class DeleteNotificationConfigSnippets { public static bool DeleteNotificationConfig(string organizationId, string notificationConfigId) { NotificationConfigName notificationConfigName = new NotificationConfigName(organizationId, notificationConfigId); SecurityCenterClient client = SecurityCenterClient.Create(); client.DeleteNotificationConfig(notificationConfigName); Console.WriteLine($"Deleted Notification config: {notificationConfigName}"); return true; } } // [END scc_delete_notification_config]
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // [START scc_delete_notification_config] using Google.Cloud.SecurityCenter.V1; using System; /// <summary>Snippet for DeleteNotificationConfig</summary> public class DeleteNotificationConfigSnippets { public static bool DeleteNotificationConfig(string organizationId, string notificationConfigId) { NotificationConfigName notificationConfigName = new NotificationConfigName(organizationId, notificationConfigId); SecurityCenterClient client = SecurityCenterClient.Create(); client.DeleteNotificationConfig(notificationConfigName); Console.WriteLine($"Deleted Notification config: {notificationConfigName}"); return true; } } // [END] scc_delete_notification_config]
apache-2.0
C#
ed26c3359c9782b20d8927115deaeeb5e63e2836
Remove private setters to make class immutable
productinfo/eShopOnContainers,andrelmp/eShopOnContainers,andrelmp/eShopOnContainers,albertodall/eShopOnContainers,albertodall/eShopOnContainers,andrelmp/eShopOnContainers,productinfo/eShopOnContainers,dotnet-architecture/eShopOnContainers,andrelmp/eShopOnContainers,productinfo/eShopOnContainers,skynode/eShopOnContainers,albertodall/eShopOnContainers,skynode/eShopOnContainers,albertodall/eShopOnContainers,skynode/eShopOnContainers,productinfo/eShopOnContainers,skynode/eShopOnContainers,dotnet-architecture/eShopOnContainers,dotnet-architecture/eShopOnContainers,productinfo/eShopOnContainers,skynode/eShopOnContainers,dotnet-architecture/eShopOnContainers,dotnet-architecture/eShopOnContainers,andrelmp/eShopOnContainers,andrelmp/eShopOnContainers,albertodall/eShopOnContainers,productinfo/eShopOnContainers
src/Services/Ordering/Ordering.Domain/Events/OrderStartedDomainEvent.cs
src/Services/Ordering/Ordering.Domain/Events/OrderStartedDomainEvent.cs
using MediatR; using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate; using System; using System.Collections.Generic; using System.Text; namespace Ordering.Domain.Events { /// <summary> /// Event used when an order is created /// </summary> public class OrderStartedDomainEvent : INotification { public string UserId { get; } public int CardTypeId { get; } public string CardNumber { get; } public string CardSecurityNumber { get; } public string CardHolderName { get; } public DateTime CardExpiration { get; } public Order Order { get; } public OrderStartedDomainEvent(Order order, string userId, int cardTypeId, string cardNumber, string cardSecurityNumber, string cardHolderName, DateTime cardExpiration) { Order = order; UserId = userId; CardTypeId = cardTypeId; CardNumber = cardNumber; CardSecurityNumber = cardSecurityNumber; CardHolderName = cardHolderName; CardExpiration = cardExpiration; } } }
using MediatR; using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate; using System; using System.Collections.Generic; using System.Text; namespace Ordering.Domain.Events { /// <summary> /// Event used when an order is created /// </summary> public class OrderStartedDomainEvent : INotification { public string UserId { get; private set; } public int CardTypeId { get; private set; } public string CardNumber { get; private set; } public string CardSecurityNumber { get; private set; } public string CardHolderName { get; private set; } public DateTime CardExpiration { get; private set; } public Order Order { get; private set; } public OrderStartedDomainEvent(Order order, string userId, int cardTypeId, string cardNumber, string cardSecurityNumber, string cardHolderName, DateTime cardExpiration) { Order = order; UserId = userId; CardTypeId = cardTypeId; CardNumber = cardNumber; CardSecurityNumber = cardSecurityNumber; CardHolderName = cardHolderName; CardExpiration = cardExpiration; } } }
mit
C#
ab27c87d4b26a0ab16c87918de797ea8adbc967f
Fix non-existant ref vars in function calls.
KerbaeAdAstra/KerbalFuture
KerbalFuture/HelperFiles/WarpHelp.cs
KerbalFuture/HelperFiles/WarpHelp.cs
using System; namespace Hlpr { class WarpHelp { public static double Distance(double x1, double y1, double z1, double x2, double y2, double z2) { double dis; dis = Math.Pow(x1-x2,2) + Math.Pow(y1-y2,2) + Math.Pow(z1-z2,2); dis = Math.Pow(dis,0.5); return dis; } public static double Distance(Vector3d v1, Vector3d v2) { double dis, x1, x2, y1, y2, z1, z2; ConvertVector3dToXYZCoords(v1, ref x1, ref y1, ref z1); ConvertVector3dToXYZCoords(v2, ref x2, ref y2, ref z2); dis = Math.Pow(x1-x2,2) + Math.Pow(y1-y2,2) + Math.Pow(z1-z2,2); dis = Math.Pow(dis,0.5); return dis; } } }
using System; namespace Hlpr { class WarpHelp { public static double Distance(double x1, double y1, double z1, double x2, double y2, double z2) { double dis; dis = Math.Pow(x1-x2,2) + Math.Pow(y1-y2,2) + Math.Pow(z1-z2,2); dis = Math.Pow(dis,0.5); return dis; } public static double Distance(Vector3d v1, Vector3d v2) { double dis, x1, x2, y1, y2, z1, z2; ConvertVector3dToXYZCoords(v1, x1, y1, z1); ConvertVector3dToXYZCoords(v2, x2, y2, z2); dis = Math.Pow(x1-x2,2) + Math.Pow(y1-y2,2) + Math.Pow(z1-z2,2); dis = Math.Pow(dis,0.5); return dis; } } }
mit
C#
067daf3d4a1d4bc7b94364905676086fe0ae3246
Update AssemblyInfo.cs
getAddress/Sequence
getAddress.Sequence.Azure.Tests/Properties/AssemblyInfo.cs
getAddress.Sequence.Azure.Tests/Properties/AssemblyInfo.cs
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("GetAddress.Sequence.Azure.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("GetAddress.Sequence.Azure.Tests")] [assembly: AssemblyCopyright("Copyright © Microsoft 2014")] [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("b95444ff-6dd8-4168-b377-4a90da5ae9be")] // 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")]
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("Instanda.Sequence.Azure.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Instanda.Sequence.Azure.Tests")] [assembly: AssemblyCopyright("Copyright © Microsoft 2014")] [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("b95444ff-6dd8-4168-b377-4a90da5ae9be")] // 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")]
mit
C#
785c76cb1bea4b06e7d7ed534a2a4206127d25a1
test bug
Chaojincoolbean/Fly
Fly/Assets/_Script/InputManager.cs
Fly/Assets/_Script/InputManager.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class InputManager : MonoBehaviour { public GameObject CameraRig; public GameObject LeftController; public GameObject RightController; public Vector3 LLT; //LLT = LastLeftContollerPosition public Vector3 LRT; //LRT = LastRightContollerPosition public Vector3 CLT; //CLT = CurrentLeftControllerPosition public Vector3 CRT; //CRT = CurrentRightControllerPosition public float StandandY = 1.4f; //Where the player's arm is on Y position when they raise public float initTimeDelay = 4f; // Use this for initialization void Start () { LLT = LRT = CLT = CRT = Vector3.zero; } // Update is called once per frame void Update () { if (Time.time > initTimeDelay) { CLT = LeftController.transform.position; CRT = RightController.transform.position; if ((CLT.y < StandandY) & (LLT.y > StandandY) & (CRT.y < StandandY) & (LRT.y > StandandY)) { CameraRig.gameObject.transform.position = new Vector3 (CameraRig.gameObject.transform.position.x, CameraRig.gameObject.transform.position.y + 1f, CameraRig.gameObject.transform.position.z); } LLT = CLT; LRT = CRT; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class InputManager : MonoBehaviour { public GameObject CameraRig; public GameObject LeftController; public GameObject RightController; public Transform LLT; //LLT = LastLeftContollerTransform public Transform LRT; //LRT = LastRightContollerTransform public Transform CLT; //CLT = CurrentLeftControllerTransform public Transform CRT; //CRT = CurrentRightControllerTransform public float StandandY = 1.4f; //Where the player's arm is on Y position when they raise public float initTimeDelay = 4f; // Use this for initialization void Start () { LLT.position = Vector3.zero; LRT.position = Vector3.zero; } // Update is called once per frame void Update () { if (Time.time > initTimeDelay) { CLT.position = LeftController.transform.position; CRT.position = RightController.transform.position; if ((CLT.position.y < StandandY) & (LLT.position.y > StandandY) & (CRT.position.y < StandandY) & (LRT.position.y > StandandY)) { CameraRig.gameObject.transform.position = new Vector3 (CameraRig.gameObject.transform.position.x, CameraRig.gameObject.transform.position.y + 1f, CameraRig.gameObject.transform.position.z); } LLT.position = CLT.position; LRT.position = CRT.position; } } }
unlicense
C#
f1b341d8723d75e16995aa3e2b6464216cd4cf7c
Bump version number.
chripf/My-FyiReporting,maratoss/My-FyiReporting,chripf/My-FyiReporting,daniellor/My-FyiReporting,daniellor/My-FyiReporting,majorsilence/My-FyiReporting,chripf/My-FyiReporting,maratoss/My-FyiReporting,maratoss/My-FyiReporting,daniellor/My-FyiReporting,majorsilence/My-FyiReporting,chripf/My-FyiReporting,maratoss/My-FyiReporting,maratoss/My-FyiReporting,maratoss/My-FyiReporting,majorsilence/My-FyiReporting,majorsilence/My-FyiReporting,majorsilence/My-FyiReporting,chripf/My-FyiReporting,daniellor/My-FyiReporting,daniellor/My-FyiReporting,majorsilence/My-FyiReporting,chripf/My-FyiReporting,maratoss/My-FyiReporting,daniellor/My-FyiReporting,daniellor/My-FyiReporting,chripf/My-FyiReporting,majorsilence/My-FyiReporting
LibRdlCrossPlatformViewer/Properties/AssemblyInfo.cs
LibRdlCrossPlatformViewer/Properties/AssemblyInfo.cs
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("LibRdlCrossPlatformViewer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LibRdlCrossPlatformViewer")] [assembly: AssemblyCopyright("Copyright © 2012")] [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("5f0f0c79-d82f-48d4-b7d3-3bfbb529c6e5")] // 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("4.5.*")]
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("LibRdlCrossPlatformViewer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LibRdlCrossPlatformViewer")] [assembly: AssemblyCopyright("Copyright © 2012")] [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("5f0f0c79-d82f-48d4-b7d3-3bfbb529c6e5")] // 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")]
apache-2.0
C#
61b396f235bedbd8306a26f84cbf5472df9f92d8
Remove redundant length check
ppy/osu,peppy/osu,ZLima12/osu,smoogipoo/osu,ZLima12/osu,ppy/osu,EVAST9919/osu,johnneijzen/osu,2yangk23/osu,ppy/osu,2yangk23/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,peppy/osu,UselessToucan/osu,EVAST9919/osu,smoogipoo/osu,UselessToucan/osu,johnneijzen/osu,smoogipooo/osu,peppy/osu-new
osu.Game.Rulesets.Mania/Replays/ManiaReplayFrame.cs
osu.Game.Rulesets.Mania/Replays/ManiaReplayFrame.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Game.Beatmaps; using osu.Game.Replays.Legacy; using osu.Game.Rulesets.Mania.Beatmaps; using osu.Game.Rulesets.Replays; using osu.Game.Rulesets.Replays.Types; namespace osu.Game.Rulesets.Mania.Replays { public class ManiaReplayFrame : ReplayFrame, IConvertibleReplayFrame { public List<ManiaAction> Actions = new List<ManiaAction>(); public ManiaReplayFrame() { } public ManiaReplayFrame(double time, params ManiaAction[] actions) : base(time) { Actions.AddRange(actions); } public void ConvertFrom(LegacyReplayFrame legacyFrame, IBeatmap beatmap, ReplayFrame lastFrame = null) { // We don't need to fully convert, just create the converter var converter = new ManiaBeatmapConverter(beatmap); // NB: Via co-op mod, osu-stable can have two stages with floor(col/2) and ceil(col/2) columns. This will need special handling // elsewhere in the game if we do choose to support the old co-op mod anyway. For now, assume that there is only one stage. var stage = new StageDefinition { Columns = converter.TargetColumns }; var normalAction = ManiaAction.Key1; var specialAction = ManiaAction.Special1; int activeColumns = (int)(legacyFrame.MouseX ?? 0); int counter = 0; while (activeColumns > 0) { var isSpecial = stage.IsSpecialColumn(counter); if ((activeColumns & 1) > 0) Actions.Add(isSpecial ? specialAction : normalAction); if (isSpecial) specialAction++; else normalAction++; counter++; activeColumns >>= 1; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Game.Beatmaps; using osu.Game.Replays.Legacy; using osu.Game.Rulesets.Mania.Beatmaps; using osu.Game.Rulesets.Replays; using osu.Game.Rulesets.Replays.Types; namespace osu.Game.Rulesets.Mania.Replays { public class ManiaReplayFrame : ReplayFrame, IConvertibleReplayFrame { public List<ManiaAction> Actions = new List<ManiaAction>(); public ManiaReplayFrame() { } public ManiaReplayFrame(double time, params ManiaAction[] actions) : base(time) { if (actions.Length > 0) Actions.AddRange(actions); } public void ConvertFrom(LegacyReplayFrame legacyFrame, IBeatmap beatmap, ReplayFrame lastFrame = null) { // We don't need to fully convert, just create the converter var converter = new ManiaBeatmapConverter(beatmap); // NB: Via co-op mod, osu-stable can have two stages with floor(col/2) and ceil(col/2) columns. This will need special handling // elsewhere in the game if we do choose to support the old co-op mod anyway. For now, assume that there is only one stage. var stage = new StageDefinition { Columns = converter.TargetColumns }; var normalAction = ManiaAction.Key1; var specialAction = ManiaAction.Special1; int activeColumns = (int)(legacyFrame.MouseX ?? 0); int counter = 0; while (activeColumns > 0) { var isSpecial = stage.IsSpecialColumn(counter); if ((activeColumns & 1) > 0) Actions.Add(isSpecial ? specialAction : normalAction); if (isSpecial) specialAction++; else normalAction++; counter++; activeColumns >>= 1; } } } }
mit
C#
83a8fd136f5f0590bc81e627c4b4927af6b22647
Fix tabs
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.AspNet.Http/Features/HttpResponseFeature.cs
src/Microsoft.AspNet.Http/Features/HttpResponseFeature.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; namespace Microsoft.AspNet.Http.Features.Internal { public class HttpResponseFeature : IHttpResponseFeature { public HttpResponseFeature() { StatusCode = 200; Headers = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase); Body = Stream.Null; } public int StatusCode { get; set; } public string ReasonPhrase { get; set; } public IDictionary<string, string[]> Headers { get; set; } public Stream Body { get; set; } public bool HeadersSent { get { return false; } } public void OnSendingHeaders(Action<object> callback, object state) { throw new NotSupportedException(); } public void OnResponseCompleted(Action<object> callback, object state) { throw new NotSupportedException(); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; namespace Microsoft.AspNet.Http.Features.Internal { public class HttpResponseFeature : IHttpResponseFeature { public HttpResponseFeature() { StatusCode = 200; Headers = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase); Body = Stream.Null; } public int StatusCode { get; set; } public string ReasonPhrase { get; set; } public IDictionary<string, string[]> Headers { get; set; } public Stream Body { get; set; } public bool HeadersSent { get { return false; } } public void OnSendingHeaders(Action<object> callback, object state) { throw new NotSupportedException(); } public void OnResponseCompleted(Action<object> callback, object state) { throw new NotSupportedException(); } } }
apache-2.0
C#
765e0705a484b156127ad016b0f0ab777d83fc85
Make sure ResourcesResourceStartup is passing through the registered type
Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype
src/Glimpse.Server.Web/Framework/ResourcesResourceStartup.cs
src/Glimpse.Server.Web/Framework/ResourcesResourceStartup.cs
using System; using System.Collections.Generic; namespace Glimpse.Server.Web { public class ResourcesResourceStartup : IResourceStartup { private readonly IEnumerable<IResource> _resources; public ResourcesResourceStartup(IExtensionProvider<IResource> resourceProvider) { _resources = resourceProvider.Instances; } public void Configure(IResourceBuilder builder) { foreach (var resource in _resources) { builder.Run(resource.Name, resource.Parameters?.GenerateUriTemplate(), resource.Type, resource.Invoke); } } } }
using System; using System.Collections.Generic; namespace Glimpse.Server.Web { public class ResourcesResourceStartup : IResourceStartup { private readonly IEnumerable<IResource> _resources; public ResourcesResourceStartup(IExtensionProvider<IResource> resourceProvider) { _resources = resourceProvider.Instances; } public void Configure(IResourceBuilder builder) { foreach (var resource in _resources) { builder.Run(resource.Name, resource.Parameters?.GenerateUriTemplate(), resource.Invoke); } } } }
mit
C#
4a4b9960a64635fd2d176dc0c5dc642f3091a0f2
Relocate stopwatch.Reset call
Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training
src/ChessVariantsTraining/Models/Variant960/Clock.cs
src/ChessVariantsTraining/Models/Variant960/Clock.cs
using MongoDB.Bson.Serialization.Attributes; using System.Diagnostics; namespace ChessVariantsTraining.Models.Variant960 { public class Clock { Stopwatch stopwatch; [BsonElement("secondsLeftAfterLatestMove")] public double SecondsLeftAfterLatestMove { get; set; } [BsonElement("increment")] public int Increment { get; set; } public Clock() { stopwatch = new Stopwatch(); } public Clock(TimeControl tc) : this() { Increment = tc.Increment; SecondsLeftAfterLatestMove = tc.InitialSeconds; } public void Start() { stopwatch.Start(); } public void Pause() { stopwatch.Stop(); } public void AddIncrement() { SecondsLeftAfterLatestMove += Increment; } public void MoveMade() { Pause(); AddIncrement(); SecondsLeftAfterLatestMove = GetSecondsLeft(); stopwatch.Reset(); } public double GetSecondsLeft() { return SecondsLeftAfterLatestMove - stopwatch.Elapsed.TotalSeconds; } } }
using MongoDB.Bson.Serialization.Attributes; using System.Diagnostics; namespace ChessVariantsTraining.Models.Variant960 { public class Clock { Stopwatch stopwatch; [BsonElement("secondsLeftAfterLatestMove")] public double SecondsLeftAfterLatestMove { get; set; } [BsonElement("increment")] public int Increment { get; set; } public Clock() { stopwatch = new Stopwatch(); } public Clock(TimeControl tc) : this() { Increment = tc.Increment; SecondsLeftAfterLatestMove = tc.InitialSeconds; } public void Start() { stopwatch.Reset(); stopwatch.Start(); } public void Pause() { stopwatch.Stop(); } public void AddIncrement() { SecondsLeftAfterLatestMove += Increment; } public void MoveMade() { Pause(); AddIncrement(); SecondsLeftAfterLatestMove = GetSecondsLeft(); } public double GetSecondsLeft() { return SecondsLeftAfterLatestMove - stopwatch.Elapsed.TotalSeconds; } } }
agpl-3.0
C#
4316ce7a16be3563cca57fa886037eb680a74d8a
Correct IOperation.Accept annotation
weltkante/roslyn,panopticoncentral/roslyn,tmat/roslyn,wvdd007/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,eriawan/roslyn,dotnet/roslyn,wvdd007/roslyn,CyrusNajmabadi/roslyn,mgoertz-msft/roslyn,KevinRansom/roslyn,tannergooding/roslyn,tannergooding/roslyn,dotnet/roslyn,physhi/roslyn,diryboy/roslyn,diryboy/roslyn,physhi/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,ErikSchierboom/roslyn,tmat/roslyn,sharwell/roslyn,AmadeusW/roslyn,wvdd007/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,panopticoncentral/roslyn,bartdesmet/roslyn,AlekseyTs/roslyn,tannergooding/roslyn,dotnet/roslyn,sharwell/roslyn,tmat/roslyn,eriawan/roslyn,ErikSchierboom/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,mgoertz-msft/roslyn,diryboy/roslyn,KevinRansom/roslyn,mavasani/roslyn,mgoertz-msft/roslyn,KevinRansom/roslyn,mavasani/roslyn,physhi/roslyn,weltkante/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,AlekseyTs/roslyn,AlekseyTs/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,panopticoncentral/roslyn
src/Compilers/Core/Portable/Operations/IOperation.cs
src/Compilers/Core/Portable/Operations/IOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis { /// <summary> /// Root type for representing the abstract semantics of C# and VB statements and expressions. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> [InternalImplementationOnly] public interface IOperation { /// <summary> /// IOperation that has this operation as a child. Null for the root. /// </summary> IOperation? Parent { get; } /// <summary> /// Identifies the kind of the operation. /// </summary> OperationKind Kind { get; } /// <summary> /// Syntax that was analyzed to produce the operation. /// </summary> SyntaxNode Syntax { get; } /// <summary> /// Result type of the operation, or null if the operation does not produce a result. /// </summary> ITypeSymbol? Type { get; } /// <summary> /// If the operation is an expression that evaluates to a constant value, <see cref="Optional{Object}.HasValue"/> is true and <see cref="Optional{Object}.Value"/> is the value of the expression. Otherwise, <see cref="Optional{Object}.HasValue"/> is false. /// </summary> Optional<object?> ConstantValue { get; } /// <summary> /// An array of child operations for this operation. /// </summary> IEnumerable<IOperation> Children { get; } /// <summary> /// The source language of the IOperation. Possible values are <see cref="LanguageNames.CSharp"/> and <see cref="LanguageNames.VisualBasic"/>. /// </summary> string Language { get; } void Accept(OperationVisitor visitor); TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument); /// <summary> /// Set to True if compiler generated /implicitly computed by compiler code /// </summary> bool IsImplicit { get; } /// <summary> /// Optional semantic model that was used to generate this operation. /// Non-null for operations generated from source with <see cref="SemanticModel.GetOperation(SyntaxNode, System.Threading.CancellationToken)"/> API /// and operation callbacks made to analyzers. /// Null for operations inside a <see cref="FlowAnalysis.ControlFlowGraph"/>. /// </summary> SemanticModel? SemanticModel { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis { /// <summary> /// Root type for representing the abstract semantics of C# and VB statements and expressions. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> [InternalImplementationOnly] public interface IOperation { /// <summary> /// IOperation that has this operation as a child. Null for the root. /// </summary> IOperation? Parent { get; } /// <summary> /// Identifies the kind of the operation. /// </summary> OperationKind Kind { get; } /// <summary> /// Syntax that was analyzed to produce the operation. /// </summary> SyntaxNode Syntax { get; } /// <summary> /// Result type of the operation, or null if the operation does not produce a result. /// </summary> ITypeSymbol? Type { get; } /// <summary> /// If the operation is an expression that evaluates to a constant value, <see cref="Optional{Object}.HasValue"/> is true and <see cref="Optional{Object}.Value"/> is the value of the expression. Otherwise, <see cref="Optional{Object}.HasValue"/> is false. /// </summary> Optional<object?> ConstantValue { get; } /// <summary> /// An array of child operations for this operation. /// </summary> IEnumerable<IOperation> Children { get; } /// <summary> /// The source language of the IOperation. Possible values are <see cref="LanguageNames.CSharp"/> and <see cref="LanguageNames.VisualBasic"/>. /// </summary> string Language { get; } void Accept(OperationVisitor visitor); TResult Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument); /// <summary> /// Set to True if compiler generated /implicitly computed by compiler code /// </summary> bool IsImplicit { get; } /// <summary> /// Optional semantic model that was used to generate this operation. /// Non-null for operations generated from source with <see cref="SemanticModel.GetOperation(SyntaxNode, System.Threading.CancellationToken)"/> API /// and operation callbacks made to analyzers. /// Null for operations inside a <see cref="FlowAnalysis.ControlFlowGraph"/>. /// </summary> SemanticModel? SemanticModel { get; } } }
mit
C#
ab06d21639ae5da3c157f257e8a254d2c34f7c46
Fix namespace syntax
dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,abryukhov/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,mattbrailsford/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS
src/Umbraco.Core/Models/ContentEditing/HistoryCleanup.cs
src/Umbraco.Core/Models/ContentEditing/HistoryCleanup.cs
using System.Runtime.Serialization; namespace Umbraco.Core.Models.ContentEditing { [DataContract(Name = "historyCleanup", Namespace = "")] public class HistoryCleanup { [DataMember(Name = "preventCleanup")] public bool PreventCleanup { get; set; } [DataMember(Name = "keepAllVersionsNewerThanDays")] public int? KeepAllVersionsNewerThanDays { get;set; } [DataMember(Name = "keepLatestVersionPerDayForDays")] public int? KeepLatestVersionPerDayForDays { get;set; } } }
using System.Runtime.Serialization; namespace Umbraco.Core.Models.ContentEditing; [DataContract(Name = "historyCleanup", Namespace = "")] public class HistoryCleanup { [DataMember(Name = "preventCleanup")] public bool PreventCleanup { get; set; } [DataMember(Name = "keepAllVersionsNewerThanDays")] public int? KeepAllVersionsNewerThanDays { get;set; } [DataMember(Name = "keepLatestVersionPerDayForDays")] public int? KeepLatestVersionPerDayForDays { get;set; } }
mit
C#
27ce1f34bb43020526b5a07a75967ebd509610ee
Make the JSON model over the API control be the correct casing & make Mads happy :)
abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,NikRimington/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,abjerner/Umbraco-CMS,tompipe/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,hfloyd/Umbraco-CMS,umbraco/Umbraco-CMS,hfloyd/Umbraco-CMS,arknu/Umbraco-CMS,WebCentrum/Umbraco-CMS,madsoulswe/Umbraco-CMS,madsoulswe/Umbraco-CMS,lars-erik/Umbraco-CMS,KevinJump/Umbraco-CMS,rasmuseeg/Umbraco-CMS,madsoulswe/Umbraco-CMS,dawoe/Umbraco-CMS,lars-erik/Umbraco-CMS,abryukhov/Umbraco-CMS,rasmuseeg/Umbraco-CMS,bjarnef/Umbraco-CMS,leekelleher/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,mattbrailsford/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,lars-erik/Umbraco-CMS,robertjf/Umbraco-CMS,hfloyd/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,robertjf/Umbraco-CMS,leekelleher/Umbraco-CMS,bjarnef/Umbraco-CMS,lars-erik/Umbraco-CMS,WebCentrum/Umbraco-CMS,NikRimington/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,leekelleher/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,tompipe/Umbraco-CMS,marcemarc/Umbraco-CMS,rasmuseeg/Umbraco-CMS,dawoe/Umbraco-CMS,lars-erik/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,mattbrailsford/Umbraco-CMS,tompipe/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,WebCentrum/Umbraco-CMS,NikRimington/Umbraco-CMS,bjarnef/Umbraco-CMS,tcmorris/Umbraco-CMS,leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,KevinJump/Umbraco-CMS,bjarnef/Umbraco-CMS,mattbrailsford/Umbraco-CMS,hfloyd/Umbraco-CMS
src/Umbraco.Web/Models/ContentEditing/RollbackVersion.cs
src/Umbraco.Web/Models/ContentEditing/RollbackVersion.cs
using System; using System.Runtime.Serialization; namespace Umbraco.Web.Models.ContentEditing { [DataContract(Name = "rollbackVersion", Namespace = "")] public class RollbackVersion { [DataMember(Name = "versionId")] public int VersionId { get; set; } [DataMember(Name = "versionDate")] public DateTime VersionDate { get; set; } [DataMember(Name = "versionAuthorName")] public string VersionAuthorName { get; set; } } }
using System; namespace Umbraco.Web.Models.ContentEditing { public class RollbackVersion { public int VersionId { get; set; } public DateTime VersionDate { get; set; } public string VersionAuthorName { get; set; } } }
mit
C#
28d40a3a2b1caf12d4e8037efe53a4c93bdd1375
Fix the Xamarin encoding exception #1460
restsharp/RestSharp,PKRoma/RestSharp
src/RestSharp/Extensions/StringEncodingExtensions.cs
src/RestSharp/Extensions/StringEncodingExtensions.cs
// Copyright © 2009-2020 John Sheehan, Andrew Young, Alexey Zimarev and RestSharp community // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Text; namespace RestSharp.Extensions { public static class StringEncodingExtensions { /// <summary> /// Converts a byte array to a string, using its byte order mark to convert it to the right encoding. /// http://www.shrinkrays.net/code-snippets/csharp/an-extension-method-for-converting-a-byte-array-to-a-string.aspx /// </summary> /// <param name="buffer">An array of bytes to convert</param> /// <param name="encoding">Content encoding. Will fallback to UTF8 if not a valid encoding.</param> /// <returns>The byte as a string.</returns> [Obsolete("This method will be removed soon. If you use it, please copy the code to your project.")] public static string AsString(this byte[] buffer, string? encoding) { var enc = encoding.IsEmpty() ? Encoding.UTF8 : Encoding.GetEncoding(encoding) ?? Encoding.UTF8; return AsString(buffer, enc); } /// <summary> /// Converts a byte array to a string, using its byte order mark to convert it to the right encoding. /// http://www.shrinkrays.net/code-snippets/csharp/an-extension-method-for-converting-a-byte-array-to-a-string.aspx /// </summary> /// <param name="buffer">An array of bytes to convert</param> /// <returns>The byte as a string using UTF8.</returns> [Obsolete("This method will be removed soon. If you use it, please copy the code to your project.")] public static string AsString(this byte[] buffer) => AsString(buffer, Encoding.UTF8); static string AsString(byte[] buffer, Encoding encoding) => buffer == null ? "" : encoding.GetString(buffer, 0, buffer.Length); } }
// Copyright © 2009-2020 John Sheehan, Andrew Young, Alexey Zimarev and RestSharp community // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Text; namespace RestSharp.Extensions { public static class StringEncodingExtensions { static readonly Dictionary<string, Encoding> Encodings = new Dictionary<string, Encoding>(); static StringEncodingExtensions() { var encodings = Encoding.GetEncodings(); foreach (var encoding in encodings) { Encodings[encoding.Name] = encoding.GetEncoding(); } } /// <summary> /// Converts a byte array to a string, using its byte order mark to convert it to the right encoding. /// http://www.shrinkrays.net/code-snippets/csharp/an-extension-method-for-converting-a-byte-array-to-a-string.aspx /// </summary> /// <param name="buffer">An array of bytes to convert</param> /// <param name="encoding">Content encoding. Will fallback to UTF8 if not a valid encoding.</param> /// <returns>The byte as a string.</returns> [Obsolete("This method will be removed soon. If you use it, please copy the code to your project.")] public static string AsString(this byte[] buffer, string? encoding) { var enc = encoding.IsEmpty() ? Encoding.UTF8 : Encodings.TryGetValue(encoding!, out var e) ? e : Encoding.UTF8; return AsString(buffer, enc); } /// <summary> /// Converts a byte array to a string, using its byte order mark to convert it to the right encoding. /// http://www.shrinkrays.net/code-snippets/csharp/an-extension-method-for-converting-a-byte-array-to-a-string.aspx /// </summary> /// <param name="buffer">An array of bytes to convert</param> /// <returns>The byte as a string using UTF8.</returns> [Obsolete("This method will be removed soon. If you use it, please copy the code to your project.")] public static string AsString(this byte[] buffer) => AsString(buffer, Encoding.UTF8); static string AsString(byte[] buffer, Encoding encoding) => buffer == null ? "" : encoding.GetString(buffer, 0, buffer.Length); } }
apache-2.0
C#
aa4a38760ee768e140bacc8c84d975f76d7f46aa
Bump version
sendwithus/sendwithus_csharp
Sendwithus/Properties/AssemblyInfo.cs
Sendwithus/Properties/AssemblyInfo.cs
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("SendwithusClient")] [assembly: AssemblyDescription("Sendwithus C# Client Library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("sendwithus")] [assembly: AssemblyProduct("Sendwithus")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e63b982d-d5e3-4f46-9096-e1bd8f72afba")] // 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("0.0.2.0")] [assembly: AssemblyFileVersion("0.0.2.0")]
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("SendwithusClient")] [assembly: AssemblyDescription("Sendwithus C# Client Library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("sendwithus")] [assembly: AssemblyProduct("Sendwithus")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e63b982d-d5e3-4f46-9096-e1bd8f72afba")] // 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("0.0.1.3")] [assembly: AssemblyFileVersion("0.0.1.3")]
apache-2.0
C#
cb5f4f6586ca4a9557956cf879779f7a53f8ac47
Add new CefMenuCommand enum items
Livit/CefSharp,jamespearce2006/CefSharp,jamespearce2006/CefSharp,jamespearce2006/CefSharp,Livit/CefSharp,wangzheng888520/CefSharp,Livit/CefSharp,jamespearce2006/CefSharp,wangzheng888520/CefSharp,jamespearce2006/CefSharp,wangzheng888520/CefSharp,wangzheng888520/CefSharp,Livit/CefSharp
CefSharp/CefMenuCommand.cs
CefSharp/CefMenuCommand.cs
// Copyright © 2010-2016 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. namespace CefSharp { public enum CefMenuCommand { NotFound = -1, // Navigation. Back = 100, Forward = 101, Reload = 102, ReloadNoCache = 103, StopLoad = 104, // Editing. Undo = 110, Redo = 111, Cut = 112, Copy = 113, Paste = 114, Delete = 115, SelectAll = 116, // Miscellaneous. Find = 130, Print = 131, ViewSource = 132, // Spell checking word correction suggestions. SpellCheckSuggestion0 = 200, SpellCheckSuggestion1 = 201, SpellCheckSuggestion2 = 202, SpellCheckSuggestion3 = 203, SpellCheckSuggestion4 = 204, SpellCheckLastSuggestion = 204, SpellCheckNoSuggestions = 205, AddToDictionary = 206, /// <summary> /// Custom menu items originating from the renderer process. For example, plugin placeholder menu items or Flash menu items. /// This is the first entry /// </summary> CustomFirst = 220, /// <summary> /// Custom menu items originating from the renderer process. For example, plugin placeholder menu items or Flash menu items. /// This is the last entry /// </summary> CustomLast = 250, // All user-defined menu IDs should come between MENU_ID_USER_FIRST and // MENU_ID_USER_LAST to avoid overlapping the Chromium and CEF ID ranges // defined in the tools/gritsettings/resource_ids file. UserFirst = 26500, UserLast = 28500 } }
// Copyright © 2010-2016 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. namespace CefSharp { public enum CefMenuCommand { NotFound = -1, // Navigation. Back = 100, Forward = 101, Reload = 102, ReloadNoCache = 103, StopLoad = 104, // Editing. Undo = 110, Redo = 111, Cut = 112, Copy = 113, Paste = 114, Delete = 115, SelectAll = 116, // Miscellaneous. Find = 130, Print = 131, ViewSource = 132, // Spell checking word correction suggestions. SpellCheckSuggestion0 = 200, SpellCheckSuggestion1 = 201, SpellCheckSuggestion2 = 202, SpellCheckSuggestion3 = 203, SpellCheckSuggestion4 = 204, SpellCheckLastSuggestion = 204, SpellCheckNoSuggestions = 205, AddToDictionary = 206, // All user-defined menu IDs should come between MENU_ID_USER_FIRST and // MENU_ID_USER_LAST to avoid overlapping the Chromium and CEF ID ranges // defined in the tools/gritsettings/resource_ids file. UserFirst = 26500, UserLast = 28500 } }
bsd-3-clause
C#
842fe32003244c5934cf0f1b8bbeb8648c74f08d
Update test values
ppy/osu,ppy/osu,peppy/osu,peppy/osu,peppy/osu,ppy/osu
osu.Game.Rulesets.Osu.Tests/OsuDifficultyCalculatorTest.cs
osu.Game.Rulesets.Osu.Tests/OsuDifficultyCalculatorTest.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Osu.Difficulty; using osu.Game.Rulesets.Osu.Mods; using osu.Game.Tests.Beatmaps; namespace osu.Game.Rulesets.Osu.Tests { [TestFixture] public class OsuDifficultyCalculatorTest : DifficultyCalculatorTest { protected override string ResourceAssembly => "osu.Game.Rulesets.Osu"; [TestCase(6.6369583000323935d, 206, "diffcalc-test")] [TestCase(1.4476531024675374d, 45, "zero-length-sliders")] public void Test(double expectedStarRating, int expectedMaxCombo, string name) => base.Test(expectedStarRating, expectedMaxCombo, name); [TestCase(8.8816128335486386d, 206, "diffcalc-test")] [TestCase(1.7540389962596916d, 45, "zero-length-sliders")] public void TestClockRateAdjusted(double expectedStarRating, int expectedMaxCombo, string name) => Test(expectedStarRating, expectedMaxCombo, name, new OsuModDoubleTime()); [TestCase(6.6369583000323935d, 239, "diffcalc-test")] [TestCase(1.4476531024675374d, 54, "zero-length-sliders")] public void TestClassicMod(double expectedStarRating, int expectedMaxCombo, string name) => Test(expectedStarRating, expectedMaxCombo, name, new OsuModClassic()); protected override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap) => new OsuDifficultyCalculator(new OsuRuleset().RulesetInfo, beatmap); protected override Ruleset CreateRuleset() => new OsuRuleset(); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Osu.Difficulty; using osu.Game.Rulesets.Osu.Mods; using osu.Game.Tests.Beatmaps; namespace osu.Game.Rulesets.Osu.Tests { [TestFixture] public class OsuDifficultyCalculatorTest : DifficultyCalculatorTest { protected override string ResourceAssembly => "osu.Game.Rulesets.Osu"; [TestCase(6.6972307565739273d, 206, "diffcalc-test")] [TestCase(1.4484754139145539d, 45, "zero-length-sliders")] public void Test(double expectedStarRating, int expectedMaxCombo, string name) => base.Test(expectedStarRating, expectedMaxCombo, name); [TestCase(8.9382559208689809d, 206, "diffcalc-test")] [TestCase(1.7548875851757628d, 45, "zero-length-sliders")] public void TestClockRateAdjusted(double expectedStarRating, int expectedMaxCombo, string name) => Test(expectedStarRating, expectedMaxCombo, name, new OsuModDoubleTime()); [TestCase(6.6972307218715166d, 239, "diffcalc-test")] [TestCase(1.4484754139145537d, 54, "zero-length-sliders")] public void TestClassicMod(double expectedStarRating, int expectedMaxCombo, string name) => Test(expectedStarRating, expectedMaxCombo, name, new OsuModClassic()); protected override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap) => new OsuDifficultyCalculator(new OsuRuleset().RulesetInfo, beatmap); protected override Ruleset CreateRuleset() => new OsuRuleset(); } }
mit
C#
1a60d71d3f1f6feb84943ae1e0ce715b8e4afba0
Set Datawriter executing logs to debug level
pthivierge/data-collection-service-for-pi-system,pthivierge/web-service-reader-for-pi-system,pthivierge/data-collection-service-for-pi-system,pthivierge/web-service-reader-for-pi-system,pthivierge/web-service-reader-for-pi-system,pthivierge/data-collection-service-for-pi-system
Core/Scheduler/CronTask.cs
Core/Scheduler/CronTask.cs
using System; using log4net; using Quartz; namespace DCS.Core.Scheduler { public sealed class CronTask : IJob { private readonly string _cronConfig; private readonly ILog _logger = LogManager.GetLogger(typeof(CronTask)); private readonly Action _task; private readonly string _taskName; public CronTask() { } public CronTask(string taskName, string cronConfig, Action action) { _taskName = taskName; _task = action; _cronConfig = cronConfig; } public string TaskName { get { return _taskName; } } public string CronConfig { get { return _cronConfig; } } public void Execute(IJobExecutionContext context) { var task = (CronTask)context.MergedJobDataMap.Get("task"); // executes the task _logger.Debug("Executing task : " + task.TaskName); task._task(); } } }
using System; using log4net; using Quartz; namespace DCS.Core.Scheduler { public sealed class CronTask : IJob { private readonly string _cronConfig; private readonly ILog _logger = LogManager.GetLogger(typeof(CronTask)); private readonly Action _task; private readonly string _taskName; public CronTask() { } public CronTask(string taskName, string cronConfig, Action action) { _taskName = taskName; _task = action; _cronConfig = cronConfig; } public string TaskName { get { return _taskName; } } public string CronConfig { get { return _cronConfig; } } public void Execute(IJobExecutionContext context) { var task = (CronTask)context.MergedJobDataMap.Get("task"); // executes the task _logger.Info("Executing task : " + task.TaskName); task._task(); } } }
apache-2.0
C#
6a3ec4a843300287dd0e11832b3e45407c584b34
Use Moq<Random> with a sequence instead of custom MockRandom class
DnDGen/RollGen,DnDGen/RollGen
RollGen.Tests.Unit/ExplodeTests.cs
RollGen.Tests.Unit/ExplodeTests.cs
using Albatross.Expression; using Moq; using NUnit.Framework; using RollGen.Expressions; using RollGen.PartialRolls; using System; namespace RollGen.Tests.Unit { [TestFixture] public class ExplodeTests { readonly ExpressionEvaluator evaluator = new AlbatrossExpressionEvaluator(Factory.Instance.Create()); readonly Mock<Random> random = new Mock<Random>(); [TestCase(1, 1, new[]{1, 1}, ExpectedResult = 1)] // 1d1, shouldn't explode [TestCase(1, 6, new[]{1}, ExpectedResult = 1)] // Single, no Explode [TestCase(1, 6, new[]{6, 1}, ExpectedResult = 7)] // Single, Explode once [TestCase(1, 6, new[]{6, 6, 1}, ExpectedResult = 13)] // Single, Explode twice [TestCase(3, 6, new[]{3, 4, 2}, ExpectedResult = 9)] // Multiple, no Explode [TestCase(3, 6, new[]{1, 6, 2, 2}, ExpectedResult = 11)] // Multiple, Explode once [TestCase(3, 6, new[]{5, 6, 6, 1, 2}, ExpectedResult = 20)] // Multiple, Explode twice in a row [TestCase(3, 6, new[]{6, 1, 6, 4, 2}, ExpectedResult = 19)] // Multiple, Explode twice not in a row public int ExplodeTest(int quantity, int die, int[] rolls) { var seq = random.SetupSequence(r => r.Next(die)); foreach (var roll in rolls) { seq.Returns(roll-1); } var partialRoll = new NumericPartialRoll(quantity, random.Object, evaluator); partialRoll.d(die).Explode(); return partialRoll.AsSum(); } } }
using Albatross.Expression; using NUnit.Framework; using RollGen.Expressions; using RollGen.PartialRolls; using System; using System.Collections.Generic; namespace RollGen.Tests.Unit { // False random class that returns a given array of ints, throws if exceeds array size class MockRandom : Random { private readonly Queue<int> Rolls; public MockRandom(int[] rolls) => Rolls = new Queue<int>(rolls); public override int Next() => Rolls.Dequeue() - 1; public override int Next(int maxValue) => Next(); public override int Next(int minValue, int maxValue) => Next(); } [TestFixture] public class ExplodeTests { readonly ExpressionEvaluator evaluator = new AlbatrossExpressionEvaluator(Factory.Instance.Create()); [TestCase(1, 1, new[]{1, 1}, ExpectedResult = 1)] // 1d1, shouldn't explode [TestCase(1, 6, new[]{1}, ExpectedResult = 1)] // Single, no Explode [TestCase(1, 6, new[]{6, 1}, ExpectedResult = 7)] // Single, Explode once [TestCase(1, 6, new[]{6, 6, 1}, ExpectedResult = 13)] // Single, Explode twice [TestCase(3, 6, new[]{3, 4, 2}, ExpectedResult = 9)] // Multiple, no Explode [TestCase(3, 6, new[]{1, 6, 2, 2}, ExpectedResult = 11)] // Multiple, Explode once [TestCase(3, 6, new[]{5, 6, 6, 1, 2}, ExpectedResult = 20)] // Multiple, Explode twice in a row [TestCase(3, 6, new[]{6, 1, 6, 4, 2}, ExpectedResult = 19)] // Multiple, Explode twice not in a row public int ExplodeTest(int quantity, int die, int[] rolls) { var random = new MockRandom(rolls); var partialRoll = new NumericPartialRoll(quantity, random, evaluator); partialRoll.d(die).Explode(); return partialRoll.AsSum(); } } }
mit
C#
41089a50f7d100656aa07de1649bea7aae7896c8
Bump version to 1.3.1
mwilliamson/dotnet-mammoth
Mammoth/Properties/AssemblyInfo.cs
Mammoth/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Mammoth")] [assembly: AssemblyDescription("Convert Word documents from docx to simple HTML")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Michael Williamson")] [assembly: AssemblyProduct("Mammoth")] [assembly: AssemblyCopyright("Copyright © Michael Williamson 2015 - 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.3.1.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Mammoth")] [assembly: AssemblyDescription("Convert Word documents from docx to simple HTML")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Michael Williamson")] [assembly: AssemblyProduct("Mammoth")] [assembly: AssemblyCopyright("Copyright © Michael Williamson 2015 - 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.3.0.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
bsd-2-clause
C#
52f48cf414a180e95b9141935013b853a31a02fe
Add interface documentation.
matrostik/SQLitePCL.pretty,bordoley/SQLitePCL.pretty
SQLitePCL.pretty.Orm/Interfaces.cs
SQLitePCL.pretty.Orm/Interfaces.cs
using System; using System.Collections.Generic; namespace SQLitePCL.pretty.Orm { /// <summary> /// The mapping of a type to a SQL Table. /// </summary> public interface ITableMapping : IReadOnlyDictionary<string, ColumnMapping> { /// <summary> /// Gets the name of the table. /// </summary> String TableName { get; } /// <summary> /// Gets the table indexes. /// </summary> IEnumerable<IndexInfo> Indexes { get; } } /// <summary> /// The mapping of a type <see typeparamref="T"/> to a SQL Table. /// </summary> public interface ITableMapping<T> : ITableMapping { /// <summary> /// Converts a result set row to an instance of type T. /// </summary> /// <returns>An instance of type T.</returns> /// <param name="row">The result set row.</param> T ToObject(IReadOnlyList<IResultSetValue> row); } /// <summary> /// An <see cref="IStatement"/> that allows the current value to be retrieved /// as an instance T based upon an underlying table mapping. /// </summary> public interface ITableMappedStatement<T> : IStatement { /// <summary> /// The underlying <see cref="ITableMapping&lt;T&gt;"/> used to map the result set to an instance of T. /// </summary> ITableMapping<T> Mapping { get; } /// <summary> /// Gets the current result value at the current position of the statement enumerator. /// </summary> new T Current { get; } } }
using System; using System.Collections.Generic; namespace SQLitePCL.pretty.Orm { public interface ITableMapping : IReadOnlyDictionary<string, ColumnMapping> { String TableName { get; } ColumnMapping this[string column] { get; } IEnumerable<IndexInfo> Indexes { get; } } public interface ITableMapping<T> : ITableMapping { T ToObject(IReadOnlyList<IResultSetValue> row); } public interface ITableMappedStatement<T> : IStatement { ITableMapping<T> Mapping { get; } T Current { get; } } }
apache-2.0
C#
da64a7f22c0df36ae927d58e42f98960c9d11671
fix up AssemblyInfo.cs
NFig/NFig.UI,NFig/NFig.UI,NFig/NFig.UI,NFig/NFig.UI
NFig.UI/Properties/AssemblyInfo.cs
NFig.UI/Properties/AssemblyInfo.cs
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("NFig.UI")] [assembly: AssemblyDescription("A User Interface for the NFig settings library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NFig.UI")] [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("4f4da66b-9c9b-4869-a25c-97830f14fbcb")] // 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("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyInformationalVersion("2.0.0.0")]
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("NFig.UI")] [assembly: AssemblyDescription("A User Interface for the NFig settings library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NFig.UI")] [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("4f4da66b-9c9b-4869-a25c-97830f14fbcb")] // 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")] [assembly: AssemblyInformationalVersion("1.0.0.0")]
mit
C#
b83ecea705f551cd07ea883c967cdb55622d87b3
fix net core tests
Fody/Fody,GeertvanHorrik/Fody
Tests/FodyHelpers/PeVerifierTests.cs
Tests/FodyHelpers/PeVerifierTests.cs
using System; using System.IO; using Fody; using Mono.Cecil; using Xunit; #pragma warning disable 618 public class PeVerifierTests : TestBase { [Fact] public void StaticPathResolution() { Assert.True(PeVerifier.FoundPeVerify); } [Fact] public void Should_verify_current_assembly() { #if (NET46) var verify = PeVerifier.Verify(GetAssemblyPath(), System.Linq.Enumerable.Empty<string>(), out var output); #else var verify = PeVerifier.Verify(GetAssemblyPath(), GetNetCoreIgnoreCodes(), out var output); #endif Assert.True(verify); Assert.NotNull(output); Assert.NotEmpty(output); } [Fact] public void Same_assembly_should_not_throw() { var assemblyPath = GetAssemblyPath().ToLowerInvariant(); var newAssemblyPath = assemblyPath.Replace(".dll", "2.dll"); File.Copy(assemblyPath, newAssemblyPath, true); #if (NET46) PeVerifier.ThrowIfDifferent(assemblyPath, newAssemblyPath); #else PeVerifier.ThrowIfDifferent(assemblyPath, newAssemblyPath, ignoreCodes: GetNetCoreIgnoreCodes()); #endif File.Delete(newAssemblyPath); } private static string[] GetNetCoreIgnoreCodes() { return new[] {"0x80070002", "0x80131869"}; } [Fact] public void Invalid_assembly_should_throw() { var assemblyPath = GetAssemblyPath().ToLowerInvariant(); var newAssemblyPath = assemblyPath.Replace(".dll", "2.dll"); File.Copy(assemblyPath, newAssemblyPath, true); using (var moduleDefinition = ModuleDefinition.ReadModule(assemblyPath)) { moduleDefinition.AssemblyReferences.Clear(); moduleDefinition.Write(newAssemblyPath); } Assert.Throws<Exception>(() => PeVerifier.ThrowIfDifferent(assemblyPath, newAssemblyPath)); File.Delete(newAssemblyPath); } static string GetAssemblyPath() { var assembly = typeof(TestBase).Assembly; var uri = new UriBuilder(assembly.CodeBase); return Uri.UnescapeDataString(uri.Path); } }
using System; using System.IO; using System.Linq; using Fody; using Mono.Cecil; using Xunit; #pragma warning disable 618 public class PeVerifierTests : TestBase { [Fact] public void StaticPathResolution() { Assert.True(PeVerifier.FoundPeVerify); } [Fact] public void Should_verify_current_assembly() { var verify = PeVerifier.Verify(GetAssemblyPath(), Enumerable.Empty<string>(), out var output); Assert.True(verify); Assert.NotNull(output); Assert.NotEmpty(output); } [Fact] public void Same_assembly_should_not_throw() { var assemblyPath = GetAssemblyPath().ToLowerInvariant(); var newAssemblyPath = assemblyPath.Replace(".dll", "2.dll"); File.Copy(assemblyPath, newAssemblyPath, true); #if (NET46) PeVerifier.ThrowIfDifferent(assemblyPath, newAssemblyPath); #else PeVerifier.ThrowIfDifferent(assemblyPath, newAssemblyPath, ignoreCodes: new[] {"0x80070002", "0x80131869"}); #endif File.Delete(newAssemblyPath); } [Fact] public void Invalid_assembly_should_throw() { var assemblyPath = GetAssemblyPath().ToLowerInvariant(); var newAssemblyPath = assemblyPath.Replace(".dll", "2.dll"); File.Copy(assemblyPath, newAssemblyPath, true); using (var moduleDefinition = ModuleDefinition.ReadModule(assemblyPath)) { moduleDefinition.AssemblyReferences.Clear(); moduleDefinition.Write(newAssemblyPath); } Assert.Throws<Exception>(() => PeVerifier.ThrowIfDifferent(assemblyPath, newAssemblyPath)); File.Delete(newAssemblyPath); } static string GetAssemblyPath() { var assembly = typeof(TestBase).Assembly; var uri = new UriBuilder(assembly.CodeBase); return Uri.UnescapeDataString(uri.Path); } }
mit
C#
1297632f5b09127a78426cefef03a07a93ed270a
Bump up fade in/out time
JetBrains/resharper-presentation-assistant
src/resharper-presentation-assistant/FadingWpfPopupWindow.cs
src/resharper-presentation-assistant/FadingWpfPopupWindow.cs
using System; using System.Windows; using System.Windows.Media.Animation; using JetBrains.DataFlow; using JetBrains.UI.PopupWindowManager; namespace JetBrains.ReSharper.Plugins.PresentationAssistant { public class FadingWpfPopupWindow : WpfPopupWindow { private static readonly TimeSpan Duration = TimeSpan.FromMilliseconds(300); private readonly Window window; private readonly double opacity; public FadingWpfPopupWindow(LifetimeDefinition lifetimeDefinition, IPopupWindowContext context, PopupWindowMutex mutex, PopupWindowManager popupWindowManager, Window window, double opacity, HideFlags hideFlags = HideFlags.None) : base(lifetimeDefinition, context, mutex, popupWindowManager, window, hideFlags) { this.window = window; this.opacity = opacity; window.AllowsTransparency = true; } protected override void ShowWindowCore() { window.Opacity = 0; window.Visibility = Visibility.Visible; var animation = new DoubleAnimation(opacity, Duration); window.BeginAnimation(UIElement.OpacityProperty, animation); } protected override void HideWindowCore() { var animation = new DoubleAnimation(0, Duration); EventHandler handler = null; handler = (s, e) => { window.Hide(); animation.Completed -= handler; }; animation.Completed += handler; window.BeginAnimation(UIElement.OpacityProperty, animation); } } }
using System; using System.Windows; using System.Windows.Media.Animation; using JetBrains.DataFlow; using JetBrains.UI.PopupWindowManager; namespace JetBrains.ReSharper.Plugins.PresentationAssistant { public class FadingWpfPopupWindow : WpfPopupWindow { private static readonly TimeSpan Duration = TimeSpan.FromMilliseconds(200); private readonly Window window; private readonly double opacity; public FadingWpfPopupWindow(LifetimeDefinition lifetimeDefinition, IPopupWindowContext context, PopupWindowMutex mutex, PopupWindowManager popupWindowManager, Window window, double opacity, HideFlags hideFlags = HideFlags.None) : base(lifetimeDefinition, context, mutex, popupWindowManager, window, hideFlags) { this.window = window; this.opacity = opacity; window.AllowsTransparency = true; } protected override void ShowWindowCore() { window.Opacity = 0; window.Visibility = Visibility.Visible; var animation = new DoubleAnimation(opacity, Duration); window.BeginAnimation(UIElement.OpacityProperty, animation); } protected override void HideWindowCore() { var animation = new DoubleAnimation(0, Duration); EventHandler handler = null; handler = (s, e) => { window.Hide(); animation.Completed -= handler; }; animation.Completed += handler; window.BeginAnimation(UIElement.OpacityProperty, animation); } } }
apache-2.0
C#
4c3160e6e23290ce96b8a6ad765923156ab4f890
Update RectangleShapeControl.xaml.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D
src/Core2D.UI/Views/Shapes/RectangleShapeControl.xaml.cs
src/Core2D.UI/Views/Shapes/RectangleShapeControl.xaml.cs
using Avalonia.Controls; using Avalonia.Markup.Xaml; using Core2D.Editor; using Core2D.Editors; using Core2D.Shapes; using Core2D.UI.Views.Editors; namespace Core2D.UI.Views.Shapes { /// <summary> /// Interaction logic for <see cref="RectangleShapeControl"/> xaml. /// </summary> public class RectangleShapeControl : UserControl { /// <summary> /// Initializes a new instance of the <see cref="RectangleShapeControl"/> class. /// </summary> public RectangleShapeControl() { InitializeComponent(); } /// <summary> /// Initialize the Xaml components. /// </summary> private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } /// <summary> /// Edit shape text binding. /// </summary> public void OnEditTextBinding(object shape) { if (this.VisualRoot is TopLevel topLevel && topLevel.DataContext is IProjectEditor editor && shape is ITextShape text) { var window = new TextBindingEditorWindow() { DataContext = new TextBindingEditor() { Editor = editor, Text = text } }; window.ShowDialog(topLevel as Window); } } } }
using Avalonia.Controls; using Avalonia.Markup.Xaml; using Core2D.Editor; using Core2D.Editors; using Core2D.Shapes; using Core2D.UI.Views.Editors; namespace Core2D.UI.Views.Shapes { /// <summary> /// Interaction logic for <see cref="RectangleShapeControl"/> xaml. /// </summary> public class RectangleShapeControl : UserControl { /// <summary> /// Initializes a new instance of the <see cref="RectangleShapeControl"/> class. /// </summary> public RectangleShapeControl() { InitializeComponent(); } /// <summary> /// Initialize the Xaml components. /// </summary> private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } /// <summary> /// Edit shape text binding. /// </summary> public void OnEditTextBinding(object shape) { if (this.VisualRoot is TopLevel topLevel && topLevel.DataContext is IProjectEditor editor && shape is ITextShape text) { var window = new TextBindingEditorWindow() { DataContext = new TextBindingEditor() { Editor = editor, Text = text, CaretIndex = text.Text.Length } }; window.ShowDialog(topLevel as Window); } } } }
mit
C#
f43a80a92f58ebeb41ac93aaf6bcaf941e76ca06
remove unneeded comments
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
src/FilterLists.Services/Implementations/TableService.cs
src/FilterLists.Services/Implementations/TableService.cs
using System.IO; using System.Net.Http; using System.Threading.Tasks; using CsvHelper; using FilterLists.Data.Models.Implementations; using FilterLists.Data.Repositories.Contracts; using FilterLists.Services.Contracts; namespace FilterLists.Services.Implementations { public class TableService : ITableService { private readonly ITableCsvRepository _tableCsvRepository; public TableService(ITableCsvRepository tableCsvRepository) { _tableCsvRepository = tableCsvRepository; } public void UpdateTables() { UpdateListTable(); } public void UpdateListTable() { var localCsvFilePath = FetchFile(_tableCsvRepository.GetUrlByName("List"), "List").Result; TextReader textReader = File.OpenText(localCsvFilePath); var csv = new CsvReader(textReader); csv.Configuration.MissingFieldFound = null; var records = csv.GetRecords<List>(); //TODO: delete file when finished } private static async Task<string> FetchFile(string url, string fileName) { var response = await new HttpClient().GetAsync(url); response.EnsureSuccessStatusCode(); var path = Path.Combine(Directory.GetCurrentDirectory(), "csv"); Directory.CreateDirectory(path); var file = Path.Combine(path, fileName + ".csv"); using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None)) { await response.Content.CopyToAsync(fileStream); } return file; } } }
using System.IO; using System.Net.Http; using System.Threading.Tasks; using CsvHelper; using FilterLists.Data.Models.Implementations; using FilterLists.Data.Repositories.Contracts; using FilterLists.Services.Contracts; namespace FilterLists.Services.Implementations { public class TableService : ITableService { private readonly ITableCsvRepository _tableCsvRepository; public TableService(ITableCsvRepository tableCsvRepository) { _tableCsvRepository = tableCsvRepository; } /// <summary> /// update all tables via .CSVs from GitHub /// </summary> public void UpdateTables() { UpdateListTable(); } /// <summary> /// update table via List.csv from GitHub /// </summary> public void UpdateListTable() { var localCsvFilePath = FetchFile(_tableCsvRepository.GetUrlByName("List"), "List").Result; TextReader textReader = File.OpenText(localCsvFilePath); var csv = new CsvReader(textReader); csv.Configuration.MissingFieldFound = null; var records = csv.GetRecords<List>(); //TODO: delete file when finished } /// <summary> /// fetch file as string from internet /// </summary> /// <param name="url">URL of file to fetch</param> /// <param name="fileName">name to save file as</param> /// <returns>string of file</returns> private static async Task<string> FetchFile(string url, string fileName) { var response = await new HttpClient().GetAsync(url); response.EnsureSuccessStatusCode(); var path = Path.Combine(Directory.GetCurrentDirectory(), "csv"); Directory.CreateDirectory(path); var file = Path.Combine(path, fileName + ".csv"); using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None)) { await response.Content.CopyToAsync(fileStream); } return file; } } }
mit
C#
07596cd837dfcffab17b7a5e2d59f0a60c944cfb
Update REST API version to v3
arthurrump/Zermelo.API
Zermelo.API/Services/UrlBuilder.cs
Zermelo.API/Services/UrlBuilder.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Zermelo.API.Interfaces; using Zermelo.API.Services.Interfaces; namespace Zermelo.API.Services { internal class UrlBuilder : IUrlBuilder { const string _https = "https://"; const string _baseUrl = "zportal.nl/api"; const string _apiVersion = "v3"; const string _accessToken = "access_token"; public string GetAuthenticatedUrl(IAuthentication auth, string endpoint, Dictionary<string, string> options = null) { string url = GetUrl(auth.Host, endpoint, options); if (url.Contains("?")) url += "&"; else url += "?"; url += $"{_accessToken}={auth.Token}"; return url; } public string GetUrl(string host, string endpoint, Dictionary<string, string> options = null) { string url = $"{_https}{host}.{_baseUrl}/{_apiVersion}/{endpoint}"; if (options != null) { url += "?"; foreach (var x in options) { url += $"{x.Key}={x.Value}&"; } url = url.TrimEnd('&'); } return url; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Zermelo.API.Interfaces; using Zermelo.API.Services.Interfaces; namespace Zermelo.API.Services { internal class UrlBuilder : IUrlBuilder { const string _https = "https://"; const string _baseUrl = "zportal.nl/api"; const string _apiVersion = "v2"; const string _accessToken = "access_token"; public string GetAuthenticatedUrl(IAuthentication auth, string endpoint, Dictionary<string, string> options = null) { string url = GetUrl(auth.Host, endpoint, options); if (url.Contains("?")) url += "&"; else url += "?"; url += $"{_accessToken}={auth.Token}"; return url; } public string GetUrl(string host, string endpoint, Dictionary<string, string> options = null) { string url = $"{_https}{host}.{_baseUrl}/{_apiVersion}/{endpoint}"; if (options != null) { url += "?"; foreach (var x in options) { url += $"{x.Key}={x.Value}&"; } url = url.TrimEnd('&'); } return url; } } }
mit
C#
fcaf41e724763853828c8933af6a5139227ddbd8
Fix message.
msgpack/msgpack-cli,scopely/msgpack-cli,modulexcite/msgpack-cli,modulexcite/msgpack-cli,msgpack/msgpack-cli,undeadlabs/msgpack-cli,scopely/msgpack-cli,undeadlabs/msgpack-cli
cli/test/MsgPack.UnitTest/Properties/AssemblyInfo.cs
cli/test/MsgPack.UnitTest/Properties/AssemblyInfo.cs
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010 FUJIWARA, Yusuke // // 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 -- License Terms -- using System; using System.Reflection; using System.Runtime.InteropServices; using System.Resources; [assembly: AssemblyTitle( "Unit test of MessagePack for CLI" )] [assembly: AssemblyDescription( "Unit test of MessagePack CLI binding" )] [assembly: AssemblyConfiguration( "Develop" )] [assembly: AssemblyProduct( "MessagePack" )] [assembly: AssemblyCopyright( "Copyright © FUJIWARA, Yusuke 2010" )] [assembly: ComVisible( false )] [assembly: CLSCompliant( true )] [assembly: NeutralResourcesLanguage( "en-US" )] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "0.1.0.0" )] [assembly: AssemblyInformationalVersion( "0.1" )]
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010 FUJIWARA, Yusuke // // 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 -- License Terms -- using System; using System.Reflection; using System.Runtime.InteropServices; using System.Resources; [assembly: AssemblyTitle( "Unit test of MessagePack for C#" )] [assembly: AssemblyDescription( "Unit test of MessagePack C# binding" )] [assembly: AssemblyConfiguration( "Develop" )] [assembly: AssemblyProduct( "MessagePack" )] [assembly: AssemblyCopyright( "Copyright © FUJIWARA, Yusuke 2010" )] [assembly: ComVisible( false )] [assembly: CLSCompliant( true )] [assembly: NeutralResourcesLanguage( "en-US" )] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "0.1.0.0" )] [assembly: AssemblyInformationalVersion( "0.1" )]
apache-2.0
C#
9aa4bd0c8ca3d2d23fcf8eef1d972c593c8b06aa
Remove Console debug line that broke logic
tgstation/tgstation-server-tools,tgstation/tgstation-server,tgstation/tgstation-server
src/Tgstation.Server.Host/Database/MySqlDatabaseContext.cs
src/Tgstation.Server.Host/Database/MySqlDatabaseContext.cs
using Microsoft.EntityFrameworkCore; using Pomelo.EntityFrameworkCore.MySql.Infrastructure; using System; using Tgstation.Server.Host.Configuration; namespace Tgstation.Server.Host.Database { /// <summary> /// <see cref="DatabaseContext"/> for MySQL /// </summary> sealed class MySqlDatabaseContext : DatabaseContext { /// <inheritdoc /> protected override DeleteBehavior RevInfoCompileJobDeleteBehavior => DeleteBehavior.Cascade; /// <summary> /// Construct a <see cref="MySqlDatabaseContext"/> /// </summary> /// <param name="dbContextOptions">The <see cref="DbContextOptions{TContext}"/> for the <see cref="DatabaseContext"/></param> public MySqlDatabaseContext(DbContextOptions<MySqlDatabaseContext> dbContextOptions) : base(dbContextOptions) { } /// <summary> /// Configure the <see cref="MySqlDatabaseContext"/>. /// </summary> /// <param name="options">The <see cref="DbContextOptionsBuilder"/> to configure.</param> /// <param name="databaseConfiguration">The <see cref="DatabaseConfiguration"/>.</param> public static void ConfigureWith(DbContextOptionsBuilder options, DatabaseConfiguration databaseConfiguration) { if (options == null) throw new ArgumentNullException(nameof(options)); if (databaseConfiguration == null) throw new ArgumentNullException(nameof(databaseConfiguration)); if (databaseConfiguration.DatabaseType != DatabaseType.MariaDB && databaseConfiguration.DatabaseType != DatabaseType.MySql) throw new InvalidOperationException($"Invalid DatabaseType for {nameof(MySqlDatabaseContext)}!"); options.UseMySql( databaseConfiguration.ConnectionString, mySqlOptions => { mySqlOptions.EnableRetryOnFailure(); if (!String.IsNullOrEmpty(databaseConfiguration.ServerVersion)) mySqlOptions.ServerVersion( Version.Parse(databaseConfiguration.ServerVersion), databaseConfiguration.DatabaseType == DatabaseType.MariaDB ? ServerType.MariaDb : ServerType.MySql); }); } } }
using Microsoft.EntityFrameworkCore; using Pomelo.EntityFrameworkCore.MySql.Infrastructure; using System; using Tgstation.Server.Host.Configuration; namespace Tgstation.Server.Host.Database { /// <summary> /// <see cref="DatabaseContext"/> for MySQL /// </summary> sealed class MySqlDatabaseContext : DatabaseContext { /// <inheritdoc /> protected override DeleteBehavior RevInfoCompileJobDeleteBehavior => DeleteBehavior.Cascade; /// <summary> /// Construct a <see cref="MySqlDatabaseContext"/> /// </summary> /// <param name="dbContextOptions">The <see cref="DbContextOptions{TContext}"/> for the <see cref="DatabaseContext"/></param> public MySqlDatabaseContext(DbContextOptions<MySqlDatabaseContext> dbContextOptions) : base(dbContextOptions) { } /// <summary> /// Configure the <see cref="MySqlDatabaseContext"/>. /// </summary> /// <param name="options">The <see cref="DbContextOptionsBuilder"/> to configure.</param> /// <param name="databaseConfiguration">The <see cref="DatabaseConfiguration"/>.</param> public static void ConfigureWith(DbContextOptionsBuilder options, DatabaseConfiguration databaseConfiguration) { if (options == null) throw new ArgumentNullException(nameof(options)); if (databaseConfiguration == null) throw new ArgumentNullException(nameof(databaseConfiguration)); if (databaseConfiguration.DatabaseType != DatabaseType.MariaDB && databaseConfiguration.DatabaseType != DatabaseType.MySql) throw new InvalidOperationException($"Invalid DatabaseType for {nameof(MySqlDatabaseContext)}!"); options.UseMySql( databaseConfiguration.ConnectionString, mySqlOptions => { mySqlOptions.EnableRetryOnFailure(); if (!String.IsNullOrEmpty(databaseConfiguration.ServerVersion)) Console.WriteLine("SQLVERSION: " + databaseConfiguration.DatabaseType); mySqlOptions.ServerVersion( Version.Parse(databaseConfiguration.ServerVersion), databaseConfiguration.DatabaseType == DatabaseType.MariaDB ? ServerType.MariaDb : ServerType.MySql); }); } } }
agpl-3.0
C#