Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Update to deal with breaking Features change in httpabstraction
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Features; namespace Glimpse.Server.Web { public class RequestAuthorizerAllowRemote : IRequestAuthorizer { private readonly IAllowRemoteProvider _allowRemoteProvider; public RequestAuthorizerAllowRemote(IAllowRemoteProvider allowRemoteProvider) { _allowRemoteProvider = allowRemoteProvider; } public bool AllowUser(HttpContext context) { var connectionFeature = context.GetFeature<IHttpConnectionFeature>(); return _allowRemoteProvider.AllowRemote || (connectionFeature != null && connectionFeature.IsLocal); } } }
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Features; namespace Glimpse.Server.Web { public class RequestAuthorizerAllowRemote : IRequestAuthorizer { private readonly IAllowRemoteProvider _allowRemoteProvider; public RequestAuthorizerAllowRemote(IAllowRemoteProvider allowRemoteProvider) { _allowRemoteProvider = allowRemoteProvider; } public bool AllowUser(HttpContext context) { var connectionFeature = context.Features.Get<IHttpConnectionFeature>(); return _allowRemoteProvider.AllowRemote || (connectionFeature != null && connectionFeature.IsLocal); } } }
Make a little section of code easier to debug
using System.Linq; using ZBuildLights.Core.Models; namespace ZBuildLights.Core.Services { public class UnassignedLightService : IUnassignedLightService { private readonly IZWaveNetwork _network; public UnassignedLightService(IZWaveNetwork network) { _network = network; } public void SetUnassignedLights(MasterModel masterModel) { var allLights = masterModel.AllLights; var allSwitches = _network.GetAllSwitches(); var switchesAlreadyInAProject = allSwitches .Where(sw => allLights.Any(l =>l.ZWaveIdentity.Equals(sw.ZWaveIdentity)) ).ToArray(); var newSwitches = allSwitches.Except(switchesAlreadyInAProject); var newLights = newSwitches.Select(x => new Light(x.ZWaveIdentity)).ToArray(); masterModel.AddUnassignedLights(newLights); } } }
using System.Linq; using ZBuildLights.Core.Models; namespace ZBuildLights.Core.Services { public class UnassignedLightService : IUnassignedLightService { private readonly IZWaveNetwork _network; public UnassignedLightService(IZWaveNetwork network) { _network = network; } public void SetUnassignedLights(MasterModel masterModel) { var allLights = masterModel.AllLights; var allSwitches = _network.GetAllSwitches(); var switchesAlreadyInAProject = allSwitches .Where(sw => allLights.Any(l => { var lightIdentity = l.ZWaveIdentity; var switchIdentity = sw.ZWaveIdentity; return lightIdentity.Equals(switchIdentity); }) ).ToArray(); var newSwitches = allSwitches.Except(switchesAlreadyInAProject); var newLights = newSwitches.Select(x => new Light(x.ZWaveIdentity)).ToArray(); masterModel.AddUnassignedLights(newLights); } } }
Add `using System` to fix this file being detected as Smalltalk
namespace ValveResourceFormat { public enum VTexFormat { #pragma warning disable 1591 UNKNOWN = 0, DXT1 = 1, DXT5 = 2, I8 = 3, // TODO: Not used in dota RGBA8888 = 4, R16 = 5, // TODO: Not used in dota RG1616 = 6, // TODO: Not used in dota RGBA16161616 = 7, // TODO: Not used in dota R16F = 8, // TODO: Not used in dota RG1616F = 9, // TODO: Not used in dota RGBA16161616F = 10, // TODO: Not used in dota R32F = 11, // TODO: Not used in dota RG3232F = 12, // TODO: Not used in dota RGB323232F = 13, // TODO: Not used in dota RGBA32323232F = 14, // TODO: Not used in dota PNG = 16 // TODO: resourceinfo doesn't know about this #pragma warning restore 1591 } }
using System; namespace ValveResourceFormat { public enum VTexFormat { #pragma warning disable 1591 UNKNOWN = 0, DXT1 = 1, DXT5 = 2, I8 = 3, // TODO: Not used in dota RGBA8888 = 4, R16 = 5, // TODO: Not used in dota RG1616 = 6, // TODO: Not used in dota RGBA16161616 = 7, // TODO: Not used in dota R16F = 8, // TODO: Not used in dota RG1616F = 9, // TODO: Not used in dota RGBA16161616F = 10, // TODO: Not used in dota R32F = 11, // TODO: Not used in dota RG3232F = 12, // TODO: Not used in dota RGB323232F = 13, // TODO: Not used in dota RGBA32323232F = 14, // TODO: Not used in dota PNG = 16 // TODO: resourceinfo doesn't know about this #pragma warning restore 1591 } }
Update assembly info informational version
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("DataDogCSharp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DataDogCSharp")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bdc14997-0981-470e-9497-e0fd00289ad6")] // 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("DataDogCSharp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DataDogCSharp")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bdc14997-0981-470e-9497-e0fd00289ad6")] // 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("0.0.2-beta")]
Compress only the vessel proto. TEST
using Lidgren.Network; using LmpCommon.Message.Types; namespace LmpCommon.Message.Data.Vessel { public class VesselProtoMsgData : VesselBaseMsgData { internal VesselProtoMsgData() { } public int NumBytes; public byte[] Data = new byte[0]; public override VesselMessageType VesselMessageType => VesselMessageType.Proto; public override string ClassName { get; } = nameof(VesselProtoMsgData); internal override void InternalSerialize(NetOutgoingMessage lidgrenMsg) { base.InternalSerialize(lidgrenMsg); lidgrenMsg.Write(NumBytes); lidgrenMsg.Write(Data, 0, NumBytes); } internal override void InternalDeserialize(NetIncomingMessage lidgrenMsg) { base.InternalDeserialize(lidgrenMsg); NumBytes = lidgrenMsg.ReadInt32(); if (Data.Length < NumBytes) Data = new byte[NumBytes]; lidgrenMsg.ReadBytes(Data, 0, NumBytes); } internal override int InternalGetMessageSize() { return base.InternalGetMessageSize() + sizeof(int) + sizeof(byte) * NumBytes; } } }
using Lidgren.Network; using LmpCommon.Message.Types; namespace LmpCommon.Message.Data.Vessel { public class VesselProtoMsgData : VesselBaseMsgData { internal VesselProtoMsgData() { } public override bool CompressCondition => true; public int NumBytes; public byte[] Data = new byte[0]; public override VesselMessageType VesselMessageType => VesselMessageType.Proto; public override string ClassName { get; } = nameof(VesselProtoMsgData); internal override void InternalSerialize(NetOutgoingMessage lidgrenMsg) { base.InternalSerialize(lidgrenMsg); if (CompressCondition) { var compressedData = CachedQuickLz.CachedQlz.Compress(Data, NumBytes, out NumBytes); CachedQuickLz.ArrayPool<byte>.Recycle(Data); Data = compressedData; } lidgrenMsg.Write(NumBytes); lidgrenMsg.Write(Data, 0, NumBytes); if (CompressCondition) { CachedQuickLz.ArrayPool<byte>.Recycle(Data); } } internal override void InternalDeserialize(NetIncomingMessage lidgrenMsg) { base.InternalDeserialize(lidgrenMsg); NumBytes = lidgrenMsg.ReadInt32(); if (Data.Length < NumBytes) Data = new byte[NumBytes]; lidgrenMsg.ReadBytes(Data, 0, NumBytes); if (Compressed) { var decompressedData = CachedQuickLz.CachedQlz.Decompress(Data, out NumBytes); CachedQuickLz.ArrayPool<byte>.Recycle(Data); Data = decompressedData; } } internal override int InternalGetMessageSize() { return base.InternalGetMessageSize() + sizeof(int) + sizeof(byte) * NumBytes; } } }
Revert "Fix for an odd crash we were experiencing"
using System; namespace Xamarin.Forms.Xaml { [ContentProperty("TypeName")] public class TypeExtension : IMarkupExtension<Type> { public string TypeName { get; set; } public Type ProvideValue(IServiceProvider serviceProvider) { if (serviceProvider == null) throw new ArgumentNullException("serviceProvider"); var typeResolver = serviceProvider.GetService(typeof (IXamlTypeResolver)) as IXamlTypeResolver; if (typeResolver == null) throw new ArgumentException("No IXamlTypeResolver in IServiceProvider"); //HACK: this fixes an extreme case in our app where we had our version of ItemsView in a ListView header, just taking this out for now and seeing what this will break if (string.IsNullOrEmpty(TypeName)) return null; return typeResolver.Resolve(TypeName, serviceProvider); } object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider) { return (this as IMarkupExtension<Type>).ProvideValue(serviceProvider); } } }
using System; namespace Xamarin.Forms.Xaml { [ContentProperty("TypeName")] public class TypeExtension : IMarkupExtension<Type> { public string TypeName { get; set; } public Type ProvideValue(IServiceProvider serviceProvider) { if (serviceProvider == null) throw new ArgumentNullException("serviceProvider"); var typeResolver = serviceProvider.GetService(typeof (IXamlTypeResolver)) as IXamlTypeResolver; if (typeResolver == null) throw new ArgumentException("No IXamlTypeResolver in IServiceProvider"); return typeResolver.Resolve(TypeName, serviceProvider); } object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider) { return (this as IMarkupExtension<Type>).ProvideValue(serviceProvider); } } }
Test project model color enforcing.
using System; using NUnit.Framework; using Toggl.Phoebe.Data.NewModels; namespace Toggl.Phoebe.Tests.Data.Models { [TestFixture] public class ProjectModelTest : ModelTest<ProjectModel> { } }
using System; using NUnit.Framework; using Toggl.Phoebe.Data.DataObjects; using Toggl.Phoebe.Data.NewModels; namespace Toggl.Phoebe.Tests.Data.Models { [TestFixture] public class ProjectModelTest : ModelTest<ProjectModel> { [Test] public void TestColorEnforcing () { var project = new ProjectModel (new ProjectData () { Id = Guid.NewGuid (), Color = 12345, }); // Make sure that we return the underlying color Assert.AreEqual (12345, project.Color); Assert.That (() => project.GetHexColor (), Throws.Nothing); // And that we enforce to the colors we know of project.Color = 54321; Assert.AreNotEqual (54321, project.Color); Assert.AreEqual (54321 % ProjectModel.HexColors.Length, project.Color); Assert.That (() => project.GetHexColor (), Throws.Nothing); } } }
Decrease number of operations to run to decrease benchmark duration from few hours to about 30 minutes
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="BenchmarkBase.cs" company="Catel development team"> // Copyright (c) 2008 - 2017 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel.Benchmarks { using BenchmarkDotNet.Attributes.Jobs; using BenchmarkDotNet.Engines; // Uncomment to make all benchmarks slower (but probably more accurate) [SimpleJob(RunStrategy.Throughput, launchCount: 1, warmupCount: 2, targetCount: 10, invocationCount: 10)] public abstract class BenchmarkBase { } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="BenchmarkBase.cs" company="Catel development team"> // Copyright (c) 2008 - 2017 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel.Benchmarks { using BenchmarkDotNet.Attributes.Jobs; using BenchmarkDotNet.Engines; // Uncomment to make all benchmarks slower (but probably more accurate) [SimpleJob(RunStrategy.Throughput, launchCount: 1, warmupCount: 3, targetCount: 10, invocationCount: 500)] public abstract class BenchmarkBase { } }
Clear IsBusy on Wallet load error
using AvalonStudio.Extensibility; using ReactiveUI; using Splat; using System; using System.Linq; using System.Reactive; using System.Reactive.Linq; using System.Threading; using WalletWasabi.Gui.Helpers; using WalletWasabi.Logging; using WalletWasabi.Wallets; namespace WalletWasabi.Gui.Controls.WalletExplorer { public class ClosedWalletViewModel : WalletViewModelBase { public ClosedWalletViewModel(Wallet wallet) : base(wallet) { OpenWalletCommand = ReactiveCommand.CreateFromTask(async () => { IsBusy = true; try { var global = Locator.Current.GetService<Global>(); if (!await global.WaitForInitializationCompletedAsync(CancellationToken.None)) { return; } await global.WalletManager.StartWalletAsync(Wallet); } catch (Exception e) { NotificationHelpers.Error($"Error loading Wallet: {Title}"); Logger.LogError(e.Message); } }, this.WhenAnyValue(x => x.IsBusy).Select(x => !x)); } public ReactiveCommand<Unit, Unit> OpenWalletCommand { get; } } }
using AvalonStudio.Extensibility; using ReactiveUI; using Splat; using System; using System.Linq; using System.Reactive; using System.Reactive.Linq; using System.Threading; using WalletWasabi.Gui.Helpers; using WalletWasabi.Logging; using WalletWasabi.Wallets; namespace WalletWasabi.Gui.Controls.WalletExplorer { public class ClosedWalletViewModel : WalletViewModelBase { public ClosedWalletViewModel(Wallet wallet) : base(wallet) { OpenWalletCommand = ReactiveCommand.CreateFromTask(async () => { IsBusy = true; try { var global = Locator.Current.GetService<Global>(); if (!await global.WaitForInitializationCompletedAsync(CancellationToken.None)) { return; } await global.WalletManager.StartWalletAsync(Wallet); } catch (Exception e) { NotificationHelpers.Error($"Error loading Wallet: {Title}"); Logger.LogError(e.Message); } finally { IsBusy = false; } }, this.WhenAnyValue(x => x.IsBusy).Select(x => !x)); } public ReactiveCommand<Unit, Unit> OpenWalletCommand { get; } } }
Update console to show parsing duration
using DemoParser_Core; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoParser_Console { class Program { static void Main(string[] args) { Console.WriteLine(DateTime.Now); Stream inputStream = new FileStream(args[0], FileMode.Open); DemoParser parser = new DemoParser(inputStream); parser.ParseDemo(true); Console.WriteLine(DateTime.Now); Console.ReadKey(); } } }
using DemoParser_Core; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoParser_Console { class Program { static void Main(string[] args) { DateTime begin; DateTime end; Stream inputStream = new FileStream(args[0], FileMode.Open); Console.WriteLine("Parsing..."); begin = DateTime.Now; DemoParser parser = new DemoParser(inputStream); parser.ParseDemo(true); end = DateTime.Now; Console.WriteLine(String.Format("Started: {0}", begin.ToString("HH:mm:ss.ffffff"))); Console.WriteLine(String.Format("Finished: {0}", end.ToString("HH:mm:ss.ffffff"))); Console.WriteLine(String.Format("\nTotal: {0}", (end - begin))); Console.ReadKey(); } } }
Add unit test for all action method on CropController
using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using NUnit.Framework; using Oogstplanner.Services; using Oogstplanner.Controllers; using Oogstplanner.Models; using Oogstplanner.Repositories; namespace Oogstplanner.Tests { [TestFixture] public class CropControllerTest { private CropController controller; [TestFixtureSetUp] public void Setup() { // Initialize a fake database with one crop. var db = new FakeOogstplannerContext { Crops = { new Crop { Id = 1, Name = "Broccoli", SowingMonths = Month.May ^ Month.June ^ Month.October ^ Month.November } } }; this.controller = new CropController(new CropProvider(new CropRepository(db))); } [Test] public void Controllers_Crop_Index_AllCrops() { // Arrange var expectedResult = "Broccoli"; // Act var viewResult = controller.Index(); var actualResult = ((IEnumerable<Crop>)viewResult.ViewData.Model).Single().Name; // Assert Assert.AreEqual(expectedResult, actualResult, "Since there is only a broccoli in the database the index method should return it."); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using NUnit.Framework; using Oogstplanner.Services; using Oogstplanner.Controllers; using Oogstplanner.Models; using Oogstplanner.Repositories; namespace Oogstplanner.Tests { [TestFixture] public class CropControllerTest { private CropController controller; [TestFixtureSetUp] public void Setup() { // Initialize a fake database with one crop. var db = new FakeOogstplannerContext { Crops = { new Crop { Id = 1, Name = "Broccoli", SowingMonths = Month.May ^ Month.June ^ Month.October ^ Month.November } } }; this.controller = new CropController(new CropProvider(new CropRepository(db))); } [Test] public void Controllers_Crop_Index_AllCrops() { // Arrange const string expectedResult = "Broccoli"; // Act var viewResult = controller.Index(); var actualResult = ((IEnumerable<Crop>)viewResult.ViewData.Model).Single().Name; // Assert Assert.AreEqual(expectedResult, actualResult, "Since there is only a broccoli in the database the index method should return it."); } [Test] public void Controllers_Crop_All() { // Arrange const string expectedResult = "Broccoli"; // Act var viewResult = controller.All(); var actualResult = ((ContentResult)viewResult).Content; // Assert Assert.IsTrue(actualResult.Contains(expectedResult), "Since there is a broccoli in the database the JSON string returned by the all " + "method should contain it."); } } }
Fix login link on register page
@{ ViewBag.Title = "Registreer je vandaag bij de Oogstplanner"; } <div class="flowtype-area"> <!-- START RESPONSIVE RECTANGLE LAYOUT --> <!-- Top bar --> <div id="top"> </div> <!-- Fixed main screen --> <div id="login" class="bg imglogin"> <div class="row"> <div class="mainbox col-md-12 col-sm-12 col-xs-12"> <div class="panel panel-info"> <div class="panel-heading"> <div class="panel-title">Registreer je vandaag bij de Oogstplanner</div> <div class="panel-side-link"> <a id="signin-link" href="#">Inloggen</a> </div> </div> <div class="panel-body"> @{ Html.RenderPartial("_RegisterForm"); } </div><!-- End panel body --> </div><!-- End panel --> </div><!-- End signup box --> </div><!-- End row --> </div><!-- End main login div --> <!-- END RESPONSIVE RECTANGLES LAYOUT --> </div><!-- End flowtype-area -->
@{ ViewBag.Title = "Registreer je vandaag bij de Oogstplanner"; } <div class="flowtype-area"> <!-- START RESPONSIVE RECTANGLE LAYOUT --> <!-- Top bar --> <div id="top"> </div> <!-- Fixed main screen --> <div id="login" class="bg imglogin"> <div class="row"> <div class="mainbox col-md-12 col-sm-12 col-xs-12"> <div class="panel panel-info"> <div class="panel-heading"> <div class="panel-title">Registreer je vandaag bij de Oogstplanner</div> <div class="panel-side-link"> @Html.ActionLink("Inloggen", "Login") </div> </div> <div class="panel-body"> @{ Html.RenderPartial("_RegisterForm"); } </div><!-- End panel body --> </div><!-- End panel --> </div><!-- End signup box --> </div><!-- End row --> </div><!-- End main login div --> <!-- END RESPONSIVE RECTANGLES LAYOUT --> </div><!-- End flowtype-area -->
Split the CanCombineTwoNs test code into two line.
using sdmap.Runtime; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace sdmap.test.IntegratedTest { public class NamespaceTest { [Fact] public void CanReferenceOtherInOneNamespace() { var code = "namespace ns{sql v1{1#include<v2>} sql v2{2}}"; var rt = new SdmapRuntime(); rt.AddSourceCode(code); var result = rt.Emit("ns.v1", new { A = true }); Assert.Equal("12", result); } [Fact] public void CanCombineTwoNs() { var code = "namespace ns1{sql sql{1#include<ns2.sql>}} namespace ns2{sql sql{2}}"; var rt = new SdmapRuntime(); rt.AddSourceCode(code); var result = rt.Emit("ns1.sql", null); Assert.Equal("12", result); } } }
using sdmap.Runtime; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace sdmap.test.IntegratedTest { public class NamespaceTest { [Fact] public void CanReferenceOtherInOneNamespace() { var code = "namespace ns{sql v1{1#include<v2>} sql v2{2}}"; var rt = new SdmapRuntime(); rt.AddSourceCode(code); var result = rt.Emit("ns.v1", new { A = true }); Assert.Equal("12", result); } [Fact] public void CanCombineTwoNs() { var code = "namespace ns1{sql sql{1#include<ns2.sql>}} \r\n" + "namespace ns2{sql sql{2}}"; var rt = new SdmapRuntime(); rt.AddSourceCode(code); var result = rt.Emit("ns1.sql", null); Assert.Equal("12", result); } } }
Write to console on failed apu write
namespace JAGBE.GB.Computation { internal sealed class Apu { private byte NR50; private byte NR51; private byte NR52; internal void Clear() { this.NR50 = 0; this.NR51 = 0; } internal byte GetRegister(byte num) { switch (num) { case 0x24: return this.NR50; case 0x25: return this.NR51; case 0x26: return (byte)(this.NR52 | 0x70); default: return 0xFF; } } internal bool SetRegister(byte num, byte value) { switch (num) { case 0x24: this.NR50 = value; return true; case 0x25: this.NR51 = value; return true; case 0x26: this.NR52 = (byte)((value & 0x80) | (this.NR52 & 0x7F)); if (!this.NR52.GetBit(7)) { Clear(); } return true; default: return false; } } } }
using System; namespace JAGBE.GB.Computation { internal sealed class Apu { private byte NR50; private byte NR51; private byte NR52; internal void Clear() { this.NR50 = 0; this.NR51 = 0; } internal byte GetRegister(byte num) { switch (num) { case 0x24: return this.NR50; case 0x25: return this.NR51; case 0x26: return (byte)(this.NR52 | 0x70); default: Console.WriteLine("Possible bad Read from ALU 0x" + num.ToString("X2") + " (reg number)"); return 0xFF; } } internal bool SetRegister(byte num, byte value) { switch (num) { case 0x24: this.NR50 = value; return true; case 0x25: this.NR51 = value; return true; case 0x26: this.NR52 = (byte)((value & 0x80) | (this.NR52 & 0x7F)); if (!this.NR52.GetBit(7)) { Clear(); } return true; default: return false; } } } }
Fix lock of scrapes list
using System; using System.Collections.Generic; using System.Text; using MonoTorrent.Client; using MonoTorrent.Common; namespace MonoTorrent.Tracker { public class RequestMonitor { #region Member Variables private SpeedMonitor announces; private SpeedMonitor scrapes; #endregion Member Variables #region Properties public int AnnounceRate { get { return announces.Rate; } } public int ScrapeRate { get { return scrapes.Rate; } } public int TotalAnnounces { get { return (int)announces.Total; } } public int TotalScrapes { get { return (int)scrapes.Total; } } #endregion Properties #region Constructors public RequestMonitor() { announces = new SpeedMonitor(); scrapes = new SpeedMonitor(); } #endregion Constructors #region Methods internal void AnnounceReceived() { lock (announces) announces.AddDelta(1); } internal void ScrapeReceived() { lock (announces) scrapes.AddDelta(1); } #endregion Methods internal void Tick() { lock (announces) this.announces.Tick(); lock (scrapes) this.scrapes.Tick(); } } }
using System; using System.Collections.Generic; using System.Text; using MonoTorrent.Client; using MonoTorrent.Common; namespace MonoTorrent.Tracker { public class RequestMonitor { #region Member Variables private SpeedMonitor announces; private SpeedMonitor scrapes; #endregion Member Variables #region Properties public int AnnounceRate { get { return announces.Rate; } } public int ScrapeRate { get { return scrapes.Rate; } } public int TotalAnnounces { get { return (int)announces.Total; } } public int TotalScrapes { get { return (int)scrapes.Total; } } #endregion Properties #region Constructors public RequestMonitor() { announces = new SpeedMonitor(); scrapes = new SpeedMonitor(); } #endregion Constructors #region Methods internal void AnnounceReceived() { lock (announces) announces.AddDelta(1); } internal void ScrapeReceived() { lock (scrapes) scrapes.AddDelta(1); } #endregion Methods internal void Tick() { lock (announces) this.announces.Tick(); lock (scrapes) this.scrapes.Tick(); } } }
Fix broken (admittedly crappy) test.
using NUnit.Framework; using TeamCityBuildChanges.Output; using TeamCityBuildChanges.Testing; namespace TeamCityBuildChanges.Tests { [TestFixture] public class HtmlOutputTests { [Test] public void CanRenderSimpleTemplate() { var result = new RazorOutputRenderer(@".\templates\text.cshtml").Render(TestHelpers.CreateSimpleChangeManifest()); Assert.True(result.ToString().StartsWith("Version"));//Giddyup. } } }
using System.Globalization; using NUnit.Framework; using TeamCityBuildChanges.Output; using TeamCityBuildChanges.Testing; namespace TeamCityBuildChanges.Tests { [TestFixture] public class HtmlOutputTests { [Test] public void CanRenderSimpleTemplate() { var result = new RazorOutputRenderer(@".\templates\text.cshtml").Render(TestHelpers.CreateSimpleChangeManifest()); Assert.True(result.ToString(CultureInfo.InvariantCulture).StartsWith(" Version"));//Giddyup. } } }
Set proper version for WixUiClient
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("Shimmer.WiXUiClient")] [assembly: AssemblyDescription("Shimmer library for creating custom Setup UIs")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("GitHub")] [assembly: AssemblyProduct("Shimmer")] [assembly: AssemblyCopyright("Copyright © 2012 GitHub")] // 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("df7541af-f05d-47ff-ad41-8582c41c9406")] // 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("Shimmer.WiXUiClient")] [assembly: AssemblyDescription("Shimmer library for creating custom Setup UIs")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("GitHub")] [assembly: AssemblyProduct("Shimmer")] [assembly: AssemblyCopyright("Copyright © 2012 GitHub")] // 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("df7541af-f05d-47ff-ad41-8582c41c9406")] // 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.5.0.0")] [assembly: AssemblyFileVersion("0.5.0.0")]
Add dynamic method constuctor codes (didn't use it yet, other developer may learn something from the function)
using System; using System.Collections.Generic; using System.Linq.Expressions; namespace LiteNetLibManager.Utils { public class Reflection { private static readonly Dictionary<string, ObjectActivator> objectActivators = new Dictionary<string, ObjectActivator>(); private static string tempTypeName; // Improve reflection constructor performance with Linq expression (https://rogerjohansson.blog/2008/02/28/linq-expressions-creating-objects/) public delegate object ObjectActivator(); public static ObjectActivator GetActivator(Type type) { tempTypeName = type.FullName; if (!objectActivators.ContainsKey(tempTypeName)) { if (type.IsClass) objectActivators.Add(tempTypeName, Expression.Lambda<ObjectActivator>(Expression.New(type)).Compile()); else objectActivators.Add(tempTypeName, Expression.Lambda<ObjectActivator>(Expression.Convert(Expression.New(type), typeof(object))).Compile()); } return objectActivators[tempTypeName]; } } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection.Emit; namespace LiteNetLibManager.Utils { public class Reflection { private static readonly Dictionary<string, Func<object>> expressionActivators = new Dictionary<string, Func<object>>(); private static readonly Dictionary<string, DynamicMethod> dynamicMethodActivators = new Dictionary<string, DynamicMethod>(); // Improve reflection constructor performance with Linq expression (https://rogerjohansson.blog/2008/02/28/linq-expressions-creating-objects/) public static object GetExpressionActivator(Type type) { if (!expressionActivators.ContainsKey(type.FullName)) { if (type.IsClass) expressionActivators.Add(type.FullName, Expression.Lambda<Func<object>>(Expression.New(type)).Compile()); else expressionActivators.Add(type.FullName, Expression.Lambda<Func<object>>(Expression.Convert(Expression.New(type), typeof(object))).Compile()); } return expressionActivators[type.FullName].Invoke(); } public static object GetDynamicMethodActivator(Type type) { if (!dynamicMethodActivators.ContainsKey(type.FullName)) { DynamicMethod method = new DynamicMethod("", typeof(object), Type.EmptyTypes); ILGenerator il = method.GetILGenerator(); if (type.IsValueType) { var local = il.DeclareLocal(type); il.Emit(OpCodes.Ldloc, local); il.Emit(OpCodes.Box, type); il.Emit(OpCodes.Ret); } else { var ctor = type.GetConstructor(Type.EmptyTypes); il.Emit(OpCodes.Newobj, ctor); il.Emit(OpCodes.Ret); } dynamicMethodActivators.Add(type.FullName, method); } return dynamicMethodActivators[type.FullName].Invoke(null, null); } } }
Remove illegal await in catch block.
using System.Net.Sockets; using System.Threading.Tasks; using Version = Msg.Core.Versioning.Version; using System.Linq; namespace Msg.Infrastructure.Server { class ClientRequestProcessor { readonly AmqpSettings settings; public ClientRequestProcessor (AmqpSettings settings) { this.settings = settings; } public async Task ProcessClient (TcpClient client) { var stream = client.GetStream (); try { var version = await stream.ReadVersionAsync (); if (IsVersionSupported (version)) { await stream.WriteVersionAsync (version); } else { await stream.WriteVersionAsync (this.settings.PreferredVersion); } } catch { await stream.WriteVersionAsync (this.settings.PreferredVersion); } finally { if (client.Connected) { client.Close (); } } } bool IsVersionSupported (Version version) { return this.settings.SupportedVersions.Any (range => range.Contains (version)); } } }
using System.Net.Sockets; using System.Threading.Tasks; using Version = Msg.Core.Versioning.Version; using System.Linq; namespace Msg.Infrastructure.Server { class ClientRequestProcessor { readonly AmqpSettings settings; public ClientRequestProcessor (AmqpSettings settings) { this.settings = settings; } public async Task ProcessClient (TcpClient client) { var stream = client.GetStream (); try { var version = await stream.ReadVersionAsync (); if (IsVersionSupported (version)) { await stream.WriteVersionAsync (version); } else { await stream.WriteVersionAsync (this.settings.PreferredVersion); } } finally { if (client.Connected) { client.Close (); } } } bool IsVersionSupported (Version version) { return this.settings.SupportedVersions.Any (range => range.Contains (version)); } } }
Store the already serialised RaygunMessage object.
using System.Collections.Generic; using Mindscape.Raygun4Net.Messages; namespace Mindscape.Raygun4Net.Storage { public interface IRaygunOfflineStorage { /// <summary> /// Persist the <paramref name="message"/>> to local storage. /// </summary> /// <param name="message">The error report to store locally.</param> /// <param name="apiKey">The key for which these file are associated with.</param> /// <returns></returns> bool Store(RaygunMessage message, string apiKey); /// <summary> /// Retrieve all files from local storage. /// </summary> /// <param name="apiKey">The key for which these file are associated with.</param> /// <returns>A container of files that are currently stored locally.</returns> IList<IRaygunFile> FetchAll(string apiKey); /// <summary> /// Delete a file from local storage that has the following <paramref name="name"/>. /// </summary> /// <param name="name">The filename of the local file.</param> /// <param name="apiKey">The key for which these file are associated with.</param> /// <returns></returns> bool Remove(string name, string apiKey); } }
using System.Collections.Generic; using Mindscape.Raygun4Net.Messages; namespace Mindscape.Raygun4Net.Storage { public interface IRaygunOfflineStorage { /// <summary> /// Persist the <paramref name="message"/>> to local storage. /// </summary> /// <param name="message">The serialized error report to store locally.</param> /// <param name="apiKey">The key for which these file are associated with.</param> /// <returns></returns> bool Store(string message, string apiKey); /// <summary> /// Retrieve all files from local storage. /// </summary> /// <param name="apiKey">The key for which these file are associated with.</param> /// <returns>A container of files that are currently stored locally.</returns> IList<IRaygunFile> FetchAll(string apiKey); /// <summary> /// Delete a file from local storage that has the following <paramref name="name"/>. /// </summary> /// <param name="name">The filename of the local file.</param> /// <param name="apiKey">The key for which these file are associated with.</param> /// <returns></returns> bool Remove(string name, string apiKey); } }
Make the include file adder well known in the interface. We may have to add IncludeFiles too in a bit.
 namespace LinqToTTreeInterfacesLib { /// <summary> /// Interface for implementing an object that will contain a complete single query /// </summary> public interface IGeneratedCode { /// <summary> /// Add a new statement to the current spot where the "writing" currsor is pointed. /// </summary> /// <param name="s"></param> void Add(IStatement s); /// <summary> /// Book a variable at the inner most scope /// </summary> /// <param name="v"></param> void Add(IVariable v); /// <summary> /// This variable's inital value is "complex" and must be transfered over the wire in some way other than staight into the code /// (for example, a ROOT object that needs to be written to a TFile). /// </summary> /// <param name="v"></param> void QueueForTransfer(string key, object value); /// <summary> /// Returns the outter most coding block /// </summary> IBookingStatementBlock CodeBody { get; } } }
 namespace LinqToTTreeInterfacesLib { /// <summary> /// Interface for implementing an object that will contain a complete single query /// </summary> public interface IGeneratedCode { /// <summary> /// Add a new statement to the current spot where the "writing" currsor is pointed. /// </summary> /// <param name="s"></param> void Add(IStatement s); /// <summary> /// Book a variable at the inner most scope /// </summary> /// <param name="v"></param> void Add(IVariable v); /// <summary> /// This variable's inital value is "complex" and must be transfered over the wire in some way other than staight into the code /// (for example, a ROOT object that needs to be written to a TFile). /// </summary> /// <param name="v"></param> void QueueForTransfer(string key, object value); /// <summary> /// Returns the outter most coding block /// </summary> IBookingStatementBlock CodeBody { get; } /// <summary> /// Adds an include file to be included for this query's C++ file. /// </summary> /// <param name="filename"></param> void AddIncludeFile(string filename); } }
Fix null reference exception when spawning Fungus objects in Unity 5.1
using UnityEngine; using UnityEditor; using System.IO; using System.Collections; namespace Fungus { public class FlowchartMenuItems { [MenuItem("Tools/Fungus/Create/Flowchart", false, 0)] static void CreateFlowchart() { GameObject go = SpawnPrefab("Flowchart"); go.transform.position = Vector3.zero; } public static GameObject SpawnPrefab(string prefabName) { GameObject prefab = Resources.Load<GameObject>(prefabName); if (prefab == null) { return null; } GameObject go = PrefabUtility.InstantiatePrefab(prefab) as GameObject; PrefabUtility.DisconnectPrefabInstance(go); Camera sceneCam = SceneView.currentDrawingSceneView.camera; Vector3 pos = sceneCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 10f)); pos.z = 0f; go.transform.position = pos; Selection.activeGameObject = go; Undo.RegisterCreatedObjectUndo(go, "Create Object"); return go; } } }
using UnityEngine; using UnityEditor; using System.IO; using System.Collections; namespace Fungus { public class FlowchartMenuItems { [MenuItem("Tools/Fungus/Create/Flowchart", false, 0)] static void CreateFlowchart() { GameObject go = SpawnPrefab("Flowchart"); go.transform.position = Vector3.zero; } public static GameObject SpawnPrefab(string prefabName) { GameObject prefab = Resources.Load<GameObject>(prefabName); if (prefab == null) { return null; } GameObject go = PrefabUtility.InstantiatePrefab(prefab) as GameObject; PrefabUtility.DisconnectPrefabInstance(go); SceneView view = SceneView.currentDrawingSceneView; if (view != null) { Camera sceneCam = view.camera; Vector3 pos = sceneCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 10f)); pos.z = 0f; go.transform.position = pos; } Selection.activeGameObject = go; Undo.RegisterCreatedObjectUndo(go, "Create Object"); return go; } } }
Move variable declaration to the top of method
using System; class Solution { static void Main() { int b; double c, s = 0.0; string line; while ((line = Console.ReadLine()) != null) { string[] numbers = line.Split(' '); b = Convert.ToInt16(numbers[1]); c = Convert.ToDouble(numbers[2]); s += c * b; } Console.WriteLine("VALOR A PAGAR: R$ {0:F2}", s); } }
using System; class Solution { static void Main() { int b; double c, s = 0.0; string line; string[] numbers; while ((line = Console.ReadLine()) != null) { numbers = line.Split(' '); b = Convert.ToInt16(numbers[1]); c = Convert.ToDouble(numbers[2]); s += c * b; } Console.WriteLine("VALOR A PAGAR: R$ {0:F2}", s); } }
Fix a typo in the GitHub.UI.Reactive assembly title
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Markup; [assembly: AssemblyTitle("GitHub.UI.Recative")] [assembly: AssemblyDescription("GitHub flavored WPF styles and controls that require Rx and RxUI")] [assembly: Guid("885a491c-1d13-49e7-baa6-d61f424befcb")] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] [assembly: XmlnsDefinition("https://github.com/github/VisualStudio", "GitHub.UI")]
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Markup; [assembly: AssemblyTitle("GitHub.UI.Reactive")] [assembly: AssemblyDescription("GitHub flavored WPF styles and controls that require Rx and RxUI")] [assembly: Guid("885a491c-1d13-49e7-baa6-d61f424befcb")] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] [assembly: XmlnsDefinition("https://github.com/github/VisualStudio", "GitHub.UI")]
Use friendly url while sending transfer
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Neblina.Api.Core; using Neblina.Api.Models.TransferViewModels; using Neblina.Api.Core.Models; namespace Neblina.Api.Controllers { [Route("transfers")] public class TransferController : Controller { private IUnitOfWork _repos; private int _accountId; public TransferController(IUnitOfWork repos) { _repos = repos; _accountId = 1; } // POST transfers/send [HttpPost("send")] public IActionResult Send(TransactionType type, [FromBody]SendTransferViewModel transfer) { var transaction = new Transaction() { Date = DateTime.Now, Description = "Transfer sent", AccountId = _accountId, DestinationBankId = transfer.DestinationBankId, DestinationAccountId = transfer.DestinationAccountId, Amount = transfer.Amount * -1, Type = type, Status = TransactionStatus.Pending }; _repos.Transactions.Add(transaction); _repos.SaveAndApply(); var receipt = new SendTransferReceiptViewModel() { TransactionId = transaction.TransactionId, DestinationBankId = transfer.DestinationBankId, DestinationAccountId = transfer.DestinationAccountId, Amount = transaction.Amount }; return Ok(receipt); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Neblina.Api.Core; using Neblina.Api.Models.TransferViewModels; using Neblina.Api.Core.Models; namespace Neblina.Api.Controllers { [Route("transfers")] public class TransferController : Controller { private IUnitOfWork _repos; private int _accountId; public TransferController(IUnitOfWork repos) { _repos = repos; _accountId = 1; } // POST transfers/send [HttpPost("send")] public IActionResult Send(string bank, bool scheduled, [FromBody]SendTransferViewModel transfer) { TransactionType type; switch (bank) { case "same": type = scheduled ? TransactionType.SameBankScheduled : TransactionType.SameBankRealTime; break; case "another": type = scheduled ? TransactionType.AnotherBankScheduled : TransactionType.AnotherBankRealTime; break; default: return NotFound(); } var transaction = new Transaction() { Date = DateTime.Now, Description = "Transfer sent", AccountId = _accountId, DestinationBankId = transfer.DestinationBankId, DestinationAccountId = transfer.DestinationAccountId, Amount = transfer.Amount * -1, Type = type, Status = TransactionStatus.Pending }; _repos.Transactions.Add(transaction); _repos.SaveAndApply(); var receipt = new SendTransferReceiptViewModel() { TransactionId = transaction.TransactionId, DestinationBankId = transfer.DestinationBankId, DestinationAccountId = transfer.DestinationAccountId, Amount = transaction.Amount }; return Ok(receipt); } } }
Fix a bug that admiral information is not updated.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Grabacr07.KanColleWrapper; using Grabacr07.KanColleWrapper.Models; using Livet; using Livet.EventListeners; namespace Grabacr07.KanColleViewer.ViewModels { public class AdmiralViewModel : ViewModel { #region Model 変更通知プロパティ public Admiral Model { get { return KanColleClient.Current.Homeport.Admiral; } } #endregion public AdmiralViewModel() { this.CompositeDisposable.Add(new PropertyChangedEventListener(KanColleClient.Current.Homeport) { {"Admiral", (sender, args) => this.Update() }, }); } private void Update() { this.RaisePropertyChanged("Admiral"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Grabacr07.KanColleWrapper; using Grabacr07.KanColleWrapper.Models; using Livet; using Livet.EventListeners; namespace Grabacr07.KanColleViewer.ViewModels { public class AdmiralViewModel : ViewModel { #region Model 変更通知プロパティ public Admiral Model { get { return KanColleClient.Current.Homeport.Admiral; } } #endregion public AdmiralViewModel() { this.CompositeDisposable.Add(new PropertyChangedEventListener(KanColleClient.Current.Homeport) { { "Admiral", (sender, args) => this.Update() }, }); } private void Update() { this.RaisePropertyChanged("Model"); } } }
Make pagination list result enumerable.
namespace TraktApiSharp.Objects.Basic { using System.Collections.Generic; /// <summary> /// Represents results of requests supporting pagination.<para /> /// Contains the current page, the item limitation per page, the total page count, the total item count /// and can also contain the total user count (e.g. in trending shows and movies requests). /// </summary> /// <typeparam name="ListItem">The underlying item type of the list results.</typeparam> public class TraktPaginationListResult<ListItem> { /// <summary>Gets or sets the actual list results.</summary> public IEnumerable<ListItem> Items { get; set; } /// <summary>Gets or sets the current page number.</summary> public int? Page { get; set; } /// <summary>Gets or sets the item limitation per page.</summary> public int? Limit { get; set; } /// <summary>Gets or sets the total page count.</summary> public int? PageCount { get; set; } /// <summary>Gets or sets the total item results count.</summary> public int? ItemCount { get; set; } /// <summary> /// Gets or sets the total user count. /// <para> /// May be only supported for trending shows and movies requests. /// </para> /// </summary> public int? UserCount { get; set; } } }
namespace TraktApiSharp.Objects.Basic { using System.Collections; using System.Collections.Generic; /// <summary> /// Represents results of requests supporting pagination.<para /> /// Contains the current page, the item limitation per page, the total page count, the total item count /// and can also contain the total user count (e.g. in trending shows and movies requests). /// </summary> /// <typeparam name="ListItem">The underlying item type of the list results.</typeparam> public class TraktPaginationListResult<ListItem> : IEnumerable<ListItem> { /// <summary>Gets or sets the actual list results.</summary> public IEnumerable<ListItem> Items { get; set; } /// <summary>Gets or sets the current page number.</summary> public int? Page { get; set; } /// <summary>Gets or sets the item limitation per page.</summary> public int? Limit { get; set; } /// <summary>Gets or sets the total page count.</summary> public int? PageCount { get; set; } /// <summary>Gets or sets the total item results count.</summary> public int? ItemCount { get; set; } /// <summary> /// Gets or sets the total user count. /// <para> /// May be only supported for trending shows and movies requests. /// </para> /// </summary> public int? UserCount { get; set; } public IEnumerator<ListItem> GetEnumerator() { return Items.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
Add view for news details route
@model PhotoLife.ViewModels.News.NewsDetailsViewModel @{ ViewBag.Title = "NewsDetails"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>NewsDetails</h2> <div> <h4>NewsDetailsViewModel</h4> <hr /> <dl class="dl-horizontal"> <dt> @Html.DisplayNameFor(model => model.Title) </dt> <dd> @Html.DisplayFor(model => model.Title) </dd> <dt> @Html.DisplayNameFor(model => model.Text) </dt> <dd> @Html.DisplayFor(model => model.Text) </dd> <dt> @Html.DisplayNameFor(model => model.ImageUrl) </dt> <dd> @Html.DisplayFor(model => model.ImageUrl) </dd> <dt> @Html.DisplayNameFor(model => model.DatePublished) </dt> <dd> @Html.DisplayFor(model => model.DatePublished) </dd> <dt> @Html.DisplayNameFor(model => model.Views) </dt> <dd> @Html.DisplayFor(model => model.Views) </dd> </dl> </div> <p> @Html.ActionLink("Edit", "Edit", new { id = Model.Id }) | @Html.ActionLink("Back to List", "Index") </p>
@model PhotoLife.ViewModels.News.NewsDetailsViewModel @{ ViewBag.Title = "NewsDetails"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>NewsDetails</h2> <div> <h4>NewsDetailsViewModel</h4> <hr /> <dl class="dl-horizontal"> <dt> @Html.DisplayNameFor(model => model.Title) </dt> <dd> @Html.DisplayFor(model => model.Title) </dd> <dt> @Html.DisplayNameFor(model => model.ImageUrl) </dt> <dd> @Html.DisplayFor(model => model.ImageUrl) </dd> <dt> @Html.DisplayNameFor(model => model.DatePublished) </dt> <dd> @Html.DisplayFor(model => model.DatePublished) </dd> <dt> @Html.DisplayNameFor(model => model.Views) </dt> <dd> @Html.DisplayFor(model => model.Views) </dd> </dl> </div> @Html.Raw(HttpUtility.HtmlDecode(Model.Text)) <p> @Html.ActionLink("Edit", "Edit", new { id = Model.Id }) | @Html.ActionLink("Back to List", "Index") </p>
Increase timeout from 20s to 2 minutes.
using System; using System.Diagnostics; using System.Threading; namespace RedGate.AppHost.Server { internal class StartProcessWithTimeout : IProcessStartOperation { private readonly IProcessStartOperation m_WrappedProcessStarter; private static readonly TimeSpan s_TimeOut = TimeSpan.FromSeconds(20); public StartProcessWithTimeout(IProcessStartOperation wrappedProcessStarter) { if (wrappedProcessStarter == null) throw new ArgumentNullException("wrappedProcessStarter"); m_WrappedProcessStarter = wrappedProcessStarter; } public Process StartProcess(string assemblyName, string remotingId, bool openDebugConsole = false) { using (var signal = new EventWaitHandle(false, EventResetMode.ManualReset, remotingId)) { var process = m_WrappedProcessStarter.StartProcess(assemblyName, remotingId, openDebugConsole); WaitForReadySignal(signal); return process; } } private static void WaitForReadySignal(EventWaitHandle signal) { if (!signal.WaitOne(s_TimeOut)) throw new ApplicationException("WPF child process didn't respond quickly enough"); } } }
using System; using System.Diagnostics; using System.Threading; namespace RedGate.AppHost.Server { internal class StartProcessWithTimeout : IProcessStartOperation { private readonly IProcessStartOperation m_WrappedProcessStarter; private static readonly TimeSpan s_TimeOut = TimeSpan.FromMinutes(2); public StartProcessWithTimeout(IProcessStartOperation wrappedProcessStarter) { if (wrappedProcessStarter == null) throw new ArgumentNullException("wrappedProcessStarter"); m_WrappedProcessStarter = wrappedProcessStarter; } public Process StartProcess(string assemblyName, string remotingId, bool openDebugConsole = false) { using (var signal = new EventWaitHandle(false, EventResetMode.ManualReset, remotingId)) { var process = m_WrappedProcessStarter.StartProcess(assemblyName, remotingId, openDebugConsole); WaitForReadySignal(signal); return process; } } private static void WaitForReadySignal(EventWaitHandle signal) { if (!signal.WaitOne(s_TimeOut)) throw new ApplicationException("WPF child process didn't respond quickly enough"); } } }
Change calling convention of ImGuiInputTextCallback
namespace ImGuiNET { public unsafe delegate int ImGuiInputTextCallback(ImGuiInputTextCallbackData* data); }
using System.Runtime.InteropServices; namespace ImGuiNET { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate int ImGuiInputTextCallback(ImGuiInputTextCallbackData* data); }
Update test RP to include client id in change email / password links
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Test relying party</title> </head> <body> <div> @if (User.Identity.IsAuthenticated) { <span><a href="https://localhost:44334/account/changeemail?returnUrl=@Url.Action("Index", "Home", null, Request.Url.Scheme)">Change Email</a></span> <span><a href="https://localhost:44334/account/changepassword?returnUrl=@Url.Action("Index", "Home", null, Request.Url.Scheme)">Change Password</a></span> <span><a href="@Url.Action("Logout", "Home")">Logout</a></span> } else { <span><a href="@Url.Action("Login", "Home")">Login</a></span> } </div> <div> @RenderBody() </div> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Test relying party</title> </head> <body> <div> @if (User.Identity.IsAuthenticated) { <span><a href="https://localhost:44334/account/changeemail?clientid=testrp&returnUrl=@Url.Action("Index", "Home", null, Request.Url.Scheme)">Change Email</a></span> <span><a href="https://localhost:44334/account/changepassword?clientid=testrp&returnUrl=@Url.Action("Index", "Home", null, Request.Url.Scheme)">Change Password</a></span> <span><a href="@Url.Action("Logout", "Home")">Logout</a></span> } else { <span><a href="@Url.Action("Login", "Home")">Login</a></span> } </div> <div> @RenderBody() </div> </body> </html>
Make XNAControls internals visible to XNAControls.Test
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("XNAControls")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("XNAControls")] [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("8314a04c-752e-49fb-828d-40ef66d2ce39")] // 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("XNAControls")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("XNAControls")] [assembly: AssemblyCopyright("Copyright © Ethan Moffat 2014-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("8314a04c-752e-49fb-828d-40ef66d2ce39")] // 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:InternalsVisibleTo("XNAControls.Test")]
Fix double Ergo auth request header problem
using System.Text; namespace Miningcore.Blockchain.Ergo; public partial class ErgoClient { public Dictionary<string, string> RequestHeaders { get; } = new(); private Task PrepareRequestAsync(HttpClient client, HttpRequestMessage request, StringBuilder url, CancellationToken ct) { foreach(var pair in RequestHeaders) request.Headers.Add(pair.Key, pair.Value); return Task.CompletedTask; } private Task PrepareRequestAsync(HttpClient client, HttpRequestMessage request, String url, CancellationToken ct) { foreach(var pair in RequestHeaders) request.Headers.Add(pair.Key, pair.Value); return Task.CompletedTask; } private Task PrepareRequestAsync(HttpClient client, HttpRequestMessage request, string url) { return Task.CompletedTask; } private static Task ProcessResponseAsync(HttpClient client, HttpResponseMessage response, CancellationToken ct) { return Task.CompletedTask; } }
using System.Text; namespace Miningcore.Blockchain.Ergo; public partial class ErgoClient { public Dictionary<string, string> RequestHeaders { get; } = new(); private Task PrepareRequestAsync(HttpClient client, HttpRequestMessage request, StringBuilder url, CancellationToken ct) { foreach(var pair in RequestHeaders) request.Headers.Add(pair.Key, pair.Value); return Task.CompletedTask; } private Task PrepareRequestAsync(HttpClient client, HttpRequestMessage request, String url, CancellationToken ct) { return Task.CompletedTask; } private Task PrepareRequestAsync(HttpClient client, HttpRequestMessage request, string url) { return Task.CompletedTask; } private static Task ProcessResponseAsync(HttpClient client, HttpResponseMessage response, CancellationToken ct) { return Task.CompletedTask; } }
Update dotnet tests for 3.1.302.
using OmniSharp.Services; using TestUtility; using Xunit; using Xunit.Abstractions; namespace OmniSharp.Tests { public class DotNetCliServiceFacts : AbstractTestFixture { public DotNetCliServiceFacts(ITestOutputHelper output) : base(output) { } [Fact] public void GetVersion() { using (var host = CreateOmniSharpHost(dotNetCliVersion: DotNetCliVersion.Current)) { var dotNetCli = host.GetExport<IDotNetCliService>(); var version = dotNetCli.GetVersion(); Assert.Equal(3, version.Major); Assert.Equal(1, version.Minor); Assert.Equal(201, version.Patch); Assert.Equal("", version.Release); } } [Fact] public void GetInfo() { using (var host = CreateOmniSharpHost(dotNetCliVersion: DotNetCliVersion.Current)) { var dotNetCli = host.GetExport<IDotNetCliService>(); var info = dotNetCli.GetInfo(); Assert.Equal(3, info.Version.Major); Assert.Equal(1, info.Version.Minor); Assert.Equal(201, info.Version.Patch); Assert.Equal("", info.Version.Release); } } } }
using OmniSharp.Services; using TestUtility; using Xunit; using Xunit.Abstractions; namespace OmniSharp.Tests { public class DotNetCliServiceFacts : AbstractTestFixture { public DotNetCliServiceFacts(ITestOutputHelper output) : base(output) { } [Fact] public void GetVersion() { using (var host = CreateOmniSharpHost(dotNetCliVersion: DotNetCliVersion.Current)) { var dotNetCli = host.GetExport<IDotNetCliService>(); var version = dotNetCli.GetVersion(); Assert.Equal(3, version.Major); Assert.Equal(1, version.Minor); Assert.Equal(302, version.Patch); Assert.Equal("", version.Release); } } [Fact] public void GetInfo() { using (var host = CreateOmniSharpHost(dotNetCliVersion: DotNetCliVersion.Current)) { var dotNetCli = host.GetExport<IDotNetCliService>(); var info = dotNetCli.GetInfo(); Assert.Equal(3, info.Version.Major); Assert.Equal(1, info.Version.Minor); Assert.Equal(302, info.Version.Patch); Assert.Equal("", info.Version.Release); } } } }
Fix typo in XML doc
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; namespace Microsoft.AspNetCore.Mvc.ApplicationParts { /// <summary> /// A provider for a given <typeparamref name="TFeature"/> feature. /// </summary> /// <typeparam name="TFeature">The type of the feature.</typeparam> public interface IApplicationFeatureProvider<TFeature> : IApplicationFeatureProvider { /// <summary> /// Updates the <paramref name="feature"/> intance. /// </summary> /// <param name="parts">The list of <see cref="ApplicationPart"/>s of the /// application. /// </param> /// <param name="feature">The feature instance to populate.</param> void PopulateFeature(IEnumerable<ApplicationPart> parts, TFeature feature); } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; namespace Microsoft.AspNetCore.Mvc.ApplicationParts { /// <summary> /// A provider for a given <typeparamref name="TFeature"/> feature. /// </summary> /// <typeparam name="TFeature">The type of the feature.</typeparam> public interface IApplicationFeatureProvider<TFeature> : IApplicationFeatureProvider { /// <summary> /// Updates the <paramref name="feature"/> instance. /// </summary> /// <param name="parts">The list of <see cref="ApplicationPart"/>s of the /// application. /// </param> /// <param name="feature">The feature instance to populate.</param> void PopulateFeature(IEnumerable<ApplicationPart> parts, TFeature feature); } }
Add open folder button to open currently selected tournament
// 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 osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Graphics.UserInterface; using osu.Game.Tournament.IO; namespace osu.Game.Tournament.Screens.Setup { internal class TournamentSwitcher : ActionableInfo { private OsuDropdown<string> dropdown; [Resolved] private TournamentGameBase game { get; set; } [BackgroundDependencyLoader] private void load(TournamentStorage storage) { string startupTournament = storage.CurrentTournament.Value; dropdown.Current = storage.CurrentTournament; dropdown.Items = storage.ListTournaments(); dropdown.Current.BindValueChanged(v => Button.Enabled.Value = v.NewValue != startupTournament, true); Action = () => game.GracefullyExit(); ButtonText = "Close osu!"; } protected override Drawable CreateComponent() { var drawable = base.CreateComponent(); FlowContainer.Insert(-1, dropdown = new OsuDropdown<string> { Width = 510 }); return drawable; } } }
// 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 osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Graphics.UserInterface; using osu.Game.Tournament.IO; namespace osu.Game.Tournament.Screens.Setup { internal class TournamentSwitcher : ActionableInfo { private OsuDropdown<string> dropdown; private OsuButton folderButton; [Resolved] private TournamentGameBase game { get; set; } [BackgroundDependencyLoader] private void load(TournamentStorage storage) { string startupTournament = storage.CurrentTournament.Value; dropdown.Current = storage.CurrentTournament; dropdown.Items = storage.ListTournaments(); dropdown.Current.BindValueChanged(v => Button.Enabled.Value = v.NewValue != startupTournament, true); Action = () => game.GracefullyExit(); folderButton.Action = storage.PresentExternally; ButtonText = "Close osu!"; } protected override Drawable CreateComponent() { var drawable = base.CreateComponent(); FlowContainer.Insert(-1, dropdown = new OsuDropdown<string> { Width = 510 }); FlowContainer.Insert(-2, folderButton = new TriangleButton { Text = "Open folder", Width = 100 }); return drawable; } } }
Throw an exception if a popover is attempted to be shown without a parent `PopoverContainer`
// 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 osu.Framework.Graphics; using osu.Framework.Graphics.Cursor; #nullable enable namespace osu.Framework.Extensions { public static class PopoverExtensions { /// <summary> /// Shows the popover for <paramref name="hasPopover"/> on its nearest <see cref="PopoverContainer"/> ancestor. /// </summary> public static void ShowPopover(this IHasPopover hasPopover) => setTargetOnNearestPopover((Drawable)hasPopover, hasPopover); /// <summary> /// Hides the popover shown on <paramref name="drawable"/>'s nearest <see cref="PopoverContainer"/> ancestor. /// </summary> public static void HidePopover(this Drawable drawable) => setTargetOnNearestPopover(drawable, null); private static void setTargetOnNearestPopover(Drawable origin, IHasPopover? target) => origin.FindClosestParent<PopoverContainer>()?.SetTarget(target); } }
// 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; using osu.Framework.Graphics; using osu.Framework.Graphics.Cursor; #nullable enable namespace osu.Framework.Extensions { public static class PopoverExtensions { /// <summary> /// Shows the popover for <paramref name="hasPopover"/> on its nearest <see cref="PopoverContainer"/> ancestor. /// </summary> public static void ShowPopover(this IHasPopover hasPopover) => setTargetOnNearestPopover((Drawable)hasPopover, hasPopover); /// <summary> /// Hides the popover shown on <paramref name="drawable"/>'s nearest <see cref="PopoverContainer"/> ancestor. /// </summary> public static void HidePopover(this Drawable drawable) => setTargetOnNearestPopover(drawable, null); private static void setTargetOnNearestPopover(Drawable origin, IHasPopover? target) { var popoverContainer = origin.FindClosestParent<PopoverContainer>() ?? throw new InvalidOperationException($"Cannot show or hide a popover without a parent {nameof(PopoverContainer)} in the hierarchy"); popoverContainer.SetTarget(target); } } }
Change 3M performance test to 5M
using System; using System.Collections.Generic; using System.Linq; namespace Silverpop.Core.Performance { internal class Program { private static void Main(string[] args) { var tagValue = new string( Enumerable.Repeat("ABC", 1000) .SelectMany(x => x) .ToArray()); var personalizationTags = new TestPersonalizationTags() { TagA = tagValue, TagB = tagValue, TagC = tagValue, TagD = tagValue, TagE = tagValue, TagF = tagValue, TagG = tagValue, TagH = tagValue, TagI = tagValue, TagJ = tagValue, TagK = tagValue, TagL = tagValue, TagM = tagValue, TagN = tagValue, TagO = tagValue }; var numberOfTags = personalizationTags.GetType().GetProperties().Count(); Console.WriteLine("Testing 1 million recipients with {0} tags using batches of 5000:", numberOfTags); new TransactMessagePerformance() .InvokeGetRecipientBatchedMessages(1000000, 5000, personalizationTags); Console.WriteLine("Testing 3 million recipients with {0} tags using batches of 5000:", numberOfTags); new TransactMessagePerformance() .InvokeGetRecipientBatchedMessages(3000000, 5000, personalizationTags); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; namespace Silverpop.Core.Performance { internal class Program { private static void Main(string[] args) { var tagValue = new string( Enumerable.Repeat("ABC", 1000) .SelectMany(x => x) .ToArray()); var personalizationTags = new TestPersonalizationTags() { TagA = tagValue, TagB = tagValue, TagC = tagValue, TagD = tagValue, TagE = tagValue, TagF = tagValue, TagG = tagValue, TagH = tagValue, TagI = tagValue, TagJ = tagValue, TagK = tagValue, TagL = tagValue, TagM = tagValue, TagN = tagValue, TagO = tagValue }; var numberOfTags = personalizationTags.GetType().GetProperties().Count(); Console.WriteLine("Testing 1 million recipients with {0} tags using batches of 5000:", numberOfTags); new TransactMessagePerformance() .InvokeGetRecipientBatchedMessages(1000000, 5000, personalizationTags); Console.WriteLine("Testing 5 million recipients with {0} tags using batches of 5000:", numberOfTags); new TransactMessagePerformance() .InvokeGetRecipientBatchedMessages(5000000, 5000, personalizationTags); Console.ReadLine(); } } }
Add a space between "Test" and "Email" in the UI.
using BTCPayServer.Services.Mails; using Microsoft.AspNetCore.Mvc.Rendering; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace BTCPayServer.Models.ServerViewModels { public class EmailsViewModel { public string StatusMessage { get; set; } public EmailSettings Settings { get; set; } [EmailAddress] public string TestEmail { get; set; } } }
using BTCPayServer.Services.Mails; using Microsoft.AspNetCore.Mvc.Rendering; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace BTCPayServer.Models.ServerViewModels { public class EmailsViewModel { public string StatusMessage { get; set; } public EmailSettings Settings { get; set; } [EmailAddress] [Display(Name = "Test Email")] public string TestEmail { get; set; } } }
Load images in the test folder
using System; using System.IO; using System.Linq; using NUnit.Framework; namespace photo.exif.unit.test { [TestFixture("Images/Canon PowerShot SX500 IS.JPG")] [TestFixture("Images/Nikon COOLPIX P510.JPG")] [TestFixture("Images/Panasonic Lumix DMC-FZ200.JPG")] [TestFixture("Images/Samsung SIII.jpg")] public class ParserTest { public ParserTest(string path) { _path = path; _parser = new Parser(); } private readonly string _path; private readonly Parser _parser; [Test] public void Test_parse_path_return_some_data() { var data = _parser.Parse(_path); data.ToList().ForEach(Console.WriteLine); Assert.That(data, Is.Not.Null); Assert.That(data, Is.Not.Empty); } [Test] public void Test_parse_stream_return_some_data() { var data = _parser.Parse(new FileStream(_path,FileMode.Open)); data.ToList().ForEach(Console.WriteLine); Assert.That(data, Is.Not.Null); Assert.That(data, Is.Not.Empty); } } }
using System; using System.IO; using System.Linq; using NUnit.Framework; namespace photo.exif.unit.test { public class ParserTest { public ParserTest() { _parser = new Parser(); } private readonly Parser _parser; static string[] paths = Directory.GetFiles( Environment.CurrentDirectory, "*.jpg", SearchOption.AllDirectories); [Test, TestCaseSource("paths")] public void Test_parse_path_return_some_data(string path) { var data = _parser.Parse(path); data.ToList().ForEach(Console.WriteLine); Assert.That(data, Is.Not.Null); Assert.That(data, Is.Not.Empty); } [Test, TestCaseSource("paths")] public void Test_parse_stream_return_some_data(string path) { var data = _parser.Parse(new FileStream(path,FileMode.Open)); data.ToList().ForEach(Console.WriteLine); Assert.That(data, Is.Not.Null); Assert.That(data, Is.Not.Empty); } } }
Call base Handle if Decoratee not handled
namespace Miruken.Callback { using System; public abstract class HandlerDecorator : Handler, IDecorator { protected HandlerDecorator(IHandler decoratee) { if (decoratee == null) throw new ArgumentNullException(nameof(decoratee)); Decoratee = decoratee; } public IHandler Decoratee { get; } object IDecorator.Decoratee => Decoratee; protected override bool HandleCallback( object callback, ref bool greedy, IHandler composer) { return Decoratee.Handle(callback, ref greedy, composer); } } }
namespace Miruken.Callback { using System; public abstract class HandlerDecorator : Handler, IDecorator { protected HandlerDecorator(IHandler decoratee) { if (decoratee == null) throw new ArgumentNullException(nameof(decoratee)); Decoratee = decoratee; } public IHandler Decoratee { get; } object IDecorator.Decoratee => Decoratee; protected override bool HandleCallback( object callback, ref bool greedy, IHandler composer) { return Decoratee.Handle(callback, ref greedy, composer) || base.HandleCallback(callback, ref greedy, composer); } } }
Change slack error message text.
using System; using AzureStorage.Queue; using Common.Log; using CompetitionPlatform.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; namespace CompetitionPlatform.Exceptions { public class GlobalExceptionFilter : IExceptionFilter, IDisposable { private readonly ILog _log; private readonly IAzureQueue<SlackMessage> _slackMessageQueue; public GlobalExceptionFilter(ILog log, string slackNotificationsConnString) { _log = log; if (!string.IsNullOrEmpty(slackNotificationsConnString)) { _slackMessageQueue = new AzureQueue<SlackMessage>(slackNotificationsConnString, "slack-notifications"); } _slackMessageQueue = new QueueInMemory<SlackMessage>(); } public void OnException(ExceptionContext context) { var controller = context.RouteData.Values["controller"]; var action = context.RouteData.Values["action"]; _log.WriteError("Exception", "LykkeStreams", $"Controller: {controller}, action: {action}", context.Exception).Wait(); var message = new SlackMessage { Type = "Errors", //Errors, Info Sender = "Lykke Streams", Message = "Message occured in: " + controller + ", " + action + " - " + context.Exception }; _slackMessageQueue.PutMessageAsync(message).Wait(); } public void Dispose() { } } }
using System; using AzureStorage.Queue; using Common.Log; using CompetitionPlatform.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; namespace CompetitionPlatform.Exceptions { public class GlobalExceptionFilter : IExceptionFilter, IDisposable { private readonly ILog _log; private readonly IAzureQueue<SlackMessage> _slackMessageQueue; public GlobalExceptionFilter(ILog log, string slackNotificationsConnString) { _log = log; if (!string.IsNullOrEmpty(slackNotificationsConnString)) { _slackMessageQueue = new AzureQueue<SlackMessage>(slackNotificationsConnString, "slack-notifications"); } else { _slackMessageQueue = new QueueInMemory<SlackMessage>(); } } public void OnException(ExceptionContext context) { var controller = context.RouteData.Values["controller"]; var action = context.RouteData.Values["action"]; _log.WriteError("Exception", "LykkeStreams", $"Controller: {controller}, action: {action}", context.Exception).Wait(); var message = new SlackMessage { Type = "Errors", //Errors, Info Sender = "Lykke Streams", Message = "Occured in: " + controller + "Controller, " + action + " - " + context.Exception.GetType() }; _slackMessageQueue.PutMessageAsync(message).Wait(); } public void Dispose() { } } }
Revert "Refactor the menu's max height to be a property"
// 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; using osu.Framework.Graphics; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays.Settings { public class SettingsEnumDropdown<T> : SettingsDropdown<T> where T : struct, Enum { protected override OsuDropdown<T> CreateDropdown() => new DropdownControl(); protected new class DropdownControl : OsuEnumDropdown<T> { protected virtual int MenuMaxHeight => 200; public DropdownControl() { Margin = new MarginPadding { Top = 5 }; RelativeSizeAxes = Axes.X; } protected override DropdownMenu CreateMenu() => base.CreateMenu().With(m => m.MaxHeight = MenuMaxHeight); } } }
// 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; using osu.Framework.Graphics; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays.Settings { public class SettingsEnumDropdown<T> : SettingsDropdown<T> where T : struct, Enum { protected override OsuDropdown<T> CreateDropdown() => new DropdownControl(); protected new class DropdownControl : OsuEnumDropdown<T> { public DropdownControl() { Margin = new MarginPadding { Top = 5 }; RelativeSizeAxes = Axes.X; } protected override DropdownMenu CreateMenu() => base.CreateMenu().With(m => m.MaxHeight = 200); } } }
Fix cannot load firebase analytics type.
using System; using System.Reflection; namespace EE.Internal { internal class FirebaseAnalyticsImpl : IFirebaseAnalyticsImpl { private readonly MethodInfo _methodSetCurrentScreen; public FirebaseAnalyticsImpl() { var type = Type.GetType("Firebase.Analytics.FirebaseAnalytics, Firebase.Crashlytics"); if (type == null) { throw new ArgumentException("Cannot find FirebaseAnalytics"); } _methodSetCurrentScreen = type.GetMethod("SetCurrentScreen", new[] {typeof(string), typeof(string)}); } public void SetCurrentScreen(string screenName, string screenClass) { _methodSetCurrentScreen.Invoke(null, new object[] {screenName, screenClass}); } } }
using System; using System.Reflection; namespace EE.Internal { internal class FirebaseAnalyticsImpl : IFirebaseAnalyticsImpl { private readonly MethodInfo _methodSetCurrentScreen; public FirebaseAnalyticsImpl() { var type = Type.GetType("Firebase.Analytics.FirebaseAnalytics, Firebase.Analytics"); if (type == null) { throw new ArgumentException("Cannot find FirebaseAnalytics"); } _methodSetCurrentScreen = type.GetMethod("SetCurrentScreen", new[] {typeof(string), typeof(string)}); } public void SetCurrentScreen(string screenName, string screenClass) { _methodSetCurrentScreen.Invoke(null, new object[] {screenName, screenClass}); } } }
Add sqlite migrate on startup
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Builder; namespace RedCard.API { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .Build(); host.Run(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Builder; using RedCard.API.Contexts; using Microsoft.EntityFrameworkCore; namespace RedCard.API { public class Program { public static void Main(string[] args) { using (var context = new ApplicationDbContext()) { context.Database.Migrate(); } var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .Build(); host.Run(); } } }
Set correct min and max values
using System.Collections.Generic; namespace WalletWasabi.Fluent.ViewModels { public class TestLineChartViewModel { public double XAxisCurrentValue { get; set; } = 36; public double XAxisMinValue { get; set; } = 2; public double XAxisMaxValue { get; set; } = 864; public List<string> XAxisLabels => new List<string>() { "1w", "3d", "1d", "12h", "6h", "3h", "1h", "30m", "20m", "fastest" }; public List<double> XAxisValues => new List<double>() { 1008, 432, 144, 72, 36, 18, 6, 3, 2, 1, }; public List<double> YAxisValues => new List<double>() { 4, 4, 7, 22, 57, 97, 102, 123, 123, 185 }; } }
using System.Collections.Generic; namespace WalletWasabi.Fluent.ViewModels { public class TestLineChartViewModel { public double XAxisCurrentValue { get; set; } = 36; public double XAxisMinValue { get; set; } = 1; public double XAxisMaxValue { get; set; } = 1008; public List<string> XAxisLabels => new List<string>() { "1w", "3d", "1d", "12h", "6h", "3h", "1h", "30m", "20m", "fastest" }; public List<double> XAxisValues => new List<double>() { 1008, 432, 144, 72, 36, 18, 6, 3, 2, 1, }; public List<double> YAxisValues => new List<double>() { 4, 4, 7, 22, 57, 97, 102, 123, 123, 185 }; } }
Revert "Fix The GlowWindow in the taskmanager"
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Interactivity; using MahApps.Metro.Controls; namespace MahApps.Metro.Behaviours { public class GlowWindowBehavior : Behavior<Window> { private GlowWindow left, right, top, bottom; protected override void OnAttached() { base.OnAttached(); this.AssociatedObject.Loaded += (sender, e) => { left = new GlowWindow(this.AssociatedObject, GlowDirection.Left); right = new GlowWindow(this.AssociatedObject, GlowDirection.Right); top = new GlowWindow(this.AssociatedObject, GlowDirection.Top); bottom = new GlowWindow(this.AssociatedObject, GlowDirection.Bottom); left.Owner = (MetroWindow)sender; right.Owner = (MetroWindow)sender; top.Owner = (MetroWindow)sender; bottom.Owner = (MetroWindow)sender; Show(); left.Update(); right.Update(); top.Update(); bottom.Update(); }; this.AssociatedObject.Closed += (sender, args) => { if (left != null) left.Close(); if (right != null) right.Close(); if (top != null) top.Close(); if (bottom != null) bottom.Close(); }; } public void Hide() { left.Hide(); right.Hide(); bottom.Hide(); top.Hide(); } public void Show() { left.Show(); right.Show(); top.Show(); bottom.Show(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Interactivity; using MahApps.Metro.Controls; namespace MahApps.Metro.Behaviours { public class GlowWindowBehavior : Behavior<Window> { private GlowWindow left, right, top, bottom; protected override void OnAttached() { base.OnAttached(); this.AssociatedObject.Loaded += (sender, e) => { left = new GlowWindow(this.AssociatedObject, GlowDirection.Left); right = new GlowWindow(this.AssociatedObject, GlowDirection.Right); top = new GlowWindow(this.AssociatedObject, GlowDirection.Top); bottom = new GlowWindow(this.AssociatedObject, GlowDirection.Bottom); Show(); left.Update(); right.Update(); top.Update(); bottom.Update(); }; this.AssociatedObject.Closed += (sender, args) => { if (left != null) left.Close(); if (right != null) right.Close(); if (top != null) top.Close(); if (bottom != null) bottom.Close(); }; } public void Hide() { left.Hide(); right.Hide(); bottom.Hide(); top.Hide(); } public void Show() { left.Show(); right.Show(); top.Show(); bottom.Show(); } } }
Correct compile error in tests
 namespace NakedObjects.Web.UnitTests.Selenium { public static class TestConfig { //public const string BaseUrl = "http://localhost:49998/"; public const string BaseUrl = "http://nakedobjectstest.azurewebsites.net/"; } }
 namespace NakedObjects.Selenium { public static class TestConfig { //public const string BaseUrl = "http://localhost:49998/"; public const string BaseUrl = "http://nakedobjectstest.azurewebsites.net/"; } }
Use strings for IDs (for flexibility)
using System; using System.Windows.Forms; namespace MultiMiner.Win.Notifications { public partial class NotificationsControl : UserControl { //events //delegate declarations public delegate void NotificationsChangedHandler(object sender); //event declarations public event NotificationsChangedHandler NotificationsChanged; public NotificationsControl() { InitializeComponent(); } public void AddNotification(int id, string text, Action clickHandler, string informationUrl = "") { NotificationControl notificationControl; foreach (Control control in containerPanel.Controls) { notificationControl = (NotificationControl)control; if ((int)notificationControl.Tag == id) return; } notificationControl = new NotificationControl(text, clickHandler, (nc) => { nc.Parent = null; if (NotificationsChanged != null) NotificationsChanged(this); }, informationUrl); notificationControl.Height = 28; notificationControl.Parent = containerPanel; notificationControl.Top = Int16.MaxValue; notificationControl.Tag = (object)id; notificationControl.BringToFront(); notificationControl.Dock = DockStyle.Top; containerPanel.ScrollControlIntoView(notificationControl); if (NotificationsChanged != null) NotificationsChanged(this); } public int NotificationCount() { return containerPanel.Controls.Count; } } }
using System; using System.Windows.Forms; namespace MultiMiner.Win.Notifications { public partial class NotificationsControl : UserControl { //events //delegate declarations public delegate void NotificationsChangedHandler(object sender); //event declarations public event NotificationsChangedHandler NotificationsChanged; public NotificationsControl() { InitializeComponent(); } public void AddNotification(string id, string text, Action clickHandler, string informationUrl = "") { NotificationControl notificationControl; foreach (Control control in containerPanel.Controls) { notificationControl = (NotificationControl)control; if ((string)notificationControl.Tag == id) return; } notificationControl = new NotificationControl(text, clickHandler, (nc) => { nc.Parent = null; if (NotificationsChanged != null) NotificationsChanged(this); }, informationUrl); notificationControl.Height = 28; notificationControl.Parent = containerPanel; notificationControl.Top = Int16.MaxValue; notificationControl.Tag = (object)id; notificationControl.BringToFront(); notificationControl.Dock = DockStyle.Top; containerPanel.ScrollControlIntoView(notificationControl); if (NotificationsChanged != null) NotificationsChanged(this); } public int NotificationCount() { return containerPanel.Controls.Count; } } }
Fix error with liquid propegation through air
using System; using TrueCraft.API; using TrueCraft.API.Logic; namespace TrueCraft.Core.Logic.Blocks { public class AirBlock : BlockProvider { public static readonly byte BlockID = 0x00; public override byte ID { get { return 0x00; } } public override double BlastResistance { get { return 0; } } public override double Hardness { get { return 100000; } } public override bool Opaque { get { return false; } } public override byte Luminance { get { return 0; } } public override string DisplayName { get { return "Air"; } } public override Tuple<int, int> GetTextureMap(byte metadata) { return new Tuple<int, int>(0, 0); } protected override ItemStack[] GetDrop(BlockDescriptor descriptor) { return new ItemStack[0]; } } }
using System; using TrueCraft.API; using TrueCraft.API.Logic; namespace TrueCraft.Core.Logic.Blocks { public class AirBlock : BlockProvider { public static readonly byte BlockID = 0x00; public override byte ID { get { return 0x00; } } public override double BlastResistance { get { return 0; } } public override double Hardness { get { return 0; } } public override bool Opaque { get { return false; } } public override byte Luminance { get { return 0; } } public override string DisplayName { get { return "Air"; } } public override Tuple<int, int> GetTextureMap(byte metadata) { return new Tuple<int, int>(0, 0); } protected override ItemStack[] GetDrop(BlockDescriptor descriptor) { return new ItemStack[0]; } } }
Move guest participation beatmap up to below loved
// 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 osu.Framework.Localisation; using osu.Game.Online.API.Requests; using osu.Game.Overlays.Profile.Sections.Beatmaps; using osu.Game.Resources.Localisation.Web; namespace osu.Game.Overlays.Profile.Sections { public class BeatmapsSection : ProfileSection { public override LocalisableString Title => UsersStrings.ShowExtraBeatmapsTitle; public override string Identifier => @"beatmaps"; public BeatmapsSection() { Children = new[] { new PaginatedBeatmapContainer(BeatmapSetType.Favourite, User, UsersStrings.ShowExtraBeatmapsFavouriteTitle), new PaginatedBeatmapContainer(BeatmapSetType.Ranked, User, UsersStrings.ShowExtraBeatmapsRankedTitle), new PaginatedBeatmapContainer(BeatmapSetType.Loved, User, UsersStrings.ShowExtraBeatmapsLovedTitle), new PaginatedBeatmapContainer(BeatmapSetType.Pending, User, UsersStrings.ShowExtraBeatmapsPendingTitle), new PaginatedBeatmapContainer(BeatmapSetType.Guest, User, UsersStrings.ShowExtraBeatmapsGuestTitle), new PaginatedBeatmapContainer(BeatmapSetType.Graveyard, User, UsersStrings.ShowExtraBeatmapsGraveyardTitle) }; } } }
// 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 osu.Framework.Localisation; using osu.Game.Online.API.Requests; using osu.Game.Overlays.Profile.Sections.Beatmaps; using osu.Game.Resources.Localisation.Web; namespace osu.Game.Overlays.Profile.Sections { public class BeatmapsSection : ProfileSection { public override LocalisableString Title => UsersStrings.ShowExtraBeatmapsTitle; public override string Identifier => @"beatmaps"; public BeatmapsSection() { Children = new[] { new PaginatedBeatmapContainer(BeatmapSetType.Favourite, User, UsersStrings.ShowExtraBeatmapsFavouriteTitle), new PaginatedBeatmapContainer(BeatmapSetType.Ranked, User, UsersStrings.ShowExtraBeatmapsRankedTitle), new PaginatedBeatmapContainer(BeatmapSetType.Loved, User, UsersStrings.ShowExtraBeatmapsLovedTitle), new PaginatedBeatmapContainer(BeatmapSetType.Guest, User, UsersStrings.ShowExtraBeatmapsGuestTitle), new PaginatedBeatmapContainer(BeatmapSetType.Pending, User, UsersStrings.ShowExtraBeatmapsPendingTitle), new PaginatedBeatmapContainer(BeatmapSetType.Graveyard, User, UsersStrings.ShowExtraBeatmapsGraveyardTitle) }; } } }
Allow to run build even if git repo informations are not available
#tool "nuget:?package=GitVersion.CommandLine" #addin "Cake.Yaml" public class ContextInfo { public string NugetVersion { get; set; } public string AssemblyVersion { get; set; } public GitVersion Git { get; set; } public string BuildVersion { get { return NugetVersion + "-" + Git.Sha; } } } ContextInfo _versionContext = null; public ContextInfo VersionContext { get { if(_versionContext == null) throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property."); return _versionContext; } } public ContextInfo ReadContext(FilePath filepath) { _versionContext = DeserializeYamlFromFile<ContextInfo>(filepath); _versionContext.Git = GitVersion(); return _versionContext; } public void UpdateAppVeyorBuildVersionNumber() { var increment = 0; while(increment < 10) { try { var version = VersionContext.BuildVersion; if(increment > 0) version += "-" + increment; AppVeyor.UpdateBuildVersion(version); break; } catch { increment++; } } }
#tool "nuget:?package=GitVersion.CommandLine" #addin "Cake.Yaml" public class ContextInfo { public string NugetVersion { get; set; } public string AssemblyVersion { get; set; } public GitVersion Git { get; set; } public string BuildVersion { get { return NugetVersion + "-" + Git.Sha; } } } ContextInfo _versionContext = null; public ContextInfo VersionContext { get { if(_versionContext == null) throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property."); return _versionContext; } } public ContextInfo ReadContext(FilePath filepath) { _versionContext = DeserializeYamlFromFile<ContextInfo>(filepath); try { _versionContext.Git = GitVersion(); } catch { _versionContext.Git = new Cake.Common.Tools.GitVersion.GitVersion(); } return _versionContext; } public void UpdateAppVeyorBuildVersionNumber() { var increment = 0; while(increment < 10) { try { var version = VersionContext.BuildVersion; if(increment > 0) version += "-" + increment; AppVeyor.UpdateBuildVersion(version); break; } catch { increment++; } } }
Fix crash when multiple threads may exist.
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Interop; using WindowsDesktop.Interop; namespace WindowsDesktop.Internal { internal abstract class RawWindow { public string Name { get; set; } public HwndSource Source { get; private set; } public IntPtr Handle => this.Source?.Handle ?? IntPtr.Zero; public virtual void Show() { this.Show(new HwndSourceParameters(this.Name)); } protected void Show(HwndSourceParameters parameters) { this.Source = new HwndSource(parameters); this.Source.AddHook(this.WndProc); } public virtual void Close() { this.Source?.RemoveHook(this.WndProc); this.Source?.Dispose(); this.Source = null; NativeMethods.CloseWindow(this.Handle); } protected virtual IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { return IntPtr.Zero; } } }
using System; using System.Windows.Interop; using System.Windows.Threading; using WindowsDesktop.Interop; namespace WindowsDesktop.Internal { internal abstract class RawWindow { public string Name { get; set; } public HwndSource Source { get; private set; } public IntPtr Handle => this.Source?.Handle ?? IntPtr.Zero; public virtual void Show() { this.Show(new HwndSourceParameters(this.Name)); } protected void Show(HwndSourceParameters parameters) { this.Source = new HwndSource(parameters); this.Source.AddHook(this.WndProc); } public virtual void Close() { this.Source?.RemoveHook(this.WndProc); // Source could have been created on a different thread, which means we // have to Dispose of it on the UI thread or it will crash. this.Source?.Dispatcher?.BeginInvoke(DispatcherPriority.Send, (Action)(() => this.Source?.Dispose())); this.Source = null; NativeMethods.CloseWindow(this.Handle); } protected virtual IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { return IntPtr.Zero; } } }
Add standard demo sites setup as a test
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; using Certify.Models; namespace Certify.Service.Tests.Integration { [TestClass] public class ManagedCertificateTests : ServiceTestBase { [TestMethod] public async Task TestGetManagedCertificates() { var filter = new ManagedCertificateFilter(); var result = await _client.GetManagedCertificates(filter); Assert.IsNotNull(result, $"Fetched {result.Count} managed sites"); } [TestMethod] public async Task TestGetManagedCertificate() { //get full list var filter = new ManagedCertificateFilter { MaxResults = 10 }; var results = await _client.GetManagedCertificates(filter); Assert.IsTrue(results.Count > 0, "Got one or more managed sites"); //attempt to get single item var site = await _client.GetManagedCertificate(results[0].Id); Assert.IsNotNull(site, $"Fetched single managed site details"); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; using Certify.Models; using System.Collections.Generic; namespace Certify.Service.Tests.Integration { [TestClass] public class ManagedCertificateTests : ServiceTestBase { [TestMethod] public async Task TestGetManagedCertificates() { var filter = new ManagedCertificateFilter(); var result = await _client.GetManagedCertificates(filter); Assert.IsNotNull(result, $"Fetched {result.Count} managed sites"); } [TestMethod] public async Task TestGetManagedCertificate() { //get full list var filter = new ManagedCertificateFilter { MaxResults = 10 }; var results = await _client.GetManagedCertificates(filter); Assert.IsTrue(results.Count > 0, "Got one or more managed sites"); //attempt to get single item var site = await _client.GetManagedCertificate(results[0].Id); Assert.IsNotNull(site, $"Fetched single managed site details"); } [TestMethod] [Ignore] public async Task TestCreateManagedCertificates() { //get full list var list = new List<ManagedCertificate> { GetExample("msdn.webprofusion.com", 12), GetExample("demo.webprofusion.co.uk", 45), GetExample("clients.dependencymanager.com",75), GetExample("soundshed.com",32), GetExample("*.projectbids.co.uk",48), GetExample("exchange.projectbids.co.uk",19), GetExample("remote.dependencymanager.com",7), GetExample("git.example.com",56) }; foreach (var site in list) { await _client.UpdateManagedCertificate(site); } } private ManagedCertificate GetExample(string title, int numDays) { return new ManagedCertificate() { Id = Guid.NewGuid().ToString(), Name = title, DateExpiry = DateTime.Now.AddDays(numDays), DateLastRenewalAttempt = DateTime.Now.AddDays(-1), LastRenewalStatus = RequestState.Success }; } } }
Destroy bullets when they are out of bounds
using UnityEngine; using System.Collections; public class Bullet : MonoBehaviour { private float velocity = 35f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { this.transform.Translate(0, Time.deltaTime * this.velocity, 0, Space.Self); } }
using UnityEngine; using System.Collections; public class Bullet : MonoBehaviour { private float velocity = 35f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { this.transform.Translate(0, Time.deltaTime * this.velocity, 0, Space.Self); // Destroy the bullet when it is out of bounds of screen if (isOutOfScreen()) { Destroy(this.gameObject); } } private bool isOutOfScreen () { Vector3 posbullet = Camera.main.WorldToScreenPoint(this.gameObject.transform.position); float screenWidth = Camera.main.pixelWidth; float screenHeight = Camera.main.pixelHeight; if (posbullet.x < 0 || posbullet.x > screenWidth || posbullet.y < 0 || posbullet.y > screenHeight ) { return true; } return false; } }
Add copyright notice to new file
using FluentAssertions; using Microsoft.DotNet.Cli.Utils; using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using Microsoft.NET.TestFramework.Assertions; namespace Microsoft.NET.TestFramework { public static class CommandExtensions { public static ICommand EnsureExecutable(this ICommand command) { // Workaround for https://github.com/NuGet/Home/issues/4424 if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Command.Create("chmod", new[] { "755", command.CommandName }) .Execute() .Should() .Pass(); } return command; } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using FluentAssertions; using Microsoft.DotNet.Cli.Utils; using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using Microsoft.NET.TestFramework.Assertions; namespace Microsoft.NET.TestFramework { public static class CommandExtensions { public static ICommand EnsureExecutable(this ICommand command) { // Workaround for https://github.com/NuGet/Home/issues/4424 if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Command.Create("chmod", new[] { "755", command.CommandName }) .Execute() .Should() .Pass(); } return command; } } }
Fix syntax error in TimingController
using System.Collections; using System.Collections.Generic; using UnityEngine; public class YoumuSlashTimingController : MonoBehaviour { public delegate void BeatDelegate(int beat); public static BeatDelegate onBeat; [SerializeField] private YoumuSlashTimingData timingData; [SerializeField] private float StartDelay = .5f; private AudioSource musicSource; private int lastInvokedBeat; private void Awake() { onBeat = null; musicSource = GetComponent<AudioSource>(); musicSource.clip = timingData.MusicClip; timingData.initiate(musicSource); } void Start() { AudioHelper.playScheduled(musicSource, StartDelay); lastInvokedBeat = -1; onBeat += checkForSongEnd; InvokeRepeating("callOnBeat", StartDelay, timingData.getBeatDuration()); } void callOnBeat() { lastInvokedBeat++; onBeat(lastInvokedBeat); } void checkForSongEnd(int beat) print("Debug beat check"); if (lastInvokedBeat > 1 && !musicSource.isPlaying) CancelInvoke(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class YoumuSlashTimingController : MonoBehaviour { public delegate void BeatDelegate(int beat); public static BeatDelegate onBeat; [SerializeField] private YoumuSlashTimingData timingData; [SerializeField] private float StartDelay = .5f; private AudioSource musicSource; private int lastInvokedBeat; private void Awake() { onBeat = null; musicSource = GetComponent<AudioSource>(); musicSource.clip = timingData.MusicClip; timingData.initiate(musicSource); } void Start() { AudioHelper.playScheduled(musicSource, StartDelay); lastInvokedBeat = -1; onBeat += checkForSongEnd; InvokeRepeating("callOnBeat", StartDelay, timingData.getBeatDuration()); } void callOnBeat() { lastInvokedBeat++; onBeat(lastInvokedBeat); } void checkForSongEnd(int beat) { print("Debug beat check"); if (lastInvokedBeat > 1 && !musicSource.isPlaying) CancelInvoke(); } }
Fix tests to pass with newer setup
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using System.Net; namespace MultiMiner.Xgminer.Discovery.Tests { [TestClass] public class MinerFinderTests { [TestMethod] public void MinerFinder_FindsMiners() { const int times = 3; for (int i = 0; i < times; i++) { List<IPEndPoint> miners = MinerFinder.Find("192.168.0.29-100", 4028, 4029); Assert.IsTrue(miners.Count >= 4); } } [TestMethod] public void MinerFinder_ChecksMiners() { List<IPEndPoint> miners = MinerFinder.Find("192.168.0.29-100", 4028, 4029); int goodCount = miners.Count; miners.Add(new IPEndPoint(IPAddress.Parse("10.0.0.1"), 1000)); int checkCount = MinerFinder.Check(miners).Count; Assert.IsTrue(checkCount == goodCount); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using System.Net; namespace MultiMiner.Xgminer.Discovery.Tests { [TestClass] public class MinerFinderTests { [TestMethod] public void MinerFinder_FindsMiners() { const int times = 3; for (int i = 0; i < times; i++) { List<IPEndPoint> miners = MinerFinder.Find("192.168.0.29-100", 4028, 4029); Assert.IsTrue(miners.Count >= 3); } } [TestMethod] public void MinerFinder_ChecksMiners() { List<IPEndPoint> miners = MinerFinder.Find("192.168.0.29-100", 4028, 4029); int goodCount = miners.Count; miners.Add(new IPEndPoint(IPAddress.Parse("10.0.0.1"), 1000)); int checkCount = MinerFinder.Check(miners).Count; Assert.IsTrue(checkCount == goodCount); } } }
Fix scanning for MyGet versions
// Copyright 2020 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using System.Reflection; using JetBrains.Annotations; using Nuke.Common.IO; using Nuke.Common.Utilities; using Nuke.Common.ValueInjection; namespace Nuke.Common.Tooling { [PublicAPI] public class LatestMyGetVersionAttribute : ValueInjectionAttributeBase { private readonly string _feed; private readonly string _package; public LatestMyGetVersionAttribute(string feed, string package) { _feed = feed; _package = package; } public override object GetValue(MemberInfo member, object instance) { var rssFile = NukeBuild.TemporaryDirectory / $"{_feed}.xml"; HttpTasks.HttpDownloadFile($"https://www.myget.org/RSS/{_feed}", rssFile); return XmlTasks.XmlPeek(rssFile, ".//title") // TODO: regex? .First(x => x.Contains($" {_package} ")) .Split('(').Last() .Split(')').First() .TrimStart("version "); } } }
// Copyright 2020 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using System.Reflection; using JetBrains.Annotations; using Nuke.Common.IO; using Nuke.Common.Utilities; using Nuke.Common.ValueInjection; namespace Nuke.Common.Tooling { [PublicAPI] public class LatestMyGetVersionAttribute : ValueInjectionAttributeBase { private readonly string _feed; private readonly string _package; public LatestMyGetVersionAttribute(string feed, string package) { _feed = feed; _package = package; } public override object GetValue(MemberInfo member, object instance) { var rssFile = NukeBuild.TemporaryDirectory / $"{_feed}.xml"; HttpTasks.HttpDownloadFile($"https://www.myget.org/RSS/{_feed}", rssFile); return XmlTasks.XmlPeek(rssFile, ".//title") // TODO: regex? .First(x => x.Contains($"/{_package} ")) .Split('(').Last() .Split(')').First() .TrimStart("version "); } } }
Fix question submission truncation bug
@model CodeEditorSettings @if (Model.TextArea) { <textarea name="@Model.EditorName" style="display: none"></textarea> } <div id="wrapper-@Model.EditorName"></div> <script> function createEditor(text) { $('#wrapper-@Model.EditorName').html('<pre id="@Model.EditorName">' + (text != null ? text : '') + '</pre>'); createCodeEditor('@Model.EditorName', @Html.Raw(Model.TextArea ? $"$(\"textarea[name = {@Model.EditorName}]\")" : "undefined"), @Model.MinLines, @Model.MaxLines); } var initialContents = @Json.Serialize(Model.InitialContents); createEditor(initialContents); </script> @if (!string.IsNullOrEmpty(Model.RevertContents)) { <script> function revertCodeEditor() { var revertContents = @Json.Serialize(Model.RevertContents); createEditor(revertContents); } $(function() { $("#revert").css('display', '').click(revertCodeEditor); }) </script> }
@model CodeEditorSettings @if (Model.TextArea) { <textarea name="@Model.EditorName" style="display: none"></textarea> } <div id="wrapper-@Model.EditorName"></div> <script> function createEditor(text) { $('#wrapper-@Model.EditorName').html('<pre id="@Model.EditorName"></pre>'); $('#@Model.EditorName').text(text); createCodeEditor('@Model.EditorName', @Html.Raw(Model.TextArea ? $"$(\"textarea[name = {@Model.EditorName}]\")" : "undefined"), @Model.MinLines, @Model.MaxLines); } var initialContents = @Json.Serialize(Model.InitialContents); createEditor(initialContents); </script> @if (!string.IsNullOrEmpty(Model.RevertContents)) { <script> function revertCodeEditor() { var revertContents = @Json.Serialize(Model.RevertContents); createEditor(revertContents); } $(function() { $("#revert").css('display', '').click(revertCodeEditor); }) </script> }
Add method to GetPresignedUrlRequest and update to class
using System; namespace Amazon.S3 { public readonly struct GetPresignedUrlRequest { public GetPresignedUrlRequest( string host, AwsRegion region, string bucketName, string objectKey, TimeSpan expiresIn) { Host = host ?? throw new ArgumentNullException(nameof(host)); Region = region; BucketName = bucketName ?? throw new ArgumentNullException(nameof(bucketName)); Key = objectKey; ExpiresIn = expiresIn; } public readonly string Host; public readonly string BucketName; public readonly AwsRegion Region; public readonly string Key; public readonly TimeSpan ExpiresIn; } }
using System; namespace Amazon.S3 { public class GetPresignedUrlRequest { public GetPresignedUrlRequest( string method, string host, AwsRegion region, string bucketName, string objectKey, TimeSpan expiresIn) { Method = method ?? throw new ArgumentException(nameof(method)); Host = host ?? throw new ArgumentNullException(nameof(host)); Region = region; BucketName = bucketName ?? throw new ArgumentNullException(nameof(bucketName)); Key = objectKey; ExpiresIn = expiresIn; } public string Method { get; } public string Host { get; } public string BucketName { get; } public AwsRegion Region { get; } public string Key { get; } public TimeSpan ExpiresIn { get; } } }
Change library version to 0.8.1
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("CurrencyCloud")] [assembly: AssemblyDescription("CurrencyCloud API client library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Currency Cloud")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Copyright © Currency Cloud 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("e2c08eff-8a14-4c77-abd3-c9e193ae81e8")] // 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.7.4.0")] [assembly: AssemblyFileVersion("0.7.4.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("CurrencyCloud")] [assembly: AssemblyDescription("CurrencyCloud API client library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Currency Cloud")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Copyright © Currency Cloud 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("e2c08eff-8a14-4c77-abd3-c9e193ae81e8")] // 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.8.1.0")] [assembly: AssemblyFileVersion("0.8.1.0")]
Add agent to web owin middleware
using System; using System.Collections.Generic; using System.Threading.Tasks; using Glimpse.Host.Web.Owin.Framework; namespace Glimpse.Host.Web.Owin { public class GlimpseMiddleware { private readonly Func<IDictionary<string, object>, Task> _innerNext; public GlimpseMiddleware(Func<IDictionary<string, object>, Task> innerNext) { _innerNext = innerNext; } public async Task Invoke(IDictionary<string, object> environment) { var newContext = new HttpContext(environment); await _innerNext(environment); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Glimpse.Host.Web.Owin.Framework; using Glimpse.Agent.Web; namespace Glimpse.Host.Web.Owin { public class GlimpseMiddleware { private readonly Func<IDictionary<string, object>, Task> _innerNext; private readonly WebAgentRuntime _runtime; public GlimpseMiddleware(Func<IDictionary<string, object>, Task> innerNext) { _innerNext = innerNext; _runtime = new WebAgentRuntime(); // TODO: This shouldn't have this direct depedency } public async Task Invoke(IDictionary<string, object> environment) { var newContext = new HttpContext(environment); _runtime.Begin(newContext); await _innerNext(environment); _runtime.End(newContext); } } }
Disable tinting option on Android
using System; using Android.Views; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using Android.Graphics; using System.ComponentModel; using CrossPlatformTintedImage; using CrossPlatformTintedImage.Droid; [assembly:ExportRendererAttribute(typeof(TintedImage), typeof(TintedImageRenderer))] namespace CrossPlatformTintedImage.Droid { public class TintedImageRenderer : ImageRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Image> e) { base.OnElementChanged(e); SetTint(); } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == TintedImage.TintColorProperty.PropertyName) SetTint(); } void SetTint() { if (Control != null && Element != null) { var colorFilter = new PorterDuffColorFilter(((TintedImage) Element).TintColor.ToAndroid(), PorterDuff.Mode.SrcIn); Control.SetColorFilter(colorFilter); } } } }
using System; using Android.Views; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using Android.Graphics; using System.ComponentModel; using CrossPlatformTintedImage; using CrossPlatformTintedImage.Droid; [assembly:ExportRendererAttribute(typeof(TintedImage), typeof(TintedImageRenderer))] namespace CrossPlatformTintedImage.Droid { public class TintedImageRenderer : ImageRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Image> e) { base.OnElementChanged(e); SetTint(); } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == TintedImage.TintColorProperty.PropertyName) SetTint(); } void SetTint() { if (Control == null || Element == null) return; if (((TintedImage)Element).TintColor.Equals(Xamarin.Forms.Color.Transparent)) { //Turn off tinting if (Control.ColorFilter != null) Control.ClearColorFilter(); return; } //Apply tint color var colorFilter = new PorterDuffColorFilter(((TintedImage)Element).TintColor.ToAndroid(), PorterDuff.Mode.SrcIn); Control.SetColorFilter(colorFilter); } } }
Mark render start point as graph part (obviously)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FeralTic.DX11; namespace VVVV.DX11 { public interface IAttachableWindow { void AttachContext(DX11RenderContext renderContext); IntPtr WindowHandle { get; } } public interface IDX11RenderStartPoint { DX11RenderContext RenderContext { get; } bool Enabled { get; } void Present(); } public interface IDX11RenderWindow : IDX11RenderStartPoint , IAttachableWindow { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FeralTic.DX11; namespace VVVV.DX11 { public interface IAttachableWindow { void AttachContext(DX11RenderContext renderContext); IntPtr WindowHandle { get; } } public interface IDX11RenderStartPoint : IDX11RenderGraphPart { DX11RenderContext RenderContext { get; } bool Enabled { get; } void Present(); } public interface IDX11RenderWindow : IDX11RenderStartPoint , IAttachableWindow { } }
Change "Ok" to "OK" in message dialogs
using System.Windows; namespace GitMind.Common.MessageDialogs { /// <summary> /// Interaction logic for MessageDialog.xaml /// </summary> public partial class MessageDialog : Window { public MessageDialog( Window owner, string message, string title, MessageBoxButton button, MessageBoxImage image) { Owner = owner; InitializeComponent(); MessageDialogViewModel viewModel = new MessageDialogViewModel(); DataContext = viewModel; viewModel.Title = title; viewModel.Message = message; viewModel.IsInfo = image == MessageBoxImage.Information; viewModel.IsQuestion = image == MessageBoxImage.Question; viewModel.IsWarn = image == MessageBoxImage.Warning; viewModel.IsError = image == MessageBoxImage.Error; if (button == MessageBoxButton.OK) { viewModel.OkText = "Ok"; viewModel.IsCancelVisible = false; } else if (button == MessageBoxButton.OKCancel) { viewModel.OkText = "Ok"; viewModel.CancelText = "Cancel"; viewModel.IsCancelVisible = true; } else if (button == MessageBoxButton.YesNo) { viewModel.OkText = "Yes"; viewModel.CancelText = "No"; viewModel.IsCancelVisible = true; } } } }
using System.Windows; namespace GitMind.Common.MessageDialogs { /// <summary> /// Interaction logic for MessageDialog.xaml /// </summary> public partial class MessageDialog : Window { public MessageDialog( Window owner, string message, string title, MessageBoxButton button, MessageBoxImage image) { Owner = owner; InitializeComponent(); MessageDialogViewModel viewModel = new MessageDialogViewModel(); DataContext = viewModel; viewModel.Title = title; viewModel.Message = message; viewModel.IsInfo = image == MessageBoxImage.Information; viewModel.IsQuestion = image == MessageBoxImage.Question; viewModel.IsWarn = image == MessageBoxImage.Warning; viewModel.IsError = image == MessageBoxImage.Error; if (button == MessageBoxButton.OK) { viewModel.OkText = "OK"; viewModel.IsCancelVisible = false; } else if (button == MessageBoxButton.OKCancel) { viewModel.OkText = "OK"; viewModel.CancelText = "Cancel"; viewModel.IsCancelVisible = true; } else if (button == MessageBoxButton.YesNo) { viewModel.OkText = "Yes"; viewModel.CancelText = "No"; viewModel.IsCancelVisible = true; } } } }
Change - finished compliance for to_number function.
using System; using DevLab.JmesPath.Interop; using Newtonsoft.Json.Linq; namespace DevLab.JmesPath.Functions { public class ToNumberFunction : JmesPathFunction { public ToNumberFunction() : base("to_number", 1) { } public override bool Validate(params JToken[] args) { return true; } public override JToken Execute(params JToken[] args) { return new JValue(Convert.ToInt32(args[0].Value<int>())); } } }
using System; using System.Globalization; using DevLab.JmesPath.Interop; using Newtonsoft.Json.Linq; namespace DevLab.JmesPath.Functions { public class ToNumberFunction : JmesPathFunction { public ToNumberFunction() : base("to_number", 1) { } public override bool Validate(params JToken[] args) { return true; } public override JToken Execute(params JToken[] args) { var arg = args[0]; if (args[0] == null) return null; switch (arg.Type) { case JTokenType.Integer: case JTokenType.Float: return arg; case JTokenType.String: { var value = args[0].Value<string>(); int i =0 ; double d = 0; if (int.TryParse(value, out i)) return new JValue(i); else if (double.TryParse(value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d)) return new JValue(d); return null; } default: return null; } } } }
Use static properties instead of static constructor ==> if exception is thrown, detailed information is available, else TypeInitialiser exception is thrown
using System.Collections.Generic; using NHibernate; using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; namespace PPWCode.Vernacular.NHibernate.I.Test { public static class NhConfigurator { private const string ConnectionString = "Data Source=:memory:;Version=3;New=True;"; private static readonly Configuration s_Configuration; private static readonly ISessionFactory s_SessionFactory; static NhConfigurator() { s_Configuration = new Configuration() .Configure() .DataBaseIntegration( db => { db.Dialect<SQLiteDialect>(); db.Driver<SQLite20Driver>(); db.ConnectionProvider<TestConnectionProvider>(); db.ConnectionString = ConnectionString; }) .SetProperty(Environment.CurrentSessionContextClass, "thread_static"); IDictionary<string, string> props = s_Configuration.Properties; if (props.ContainsKey(Environment.ConnectionStringName)) { props.Remove(Environment.ConnectionStringName); } s_SessionFactory = s_Configuration.BuildSessionFactory(); } public static Configuration Configuration { get { return s_Configuration; } } public static ISessionFactory SessionFactory { get { return s_SessionFactory; } } } }
using System.Collections.Generic; using NHibernate; using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; namespace PPWCode.Vernacular.NHibernate.I.Test { public static class NhConfigurator { private const string ConnectionString = "Data Source=:memory:;Version=3;New=True;"; private static readonly object s_Locker = new object(); private static volatile Configuration s_Configuration; private static volatile ISessionFactory s_SessionFactory; public static Configuration Configuration { get { if (s_Configuration == null) { lock (s_Locker) { if (s_Configuration == null) { s_Configuration = new Configuration() .Configure() .DataBaseIntegration( db => { db.Dialect<SQLiteDialect>(); db.Driver<SQLite20Driver>(); db.ConnectionProvider<TestConnectionProvider>(); db.ConnectionString = ConnectionString; }) .SetProperty(Environment.CurrentSessionContextClass, "thread_static"); IDictionary<string, string> props = s_Configuration.Properties; if (props.ContainsKey(Environment.ConnectionStringName)) { props.Remove(Environment.ConnectionStringName); } } } } return s_Configuration; } } public static ISessionFactory SessionFactory { get { if (s_SessionFactory == null) { lock (s_Locker) { if (s_SessionFactory == null) { s_SessionFactory = Configuration.BuildSessionFactory(); } } } return s_SessionFactory; } } } }
Add some complexity to test cases.
using System; using System.Collections.Generic; using Xunit; namespace CSharpViaTest.IOs._10_HandleText { /* * Description * =========== * * This test will introduce the concept of Codepoint and surrogate pair to you. But * for the most of the cases, the character can fit in 16-bit unicode character. * * Difficulty: Super Easy */ public class CalculateTextCharLength { static IEnumerable<object[]> TestCases() => new[] { new object[]{"", 0}, new object[]{"1", 1}, new object[]{char.ConvertFromUtf32(0x2A601), 1} }; #region Please modifies the code to pass the test static int GetCharacterLength(string text) { throw new NotImplementedException(); } #endregion [Theory] [MemberData(nameof(TestCases))] public void should_calculate_text_character_length(string testString, int expectedLength) { Assert.Equal(expectedLength, GetCharacterLength(testString)); } } }
using System; using System.Collections.Generic; using Xunit; namespace CSharpViaTest.IOs._10_HandleText { /* * Description * =========== * * This test will introduce the concept of Codepoint and surrogate pair to you. But * for the most of the cases, the character can fit in 16-bit unicode character. * * Difficulty: Super Easy */ public class CalculateTextCharLength { static IEnumerable<object[]> TestCases() => new[] { new object[]{"", 0}, new object[]{"12345", 5}, new object[]{char.ConvertFromUtf32(0x2A601) + "1234", 5} }; #region Please modifies the code to pass the test static int GetCharacterLength(string text) { throw new NotImplementedException(); } #endregion [Theory] [MemberData(nameof(TestCases))] public void should_calculate_text_character_length(string testString, int expectedLength) { Assert.Equal(expectedLength, GetCharacterLength(testString)); } } }
Add next page command property
using Newtonsoft.Json; namespace Dnn.PersonaBar.Library.Prompt.Models { /// <summary> /// Standard response object sent to client /// </summary> public class ConsoleResultModel { // the returned result - text or HTML [JsonProperty(PropertyName = "output")] public string Output; // is the output an error message? [JsonProperty(PropertyName = "isError")] public bool IsError; // is the Output HTML? [JsonProperty(PropertyName = "isHtml")] public bool IsHtml; // should the client reload after processing the command [JsonProperty(PropertyName = "mustReload")] public bool MustReload; // the response contains data to be formatted by the client [JsonProperty(PropertyName = "data")] public object Data; // optionally tell the client in what order the fields should be displayed [JsonProperty(PropertyName = "fieldOrder")] public string[] FieldOrder; [JsonProperty(PropertyName = "pagingInfo")] public PagingInfo PagingInfo; [JsonProperty(PropertyName = "records")] public int Records { get; set; } public ConsoleResultModel() { } public ConsoleResultModel(string output) { Output = output; } } }
using Newtonsoft.Json; namespace Dnn.PersonaBar.Library.Prompt.Models { /// <summary> /// Standard response object sent to client /// </summary> public class ConsoleResultModel { // the returned result - text or HTML [JsonProperty(PropertyName = "output")] public string Output; // is the output an error message? [JsonProperty(PropertyName = "isError")] public bool IsError; // is the Output HTML? [JsonProperty(PropertyName = "isHtml")] public bool IsHtml; // should the client reload after processing the command [JsonProperty(PropertyName = "mustReload")] public bool MustReload; // the response contains data to be formatted by the client [JsonProperty(PropertyName = "data")] public object Data; // optionally tell the client in what order the fields should be displayed [JsonProperty(PropertyName = "fieldOrder")] public string[] FieldOrder; [JsonProperty(PropertyName = "pagingInfo")] public PagingInfo PagingInfo; [JsonProperty(PropertyName = "nextPageCommand")] public string NextPageCommand; [JsonProperty(PropertyName = "records")] public int Records { get; set; } public ConsoleResultModel() { } public ConsoleResultModel(string output) { Output = output; } } }
Add dependency on Sequence and Fungus Script components
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; namespace Fungus { public class EventHandlerInfoAttribute : Attribute { public EventHandlerInfoAttribute(string category, string eventHandlerName, string helpText) { this.Category = category; this.EventHandlerName = eventHandlerName; this.HelpText = helpText; } public string Category { get; set; } public string EventHandlerName { get; set; } public string HelpText { get; set; } } /** * A Sequence may have an associated Event Handler which starts executing the sequence when * a specific event occurs. * To create a custom Event Handler, simply subclass EventHandler and call the ExecuteSequence() method * when the event occurs. * Add an EventHandlerInfo attibute and your new EventHandler class will automatically appear in the * 'Start Event' dropdown menu when a sequence is selected. */ public class EventHandler : MonoBehaviour { [HideInInspector] public Sequence parentSequence; /** * The Event Handler should call this method when the event is detected. */ public virtual bool ExecuteSequence() { if (parentSequence == null) { return false; } FungusScript fungusScript = parentSequence.GetFungusScript(); return fungusScript.ExecuteSequence(parentSequence); } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; namespace Fungus { public class EventHandlerInfoAttribute : Attribute { public EventHandlerInfoAttribute(string category, string eventHandlerName, string helpText) { this.Category = category; this.EventHandlerName = eventHandlerName; this.HelpText = helpText; } public string Category { get; set; } public string EventHandlerName { get; set; } public string HelpText { get; set; } } /** * A Sequence may have an associated Event Handler which starts executing the sequence when * a specific event occurs. * To create a custom Event Handler, simply subclass EventHandler and call the ExecuteSequence() method * when the event occurs. * Add an EventHandlerInfo attibute and your new EventHandler class will automatically appear in the * 'Start Event' dropdown menu when a sequence is selected. */ [RequireComponent(typeof(Sequence))] [RequireComponent(typeof(FungusScript))] public class EventHandler : MonoBehaviour { [HideInInspector] public Sequence parentSequence; /** * The Event Handler should call this method when the event is detected. */ public virtual bool ExecuteSequence() { if (parentSequence == null) { return false; } FungusScript fungusScript = parentSequence.GetFungusScript(); return fungusScript.ExecuteSequence(parentSequence); } } }
Change link title to manage reservations
@model SFA.DAS.EmployerAccounts.Web.ViewModels.AccountDashboardViewModel @if (Model.ReservedFundingToShow != null) { <h3 class="das-panel__heading">Apprenticeship funding secured</h3> <dl class="das-definition-list das-definition-list--with-separator"> <dt class="das-definition-list__title">Legal entity:</dt> <dd class="das-definition-list__definition">@Model.ReservedFundingToShowLegalEntityName</dd> <dt class="das-definition-list__title">Training course:</dt> <dd class="das-definition-list__definition">@Model.ReservedFundingToShow.CourseName</dd> <dt class="das-definition-list__title">Start and end date: </dt> <dd class="das-definition-list__definition">@Model.ReservedFundingToShow.StartDate.ToString("MMMM yyyy") to @Model.ReservedFundingToShow.EndDate.ToString("MMMM yyyy")</dd> </dl> } @if (Model.RecentlyAddedReservationId != null && Model.ReservedFundingToShow?.ReservationId != Model.RecentlyAddedReservationId) { <p>We're dealing with your request for funding, please check back later.</p> } <p><a href="@Url.ReservationsAction("reservations/manage")" class="das-panel__link">Check and secure funding now</a> </p>
@model SFA.DAS.EmployerAccounts.Web.ViewModels.AccountDashboardViewModel @if (Model.ReservedFundingToShow != null) { <h3 class="das-panel__heading">Apprenticeship funding secured</h3> <dl class="das-definition-list das-definition-list--with-separator"> <dt class="das-definition-list__title">Legal entity:</dt> <dd class="das-definition-list__definition">@Model.ReservedFundingToShowLegalEntityName</dd> <dt class="das-definition-list__title">Training course:</dt> <dd class="das-definition-list__definition">@Model.ReservedFundingToShow.CourseName</dd> <dt class="das-definition-list__title">Start and end date: </dt> <dd class="das-definition-list__definition">@Model.ReservedFundingToShow.StartDate.ToString("MMMM yyyy") to @Model.ReservedFundingToShow.EndDate.ToString("MMMM yyyy")</dd> </dl> } @if (Model.RecentlyAddedReservationId != null && Model.ReservedFundingToShow?.ReservationId != Model.RecentlyAddedReservationId) { <p>We're dealing with your request for funding, please check back later.</p> } <p><a href="@Url.ReservationsAction("reservations/manage")" class="das-panel__link">Manage reservations</a> </p>
Test for IList<T> and IEnumerable<T>
using System; using System.Collections.Generic; namespace DevelopmentInProgress.DipMapper.Test { public class TestDapperClass { public int Id { get; set; } public string Name { get; set; } public DateTime Date { get; set; } public IEnumerable<TestDapperClass> TestDataClasses { get; set; } } }
using System; using System.Collections.Generic; namespace DevelopmentInProgress.DipMapper.Test { public class TestDapperClass { public int Id { get; set; } public string Name { get; set; } public DateTime Date { get; set; } public IEnumerable<TestDapperClass> TestDataClasses { get; set; } public IList<TestDapperClass> TestDataClasse { get; set; } } }
Correct inconsistent use of tabs and spaces.
using System.Windows.Controls; namespace PopulousStringEditor.Views { /// <summary> /// Interaction logic for StringComparisonView.xaml /// </summary> public partial class StringComparisonView : UserControl { /// <summary>Gets or sets the visibility of the referenced strings.</summary> public System.Windows.Visibility ReferenceStringsVisiblity { get { return ReferenceStringsColumn.Visibility; } set { ReferenceStringsColumn.Visibility = value; } } /// <summary> /// Default constructor. /// </summary> public StringComparisonView() { InitializeComponent(); } } }
using System.Windows.Controls; namespace PopulousStringEditor.Views { /// <summary> /// Interaction logic for StringComparisonView.xaml /// </summary> public partial class StringComparisonView : UserControl { /// <summary>Gets or sets the visibility of the referenced strings.</summary> public System.Windows.Visibility ReferenceStringsVisiblity { get { return ReferenceStringsColumn.Visibility; } set { ReferenceStringsColumn.Visibility = value; } } /// <summary> /// Default constructor. /// </summary> public StringComparisonView() { InitializeComponent(); } } }
Change configurations to decimal value
using System; namespace Take.Blip.Builder.Hosting { public class ConventionsConfiguration : IConfiguration { public virtual TimeSpan InputProcessingTimeout => TimeSpan.FromMinutes(1); public virtual string RedisStorageConfiguration => "localhost"; public virtual int RedisDatabase => 0; public virtual int MaxTransitionsByInput => 10; public virtual int TraceQueueBoundedCapacity => 512; public virtual int TraceQueueMaxDegreeOfParallelism => 512; public virtual TimeSpan TraceTimeout => TimeSpan.FromSeconds(5); public virtual string RedisKeyPrefix => "builder"; public bool ContactCacheEnabled => true; public virtual TimeSpan ContactCacheExpiration => TimeSpan.FromMinutes(30); public virtual TimeSpan DefaultActionExecutionTimeout => TimeSpan.FromSeconds(30); public int ExecuteScriptLimitRecursion => 50; public int ExecuteScriptMaxStatements => 1000; public long ExecuteScriptLimitMemory => 0x100000; // 1MiB or 1 << 20 public long ExecuteScriptLimitMemoryWarning => 0x80000; // 512KiB or 1 << 19 public TimeSpan ExecuteScriptTimeout => TimeSpan.FromSeconds(5); } }
using System; namespace Take.Blip.Builder.Hosting { public class ConventionsConfiguration : IConfiguration { public virtual TimeSpan InputProcessingTimeout => TimeSpan.FromMinutes(1); public virtual string RedisStorageConfiguration => "localhost"; public virtual int RedisDatabase => 0; public virtual int MaxTransitionsByInput => 10; public virtual int TraceQueueBoundedCapacity => 512; public virtual int TraceQueueMaxDegreeOfParallelism => 512; public virtual TimeSpan TraceTimeout => TimeSpan.FromSeconds(5); public virtual string RedisKeyPrefix => "builder"; public bool ContactCacheEnabled => true; public virtual TimeSpan ContactCacheExpiration => TimeSpan.FromMinutes(30); public virtual TimeSpan DefaultActionExecutionTimeout => TimeSpan.FromSeconds(30); public int ExecuteScriptLimitRecursion => 50; public int ExecuteScriptMaxStatements => 1000; public long ExecuteScriptLimitMemory => 1_000_000; // Nearly 1MB or 1 << 20 public long ExecuteScriptLimitMemoryWarning => 500_000; // Nearly 512KB or 1 << 19 public TimeSpan ExecuteScriptTimeout => TimeSpan.FromSeconds(5); } }
Fix build breaks mirrored from Github
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; internal partial class Interop { internal partial class mincore { internal static int DeleteVolumeMountPoint(string mountPoint) { // DeleteVolumeMountPointW is not available to store apps. // The expectation is that no store app would even have permission // to call this from the app container throw new UnauthorizedAccessException(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; internal partial class Interop { internal partial class mincore { internal static bool DeleteVolumeMountPoint(string mountPoint) { // DeleteVolumeMountPointW is not available to store apps. // The expectation is that no store app would even have permission // to call this from the app container throw new UnauthorizedAccessException(); } } }
Remove the function specific filter.
// Copyright (c) Zac Brown. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using O365.Security.ETW; namespace hiddentreasure_etw_demo { public static class PowerShellMethodExecution { public static void Run() { // For a more thorough example of how to implement this detection, // have a look at https://github.com/zacbrown/PowerShellMethodAuditor var filter = new EventFilter(Filter .EventIdIs(7937) .And(UnicodeString.Contains("Payload", "Started")) .And(UnicodeString.Contains("ContextInfo", "Command Type = Function"))); filter.OnEvent += (IEventRecord r) => { var method = r.GetUnicodeString("ContextInfo"); Console.WriteLine($"Method executed:\n{method}"); }; var provider = new Provider("Microsoft-Windows-PowerShell"); provider.AddFilter(filter); var trace = new UserTrace(); trace.Enable(provider); // Setup Ctrl-C to call trace.Stop(); Helpers.SetupCtrlC(trace); // This call is blocking. The thread that calls UserTrace.Start() // is donating itself to the ETW subsystem to pump events off // of the buffer. trace.Start(); } } }
// Copyright (c) Zac Brown. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using O365.Security.ETW; namespace hiddentreasure_etw_demo { public static class PowerShellMethodExecution { public static void Run() { // For a more thorough example of how to implement this detection, // have a look at https://github.com/zacbrown/PowerShellMethodAuditor var filter = new EventFilter(Filter .EventIdIs(7937) .And(UnicodeString.Contains("Payload", "Started"))); filter.OnEvent += (IEventRecord r) => { var method = r.GetUnicodeString("ContextInfo"); Console.WriteLine($"Method executed:\n{method}"); }; var provider = new Provider("Microsoft-Windows-PowerShell"); provider.AddFilter(filter); var trace = new UserTrace(); trace.Enable(provider); // Setup Ctrl-C to call trace.Stop(); Helpers.SetupCtrlC(trace); // This call is blocking. The thread that calls UserTrace.Start() // is donating itself to the ETW subsystem to pump events off // of the buffer. trace.Start(); } } }
Fix path for Payments API
using Newtonsoft.Json.Linq; using SnapMD.ConnectedCare.Sdk.Models; namespace SnapMD.ConnectedCare.Sdk { public class PaymentsApi : ApiCall { public PaymentsApi(string baseUrl, string bearerToken, int hospitalId, string developerId, string apiKey) : base(baseUrl, bearerToken, developerId, apiKey) { HospitalId = hospitalId; } public PaymentsApi(string baseUrl, int hospitalId) : base(baseUrl) { HospitalId = hospitalId; } public int HospitalId { get; private set; } public JObject GetCustomerProfile(int userId) { //API looks so strange //hospital/{hospitalId}/payments/{userId} var result = MakeCall(string.Format("hospital/{0}/payments", HospitalId)); return result; } public JObject RegisterProfile(int userId, object paymentData) { //hospital/{hospitalId}/payments/{userId} var result = Post(string.Format("patients/{0}/payments", userId), paymentData); return result; } public ApiResponse GetPaymentStatus(int consultationId) { var result = MakeCall<ApiResponse>(string.Format("patients/copay/{0}/paymentstatus", consultationId)); return result; } } }
using Newtonsoft.Json.Linq; using SnapMD.ConnectedCare.Sdk.Models; namespace SnapMD.ConnectedCare.Sdk { public class PaymentsApi : ApiCall { public PaymentsApi(string baseUrl, string bearerToken, int hospitalId, string developerId, string apiKey) : base(baseUrl, bearerToken, developerId, apiKey) { HospitalId = hospitalId; } public PaymentsApi(string baseUrl, int hospitalId) : base(baseUrl) { HospitalId = hospitalId; } public int HospitalId { get; private set; } public JObject GetCustomerProfile(int userId) { var result = MakeCall(string.Format("patients/{0}/payments", userId)); return result; } public JObject RegisterProfile(int userId, object paymentData) { var result = Post(string.Format("patients/{0}/payments", userId), paymentData); return result; } public ApiResponse GetPaymentStatus(int consultationId) { var result = MakeCall<ApiResponse>(string.Format("patients/copay/{0}/paymentstatus", consultationId)); return result; } } }
Fix warning on linux/mac by adding AutoGenerateBindingRedirects
using System; using System.IO; using System.Linq; using System.Reflection; using Sharpmake; namespace SharpmakeGen { [Generate] public class SharpmakeApplicationProject : Common.SharpmakeBaseProject { public SharpmakeApplicationProject() : base(generateXmlDoc: false) { Name = "Sharpmake.Application"; ApplicationManifest = "app.manifest"; } public override void ConfigureAll(Configuration conf, Target target) { base.ConfigureAll(conf, target); conf.Output = Configuration.OutputType.DotNetConsoleApp; conf.ReferencesByName.Add("System.Windows.Forms"); conf.AddPrivateDependency<SharpmakeProject>(target); conf.AddPrivateDependency<SharpmakeGeneratorsProject>(target); conf.AddPrivateDependency<Platforms.CommonPlatformsProject>(target); } } }
using System; using System.IO; using System.Linq; using System.Reflection; using Sharpmake; namespace SharpmakeGen { [Generate] public class SharpmakeApplicationProject : Common.SharpmakeBaseProject { public SharpmakeApplicationProject() : base(generateXmlDoc: false) { Name = "Sharpmake.Application"; ApplicationManifest = "app.manifest"; } public override void ConfigureAll(Configuration conf, Target target) { base.ConfigureAll(conf, target); conf.Output = Configuration.OutputType.DotNetConsoleApp; conf.Options.Add(Options.CSharp.AutoGenerateBindingRedirects.Enabled); conf.ReferencesByName.Add("System.Windows.Forms"); conf.AddPrivateDependency<SharpmakeProject>(target); conf.AddPrivateDependency<SharpmakeGeneratorsProject>(target); conf.AddPrivateDependency<Platforms.CommonPlatformsProject>(target); } } }
Fix and document the interface
using System; using System.Collections.Generic; using System.Collections.Specialized; namespace GitHub.Collections { public interface ITrackingCollection<T> : IDisposable, IList<T> where T : ICopyable<T> { IObservable<T> Listen(IObservable<T> obs); IDisposable Subscribe(); IDisposable Subscribe(Action onCompleted); void SetComparer(Func<T, T, int> theComparer); void SetFilter(Func<T, int, IList<T>, bool> filter); event NotifyCollectionChangedEventHandler CollectionChanged; } }
using System; using System.Collections.Generic; using System.Collections.Specialized; namespace GitHub.Collections { /// <summary> /// TrackingCollection is a specialization of ObservableCollection that gets items from /// an observable sequence and updates its contents in such a way that two updates to /// the same object (as defined by an Equals call) will result in one object on /// the list being updated (as opposed to having two different instances of the object /// added to the list). /// It is always sorted, either via the supplied comparer or using the default comparer /// for T /// </summary> /// <typeparam name="T"></typeparam> public interface ITrackingCollection<T> : IDisposable, IList<T> where T : ICopyable<T> { /// <summary> /// Sets up an observable as source for the collection. /// </summary> /// <param name="obs"></param> /// <returns>An observable that will return all the items that are /// fed via the original observer, for further processing by user code /// if desired</returns> IObservable<T> Listen(IObservable<T> obs); IDisposable Subscribe(); IDisposable Subscribe(Action<T> onNext, Action onCompleted); /// <summary> /// Set a new comparer for the existing data. This will cause the /// collection to be resorted and refiltered. /// </summary> /// <param name="theComparer">The comparer method for sorting, or null if not sorting</param> void SetComparer(Func<T, T, int> comparer); /// <summary> /// Set a new filter. This will cause the collection to be filtered /// </summary> /// <param name="theFilter">The new filter, or null to not have any filtering</param> void SetFilter(Func<T, int, IList<T>, bool> filter); void AddItem(T item); void RemoveItem(T item); event NotifyCollectionChangedEventHandler CollectionChanged; } }
Use 'Thread.Sleep' instead of 'await'-less 'Task.Delay'.
using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace Mirage.Urbanization.Simulation { public class NeverEndingTask { private readonly CancellationToken _token; private readonly Task _task; public NeverEndingTask(string description, Action taskAction, CancellationToken token) { if (taskAction == null) throw new ArgumentNullException(nameof(taskAction)); _token = token; _task = CreateTask(description.ToLower(), taskAction, token); } private static Task CreateTask(string description, Action taskAction, CancellationToken token) { return new Task(() => { var stopWatch = new Stopwatch(); while (true) { stopWatch.Restart(); Mirage.Urbanization.Logger.Instance.WriteLine($"Executing {description}..."); taskAction(); Mirage.Urbanization.Logger.Instance.WriteLine($"Executing {description} completed in {stopWatch.Elapsed}."); Task.Delay(2000, token).Wait(token); } // ReSharper disable once FunctionNeverReturns }, token); } public void Start() { _task.Start(); } public void Wait() { try { _task.Wait(_token); } catch (OperationCanceledException ex) { Mirage.Urbanization.Logger.Instance.WriteLine(ex); } } } }
using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace Mirage.Urbanization.Simulation { public class NeverEndingTask { private readonly CancellationToken _token; private readonly Task _task; public NeverEndingTask(string description, Action taskAction, CancellationToken token) { if (taskAction == null) throw new ArgumentNullException(nameof(taskAction)); _token = token; _task = CreateTask(description.ToLower(), taskAction, token); } private static Task CreateTask(string description, Action taskAction, CancellationToken token) { return new Task(() => { var stopWatch = new Stopwatch(); while (true) { stopWatch.Restart(); Mirage.Urbanization.Logger.Instance.WriteLine($"Executing {description}..."); taskAction(); Mirage.Urbanization.Logger.Instance.WriteLine($"Executing {description} completed in {stopWatch.Elapsed}."); Thread.Sleep(2000); } // ReSharper disable once FunctionNeverReturns }, token); } public void Start() { _task.Start(); } public void Wait() { try { _task.Wait(_token); } catch (OperationCanceledException ex) { Mirage.Urbanization.Logger.Instance.WriteLine(ex); } } } }
Remove workaround for xslt and use a XmlReader instead of a XPath navigator
using System.Text; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; namespace Tranquire.Reporting { partial class XmlDocumentObserver { /// <summary> /// Returns a HTML document that contains the report. /// </summary> /// <returns></returns> public string GetHtmlDocument() { var xmlDocument = GetXmlDocument(); // enabling debug mode workaround an null reference exception occuring internally in .net core var xslt = new XslCompiledTransform(true); var xmlReader = XmlReader.Create(typeof(XmlDocumentObserver).Assembly.GetManifestResourceStream("Tranquire.Reporting.XmlReport.xsl")); xslt.Load(xmlReader); var result = new StringBuilder(); var xmlWriter = XmlWriter.Create(result); xslt.Transform(xmlDocument.CreateNavigator(), xmlWriter); return result.ToString() .Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "<!DOCTYPE html>") .Replace("<span class=\"glyphicon then-icon\" />", "<span class=\"glyphicon then-icon\"></span>"); } } }
using System.Text; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; namespace Tranquire.Reporting { partial class XmlDocumentObserver { /// <summary> /// Returns a HTML document that contains the report. /// </summary> /// <returns></returns> public string GetHtmlDocument() { var xmlDocument = GetXmlDocument(); var xslt = new XslCompiledTransform(false); var xmlReader = XmlReader.Create(typeof(XmlDocumentObserver).Assembly.GetManifestResourceStream("Tranquire.Reporting.XmlReport.xsl")); xslt.Load(xmlReader); var result = new StringBuilder(); var xmlWriter = XmlWriter.Create(result); xslt.Transform(xmlDocument.CreateReader(), xmlWriter); return result.ToString() .Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "<!DOCTYPE html>") .Replace("<span class=\"glyphicon then-icon\" />", "<span class=\"glyphicon then-icon\"></span>"); } } }
Use culture invariant version of float.TryParse
using System.Globalization; namespace OpenSage.Data.Utilities { internal static class ParseUtility { public static float ParseFloat(string s) { return float.Parse(s, CultureInfo.InvariantCulture); } public static bool TryParseFloat(string s, out float result) { return float.TryParse(s, out result); } } }
using System.Globalization; namespace OpenSage.Data.Utilities { internal static class ParseUtility { public static float ParseFloat(string s) { return float.Parse(s, CultureInfo.InvariantCulture); } public static bool TryParseFloat(string s, out float result) { return float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out result); } } }
Fix cache update exception typo
using System; namespace HobknobClientNet { public interface IHobknobClientFactory { IHobknobClient Create(string etcdHost, int etcdPort, string applicationName, TimeSpan cacheUpdateInterval, EventHandler<CacheUpdateFailedArgs> cacheUpdateFailed); } public class HobknobClientFactory : IHobknobClientFactory { public IHobknobClient Create(string etcdHost, int etcdPort, string applicationName, TimeSpan cacheUpdateInterval, EventHandler<CacheUpdateFailedArgs> cacheUpdateFailed) { var etcdKeysPath = string.Format("http://{0}:{1}/v2/keys/", etcdHost, etcdPort); var etcdClient = new EtcdClient(new Uri(etcdKeysPath)); var featureToggleProvider = new FeatureToggleProvider(etcdClient, applicationName); var featureToggleCache = new FeatureToggleCache(featureToggleProvider, cacheUpdateInterval); var hobknobClient = new HobknobClient(featureToggleCache, applicationName); if (cacheUpdateFailed == null) throw new ArgumentNullException("cacheUpdateFailed", "Cached update handler is emtpy"); featureToggleCache.CacheUpdateFailed += cacheUpdateFailed; featureToggleCache.Initialize(); return hobknobClient; } } }
using System; namespace HobknobClientNet { public interface IHobknobClientFactory { IHobknobClient Create(string etcdHost, int etcdPort, string applicationName, TimeSpan cacheUpdateInterval, EventHandler<CacheUpdateFailedArgs> cacheUpdateFailed); } public class HobknobClientFactory : IHobknobClientFactory { public IHobknobClient Create(string etcdHost, int etcdPort, string applicationName, TimeSpan cacheUpdateInterval, EventHandler<CacheUpdateFailedArgs> cacheUpdateFailed) { var etcdKeysPath = string.Format("http://{0}:{1}/v2/keys/", etcdHost, etcdPort); var etcdClient = new EtcdClient(new Uri(etcdKeysPath)); var featureToggleProvider = new FeatureToggleProvider(etcdClient, applicationName); var featureToggleCache = new FeatureToggleCache(featureToggleProvider, cacheUpdateInterval); var hobknobClient = new HobknobClient(featureToggleCache, applicationName); if (cacheUpdateFailed == null) throw new ArgumentNullException("cacheUpdateFailed", "Cached update handler is empty"); featureToggleCache.CacheUpdateFailed += cacheUpdateFailed; featureToggleCache.Initialize(); return hobknobClient; } } }
Add failing test case for setting colour at creation
// 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 osu.Framework.Graphics; using osu.Framework.Graphics.UserInterface; using osu.Framework.Testing; namespace osu.Framework.Tests.Visual.UserInterface { public class TestSceneColourPicker : FrameworkTestScene { [SetUpSteps] public void SetUpSteps() { ColourPicker colourPicker = null; AddStep("create picker", () => Child = colourPicker = new BasicColourPicker()); AddStep("set colour externally", () => colourPicker.Current.Value = Colour4.Goldenrod); AddAssert("colour is correct", () => colourPicker.Current.Value == Colour4.Goldenrod); } } }
// 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 NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.UserInterface; namespace osu.Framework.Tests.Visual.UserInterface { public class TestSceneColourPicker : FrameworkTestScene { [Test] public void TestExternalColourSetAfterCreation() { ColourPicker colourPicker = null; AddStep("create picker", () => Child = colourPicker = new BasicColourPicker()); AddStep("set colour externally", () => colourPicker.Current.Value = Colour4.Goldenrod); AddAssert("colour is correct", () => colourPicker.Current.Value == Colour4.Goldenrod); } [Test] public void TestExternalColourSetAtCreation() { ColourPicker colourPicker = null; AddStep("create picker", () => Child = colourPicker = new BasicColourPicker { Current = { Value = Colour4.Goldenrod } }); AddAssert("colour is correct", () => colourPicker.Current.Value == Colour4.Goldenrod); } } }
Add service and container clients
using Azure.Core.Pipeline; using Azure.Test.PerfStress; using System; using System.Net.Http; namespace Azure.Storage.Blobs.PerfStress { public abstract class StorageTest<TOptions> : PerfStressTest<TOptions> where TOptions: PerfStressOptions { private const string _containerName = "perfstress"; protected BlobClient BlobClient { get; private set; } public StorageTest(string id, TOptions options) : base(id, options) { var blobName = this.GetType().Name.ToLowerInvariant() + id; var connectionString = Environment.GetEnvironmentVariable("STORAGE_CONNECTION_STRING"); if (string.IsNullOrEmpty(connectionString)) { throw new InvalidOperationException("Undefined environment variable STORAGE_CONNECTION_STRING"); } var httpClientHandler = new HttpClientHandler(); httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true; var httpClient = new HttpClient(httpClientHandler); var blobClientOptions = new BlobClientOptions(); blobClientOptions.Transport = new HttpClientTransport(httpClient); var serviceClient = new BlobServiceClient(connectionString, blobClientOptions); try { serviceClient.CreateBlobContainer(_containerName); } catch (StorageRequestFailedException) { } BlobClient = new BlobClient(connectionString, _containerName, blobName, blobClientOptions); } } }
using Azure.Core.Pipeline; using Azure.Test.PerfStress; using System; using System.Net.Http; namespace Azure.Storage.Blobs.PerfStress { public abstract class StorageTest<TOptions> : PerfStressTest<TOptions> where TOptions: PerfStressOptions { private const string _containerName = "perfstress"; protected BlobServiceClient BlobServiceClient { get; private set; } protected BlobContainerClient BlobContainerClient { get; private set; } protected BlobClient BlobClient { get; private set; } public StorageTest(string id, TOptions options) : base(id, options) { var blobName = this.GetType().Name.ToLowerInvariant() + id; var connectionString = Environment.GetEnvironmentVariable("STORAGE_CONNECTION_STRING"); if (string.IsNullOrEmpty(connectionString)) { throw new InvalidOperationException("Undefined environment variable STORAGE_CONNECTION_STRING"); } var httpClientHandler = new HttpClientHandler(); httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true; var httpClient = new HttpClient(httpClientHandler); var blobClientOptions = new BlobClientOptions(); blobClientOptions.Transport = new HttpClientTransport(httpClient); BlobServiceClient = new BlobServiceClient(connectionString, blobClientOptions); try { BlobServiceClient.CreateBlobContainer(_containerName); } catch (StorageRequestFailedException) { } BlobContainerClient = BlobServiceClient.GetBlobContainerClient(_containerName); BlobClient = BlobContainerClient.GetBlobClient(blobName); } } }
Test Major/Minor versions - Commit 2
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; // ADDED FIRST LINE namespace PracticeGit.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.Title = "Home Page"; return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; // ADDED FIRST LINE // ADDED SECOND LINE namespace PracticeGit.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.Title = "Home Page"; return View(); } } }
Fix "Picture Slideshow" "Maximum File Size" default value
using System; using System.ComponentModel; using DesktopWidgets.WidgetBase.Settings; namespace DesktopWidgets.Widgets.PictureSlideshow { public class Settings : WidgetSettingsBase { public Settings() { Width = 384; Height = 216; } [Category("General")] [DisplayName("Image Folder Path")] public string RootPath { get; set; } [Category("General")] [DisplayName("Maximum File Size (bytes)")] public double FileFilterSize { get; set; } = 1024000; [Category("General")] [DisplayName("Next Image Interval")] public TimeSpan ChangeInterval { get; set; } = TimeSpan.FromSeconds(15); [Category("General")] [DisplayName("Shuffle")] public bool Shuffle { get; set; } = true; [Category("General")] [DisplayName("Recursive")] public bool Recursive { get; set; } = false; [Category("General")] [DisplayName("Current Image Path")] public string ImageUrl { get; set; } [Category("General")] [DisplayName("Allow Dropping Images")] public bool AllowDropFiles { get; set; } = true; [Category("General")] [DisplayName("Freeze")] public bool Freeze { get; set; } } }
using System; using System.ComponentModel; using DesktopWidgets.WidgetBase.Settings; namespace DesktopWidgets.Widgets.PictureSlideshow { public class Settings : WidgetSettingsBase { public Settings() { Width = 384; Height = 216; } [Category("General")] [DisplayName("Image Folder Path")] public string RootPath { get; set; } [Category("General")] [DisplayName("Maximum File Size (bytes)")] public double FileFilterSize { get; set; } = 1048576; [Category("General")] [DisplayName("Next Image Interval")] public TimeSpan ChangeInterval { get; set; } = TimeSpan.FromSeconds(15); [Category("General")] [DisplayName("Shuffle")] public bool Shuffle { get; set; } = true; [Category("General")] [DisplayName("Recursive")] public bool Recursive { get; set; } = false; [Category("General")] [DisplayName("Current Image Path")] public string ImageUrl { get; set; } [Category("General")] [DisplayName("Allow Dropping Images")] public bool AllowDropFiles { get; set; } = true; [Category("General")] [DisplayName("Freeze")] public bool Freeze { get; set; } } }
Add missing object mapping configuration.
using System.Linq; using AutoMapper; using Abp.Authorization; using Abp.Authorization.Roles; using AbpCompanyName.AbpProjectName.Authorization.Roles; namespace AbpCompanyName.AbpProjectName.Roles.Dto { public class RoleMapProfile : Profile { public RoleMapProfile() { // Role and permission CreateMap<Permission, string>().ConvertUsing(r => r.Name); CreateMap<RolePermissionSetting, string>().ConvertUsing(r => r.Name); CreateMap<CreateRoleDto, Role>(); CreateMap<RoleDto, Role>(); CreateMap<Role, RoleDto>().ForMember(x => x.GrantedPermissions, opt => opt.MapFrom(x => x.Permissions.Where(p => p.IsGranted))); } } }
using System.Linq; using AutoMapper; using Abp.Authorization; using Abp.Authorization.Roles; using AbpCompanyName.AbpProjectName.Authorization.Roles; namespace AbpCompanyName.AbpProjectName.Roles.Dto { public class RoleMapProfile : Profile { public RoleMapProfile() { // Role and permission CreateMap<Permission, string>().ConvertUsing(r => r.Name); CreateMap<RolePermissionSetting, string>().ConvertUsing(r => r.Name); CreateMap<CreateRoleDto, Role>(); CreateMap<RoleDto, Role>(); CreateMap<Role, RoleDto>().ForMember(x => x.GrantedPermissions, opt => opt.MapFrom(x => x.Permissions.Where(p => p.IsGranted))); CreateMap<Role, RoleListDto>(); CreateMap<Role, RoleEditDto>(); CreateMap<Permission, FlatPermissionDto>(); } } }
Add menu item to create AOT configuration
#if !NO_UNITY using System; using System.Collections.Generic; using UnityEngine; namespace FullSerializer { public class fsAotConfiguration : ScriptableObject { public enum AotState { Default, Enabled, Disabled } [Serializable] public struct Entry { public AotState State; public string FullTypeName; public Entry(Type type) { FullTypeName = type.FullName; State = AotState.Default; } public Entry(Type type, AotState state) { FullTypeName = type.FullName; State = state; } } public List<Entry> aotTypes = new List<Entry>(); public string outputDirectory = "Assets/AotModels"; public bool TryFindEntry(Type type, out Entry result) { string searchFor = type.FullName; foreach (Entry entry in aotTypes) { if (entry.FullTypeName == searchFor) { result = entry; return true; } } result = default(Entry); return false; } public void UpdateOrAddEntry(Entry entry) { for (int i = 0; i < aotTypes.Count; ++i) { if (aotTypes[i].FullTypeName == entry.FullTypeName) { aotTypes[i] = entry; return; } } aotTypes.Add(entry); } } } #endif
#if !NO_UNITY using System; using System.Collections.Generic; using UnityEngine; namespace FullSerializer { [CreateAssetMenu(menuName = "Full Serializer AOT Configuration")] public class fsAotConfiguration : ScriptableObject { public enum AotState { Default, Enabled, Disabled } [Serializable] public struct Entry { public AotState State; public string FullTypeName; public Entry(Type type) { FullTypeName = type.FullName; State = AotState.Default; } public Entry(Type type, AotState state) { FullTypeName = type.FullName; State = state; } } public List<Entry> aotTypes = new List<Entry>(); public string outputDirectory = "Assets/AotModels"; public bool TryFindEntry(Type type, out Entry result) { string searchFor = type.FullName; foreach (Entry entry in aotTypes) { if (entry.FullTypeName == searchFor) { result = entry; return true; } } result = default(Entry); return false; } public void UpdateOrAddEntry(Entry entry) { for (int i = 0; i < aotTypes.Count; ++i) { if (aotTypes[i].FullTypeName == entry.FullTypeName) { aotTypes[i] = entry; return; } } aotTypes.Add(entry); } } } #endif
Tweak SMTP test "From" address.
using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Text; namespace Toolhouse.Monitoring.Dependencies { public class SmtpDependency : IDependency { public SmtpDependency(string name) { this.Name = name; } public string Name { get; private set; } public DependencyStatus Check() { // TODO: A more sophisticated test here would be opening up a socket and actually attempting to speak SMTP. using (var client = new System.Net.Mail.SmtpClient()) { var message = new MailMessage("test@example.org", "smtpdependencycheck@toolhouse.com", "SMTP test", ""); client.Send(message); } return new DependencyStatus(this, true, ""); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Text; namespace Toolhouse.Monitoring.Dependencies { public class SmtpDependency : IDependency { public SmtpDependency(string name) { this.Name = name; } public string Name { get; private set; } public DependencyStatus Check() { // TODO: A more sophisticated test here would be opening up a socket and actually attempting to speak SMTP. using (var client = new System.Net.Mail.SmtpClient()) { var message = new MailMessage("test@example.org", "smtpdependencycheck@example.org", "SMTP test", ""); client.Send(message); } return new DependencyStatus(this, true, ""); } } }
Fix type name error due to temporarily excluded project
using System; using System.Reflection; //using System.IO; //using System.Reflection; using LASI.Utilities; namespace LASI.WebApp.Tests.TestAttributes { [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] public class PreconfigureLASIAttribute : Xunit.Sdk.BeforeAfterTestAttribute { private const string ConfigFileName = "config.json"; private const string LASIComponentConfigSubkey = "Resources"; public override void Before(MethodInfo methodUnderTest) { base.Before(methodUnderTest); ConfigureLASIComponents(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), ConfigFileName), LASIComponentConfigSubkey); } private static void ConfigureLASIComponents(string fileName, string subkey) { Interop.ResourceUsageManager.SetPerformanceLevel(Interop.PerformanceProfile.High); try { Interop.Configuration.Initialize(fileName, Interop.ConfigFormat.Json, subkey); } catch (Interop.SystemAlreadyConfiguredException) { //Console.WriteLine("LASI was already setup by a previous test; continuing"); } Logger.SetToSilent(); } } }
using System; using System.Reflection; //using System.IO; //using System.Reflection; using LASI.Utilities; namespace LASI.WebApp.Tests.TestAttributes { [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] public class PreconfigureLASIAttribute : Xunit.Sdk.BeforeAfterTestAttribute { private const string ConfigFileName = "config.json"; private const string LASIComponentConfigSubkey = "Resources"; public override void Before(MethodInfo methodUnderTest) { base.Before(methodUnderTest); ConfigureLASIComponents(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), ConfigFileName), LASIComponentConfigSubkey); } private static void ConfigureLASIComponents(string fileName, string subkey) { Interop.ResourceUsageManager.SetPerformanceLevel(Interop.PerformanceProfile.High); try { Interop.Configuration.Initialize(fileName, Interop.ConfigFormat.Json, subkey); } catch (Interop.AlreadyConfiguredException) { //Console.WriteLine("LASI was already setup by a previous test; continuing"); } Logger.SetToSilent(); } } }
Fix mistake in create sprint validator - was allowing null Name
using System; using Agiil.Domain.Validation; using CSF.Validation; using CSF.Validation.Manifest.Fluent; using CSF.Validation.StockRules; namespace Agiil.Domain.Sprints { public class CreateSprintValidatorFactory : ValidatorFactoryBase<CreateSprintRequest> { protected override void ConfigureManifest(IManifestBuilder<CreateSprintRequest> builder) { builder.AddRule<NotNullRule>(); builder.AddMemberRule<RegexMatchValueRule>(x => x.Name, c => { c.Configure(r => r.Pattern = @"^\S+"); }); builder.AddRule<EndDateMustNotBeBeforeStartDateRule>(); } public CreateSprintValidatorFactory(IValidatorFactory validatorFactory) : base(validatorFactory) {} } }
using System; using Agiil.Domain.Validation; using CSF.Validation; using CSF.Validation.Manifest.Fluent; using CSF.Validation.StockRules; namespace Agiil.Domain.Sprints { public class CreateSprintValidatorFactory : ValidatorFactoryBase<CreateSprintRequest> { protected override void ConfigureManifest(IManifestBuilder<CreateSprintRequest> builder) { builder.AddRule<NotNullRule>(); builder.AddMemberRule<NotNullValueRule>(x => x.Name); builder.AddMemberRule<RegexMatchValueRule>(x => x.Name, c => { c.Configure(r => r.Pattern = @"^\S+"); }); builder.AddRule<EndDateMustNotBeBeforeStartDateRule>(); } public CreateSprintValidatorFactory(IValidatorFactory validatorFactory) : base(validatorFactory) {} } }
Return NotFound on teams user is not a member of
using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using SupportManager.DAL; namespace SupportManager.Web.Areas.Teams { [Area("Teams")] [Authorize] public abstract class BaseController : Controller { protected int TeamId => int.Parse((string) ControllerContext.RouteData.Values["teamId"]); protected SupportTeam Team { get; private set; } public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { var db = (SupportManagerContext) context.HttpContext.RequestServices.GetService(typeof(SupportManagerContext)); Team = await db.Teams.FindAsync(TeamId); if (Team == null) { context.Result = NotFound(); return; } ViewData["TeamName"] = Team.Name; await base.OnActionExecutionAsync(context, next); } } }
using System.Data.Entity; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using SupportManager.DAL; namespace SupportManager.Web.Areas.Teams { [Area("Teams")] [Authorize] public abstract class BaseController : Controller { protected int TeamId => int.Parse((string) ControllerContext.RouteData.Values["teamId"]); protected SupportTeam Team { get; private set; } public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { var db = (SupportManagerContext) context.HttpContext.RequestServices.GetService(typeof(SupportManagerContext)); Team = await db.Teams.FindAsync(TeamId); if (Team == null) { context.Result = NotFound(); return; } var userName = context.HttpContext.User.Identity.Name; if (!await db.TeamMembers.AnyAsync(x => x.TeamId == Team.Id && x.User.Login == userName)) { context.Result = NotFound(); return; } ViewData["TeamName"] = Team.Name; await base.OnActionExecutionAsync(context, next); } } }
Disable 'Delete all variables' when no environment is selected.
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Globalization; using Microsoft.Common.Core; using Microsoft.Common.Core.Shell; using Microsoft.R.Host.Client; using Microsoft.VisualStudio.R.Package.Commands; using Microsoft.VisualStudio.R.Package.Shell; using Microsoft.VisualStudio.R.Packages.R; using Microsoft.VisualStudio.R.Package.Utilities; namespace Microsoft.VisualStudio.R.Package.DataInspect.Commands { internal sealed class DeleteAllVariablesCommand : SessionCommand { public DeleteAllVariablesCommand(IRSession session) : base(session, RGuidList.RCmdSetGuid, RPackageCommandId.icmdDeleteAllVariables) { } protected override void SetStatus() { var variableWindowPane = ToolWindowUtilities.FindWindowPane<VariableWindowPane>(0); Enabled = (variableWindowPane?.IsGlobalREnvironment()) ?? true; } protected override void Handle() { if(MessageButtons.No == VsAppShell.Current.ShowMessage(Resources.Warning_DeleteAllVariables, MessageButtons.YesNo)) { return; } try { RSession.ExecuteAsync("rm(list = ls(all = TRUE))").DoNotWait(); } catch(RException ex) { VsAppShell.Current.ShowErrorMessage( string.Format(CultureInfo.InvariantCulture, Resources.Error_UnableToDeleteVariable, ex.Message)); } catch(MessageTransportException) { } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Globalization; using Microsoft.Common.Core; using Microsoft.Common.Core.Shell; using Microsoft.R.Host.Client; using Microsoft.VisualStudio.R.Package.Commands; using Microsoft.VisualStudio.R.Package.Shell; using Microsoft.VisualStudio.R.Packages.R; using Microsoft.VisualStudio.R.Package.Utilities; namespace Microsoft.VisualStudio.R.Package.DataInspect.Commands { internal sealed class DeleteAllVariablesCommand : SessionCommand { public DeleteAllVariablesCommand(IRSession session) : base(session, RGuidList.RCmdSetGuid, RPackageCommandId.icmdDeleteAllVariables) { } protected override void SetStatus() { var variableWindowPane = ToolWindowUtilities.FindWindowPane<VariableWindowPane>(0); // 'Delete all variables' button should be enabled only when the Global environment // is selected in Variable Explorer. Enabled = (variableWindowPane?.IsGlobalREnvironment()) ?? false; } protected override void Handle() { if(MessageButtons.No == VsAppShell.Current.ShowMessage(Resources.Warning_DeleteAllVariables, MessageButtons.YesNo)) { return; } try { RSession.ExecuteAsync("rm(list = ls(all = TRUE))").DoNotWait(); } catch(RException ex) { VsAppShell.Current.ShowErrorMessage( string.Format(CultureInfo.InvariantCulture, Resources.Error_UnableToDeleteVariable, ex.Message)); } catch(MessageTransportException) { } } } }
Create backup directory if missing
using System; using System.IO; using System.Security.Cryptography; namespace Nuterra.Installer { public static class InstallerUtil { public static string GetFileHash(string filePath) { if (!File.Exists(filePath)) { return null; } using (var md5 = MD5.Create()) using (var stream = File.OpenRead(filePath)) { return Convert.ToBase64String(md5.ComputeHash(stream)); } } public static string CreateAssemblyBackup(string sourceAssembly, string assemblyBackupDir, string hash) { string targetFile = Path.Combine(assemblyBackupDir, $"{hash}.dll"); if (Directory.Exists(assemblyBackupDir)) { Directory.CreateDirectory(assemblyBackupDir); } if (!File.Exists(targetFile)) { File.Copy(sourceAssembly, targetFile); } return targetFile; } public static string FormatBackupPath(string assemblyBackupDir, string hash) { return Path.Combine(assemblyBackupDir, $"{hash}.dll"); } } }
using System; using System.IO; using System.Security.Cryptography; namespace Nuterra.Installer { public static class InstallerUtil { public static string GetFileHash(string filePath) { if (!File.Exists(filePath)) { return null; } using (var md5 = MD5.Create()) using (var stream = File.OpenRead(filePath)) { return Convert.ToBase64String(md5.ComputeHash(stream)); } } public static string CreateAssemblyBackup(string sourceAssembly, string assemblyBackupDir, string hash) { string targetFile = Path.Combine(assemblyBackupDir, $"{hash}.dll"); if (!Directory.Exists(assemblyBackupDir)) { Directory.CreateDirectory(assemblyBackupDir); } if (!File.Exists(targetFile)) { File.Copy(sourceAssembly, targetFile); } return targetFile; } public static string FormatBackupPath(string assemblyBackupDir, string hash) { return Path.Combine(assemblyBackupDir, $"{hash}.dll"); } } }
Simplify GetPassedTestsInfo with XDocument and XPath
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.IO; using System.Xml; namespace Roslyn.Test.Utilities { public struct TestInfo { public decimal Time { get; } public TestInfo(decimal time) { Time = time; } public static IDictionary<string, TestInfo> GetPassedTestsInfo() { var result = new Dictionary<string, TestInfo>(); var filePath = System.Environment.GetEnvironmentVariable("OutputXmlFilePath"); if (filePath != null) { if (File.Exists(filePath)) { var doc = new XmlDocument(); doc.Load(filePath); foreach (XmlNode assemblies in doc.SelectNodes("assemblies")) { foreach (XmlNode assembly in assemblies.SelectNodes("assembly")) { foreach (XmlNode collection in assembly.SelectNodes("collection")) { foreach (XmlNode test in assembly.SelectNodes("test")) { if (test.SelectNodes("failure").Count == 0) { if (decimal.TryParse(test.Attributes["time"].InnerText, out var time)) { result.Add(test.Name, new TestInfo(time)); } } } } } } } } return result; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.IO; using System.Xml.Linq; using System.Xml.XPath; namespace Roslyn.Test.Utilities { public readonly struct TestInfo { public decimal Time { get; } public TestInfo(decimal time) { Time = time; } public static ImmutableDictionary<string, TestInfo> GetPassedTestsInfo() { var result = ImmutableDictionary.CreateBuilder<string, TestInfo>(); var filePath = System.Environment.GetEnvironmentVariable("OutputXmlFilePath"); if (filePath != null) { if (File.Exists(filePath)) { var doc = XDocument.Load(filePath); foreach (var test in doc.XPathSelectElements("/assemblies/assembly/collection/test[@result='Pass']")) { if (decimal.TryParse(test.Attribute("time").Value, out var time)) { result.Add(test.Attribute("name").Value, new TestInfo(time)); } } } } return result.ToImmutable(); } } }
Fix null category search bug
// NoteSorter.cs // <copyright file="NoteSorter.cs"> This code is protected under the MIT License. </copyright> using System.Collections.Generic; using System.Linq; namespace Todo_List { /// <summary> /// A static class containing a list of notes and methods for sorting them. /// </summary> public static class NoteSorter { /// <summary> /// Initializes static members of the <see cref="NoteSorter" /> class. /// </summary> public static NoteSorter() { Notes = new List<Note>(); } /// <summary> /// Gets or sets the list of notes currently stored in the program. /// </summary> public static List<Note> Notes { get; set; } /// <summary> /// Gets all the notes with certain category tags. /// </summary> /// <param name="categoryNames"> The list of categories. </param> /// <returns> The list of notes under the category. </returns> /// <remarks> Null categories means all categories.</remarks> public static List<Note> GetNotesByCatagory(List<string> categoryNames = null) { IEnumerable<Note> notesUnderCategories = Notes; foreach (string catergory in categoryNames) { notesUnderCategories = notesUnderCategories.Where(n => n.Categories.Contains(catergory.ToUpper())); } return notesUnderCategories.ToList(); } } }
// NoteSorter.cs // <copyright file="NoteSorter.cs"> This code is protected under the MIT License. </copyright> using System.Collections.Generic; using System.Linq; namespace Todo_List { /// <summary> /// A static class containing a list of notes and methods for sorting them. /// </summary> public static class NoteSorter { /// <summary> /// Initializes static members of the <see cref="NoteSorter" /> class. /// </summary> public static NoteSorter() { Notes = new List<Note>(); } /// <summary> /// Gets or sets the list of notes currently stored in the program. /// </summary> public static List<Note> Notes { get; set; } /// <summary> /// Gets all the notes with certain category tags. /// </summary> /// <param name="categoryNames"> The list of categories. </param> /// <returns> The list of notes under the category. </returns> /// <remarks> No category names in the list means all categories. </remarks> public static List<Note> GetNotesByCatagory(List<string> categoryNames) { IEnumerable<Note> notesUnderCategories = Notes; foreach (string catergory in categoryNames) { notesUnderCategories = notesUnderCategories.Where(n => n.Categories.Contains(catergory.ToUpper())); } return notesUnderCategories.ToList(); } } }
Fix test name and assertion.
using System; using Elastic.Xunit.Sdk; using Elastic.Xunit.XunitPlumbing; using Elasticsearch.Net; using FluentAssertions; using Tests.Framework.ManagedElasticsearch.Clusters; namespace Tests.Reproduce { public class GithubIssue2985 : IClusterFixture<WritableCluster> { private readonly WritableCluster _cluster; public GithubIssue2985(WritableCluster cluster) => _cluster = cluster; protected static string RandomString() => Guid.NewGuid().ToString("N").Substring(0, 8); [I] public void CanReadSingleOrMultipleCommonGramsCommonWordsItem() { var client = _cluster.Client; var index = $"gh2985-{RandomString()}"; var response = client.CreateIndex(index, i=> i .Settings(s=>s .Analysis(a=>a .Analyzers(an=>an .Custom("custom", c=>c.Filters("ascii_folding").Tokenizer("standard")) ) ) ) ); response.OriginalException.Should().NotBeNull().And.BeOfType<ElasticsearchClientException>(); response.OriginalException.Message.Should() .StartWith("Request failed to execute") .And.EndWith( "Type: illegal_argument_exception Reason: \"Custom Analyzer [custom] failed to find filter under name [ascii_folding]\"" ); client.DeleteIndex(index); } } }
using System; using Elastic.Xunit.Sdk; using Elastic.Xunit.XunitPlumbing; using Elasticsearch.Net; using FluentAssertions; using Tests.Framework.ManagedElasticsearch.Clusters; namespace Tests.Reproduce { public class GithubIssue2985 : IClusterFixture<WritableCluster> { private readonly WritableCluster _cluster; public GithubIssue2985(WritableCluster cluster) => _cluster = cluster; protected static string RandomString() => Guid.NewGuid().ToString("N").Substring(0, 8); [I] public void BadRequestErrorShouldBeWrappedInElasticsearchClientException() { var client = _cluster.Client; var index = $"gh2985-{RandomString()}"; var response = client.CreateIndex(index, i=> i .Settings(s=>s .Analysis(a=>a .Analyzers(an=>an .Custom("custom", c=>c.Filters("ascii_folding").Tokenizer("standard")) ) ) ) ); response.OriginalException.Should().NotBeNull().And.BeOfType<ElasticsearchClientException>(); response.OriginalException.Message.Should() .Contain( "Type: illegal_argument_exception Reason: \"Custom Analyzer [custom] failed to find filter under name [ascii_folding]\"" ); client.DeleteIndex(index); } } }
Make the namespace uniform accross the project
using System; namespace Table { public class Table { public int Width; public int Spacing; public Table(int width, int spacing) { Width = width; Spacing = spacing; } } }
using System; namespace Hangman { public class Table { public int Width; public int Spacing; public Table(int width, int spacing) { Width = width; Spacing = spacing; } } }