doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
ab8eb183-0e29-4fa3-9bda-e334c9ce93b6
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SIM.Telemetry")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SIM.Telemetry")] [assembly: AssemblyCopyright("Copyright © 2019")] [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("b91b2024-3f75-4df7-8dcc-111fb5ccaf5d")] // 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")] ``` Add AssemblyDescription to SIM.Telemetry project
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SIM.Telemetry")] [assembly: AssemblyDescription("'SIM.Telemetry' is used to track Sitecore Instance Manager utilisation statistics")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SIM.Telemetry")] [assembly: AssemblyCopyright("Copyright © 2019")] [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("b91b2024-3f75-4df7-8dcc-111fb5ccaf5d")] // 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")] ```
1076ab50-e764-4c4c-94fa-1b91c2f82052
{ "language": "C#" }
```c# using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; namespace Nest.Tests.Unit { public static class JsonExtensions { internal static bool JsonEquals(this string json, string otherjson) { var nJson = JObject.Parse(json).ToString(); var nOtherJson = JObject.Parse(otherjson).ToString(); //Assert.AreEqual(nOtherJson, nJson); return nJson == nOtherJson; } } } ``` Use deep equality rather than string comparison.
```c# using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; namespace Nest.Tests.Unit { public static class JsonExtensions { internal static bool JsonEquals(this string json, string otherjson) { var nJson = JObject.Parse(json); var nOtherJson = JObject.Parse(otherjson); return JToken.DeepEquals(nJson, nOtherJson); } } } ```
d04b9a15-2033-4432-a2c2-9b02049cdc04
{ "language": "C#" }
```c# using Newtonsoft.Json; namespace MessageBird.Objects { public class Error { [JsonProperty("code")] public int Code { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("parameter")] public string Parameter { get; set; } } } ``` Replace integer error code with enum
```c# using System.Runtime.Serialization; using Newtonsoft.Json; namespace MessageBird.Objects { public enum ErrorCode { RequestNotAllowed = 2, MissingParameters = 9, InvalidParameters = 10, NotFound = 20, NotEnoughBalance = 25, ApiNotFound = 98, InternalError = 99 } public class Error { [JsonProperty("code")] public ErrorCode Code { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("parameter")] public string Parameter { get; set; } } } ```
6268bc8d-00c9-4870-a864-3369722f63c9
{ "language": "C#" }
```c# // 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.ComponentModel; namespace osu.Game.Configuration { public enum HUDVisibilityMode { Never, [Description("Hide during gameplay")] HideDuringGameplay, [Description("Hide during breaks")] HideDuringBreaks, Always } } ``` Remove "hide during breaks" option
```c# // 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.ComponentModel; namespace osu.Game.Configuration { public enum HUDVisibilityMode { Never, [Description("Hide during gameplay")] HideDuringGameplay, Always } } ```
50f1d787-d41c-4a9e-816d-2278ade95f7b
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using Fitbit.Models; using Newtonsoft.Json.Linq; namespace Fitbit.Api.Portable { internal static class JsonDotNetSerializerExtensions { /// <summary> /// GetFriends has to do some custom manipulation with the returned representation /// </summary> /// <param name="serializer"></param> /// <param name="friendsJson"></param> /// <returns></returns> internal static List<UserProfile> GetFriends(this JsonDotNetSerializer serializer, string friendsJson) { if (string.IsNullOrWhiteSpace(friendsJson)) { throw new ArgumentNullException("friendsJson", "friendsJson can not be empty, null or whitespace."); } // todo: additional error checking of json string required serializer.RootProperty = "user"; var users = JToken.Parse(friendsJson)["friends"]; return users.Children().Select(serializer.Deserialize<UserProfile>).ToList(); } } }``` Rename variable to make it read better
```c# using System; using System.Collections.Generic; using System.Linq; using Fitbit.Models; using Newtonsoft.Json.Linq; namespace Fitbit.Api.Portable { internal static class JsonDotNetSerializerExtensions { /// <summary> /// GetFriends has to do some custom manipulation with the returned representation /// </summary> /// <param name="serializer"></param> /// <param name="friendsJson"></param> /// <returns></returns> internal static List<UserProfile> GetFriends(this JsonDotNetSerializer serializer, string friendsJson) { if (string.IsNullOrWhiteSpace(friendsJson)) { throw new ArgumentNullException("friendsJson", "friendsJson can not be empty, null or whitespace."); } // todo: additional error checking of json string required serializer.RootProperty = "user"; var friends = JToken.Parse(friendsJson)["friends"]; return friends.Children().Select(serializer.Deserialize<UserProfile>).ToList(); } } }```
2d4636bb-e11f-45ac-8090-845489732141
{ "language": "C#" }
```c# 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("CloudSearch")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CloudSearch")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8ace1017-c436-4f00-b040-84f7619af92f")] // 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.2")] [assembly: AssemblyFileVersion("1.0.0.2")] ``` Undo version number bump from personal build
```c# 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("CloudSearch")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CloudSearch")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8ace1017-c436-4f00-b040-84f7619af92f")] // 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.1")] [assembly: AssemblyFileVersion("1.0.0.1")] ```
674fc945-68ab-4c1c-a287-22ec56af3dd0
{ "language": "C#" }
```c# using System; using TagLib; public class SetPictures { public static void Main(string [] args) { if(args.Length < 2) { Console.Error.WriteLine("USAGE: mono SetPictures.exe AUDIO_PATH IMAGE_PATH_1[...IMAGE_PATH_N]"); return; } TagLib.File file = TagLib.File.Create(args[0]); Console.WriteLine("Current picture count: " + file.Tag.Pictures.Length); Picture [] pictures = new Picture[args.Length - 1]; for(int i = 1; i < args.Length; i++) { Picture picture = Picture.CreateFromPath(args[i]); pictures[i - 1] = picture; } file.Tag.Pictures = pictures; file.Save(); Console.WriteLine("New picture count: " + file.Tag.Pictures.Length); } } ``` Fix use of obsolete API
```c# using System; using TagLib; public class SetPictures { public static void Main(string [] args) { if(args.Length < 2) { Console.Error.WriteLine("USAGE: mono SetPictures.exe AUDIO_PATH IMAGE_PATH_1[...IMAGE_PATH_N]"); return; } TagLib.File file = TagLib.File.Create(args[0]); Console.WriteLine("Current picture count: " + file.Tag.Pictures.Length); Picture [] pictures = new Picture[args.Length - 1]; for(int i = 1; i < args.Length; i++) { Picture picture = new Picture(args[i]); pictures[i - 1] = picture; } file.Tag.Pictures = pictures; file.Save(); Console.WriteLine("New picture count: " + file.Tag.Pictures.Length); } } ```
4d69392b-cf70-4c18-9948-5a27fd0d3d18
{ "language": "C#" }
```c# using AxosoftAPI.NET.Core.Interfaces; using AxosoftAPI.NET.Models; namespace AxosoftAPI.NET.Interfaces { public interface IWorkLogs : IGetAllResource<WorkLog>, ICreateResource<WorkLog>, IDeleteResource<WorkLog> { } } ``` Support full API available for worklogs
```c# using AxosoftAPI.NET.Core.Interfaces; using AxosoftAPI.NET.Models; namespace AxosoftAPI.NET.Interfaces { public interface IWorkLogs : IResource<WorkLog> { } } ```
260274b7-4c93-44b8-8ad2-02ea5a553c20
{ "language": "C#" }
```c# // Copyright 2015 Palm Stone Games, Inc. All Rights Reserved. using System.IO; namespace UnrealBuildTool.Rules { public class ue4czmq : ModuleRules { public ue4czmq(TargetInfo Target) { // Include paths //PublicIncludePaths.AddRange(new string[] {}); //PrivateIncludePaths.AddRange(new string[] {}); // Dependencies PublicDependencyModuleNames.AddRange(new string[] { "Core", "Engine", }); //PrivateDependencyModuleNames.AddRange(new string[] {}); // Dynamically loaded modules //DynamicallyLoadedModuleNames.AddRange(new string[] {}); // Definitions Definitions.Add("WITH_UE4CZMQ=1"); LoadLib(Target); } public void LoadLib(TargetInfo Target) { string ModulePath = Path.GetDirectoryName(RulesCompiler.GetModuleFilename(this.GetType().Name)); // CZMQ string czmqPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/", Target.Platform.ToString(), "czmq")); PublicAdditionalLibraries.Add(Path.Combine(czmqPath, "Libraries", "czmq.lib")); PrivateIncludePaths.Add(Path.Combine(czmqPath, "Includes")); // LIBZMQ string libzmqPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/", Target.Platform.ToString(), "libzmq")); PrivateIncludePaths.Add(Path.Combine(libzmqPath, "Includes")); } } }``` Use a PrivateAdditionalLibrary for czmq.lib instead of a public one
```c# // Copyright 2015 Palm Stone Games, Inc. All Rights Reserved. using System.IO; namespace UnrealBuildTool.Rules { public class ue4czmq : ModuleRules { public ue4czmq(TargetInfo Target) { // Include paths //PublicIncludePaths.AddRange(new string[] {}); //PrivateIncludePaths.AddRange(new string[] {}); // Dependencies PublicDependencyModuleNames.AddRange(new string[] { "Core", "Engine", }); //PrivateDependencyModuleNames.AddRange(new string[] {}); // Dynamically loaded modules //DynamicallyLoadedModuleNames.AddRange(new string[] {}); // Definitions Definitions.Add("WITH_UE4CZMQ=1"); LoadLib(Target); } public void LoadLib(TargetInfo Target) { string ModulePath = Path.GetDirectoryName(RulesCompiler.GetModuleFilename(this.GetType().Name)); // CZMQ string czmqPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/", Target.Platform.ToString(), "czmq")); PrivateAdditionalLibraries.Add(Path.Combine(czmqPath, "Libraries", "czmq.lib")); PrivateIncludePaths.Add(Path.Combine(czmqPath, "Includes")); // LIBZMQ string libzmqPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/", Target.Platform.ToString(), "libzmq")); PrivateIncludePaths.Add(Path.Combine(libzmqPath, "Includes")); } } }```
321d4774-f5ae-4e59-9992-0f1a548e6c34
{ "language": "C#" }
```c# using System; using NBi.Xml; using NUnit.Framework; namespace NBi.Testing.Unit.Xml { [TestFixture] public class XmlManagerTest { [Test] public void Load_ValidFile_Success() { var filename = DiskOnFile.CreatePhysicalFile("TestSuite.xml", "NBi.Testing.Unit.Xml.Resources.TestSuiteSample.xml"); var manager = new XmlManager(); manager.Load(filename); Assert.That(manager.TestSuite, Is.Not.Null); } [Test] public void Load_ValidFile_TestContentIsCorrect() { var filename = DiskOnFile.CreatePhysicalFile("TestSuite.xml", "NBi.Testing.Unit.Xml.Resources.TestSuiteSample.xml"); var manager = new XmlManager(); manager.Load(filename); Assert.That(manager.TestSuite.Tests[0].Content, Is.Not.Null); } [Test] public void Load_InvalidFile_Successfully() { var filename = DiskOnFile.CreatePhysicalFile("TestSuiteInvalidSyntax.xml", "NBi.Testing.Unit.Xml.Resources.TestSuiteInvalidSyntax.xml"); var manager = new XmlManager(); Assert.Throws<ArgumentException>(delegate { manager.Load(filename); }); } } } ``` Fix failing test for TestContent in test redaction
```c# using System; using NBi.Xml; using NUnit.Framework; namespace NBi.Testing.Unit.Xml { [TestFixture] public class XmlManagerTest { [Test] public void Load_ValidFile_Success() { var filename = DiskOnFile.CreatePhysicalFile("TestSuite.xml", "NBi.Testing.Unit.Xml.Resources.TestSuiteSample.xml"); var manager = new XmlManager(); manager.Load(filename); Assert.That(manager.TestSuite, Is.Not.Null); } [Test] public void Load_ValidFile_TestContentIsCorrect() { var filename = DiskOnFile.CreatePhysicalFile("TestContentIsCorrect.xml", "NBi.Testing.Unit.Xml.Resources.TestSuiteSample.xml"); var manager = new XmlManager(); manager.Load(filename); Assert.That(manager.TestSuite.Tests[0].Content, Is.Not.Null); } [Test] public void Load_InvalidFile_Successfully() { var filename = DiskOnFile.CreatePhysicalFile("TestSuiteInvalidSyntax.xml", "NBi.Testing.Unit.Xml.Resources.TestSuiteInvalidSyntax.xml"); var manager = new XmlManager(); Assert.Throws<ArgumentException>(delegate { manager.Load(filename); }); } } } ```
4c8f7511-8c5c-44c7-9f50-f3a4f378cf4c
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Android.App; // 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("Binding")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Binding")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ``` Add link safe attribute support
```c# using System.Reflection; using System.Runtime.InteropServices; using Android; [assembly: AssemblyTitle("Binding")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Binding")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: LinkerSafe] ```
8df89c5b-02dc-44e0-98c8-a62c6c292f68
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design; using System.Linq; using System.Text; using System.Windows.Forms; namespace poshsecframework.PShell { class psfilenameeditor : System.Drawing.Design.UITypeEditor { public override System.Drawing.Design.UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context) { return System.Drawing.Design.UITypeEditorEditStyle.Modal; } [RefreshProperties(System.ComponentModel.RefreshProperties.All)] public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { if (context == null || context.Instance == null) { return base.EditValue(context, provider, value); } else { OpenFileDialog dlg = new OpenFileDialog(); dlg.Title = "Select " + context.PropertyDescriptor.DisplayName; dlg.FileName = (string)value; dlg.Filter = "All Files (*.*)|*.*"; if (dlg.ShowDialog() == DialogResult.OK) { value = dlg.FileName; } dlg.Dispose(); dlg = null; return value; } } } } ``` Allow File to not Exist in FileBrowse
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design; using System.Linq; using System.Text; using System.Windows.Forms; namespace poshsecframework.PShell { class psfilenameeditor : System.Drawing.Design.UITypeEditor { public override System.Drawing.Design.UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context) { return System.Drawing.Design.UITypeEditorEditStyle.Modal; } [RefreshProperties(System.ComponentModel.RefreshProperties.All)] public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { if (context == null || context.Instance == null) { return base.EditValue(context, provider, value); } else { OpenFileDialog dlg = new OpenFileDialog(); dlg.Title = "Select " + context.PropertyDescriptor.DisplayName; dlg.FileName = (string)value; dlg.Filter = "All Files (*.*)|*.*"; dlg.CheckFileExists = false; if (dlg.ShowDialog() == DialogResult.OK) { value = dlg.FileName; } dlg.Dispose(); dlg = null; return value; } } } } ```
09ea333b-b922-43dd-a469-8ade510a8045
{ "language": "C#" }
```c# using System; using Villermen.RuneScapeCacheTools.Cache; using Villermen.RuneScapeCacheTools.Cache.RuneTek5; using Xunit; using Xunit.Abstractions; namespace RuneScapeCacheToolsTests { public class RuneTek5CacheTests : IDisposable { private ITestOutputHelper _output; private RuneTek5Cache _cache; public RuneTek5CacheTests(ITestOutputHelper output) { _output = output; _cache = new RuneTek5Cache("TestData"); } /// <summary> /// Test for a file that exists, an archive file that exists and a file that doesn't exist. /// </summary> [Fact] public void TestGetFile() { var file = _cache.GetFile(12, 3); var fileData = file.Data; Assert.True(fileData.Length > 0, "File's data is empty."); var archiveFile = _cache.GetFile(17, 5); var archiveEntry = archiveFile.Entries[255]; Assert.True(archiveEntry.Length > 0, "Archive entry's data is empty."); try { _cache.GetFile(40, 30); Assert.True(false, "Cache returned a file that shouldn't exist."); } catch (CacheException exception) { Assert.True(exception.Message.Contains("incomplete"), "Non-existent file cache exception had the wrong message."); } } public void Dispose() { _cache?.Dispose(); } } }``` Add some readonly 's to tests
```c# using System; using Villermen.RuneScapeCacheTools.Cache; using Villermen.RuneScapeCacheTools.Cache.RuneTek5; using Xunit; using Xunit.Abstractions; namespace RuneScapeCacheToolsTests { public class RuneTek5CacheTests : IDisposable { private readonly ITestOutputHelper _output; private readonly RuneTek5Cache _cache; public RuneTek5CacheTests(ITestOutputHelper output) { _output = output; _cache = new RuneTek5Cache("TestData"); } /// <summary> /// Test for a file that exists, an archive file that exists and a file that doesn't exist. /// </summary> [Fact] public void TestGetFile() { var file = _cache.GetFile(12, 3); var fileData = file.Data; Assert.True(fileData.Length > 0, "File's data is empty."); var archiveFile = _cache.GetFile(17, 5); var archiveEntry = archiveFile.Entries[255]; Assert.True(archiveEntry.Length > 0, "Archive entry's data is empty."); try { _cache.GetFile(40, 30); Assert.True(false, "Cache returned a file that shouldn't exist."); } catch (CacheException exception) { Assert.True(exception.Message.Contains("incomplete"), "Non-existent file cache exception had the wrong message."); } } public void Dispose() { _cache?.Dispose(); } } }```
f6a48206-fd0d-4825-a668-8ebe92b62a7d
{ "language": "C#" }
```c# // Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. using System; using System.Linq; using PInvoke; using Xunit; using Xunit.Abstractions; using static PInvoke.WtsApi32; public class WtsApi32Facts { private readonly ITestOutputHelper output; public WtsApi32Facts(ITestOutputHelper output) { this.output = output; } [Fact] public void CheckWorkingOfWtsSafeMemoryGuard() { System.Diagnostics.Debugger.Break(); WtsSafeSessionInfoGuard wtsSafeMemoryGuard = new WtsSafeSessionInfoGuard(); int sessionCount = 0; Assert.True(WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, ref wtsSafeMemoryGuard, ref sessionCount)); Assert.NotEqual(0, sessionCount); var list = wtsSafeMemoryGuard.Take(sessionCount).ToList(); foreach (var ses in list) { this.output.WriteLine($"{ses.pWinStationName}, {ses.SessionID}, {ses.State}"); } } } ``` Delete break from the test
```c# // Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. using System; using System.Linq; using PInvoke; using Xunit; using Xunit.Abstractions; using static PInvoke.WtsApi32; public class WtsApi32Facts { private readonly ITestOutputHelper output; public WtsApi32Facts(ITestOutputHelper output) { this.output = output; } [Fact] public void CheckWorkingOfWtsSafeMemoryGuard() { WtsSafeSessionInfoGuard wtsSafeMemoryGuard = new WtsSafeSessionInfoGuard(); int sessionCount = 0; Assert.True(WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, ref wtsSafeMemoryGuard, ref sessionCount)); Assert.NotEqual(0, sessionCount); var list = wtsSafeMemoryGuard.Take(sessionCount).ToList(); foreach (var ses in list) { this.output.WriteLine($"{ses.pWinStationName}, {ses.SessionID}, {ses.State}"); } } } ```
46b1a2d4-7818-41c8-bf2a-7d01c5c7fbff
{ "language": "C#" }
```c# using System; using Microsoft.SPOT; namespace IntervalTimer { public delegate void IntervalEventHandler(object sender, EventArgs e); public class IntervalTimer { public TimeSpan ShortDuration { get; set; } public TimeSpan LongDuration { get; set; } public IntervalTimer(TimeSpan shortDuration, TimeSpan longDuration) { ShortDuration = shortDuration; LongDuration = longDuration; } public IntervalTimer(int shortSeconds, int longSeconds) { ShortDuration = new TimeSpan(0, 0, shortSeconds); LongDuration = new TimeSpan(0, 0, longSeconds); } } } ``` Use IntervalReachedEventArgs instead of EventArgs.
```c# using System; using Microsoft.SPOT; namespace IntervalTimer { public delegate void IntervalEventHandler(object sender, IntervalReachedEventArgs e); public class IntervalTimer { public TimeSpan ShortDuration { get; set; } public TimeSpan LongDuration { get; set; } public IntervalTimer(TimeSpan shortDuration, TimeSpan longDuration) { ShortDuration = shortDuration; LongDuration = longDuration; } public IntervalTimer(int shortSeconds, int longSeconds) { ShortDuration = new TimeSpan(0, 0, shortSeconds); LongDuration = new TimeSpan(0, 0, longSeconds); } } } ```
2bf07d20-6a6a-4a09-9cfc-f6522ed2a436
{ "language": "C#" }
```c# using System; using System.Web; using System.Web.Configuration; using ZMQ; namespace Nohros.Toolkit.RestQL { public class Global : HttpApplication { static readonly Context zmq_context_; #region .ctor static Global() { zmq_context_ = new Context(ZMQ.Context.DefaultIOThreads); } #endregion protected void Application_Start(object sender, EventArgs e) { string config_file_name = WebConfigurationManager.AppSettings[Strings.kConfigFileNameKey]; string config_file_path = Server.MapPath(config_file_name); Settings settings = new Settings.Loader() .Load(config_file_path, Strings.kConfigRootNodeName); var factory = new HttpQueryApplicationFactory(settings); Application[Strings.kApplicationKey] = factory.CreateQueryApplication(); } protected void Session_Start(object sender, EventArgs e) { } protected void Application_BeginRequest(object sender, EventArgs e) { } protected void Application_AuthenticateRequest(object sender, EventArgs e) { } protected void Application_Error(object sender, EventArgs e) { } protected void Session_End(object sender, EventArgs e) { } protected void Application_End(object sender, EventArgs e) { var app = Application[Strings.kApplicationKey] as HttpQueryApplication; if (app != null) { app.Stop(); app.Dispose(); } zmq_context_.Dispose(); } } } ``` Fix a bug that causes the application to not start. This happen because the Start method was not begin called.
```c# using System; using System.Web; using System.Web.Configuration; using ZMQ; namespace Nohros.Toolkit.RestQL { public class Global : HttpApplication { static readonly Context zmq_context_; #region .ctor static Global() { zmq_context_ = new Context(ZMQ.Context.DefaultIOThreads); } #endregion protected void Application_Start(object sender, EventArgs e) { string config_file_name = WebConfigurationManager.AppSettings[Strings.kConfigFileNameKey]; string config_file_path = Server.MapPath(config_file_name); Settings settings = new Settings.Loader() .Load(config_file_path, Strings.kConfigRootNodeName); var factory = new HttpQueryApplicationFactory(settings); HttpQueryApplication app = factory.CreateQueryApplication(); Application[Strings.kApplicationKey] = app; app.Start(); } protected void Session_Start(object sender, EventArgs e) { } protected void Application_BeginRequest(object sender, EventArgs e) { } protected void Application_AuthenticateRequest(object sender, EventArgs e) { } protected void Application_Error(object sender, EventArgs e) { } protected void Session_End(object sender, EventArgs e) { } protected void Application_End(object sender, EventArgs e) { var app = Application[Strings.kApplicationKey] as HttpQueryApplication; if (app != null) { app.Stop(); app.Dispose(); } zmq_context_.Dispose(); } } } ```
b85ed1e5-ca78-4a75-9413-fae02cc4e579
{ "language": "C#" }
```c# using UnityEngine; public class Settings { public static Player p1 = new RandomAI(null, 1, Color.red, Resources.Load<Sprite>("Sprites/x"), "X"), p2 = new RandomAI(null, 2, Color.blue, Resources.Load<Sprite>("Sprites/o"), "O"); } ``` Add RandomAI() method for fast generation of simple random players
```c# using UnityEngine; public class Settings { public static Player p1 = RandomAI(true), p2 = RandomAI(false); public static RandomAI RandomAI(bool firstPlayer) { int turn = firstPlayer ? 1 : 2; Color color = firstPlayer ? Color.red : Color.blue; Sprite sprite = Resources.Load<Sprite>("Sprites/" + (firstPlayer ? "x" : "o")); string name = firstPlayer ? "X" : "O"; return new RandomAI(null, turn, color, sprite, name); } } ```
8d9a5927-d829-4a5f-9fc5-81a8ad2e154c
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AvsAnLib; using ExpressionToCodeLib; using NUnit.Framework; namespace AvsAn_Test { public class StandardCasesWork { [TestCase("an", "unanticipated result")] [TestCase("a", "unanimous vote")] [TestCase("an", "honest decision")] [TestCase("a", "honeysuckle shrub")] [TestCase("an", "0800 number")] [TestCase("an", "∞ of oregano")] [TestCase("a", "NASA scientist")] [TestCase("an", "NSA analyst")] [TestCase("a", "FIAT car")] [TestCase("an", "FAA policy")] [TestCase("an", "A")] public void DoTest(string article, string word) { PAssert.That(() => AvsAn.Query(word).Article == article); } [TestCase("a", "", "")] [TestCase("a", "'", "'")] [TestCase("an", "N", "N ")] [TestCase("a", "NASA", "NAS")] public void CheckOddPrefixes(string article, string word, string prefix) { PAssert.That(() => AvsAn.Query(word).Article == article && AvsAn.Query(word).Prefix == prefix); } } } ``` Add two (currently failing) tests. Hopefully the new wikiextractor will deal with these corner cases (unissued, unilluminating).
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AvsAnLib; using ExpressionToCodeLib; using NUnit.Framework; namespace AvsAn_Test { public class StandardCasesWork { [TestCase("an", "unanticipated result")] [TestCase("a", "unanimous vote")] [TestCase("an", "honest decision")] [TestCase("a", "honeysuckle shrub")] [TestCase("an", "0800 number")] [TestCase("an", "∞ of oregano")] [TestCase("a", "NASA scientist")] [TestCase("an", "NSA analyst")] [TestCase("a", "FIAT car")] [TestCase("an", "FAA policy")] [TestCase("an", "A")] [TestCase("a", "uniformed agent")] [TestCase("an", "unissued permit")] [TestCase("an", "unilluminating argument")] public void DoTest(string article, string word) { PAssert.That(() => AvsAn.Query(word).Article == article); } [TestCase("a", "", "")] [TestCase("a", "'", "'")] [TestCase("an", "N", "N ")] [TestCase("a", "NASA", "NAS")] public void CheckOddPrefixes(string article, string word, string prefix) { PAssert.That(() => AvsAn.Query(word).Article == article && AvsAn.Query(word).Prefix == prefix); } } } ```
8980a20c-27e6-4a2c-b40d-166e236a59aa
{ "language": "C#" }
```c# namespace NHasher { internal static class HashExtensions { public static ulong RotateLeft(this ulong original, int bits) { return (original << bits) | (original >> (64 - bits)); } public static uint RotateLeft(this uint original, int bits) { return (original << bits) | (original >> (32 - bits)); } internal static unsafe ulong GetUInt64(this byte[] data, int position) { // we only read aligned longs, so a simple casting is enough fixed (byte* pbyte = &data[position]) { return *((ulong*)pbyte); } } internal static unsafe uint GetUInt32(this byte[] data, int position) { // we only read aligned longs, so a simple casting is enough fixed (byte* pbyte = &data[position]) { return *((uint*)pbyte); } } } } ``` Add AggressiveInlining for Rotate and Get functions
```c# using System.Runtime.CompilerServices; namespace NHasher { internal static class HashExtensions { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong RotateLeft(this ulong original, int bits) { return (original << bits) | (original >> (64 - bits)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint RotateLeft(this uint original, int bits) { return (original << bits) | (original >> (32 - bits)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static unsafe ulong GetUInt64(this byte[] data, int position) { // we only read aligned longs, so a simple casting is enough fixed (byte* pbyte = &data[position]) { return *((ulong*)pbyte); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static unsafe uint GetUInt32(this byte[] data, int position) { // we only read aligned longs, so a simple casting is enough fixed (byte* pbyte = &data[position]) { return *((uint*)pbyte); } } } } ```
3daa8b59-579e-430f-9f2a-f3b5533d3a38
{ "language": "C#" }
```c# using Telerik.TestingFramework.Controls.KendoUI; using Telerik.WebAii.Controls.Html; using Telerik.WebAii.Controls.Xaml; using System; using System.Collections.Generic; using System.Text; using System.Linq; using ArtOfTest.Common.UnitTesting; using ArtOfTest.WebAii.Core; using ArtOfTest.WebAii.Controls.HtmlControls; using ArtOfTest.WebAii.Controls.HtmlControls.HtmlAsserts; using ArtOfTest.WebAii.Design; using ArtOfTest.WebAii.Design.Execution; using ArtOfTest.WebAii.ObjectModel; using ArtOfTest.WebAii.Silverlight; using ArtOfTest.WebAii.Silverlight.UI; namespace MonkeyTests { public static class Constans { public static string BrowserWaitUntilReady = @"MonkeyHelper\Steps\BrowserWaitUntilReady.tstest"; public static string NavigationToBaseUrl = @"MonkeyHelper\Steps\NavigationToBaseUrl.tstest"; public static string ClickOnElement = @"MonkeyHelper\Steps\ClickOnElement.tstest"; } } ``` Change constants file. Fixed path to MonkeyHelper.
```c# using Telerik.TestingFramework.Controls.KendoUI; using Telerik.WebAii.Controls.Html; using Telerik.WebAii.Controls.Xaml; using System; using System.Collections.Generic; using System.Text; using System.Linq; using ArtOfTest.Common.UnitTesting; using ArtOfTest.WebAii.Core; using ArtOfTest.WebAii.Controls.HtmlControls; using ArtOfTest.WebAii.Controls.HtmlControls.HtmlAsserts; using ArtOfTest.WebAii.Design; using ArtOfTest.WebAii.Design.Execution; using ArtOfTest.WebAii.ObjectModel; using ArtOfTest.WebAii.Silverlight; using ArtOfTest.WebAii.Silverlight.UI; namespace MonkeyTests { public static class Constans { public static string BrowserWaitUntilReady = @"MonkeyTests\MonkeyHelper\Steps\MonkeyHelper_BrowserWaitUntilReady.tstest"; public static string NavigationToBaseUrl = @"MonkeyTests\MonkeyHelper\Steps\MonkeyHelper_NavigationToBaseUrl.tstest"; public static string ClickOnElement = @"MonkeyTests\MonkeyHelper\Steps\MonkeyHelper_ClickOnElement.tstest"; } } ```
499796f7-2e84-4a0a-abcd-e4fc64b74815
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; public class LightManager { Material LightOnMaterial; Material LightOffMaterial; public bool IsOn = true; // Use this for initialization public void UpdateLights() { GameObject[] allLights = GameObject.FindGameObjectsWithTag ("Light"); foreach (GameObject i in allLights) { i.SetActive (IsOn); } SpriteRenderer[] bitmaps = GameObject.FindObjectsOfType<SpriteRenderer>(); if (IsOn) { foreach (SpriteRenderer i in bitmaps) { i.material = LightOnMaterial; } } else { foreach (SpriteRenderer i in bitmaps) { i.material = LightOffMaterial; } } } public void SetLights(bool enabled) { IsOn = enabled; UpdateLights (); } private static LightManager instance; public static LightManager Instance { get { if(instance==null) { instance = new LightManager(); instance.LightOnMaterial = Resources.Load("Materials/LightOnMaterial", typeof(Material)) as Material; instance.LightOffMaterial = Resources.Load("Materials/LightOffMaterial", typeof(Material)) as Material; } return instance; } } } ``` Make lights not appear in menu
```c# using UnityEngine; using System.Collections; public class LightManager { Material LightOnMaterial; Material LightOffMaterial; public bool IsOn = true; // Use this for initialization public void UpdateLights() { bool lightOn = IsOn; if (!Application.loadedLevelName.StartsWith ("Level")) lightOn = false; GameObject[] allLights = GameObject.FindGameObjectsWithTag ("Light"); foreach (GameObject i in allLights) { i.SetActive (lightOn); } SpriteRenderer[] bitmaps = GameObject.FindObjectsOfType<SpriteRenderer>(); if (lightOn) { foreach (SpriteRenderer i in bitmaps) { i.material = LightOnMaterial; } } else { foreach (SpriteRenderer i in bitmaps) { i.material = LightOffMaterial; } } } public void SetLights(bool enabled) { IsOn = enabled; UpdateLights (); } private static LightManager instance; public static LightManager Instance { get { if(instance==null) { instance = new LightManager(); instance.LightOnMaterial = Resources.Load("Materials/LightOnMaterial", typeof(Material)) as Material; instance.LightOffMaterial = Resources.Load("Materials/LightOffMaterial", typeof(Material)) as Material; } return instance; } } } ```
c91a6c22-97b1-4b9c-b2b9-3b7c9cbbba26
{ "language": "C#" }
```c# using Avalonia.Controls; using System.Reactive.Disposables; namespace WalletWasabi.Gui.Behaviors { public class CommandOnDoubleClickBehavior : CommandBasedBehavior<Control> { private CompositeDisposable _disposables; protected override void OnAttached() { _disposables = new CompositeDisposable(); base.OnAttached(); _disposables.Add(AssociatedObject.AddHandler(Control.PointerPressedEvent, (sender, e) => { if(e.ClickCount == 2) { e.Handled = ExecuteCommand(); } })); } protected override void OnDetaching() { base.OnDetaching(); _disposables.Dispose(); } } } ``` Use property instead of field for CompositeDisposable
```c# using Avalonia.Controls; using System.Reactive.Disposables; namespace WalletWasabi.Gui.Behaviors { public class CommandOnDoubleClickBehavior : CommandBasedBehavior<Control> { private CompositeDisposable Disposables { get; set; } protected override void OnAttached() { Disposables = new CompositeDisposable(); base.OnAttached(); Disposables.Add(AssociatedObject.AddHandler(Control.PointerPressedEvent, (sender, e) => { if (e.ClickCount == 2) { e.Handled = ExecuteCommand(); } })); } protected override void OnDetaching() { base.OnDetaching(); Disposables?.Dispose(); } } } ```
e6406fba-842f-495b-9d2b-598234224e92
{ "language": "C#" }
```c# using Mond.Binding; namespace Mond.Libraries.Console { [MondClass("")] internal class ConsoleOutputClass { private ConsoleOutputLibrary _consoleOutput; public static MondValue Create(ConsoleOutputLibrary consoleOutput) { MondValue prototype; MondClassBinder.Bind<ConsoleOutputClass>(out prototype); var instance = new ConsoleOutputClass(); instance._consoleOutput = consoleOutput; var obj = new MondValue(MondValueType.Object); obj.UserData = instance; obj.Prototype = prototype; obj.Lock(); return obj; } [MondFunction("print")] public void Print(params MondValue[] arguments) { foreach (var v in arguments) { _consoleOutput.Out.Write((string)v); } } [MondFunction("printLn")] public void PrintLn(params MondValue[] arguments) { if (arguments.Length == 0) _consoleOutput.Out.WriteLine(); foreach (var v in arguments) { _consoleOutput.Out.Write((string)v); _consoleOutput.Out.WriteLine(); } } } } ``` Change printLn to print all values followed by a newline
```c# using Mond.Binding; namespace Mond.Libraries.Console { [MondClass("")] internal class ConsoleOutputClass { private ConsoleOutputLibrary _consoleOutput; public static MondValue Create(ConsoleOutputLibrary consoleOutput) { MondValue prototype; MondClassBinder.Bind<ConsoleOutputClass>(out prototype); var instance = new ConsoleOutputClass(); instance._consoleOutput = consoleOutput; var obj = new MondValue(MondValueType.Object); obj.UserData = instance; obj.Prototype = prototype; obj.Lock(); return obj; } [MondFunction("print")] public void Print(params MondValue[] arguments) { foreach (var v in arguments) { _consoleOutput.Out.Write((string)v); } } [MondFunction("printLn")] public void PrintLn(params MondValue[] arguments) { foreach (var v in arguments) { _consoleOutput.Out.Write((string)v); } _consoleOutput.Out.WriteLine(); } } } ```
747ddece-a7e4-4a1f-8d38-6299150eabfc
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("HALClient")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HALClient")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo("HALClient.Tests")] // 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")] ``` Set the version to a trepidatious 0.5
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("HALClient")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HALClient")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo("HALClient.Tests")] // 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")] [assembly: AssemblyFileVersion("0.5.0")] ```
1abf436e-26e7-400d-aa08-ae7d8c965e6f
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using Android.App; using Android.Content; using Android.Content.PM; using Android.Database; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Support.Design.Widget; using Android.Support.V4.Widget; using Android.Support.V4.View; using Android.Support.V7.App; using Android.Support.V7.Widget; using Android.Utilities; using Android.Views; using Android.Widget; using Java.Lang; using Fragment = Android.Support.V4.App.Fragment; using Toolbar = Android.Support.V7.Widget.Toolbar; using SearchView = Android.Support.V7.Widget.SearchView; namespace Android.Utilities { public abstract class TabFragment : Fragment { public abstract string Title { get; } protected virtual void OnGotFocus() { } protected virtual void OnLostFocus() { } public virtual void Refresh() { } public override void SetMenuVisibility(bool visible) { base.SetMenuVisibility(visible); if (visible) OnGotFocus(); else OnLostFocus(); } } }``` Use UserVisibilityHint to detect ViewPager change instead of MenuVisibility, this fixes an Exception.
```c# using System; using System.Collections.Generic; using System.Linq; using Android.App; using Android.Content; using Android.Content.PM; using Android.Database; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Support.Design.Widget; using Android.Support.V4.Widget; using Android.Support.V4.View; using Android.Support.V7.App; using Android.Support.V7.Widget; using Android.Utilities; using Android.Views; using Android.Widget; using Java.Lang; using Fragment = Android.Support.V4.App.Fragment; using Toolbar = Android.Support.V7.Widget.Toolbar; using SearchView = Android.Support.V7.Widget.SearchView; namespace Android.Utilities { public abstract class TabFragment : Fragment { public abstract string Title { get; } protected virtual void OnGotFocus() { } protected virtual void OnLostFocus() { } public virtual void Refresh() { } public override void SetMenuVisibility(bool visible) { base.SetMenuVisibility(visible); /*if (visible) OnGotFocus(); else OnLostFocus();*/ } public override bool UserVisibleHint { get { return base.UserVisibleHint; } set { base.UserVisibleHint = value; if (value) OnGotFocus(); else OnLostFocus(); } } } }```
fa37d59d-53ba-40d2-aba0-91f9c505ffa8
{ "language": "C#" }
```c# namespace SimpSim.NET { public class Registers { public delegate void ValueWrittenToOutputRegisterHandler(char output); public event ValueWrittenToOutputRegisterHandler ValueWrittenToOutputRegister; private readonly byte[] _array; public Registers() { _array = new byte[16]; } public byte this[byte register] { get { return _array[register]; } set { _array[register] = value; if (register == 0x0f && ValueWrittenToOutputRegister != null) ValueWrittenToOutputRegister((char)value); } } } }``` Use null propagation when invoking ValueWrittenToOutputRegister to prevent possible race condition.
```c# namespace SimpSim.NET { public class Registers { public delegate void ValueWrittenToOutputRegisterHandler(char output); public event ValueWrittenToOutputRegisterHandler ValueWrittenToOutputRegister; private readonly byte[] _array; public Registers() { _array = new byte[16]; } public byte this[byte register] { get { return _array[register]; } set { _array[register] = value; if (register == 0x0f) ValueWrittenToOutputRegister?.Invoke((char)value); } } } }```
2a346ddb-14c5-4c9b-a5b0-394bbd388a7a
{ "language": "C#" }
```c# using System; namespace Utils { public static class Strings { public static Tuple<string, string> SplitString(this string str, char separator) { var index = str.IndexOf(separator); var str2 = str.Length > index?str.Substring(index + 1):string.Empty; var str1 = str.Substring(0, index); return new Tuple<string, string>(str1, str2); } } } ``` Add Trim string property extension
```c# using System; namespace Utils { public static class Strings { public static Tuple<string, string> SplitString(this string str, char separator) { var index = str.IndexOf(separator); var str2 = str.Length > index?str.Substring(index + 1):string.Empty; var str1 = str.Substring(0, index); return new Tuple<string, string>(str1, str2); } public static void Trim<T>(this T obj, Expression<Func<T, string>> action) where T : class { var expression = (MemberExpression)action.Body; var member = expression.Member; Action<string> setProperty; Func<string> getPropertyValue; switch (member.MemberType) { case MemberTypes.Field: setProperty = val => ((FieldInfo)member).SetValue(obj,val); getPropertyValue = () => ((FieldInfo)member).GetValue(obj)?.ToString(); break; case MemberTypes.Property: setProperty = val => ((PropertyInfo)member).SetValue(obj, val); getPropertyValue = () => ((PropertyInfo) member).GetValue(obj)?.ToString(); break; default: throw new ArgumentOutOfRangeException(); } var trimmedString = getPropertyValue().Trim(); setProperty(trimmedString); } } } ```
613dca3b-d511-4f52-a6a8-18211c19c43a
{ "language": "C#" }
```c# using NUnit.Framework; namespace ZimmerBot.Core.Tests.BotTests { [TestFixture] public class ContinueTests : TestHelper { [Test] public void CanContinueWithEmptyTarget() { BuildBot(@" > Hello : Hi ! continue > * ! weight 0.5 : What can I help you with? "); AssertDialog("Hello", "Hi\nWhat can I help you with?"); } [Test] public void CanContinueWithLabel() { BuildBot(@" > Yo : Yaj! ! continue at HowIsItGoing <HowIsItGoing> : How is it going? > : What can I help you with? "); AssertDialog("Yo!", "Yaj!\nHow is it going?"); } [Test] public void CanContinueWithNewInput() { BuildBot(@" > Yo : Yaj! ! continue with Having Fun > Having Fun : is it fun > : What can I help you with? "); AssertDialog("Yo!", "Yaj!\nis it fun"); } } } ``` Add test showing problem with "continue with".
```c# using NUnit.Framework; namespace ZimmerBot.Core.Tests.BotTests { [TestFixture] public class ContinueTests : TestHelper { [Test] public void CanContinueWithEmptyTarget() { BuildBot(@" > Hello : Hi ! continue > * ! weight 0.5 : What can I help you with? "); AssertDialog("Hello", "Hi\nWhat can I help you with?"); } [Test] public void CanContinueWithLabel() { BuildBot(@" > Yo : Yaj! ! continue at HowIsItGoing <HowIsItGoing> : How is it going? > : What can I help you with? "); AssertDialog("Yo!", "Yaj!\nHow is it going?"); } [Test] public void CanContinueWithNewInput() { BuildBot(@" > Yo : Yaj! ! continue with Having Fun > Having Fun : is it fun > : What can I help you with? "); AssertDialog("Yo!", "Yaj!\nis it fun"); } [Test] public void CanContinueWithParameters() { BuildBot(@" > Yo + : Yaj! ! continue with Some <1> > Some + : Love '<1>' "); AssertDialog("Yo Mouse", "Yaj!\nLove 'Mouse'"); } } } ```
b6253ac4-b210-499f-bf99-dd370d83fba0
{ "language": "C#" }
```c# // 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. namespace osu.Game.Skinning { public class LegacySkinConfiguration : DefaultSkinConfiguration { public const decimal LATEST_VERSION = 2.7m; /// <summary> /// Legacy version of this skin. Null if no version was set to allow fallback to a parent skin version. /// </summary> public decimal? LegacyVersion { get; internal set; } public enum LegacySetting { Version, } } } ``` Remove unnecessary mentioning in xmldoc
```c# // 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. namespace osu.Game.Skinning { public class LegacySkinConfiguration : DefaultSkinConfiguration { public const decimal LATEST_VERSION = 2.7m; /// <summary> /// Legacy version of this skin. /// </summary> public decimal? LegacyVersion { get; internal set; } public enum LegacySetting { Version, } } } ```
c4a0a776-50bc-4ee0-a242-65e2c8b5515b
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LaunchNumbering { public class LNSettings : GameParameters.CustomParameterNode { public override GameParameters.GameMode GameMode => GameParameters.GameMode.ANY; public override bool HasPresets => false; public override string Section => "Launch Numbering"; public override int SectionOrder => 1; public override string Title => "Vessel Defaults"; [GameParameters.CustomParameterUI("Numbering Scheme")] public NumberScheme Scheme { get; set; } [GameParameters.CustomParameterUI("Show Bloc numbers")] public bool ShowBloc { get; set; } [GameParameters.CustomParameterUI("Bloc Numbering Scheme")] public NumberScheme BlocScheme { get; set; } public enum NumberScheme { Arabic, Roman } } } ``` Set suitable default settings, in accordance with the prophecy
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LaunchNumbering { public class LNSettings : GameParameters.CustomParameterNode { public override GameParameters.GameMode GameMode => GameParameters.GameMode.ANY; public override bool HasPresets => false; public override string Section => "Launch Numbering"; public override int SectionOrder => 1; public override string Title => "Vessel Defaults"; [GameParameters.CustomParameterUI("Numbering Scheme")] public NumberScheme Scheme { get; set; } [GameParameters.CustomParameterUI("Show Bloc numbers")] public bool ShowBloc { get; set; } = true; [GameParameters.CustomParameterUI("Bloc Numbering Scheme")] public NumberScheme BlocScheme { get; set; } = NumberScheme.Roman; public enum NumberScheme { Arabic, Roman } } } ```
77132644-60e8-40bf-b952-228cbf01f3a8
{ "language": "C#" }
```c# using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Assignment2Application; namespace UnitTestProject1 { [TestClass] public class UnitTest1 { FibonacciGenerator _gen = new FibonacciGenerator(); [TestMethod] public void FibonacciGeneratorBasic() { Assert.Equals(_gen.Get(0), 0); Assert.Equals(_gen.Get(1), 1); Assert.Equals(_gen.Get(2), 1); Assert.Equals(_gen.Get(3), 2); Assert.Equals(_gen.Get(4), 3); Assert.Equals(_gen.Get(5), 5); } [TestMethod] public void FibonacciGenerator9() { Assert.Equals(_gen.Get(9), 34); } [TestMethod] public void FibonacciGeneratorBig() { Assert.AreNotSame(_gen.Get(12345678), 0); } } } ``` Replace deprecated Equals API by AreEqual
```c# using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Assignment2Application; namespace UnitTestProject1 { [TestClass] public class UnitTest1 { FibonacciGenerator _gen = new FibonacciGenerator(); [TestMethod] public void FibonacciGeneratorBasic() { Assert.AreEqual(_gen.Get(0), 0); Assert.AreEqual(_gen.Get(1), 1); Assert.AreEqual(_gen.Get(2), 1); Assert.AreEqual(_gen.Get(3), 2); Assert.AreEqual(_gen.Get(4), 3); Assert.AreEqual(_gen.Get(5), 5); } [TestMethod] public void FibonacciGenerator9() { Assert.AreEqual(_gen.Get(9), 34); } [TestMethod] public void FibonacciGeneratorBig() { Assert.AreNotSame(_gen.Get(12345678), 0); } } } ```
944fb0bd-d70f-430d-9788-9846ccec5a33
{ "language": "C#" }
```c# using System; using dnlib.DotNet; namespace Confuser.Core.Project.Patterns { /// <summary> /// A function that compare the namespace of definition. /// </summary> public class NamespaceFunction : PatternFunction { internal const string FnName = "namespace"; /// <inheritdoc /> public override string Name { get { return FnName; } } /// <inheritdoc /> public override int ArgumentCount { get { return 1; } } /// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { if (!(definition is TypeDef) && !(definition is IMemberDef)) return false; object ns = Arguments[0].Evaluate(definition); var type = definition as TypeDef; if (type == null) type = ((IMemberDef)definition).DeclaringType; while (type.IsNested) type = type.DeclaringType; return type != null && type.Namespace == ns.ToString(); } } }``` Use Regex in namespace pattern
```c# using System; using System.Text.RegularExpressions; using dnlib.DotNet; namespace Confuser.Core.Project.Patterns { /// <summary> /// A function that compare the namespace of definition. /// </summary> public class NamespaceFunction : PatternFunction { internal const string FnName = "namespace"; /// <inheritdoc /> public override string Name { get { return FnName; } } /// <inheritdoc /> public override int ArgumentCount { get { return 1; } } /// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { if (!(definition is TypeDef) && !(definition is IMemberDef)) return false; var ns = Arguments[0].Evaluate(definition).ToString(); var type = definition as TypeDef; if (type == null) type = ((IMemberDef)definition).DeclaringType; while (type.IsNested) type = type.DeclaringType; return type != null && Regex.IsMatch(type.Namespace, ns); } } }```
bb3ca773-ed73-47d2-9f9b-3755dda1e649
{ "language": "C#" }
```c# using System; using System.Linq; using LinqToDB; using NUnit.Framework; namespace Tests.UserTests { [TestFixture] public class Issue1556Tests : TestBase { [Test] public void Issue1556Test([DataSources(ProviderName.Sybase, ProviderName.OracleNative)] string context) { using (var db = GetDataContext(context)) { AreEqual( from p in db.Parent from c in db.Child where p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID) select new { p, c } , db.Parent .InnerJoin(db.Child, (p,c) => p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID), (p,c) => new { p, c })); } } } } ``` Access dos not support such join syntax.
```c# using System; using System.Linq; using LinqToDB; using NUnit.Framework; namespace Tests.UserTests { [TestFixture] public class Issue1556Tests : TestBase { [Test] public void Issue1556Test( [DataSources(ProviderName.Sybase, ProviderName.OracleNative, ProviderName.Access)] string context) { using (var db = GetDataContext(context)) { AreEqual( from p in db.Parent from c in db.Child where p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID) select new { p, c } , db.Parent .InnerJoin(db.Child, (p,c) => p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID), (p,c) => new { p, c })); } } } } ```
78814593-bd12-4018-b023-b89650cc31a0
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; namespace InfinniPlatform.Core.Metadata { public class MetadataUniqueName : IEquatable<MetadataUniqueName> { private const char NamespaceSeparator = '.'; public MetadataUniqueName(string ns, string name) { Namespace = ns; Name = name; } public MetadataUniqueName(string fullQuelifiedName) { Namespace = fullQuelifiedName.Remove(fullQuelifiedName.LastIndexOf(NamespaceSeparator)); Name = fullQuelifiedName.Split(NamespaceSeparator).Last(); } public string Namespace { get; } public string Name { get; } public bool Equals(MetadataUniqueName other) { return Namespace.Equals(other.Namespace) && Name.Equals(other.Name); } public override string ToString() { return $"{Namespace}.{Name}"; } public override int GetHashCode() { return Namespace.GetHashCode() ^ Name.GetHashCode(); } } }``` Fix metadata cache case dependency
```c# using System; using System.Collections.Generic; using System.Linq; namespace InfinniPlatform.Core.Metadata { public class MetadataUniqueName : IEquatable<MetadataUniqueName> { private const char NamespaceSeparator = '.'; public MetadataUniqueName(string ns, string name) { Namespace = ns; Name = name; } public MetadataUniqueName(string fullQuelifiedName) { Namespace = fullQuelifiedName.Remove(fullQuelifiedName.LastIndexOf(NamespaceSeparator)); Name = fullQuelifiedName.Split(NamespaceSeparator).Last(); } public string Namespace { get; } public string Name { get; } public bool Equals(MetadataUniqueName other) { return Namespace.Equals(other.Namespace, StringComparison.OrdinalIgnoreCase) && Name.Equals(other.Name, StringComparison.OrdinalIgnoreCase); } public override string ToString() { return $"{Namespace}.{Name}"; } public override int GetHashCode() { return Namespace.ToLower().GetHashCode() ^ Name.ToLower().GetHashCode(); } } }```
de70a51d-6bf2-4a93-90ef-49b46ebcc9cd
{ "language": "C#" }
```c# using System.IO; using System.Text; using Antlr4.Runtime; using GraphQL.Language; using GraphQL.Parsing; namespace GraphQL.Execution { public class AntlrDocumentBuilder : IDocumentBuilder { public Document Build(string data) { var stream = new MemoryStream(Encoding.UTF8.GetBytes(data)); var reader = new StreamReader(stream); var input = new AntlrInputStream(reader); var lexer = new GraphQLLexer(input); var tokens = new CommonTokenStream(lexer); var parser = new GraphQLParser(tokens); var documentTree = parser.document(); var vistor = new GraphQLVisitor(); return vistor.Visit(documentTree) as Document; } } } ``` Clean up stream after use.
```c# using System.IO; using System.Text; using Antlr4.Runtime; using GraphQL.Language; using GraphQL.Parsing; namespace GraphQL.Execution { public class AntlrDocumentBuilder : IDocumentBuilder { public Document Build(string data) { using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(data))) using (var reader = new StreamReader(stream)) { var input = new AntlrInputStream(reader); var lexer = new GraphQLLexer(input); var tokens = new CommonTokenStream(lexer); var parser = new GraphQLParser(tokens); var documentTree = parser.document(); var vistor = new GraphQLVisitor(); return vistor.Visit(documentTree) as Document; } } } } ```
544965c3-2e64-4f24-a793-4bb9aaf216d8
{ "language": "C#" }
```c# using System; using System.Threading.Tasks; using NServiceBus; using NServiceBus.Logging; class ChaosHandler : IHandleMessages<object> { readonly ILog Log = LogManager.GetLogger<ChaosHandler>(); readonly double Thresshold = ThreadLocalRandom.NextDouble() * 0.50; public Task Handle(object message, IMessageHandlerContext context) { var result = ThreadLocalRandom.NextDouble(); if (result < Thresshold) throw new Exception($"Random chaos ({Thresshold * 100:N}% failure)"); return Task.FromResult(0); } } ``` Set failure rate to max 5%
```c# using System; using System.Threading.Tasks; using NServiceBus; using NServiceBus.Logging; class ChaosHandler : IHandleMessages<object> { readonly ILog Log = LogManager.GetLogger<ChaosHandler>(); readonly double Thresshold = ThreadLocalRandom.NextDouble() * 0.05; public Task Handle(object message, IMessageHandlerContext context) { var result = ThreadLocalRandom.NextDouble(); if (result < Thresshold) throw new Exception($"Random chaos ({Thresshold * 100:N}% failure)"); return Task.FromResult(0); } } ```
557e8c15-e487-4077-b1cb-ff7cae11f2c2
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using PhotoLife.Data.Contracts; using PhotoLife.Models; using PhotoLife.Models.Enums; using PhotoLife.Services.Contracts; namespace PhotoLife.Services { public class CategoryService : ICategoryService { private readonly IRepository<Category> categoryRepository; private readonly IUnitOfWork unitOfWork; public CategoryService(IRepository<Category> categoryRepository, IUnitOfWork unitOfWork) { if (categoryRepository == null) { throw new ArgumentNullException(nameof(categoryRepository)); } if (unitOfWork == null) { throw new ArgumentNullException(nameof(unitOfWork)); } this.categoryRepository = categoryRepository; this.unitOfWork = unitOfWork; } public Category GetCategoryByName(CategoryEnum categoryEnum) { return this.categoryRepository.GetAll.FirstOrDefault(c => c.Name.Equals(categoryEnum)); } public IEnumerable<Category> GetAll() { return this.categoryRepository.GetAll.ToList(); } } } ``` Change throw exception due to appharbor build
```c# using System; using System.Collections.Generic; using System.Linq; using PhotoLife.Data.Contracts; using PhotoLife.Models; using PhotoLife.Models.Enums; using PhotoLife.Services.Contracts; namespace PhotoLife.Services { public class CategoryService : ICategoryService { private readonly IRepository<Category> categoryRepository; private readonly IUnitOfWork unitOfWork; public CategoryService(IRepository<Category> categoryRepository, IUnitOfWork unitOfWork) { if (categoryRepository == null) { throw new ArgumentNullException("categoryRepository"); } if (unitOfWork == null) { throw new ArgumentNullException("unitOfWork"); } this.categoryRepository = categoryRepository; this.unitOfWork = unitOfWork; } public Category GetCategoryByName(CategoryEnum categoryEnum) { return this.categoryRepository.GetAll.FirstOrDefault(c => c.Name.Equals(categoryEnum)); } public IEnumerable<Category> GetAll() { return this.categoryRepository.GetAll.ToList(); } } } ```
f06a4913-06e2-4e83-94cb-c67d07ffbaf7
{ "language": "C#" }
```c# namespace SyncTrayzor.SyncThing.ApiClient { public class GenericEvent : Event { public override void Visit(IEventVisitor visitor) { visitor.Accept(this); } public override string ToString() { return $"<GenericEvent ID={this.Id} Type={this.Type} Time={this.Time}>"; } } } ``` Print 'data' fields for generic events
```c# using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace SyncTrayzor.SyncThing.ApiClient { public class GenericEvent : Event { public override void Visit(IEventVisitor visitor) { visitor.Accept(this); } [JsonProperty("data")] public JToken Data { get; set; } public override string ToString() { return $"<GenericEvent ID={this.Id} Type={this.Type} Time={this.Time} Data={this.Data.ToString(Formatting.None)}>"; } } } ```
5a817f44-83e1-4886-bfbb-788c1aa67207
{ "language": "C#" }
```c# // Copyright 2017-2018 Dirk Lemstra (https://github.com/dlemstra/line-bot-sdk-dotnet) // // Dirk Lemstra licenses this file to you under the Apache License, // version 2.0 (the "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at: // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. namespace Line.Tests { [ExcludeFromCodeCoverage] public sealed class TestConfiguration : ILineConfiguration { private TestConfiguration() { } public string ChannelAccessToken => "ChannelAccessToken"; public string ChannelSecret => "ChannelSecret"; public static ILineConfiguration Create() { return new TestConfiguration(); } public static ILineBot CreateBot() { return new LineBot(new TestConfiguration(), TestHttpClient.Create(), null); } public static ILineBot CreateBot(TestHttpClient httpClient) { return new LineBot(new TestConfiguration(), httpClient, null); } public static ILineBot CreateBot(ILineBotLogger logger) { return new LineBot(new TestConfiguration(), TestHttpClient.Create(), logger); } } } ``` Use EmptyLineBotLogger in unit tests.
```c# // Copyright 2017-2018 Dirk Lemstra (https://github.com/dlemstra/line-bot-sdk-dotnet) // // Dirk Lemstra licenses this file to you under the Apache License, // version 2.0 (the "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at: // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. namespace Line.Tests { [ExcludeFromCodeCoverage] public sealed class TestConfiguration : ILineConfiguration { private TestConfiguration() { } public string ChannelAccessToken => "ChannelAccessToken"; public string ChannelSecret => "ChannelSecret"; public static ILineConfiguration Create() { return new TestConfiguration(); } public static ILineBot CreateBot() { return new LineBot(new TestConfiguration(), TestHttpClient.Create(), new EmptyLineBotLogger()); } public static ILineBot CreateBot(TestHttpClient httpClient) { return new LineBot(new TestConfiguration(), httpClient, new EmptyLineBotLogger()); } public static ILineBot CreateBot(ILineBotLogger logger) { return new LineBot(new TestConfiguration(), TestHttpClient.Create(), logger); } } } ```
1983d5c5-1398-46a5-abac-163d3eb41cc1
{ "language": "C#" }
```c# using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace NRules.RuleModel { /// <summary> /// Sorted readonly map of named expressions. /// </summary> public class ExpressionMap : IEnumerable<NamedExpressionElement> { private readonly SortedDictionary<string, NamedExpressionElement> _expressions; public ExpressionMap(IEnumerable<NamedExpressionElement> expressions) { _expressions = new SortedDictionary<string, NamedExpressionElement>(expressions.ToDictionary(x => x.Name)); } /// <summary> /// Number of expressions in the map. /// </summary> public int Count => _expressions.Count; /// <summary> /// Retrieves expression by name. /// </summary> /// <param name="name">Expression name.</param> /// <returns>Matching expression.</returns> public NamedExpressionElement this[string name] { get { var found = _expressions.TryGetValue(name, out var result); if (!found) { throw new ArgumentException( $"Expression with the given name not found. Name={name}", nameof(name)); } return result; } } public IEnumerator<NamedExpressionElement> GetEnumerator() { return _expressions.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }``` Add Find method to expression map
```c# using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace NRules.RuleModel { /// <summary> /// Sorted readonly map of named expressions. /// </summary> public class ExpressionMap : IEnumerable<NamedExpressionElement> { private readonly SortedDictionary<string, NamedExpressionElement> _expressions; public ExpressionMap(IEnumerable<NamedExpressionElement> expressions) { _expressions = new SortedDictionary<string, NamedExpressionElement>(expressions.ToDictionary(x => x.Name)); } /// <summary> /// Number of expressions in the map. /// </summary> public int Count => _expressions.Count; /// <summary> /// Retrieves expression by name. /// </summary> /// <param name="name">Expression name.</param> /// <returns>Matching expression.</returns> public NamedExpressionElement this[string name] { get { var found = _expressions.TryGetValue(name, out var result); if (!found) { throw new ArgumentException( $"Expression with the given name not found. Name={name}", nameof(name)); } return result; } } /// <summary> /// Retrieves expression by name. /// </summary> /// <param name="name">Expression name.</param> /// <returns>Matching expression or <c>null</c>.</returns> public NamedExpressionElement Find(string name) { _expressions.TryGetValue(name, out var result); return result; } public IEnumerator<NamedExpressionElement> GetEnumerator() { return _expressions.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }```
6a9b5b97-bbe0-4ecf-ae18-89bfa77b49cd
{ "language": "C#" }
```c# using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Mono.Cecil; using System; using System.IO; namespace AspectInjector.BuildTask { public class AspectInjectorBuildTask : Task { [Required] public string Assembly { get; set; } [Required] public string OutputPath { get; set; } public override bool Execute() { try { Console.WriteLine("Aspect Injector has started for {0}", Assembly); var assemblyResolver = new DefaultAssemblyResolver(); assemblyResolver.AddSearchDirectory(OutputPath); string assemblyFile = Path.Combine(OutputPath, Assembly + ".exe"); var assembly = AssemblyDefinition.ReadAssembly(assemblyFile, new ReaderParameters { ReadingMode = Mono.Cecil.ReadingMode.Deferred, AssemblyResolver = assemblyResolver }); Console.WriteLine("Assembly has been loaded"); var injector = new AspectInjector(); injector.Process(assembly); Console.WriteLine("Assembly has been patched"); assembly.Write(assemblyFile); Console.WriteLine("Assembly has been written"); } catch (Exception e) { this.Log.LogErrorFromException(e, false, true, null); Console.Error.WriteLine(e.Message); return false; } return true; } } }``` Support debugging of modified assemblies
```c# using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Mono.Cecil; using System; using System.IO; namespace AspectInjector.BuildTask { public class AspectInjectorBuildTask : Task { [Required] public string Assembly { get; set; } [Required] public string OutputPath { get; set; } public override bool Execute() { try { Console.WriteLine("Aspect Injector has started for {0}", Assembly); var assemblyResolver = new DefaultAssemblyResolver(); assemblyResolver.AddSearchDirectory(OutputPath); string assemblyFile = Path.Combine(OutputPath, Assembly + ".exe"); string pdbFile = Path.Combine(OutputPath, Assembly + ".pdb"); var assembly = AssemblyDefinition.ReadAssembly(assemblyFile, new ReaderParameters { ReadingMode = Mono.Cecil.ReadingMode.Deferred, AssemblyResolver = assemblyResolver, ReadSymbols = true }); Console.WriteLine("Assembly has been loaded"); var injector = new AspectInjector(); injector.Process(assembly); Console.WriteLine("Assembly has been patched"); assembly.Write(assemblyFile, new WriterParameters() { WriteSymbols = true }); Console.WriteLine("Assembly has been written"); } catch (Exception e) { this.Log.LogErrorFromException(e, false, true, null); Console.Error.WriteLine(e.Message); return false; } return true; } } }```
6843a8cb-18c9-4589-bb67-635f0e8d4070
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace AllReady.Models { public class Activity { public Activity() { Tasks = new List<AllReadyTask>(); UsersSignedUp = new List<ActivitySignup>(); RequiredSkills = new List<ActivitySkill>(); } public int Id { get; set; } [Display(Name = "Tenant")] public int TenantId { get; set; } public Tenant Tenant { get; set; } [Display(Name = "Campaign")] public int CampaignId { get; set; } public Campaign Campaign { get; set; } public string Name { get; set; } public string Description { get; set; } [Display(Name = "Start date")] public DateTime StartDateTimeUtc { get; set; } [Display(Name = "End date")] public DateTime EndDateTimeUtc { get; set; } public Location Location { get; set; } public List<AllReadyTask> Tasks { get; set; } public List<ActivitySignup> UsersSignedUp { get; set; } public ApplicationUser Organizer { get; set; } [Display(Name = "Image")] public string ImageUrl { get; set; } [Display(Name = "Required skills")] public List<ActivitySkill> RequiredSkills { get; set; } } }``` Use propert initializers instead of constructor
```c# using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace AllReady.Models { public class Activity { public int Id { get; set; } [Display(Name = "Tenant")] public int TenantId { get; set; } public Tenant Tenant { get; set; } [Display(Name = "Campaign")] public int CampaignId { get; set; } public Campaign Campaign { get; set; } public string Name { get; set; } public string Description { get; set; } [Display(Name = "Start date")] public DateTime StartDateTimeUtc { get; set; } [Display(Name = "End date")] public DateTime EndDateTimeUtc { get; set; } public Location Location { get; set; } public List<AllReadyTask> Tasks { get; set; } = new List<AllReadyTask>(); public List<ActivitySignup> UsersSignedUp { get; set; } = new List<ActivitySignup>(); public ApplicationUser Organizer { get; set; } [Display(Name = "Image")] public string ImageUrl { get; set; } [Display(Name = "Required skills")] public List<ActivitySkill> RequiredSkills { get; set; } = new List<ActivitySkill>(); } }```
86fee7b3-212f-4b85-b29d-8707f4cac8ce
{ "language": "C#" }
```c# /* * SqlServerHelpers * SqlConnectionExtensions - Extension methods for SqlConnection * Authors: * Josh Keegan 26/05/2015 */ using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SqlServerHelpers.ExtensionMethods { public static class SqlConnectionExtensions { public static SqlCommand GetSqlCommand(this SqlConnection conn, SqlTransaction trans = null) { return getSqlCommand(null, conn, trans); } public static SqlCommand GetSqlCommand(this SqlConnection conn, string txtCmd, SqlTransaction trans = null) { return getSqlCommand(txtCmd, conn, trans); } private static SqlCommand getSqlCommand(string txtCmd, SqlConnection conn, SqlTransaction trans) { SqlCommand command = new SqlCommand(txtCmd, conn, trans); // Apply default command settings if (Settings.Command != null) { if (Settings.Command.CommandTimeout != null) { command.CommandTimeout = (int) Settings.Command.CommandTimeout; } // TODO: Support more default settings as they're added to CommandSettings } return command; } } } ``` Allow non-default Command Settings to be passed to GetSqlCommand()
```c# /* * SqlServerHelpers * SqlConnectionExtensions - Extension methods for SqlConnection * Authors: * Josh Keegan 26/05/2015 */ using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SqlServerHelpers.ExtensionMethods { public static class SqlConnectionExtensions { #region Public Methods public static SqlCommand GetSqlCommand(this SqlConnection conn, SqlTransaction trans = null, CommandSettings commandSettings = null) { return getSqlCommand(null, conn, trans, commandSettings); } public static SqlCommand GetSqlCommand(this SqlConnection conn, string txtCmd, SqlTransaction trans = null, CommandSettings commandSettings = null) { return getSqlCommand(txtCmd, conn, trans, commandSettings); } public static SqlCommand GetSqlCommand(this SqlConnection conn, CommandSettings commandSettings) { return GetSqlCommand(conn, null, commandSettings); } #endregion #region Private Methods private static SqlCommand getSqlCommand(string txtCmd, SqlConnection conn, SqlTransaction trans, CommandSettings commandSettings) { // If no command settings have been supplied, use the default ones as defined statically in Settings if (commandSettings == null) { commandSettings = Settings.Command; } // Make the command SqlCommand command = new SqlCommand(txtCmd, conn, trans); // Apply command settings if (commandSettings != null) { if (commandSettings.CommandTimeout != null) { command.CommandTimeout = (int) commandSettings.CommandTimeout; } // TODO: Support more default settings as they're added to CommandSettings } return command; } #endregion } } ```
68ffb953-026f-42a2-9278-20f2dd127669
{ "language": "C#" }
```c# using NUnit.Framework; using UnityEngine.Formats.Alembic.Sdk; namespace UnityEditor.Formats.Alembic.Exporter.UnitTests { class EditorTests { [Test] public void MarshalTests() { Assert.AreEqual(72,System.Runtime.InteropServices.Marshal.SizeOf(typeof(aePolyMeshData))); } } }``` Add whitespace on test file
```c# using NUnit.Framework; using UnityEngine.Formats.Alembic.Sdk; namespace UnityEditor.Formats.Alembic.Exporter.UnitTests { class EditorTests { [Test] public void MarshalTests() { Assert.AreEqual(72,System.Runtime.InteropServices.Marshal.SizeOf(typeof(aePolyMeshData))); } } } ```
d2fd1dea-7f87-4292-9dcf-c24fc075b687
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Text; using TFG.Model; namespace TFG.Logic { public class SintromLogic { private static SintromLogic _instance; public static SintromLogic Instance() { if (_instance == null) { _instance = new SintromLogic(); } return _instance; } private SintromLogic() { } public NotificationItem GetNotificationitem() { var sintromItems = DBHelper.Instance.GetSintromItemFromDate(DateTime.Now); if (sintromItems.Count > 0) { var sintromItem = sintromItems[0]; var title = HealthModulesInfo.GetStringFromResourceName("sintrom_name"); var description = string.Format(HealthModulesInfo.GetStringFromResourceName("sintrom_notification_description"), sintromItem.Fraction, sintromItem.Medicine); return new NotificationItem(title, description, true); } return null; } } } ``` Set notification for sintrom control days
```c# using System; using System.Collections.Generic; using System.Text; using TFG.Model; namespace TFG.Logic { public class SintromLogic { private static SintromLogic _instance; public static SintromLogic Instance() { if (_instance == null) { _instance = new SintromLogic(); } return _instance; } private SintromLogic() { } public NotificationItem GetNotificationitem() { var controlday = DBHelper.Instance.GetSintromINRItemFromDate(DateTime.Now); var title = HealthModulesInfo.GetStringFromResourceName("sintrom_name"); //Control Day Notification if (controlday.Count > 0 && controlday[0].Control) { var description = string.Format(HealthModulesInfo.GetStringFromResourceName("sintrom_notification_control_description")); return new NotificationItem(title, description, true); } //Treatment Day Notification var sintromItems = DBHelper.Instance.GetSintromItemFromDate(DateTime.Now); if (sintromItems.Count > 0) { var sintromItem = sintromItems[0]; var description = string.Format(HealthModulesInfo.GetStringFromResourceName("sintrom_notification_description"), sintromItem.Fraction, sintromItem.Medicine); return new NotificationItem(title, description, true); } //No Notification return null; } } } ```
403d3981-150c-4ef3-842d-7499451f81ad
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("LazyStorage")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LazyStorage")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo("LazyStorage.Tests")] // 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("4538ca36-f57b-4bec-b9d1-3540fdd28ae3")] // 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")]``` Remove version attributes from assembly info
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("LazyStorage")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LazyStorage")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo("LazyStorage.Tests")] // 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("4538ca36-f57b-4bec-b9d1-3540fdd28ae3")] ```
7d93d2ad-7cc7-4140-bf1e-e4825a517ef6
{ "language": "C#" }
```c# /* * ****************************************************************************** * Copyright 2014 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ using System.Reflection; // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.0.0")] [assembly: AssemblyFileVersion("1.2.0.0")] ``` Change version number to 1.2.1
```c# /* * ****************************************************************************** * Copyright 2014 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ using System.Reflection; // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.1.0")] [assembly: AssemblyFileVersion("1.2.1.0")] ```
8e99f9ac-606e-40e5-bcdd-b12b05d7e4b8
{ "language": "C#" }
```c# using SRPCommon.Interfaces; using SRPCommon.Util; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SRPTests.TestRenderer { // Implementation of IWorkspace that finds test files. class TestWorkspace : IWorkspace { private readonly string _baseDir; private readonly Dictionary<string, string> _files; public TestWorkspace(string baseDir) { _baseDir = baseDir; // Find all files in the TestScripts dir. _files = Directory.EnumerateFiles(_baseDir, "*", SearchOption.AllDirectories) .ToDictionary(path => Path.GetFileName(path)); } public string FindProjectFile(string name) { string path; if (_files.TryGetValue(name, out path)) { return path; } return null; } public string GetAbsolutePath(string path) { if (Path.IsPathRooted(path)) { return path; } return Path.Combine(_baseDir, path); } } } ``` Test filenames are case insensitive too.
```c# using SRPCommon.Interfaces; using SRPCommon.Util; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SRPTests.TestRenderer { // Implementation of IWorkspace that finds test files. class TestWorkspace : IWorkspace { private readonly string _baseDir; private readonly Dictionary<string, string> _files; public TestWorkspace(string baseDir) { _baseDir = baseDir; // Find all files in the TestScripts dir. _files = Directory.EnumerateFiles(_baseDir, "*", SearchOption.AllDirectories) .ToDictionary(path => Path.GetFileName(path), StringComparer.OrdinalIgnoreCase); } public string FindProjectFile(string name) { string path; if (_files.TryGetValue(name, out path)) { return path; } return null; } public string GetAbsolutePath(string path) { if (Path.IsPathRooted(path)) { return path; } return Path.Combine(_baseDir, path); } } } ```
febaeb15-93c4-4d18-9580-13387e5def3b
{ "language": "C#" }
```c# using System.Collections.Generic; using System.IO; using System.Linq; using ICSharpCode.SharpZipLib.Tar; namespace AppHarbor { public static class CompressionExtensions { public static void ToTar(this DirectoryInfo sourceDirectory, Stream output, string[] excludedDirectoryNames) { var archive = TarArchive.CreateOutputTarArchive(output); archive.RootPath = sourceDirectory.FullName.Replace(Path.DirectorySeparatorChar, '/').TrimEnd('/'); var entries = GetFiles(sourceDirectory, excludedDirectoryNames) .Select(x => TarEntry.CreateEntryFromFile(x.FullName)); foreach (var entry in entries) { archive.WriteEntry(entry, true); } archive.Close(); } private static IEnumerable<FileInfo> GetFiles(DirectoryInfo directory, string[] excludedDirectories) { return directory.GetFiles("*", SearchOption.TopDirectoryOnly) .Concat(directory.GetDirectories() .Where(x => excludedDirectories.Contains(x.Name)) .SelectMany(x => GetFiles(x, excludedDirectories))); } } } ``` Fix bug in file selection
```c# using System.Collections.Generic; using System.IO; using System.Linq; using ICSharpCode.SharpZipLib.Tar; namespace AppHarbor { public static class CompressionExtensions { public static void ToTar(this DirectoryInfo sourceDirectory, Stream output, string[] excludedDirectoryNames) { var archive = TarArchive.CreateOutputTarArchive(output); archive.RootPath = sourceDirectory.FullName.Replace(Path.DirectorySeparatorChar, '/').TrimEnd('/'); var entries = GetFiles(sourceDirectory, excludedDirectoryNames) .Select(x => TarEntry.CreateEntryFromFile(x.FullName)); foreach (var entry in entries) { archive.WriteEntry(entry, true); } archive.Close(); } private static IEnumerable<FileInfo> GetFiles(DirectoryInfo directory, string[] excludedDirectories) { return directory.GetFiles("*", SearchOption.TopDirectoryOnly) .Concat(directory.GetDirectories() .Where(x => !excludedDirectories.Contains(x.Name)) .SelectMany(x => GetFiles(x, excludedDirectories))); } } } ```
38c50b34-4ef3-409d-85a7-808a3f8a5b12
{ "language": "C#" }
```c# // dnlib: See LICENSE.txt for more info using System; using System.IO; namespace dnlib.IO { static class DataReaderFactoryFactory { static readonly bool isUnix; static DataReaderFactoryFactory() { // See http://mono-project.com/FAQ:_Technical#Mono_Platforms for platform detection. int p = (int)Environment.OSVersion.Platform; if (p == 4 || p == 6 || p == 128) isUnix = true; } public static DataReaderFactory Create(string fileName, bool mapAsImage) { var creator = CreateDataReaderFactory(fileName, mapAsImage); if (creator is not null) return creator; return ByteArrayDataReaderFactory.Create(File.ReadAllBytes(fileName), fileName); } static DataReaderFactory CreateDataReaderFactory(string fileName, bool mapAsImage) { if (!isUnix) return MemoryMappedDataReaderFactory.CreateWindows(fileName, mapAsImage); else return MemoryMappedDataReaderFactory.CreateUnix(fileName, mapAsImage); } } } ``` Use RuntimeInformation class to check environment.
```c# // dnlib: See LICENSE.txt for more info using System; using System.IO; using System.Runtime.InteropServices; namespace dnlib.IO { static class DataReaderFactoryFactory { static readonly bool isUnix; static DataReaderFactoryFactory() { // See http://mono-project.com/FAQ:_Technical#Mono_Platforms for platform detection. int p = (int)Environment.OSVersion.Platform; if (p == 4 || p == 6 || p == 128) isUnix = true; #if NETSTANDARD if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) isUnix = true; #endif } public static DataReaderFactory Create(string fileName, bool mapAsImage) { var creator = CreateDataReaderFactory(fileName, mapAsImage); if (creator is not null) return creator; return ByteArrayDataReaderFactory.Create(File.ReadAllBytes(fileName), fileName); } static DataReaderFactory CreateDataReaderFactory(string fileName, bool mapAsImage) { if (!isUnix) return MemoryMappedDataReaderFactory.CreateWindows(fileName, mapAsImage); else return MemoryMappedDataReaderFactory.CreateUnix(fileName, mapAsImage); } } } ```
08355e13-0250-44f8-be1c-e997f37f8f8e
{ "language": "C#" }
```c# using System.Web; using System.Web.Routing; namespace ConsolR.Hosting { public static class HttpHandlerExtensions { public static void MapHttpHandler<THandler>(this RouteCollection routes, string url) where THandler : IHttpHandler, new() { routes.MapHttpHandler<THandler>(null, url, null, null); } public static void MapHttpHandler<THandler>(this RouteCollection routes, string name, string url, object defaults, object constraints) where THandler : IHttpHandler, new() { var route = new Route(url, new HttpHandlerRouteHandler<THandler>()); route.Defaults = new RouteValueDictionary(defaults); route.Constraints = new RouteValueDictionary(constraints); routes.Add(name, route); } private class HttpHandlerRouteHandler<THandler> : IRouteHandler where THandler : IHttpHandler, new() { public IHttpHandler GetHttpHandler(RequestContext requestContext) { return new THandler(); } } } } ``` Fix bug in http handler constraints
```c# using System.Web; using System.Web.Routing; namespace ConsolR.Hosting { public static class HttpHandlerExtensions { public static void MapHttpHandler<THandler>(this RouteCollection routes, string url) where THandler : IHttpHandler, new() { routes.MapHttpHandler<THandler>(null, url, null, null); } public static void MapHttpHandler<THandler>(this RouteCollection routes, string name, string url, object defaults, object constraints) where THandler : IHttpHandler, new() { var route = new Route(url, new HttpHandlerRouteHandler<THandler>()); route.Defaults = new RouteValueDictionary(defaults); route.Constraints = new RouteValueDictionary(); route.Constraints.Add(name, constraints); routes.Add(name, route); } private class HttpHandlerRouteHandler<THandler> : IRouteHandler where THandler : IHttpHandler, new() { public IHttpHandler GetHttpHandler(RequestContext requestContext) { return new THandler(); } } } } ```
8a19af7a-5dd9-489a-a2c2-5208172b6b93
{ "language": "C#" }
```c# using System.Collections.Generic; namespace RazorLight.Templating { public class PageLookupResult { public PageLookupResult() { this.Success = false; } public PageLookupResult(PageLookupItem item, IReadOnlyList<PageLookupItem> viewStartEntries) { this.ViewEntry = item; this.ViewStartEntries = viewStartEntries; this.Success = true; } public bool Success { get; } public PageLookupItem ViewEntry { get; } public IReadOnlyList<PageLookupItem> ViewStartEntries { get; } } } ``` Replace default constructor with failed property on PageProvider
```c# using System.Collections.Generic; namespace RazorLight.Templating { public class PageLookupResult { public static PageLookupResult Failed => new PageLookupResult(); private PageLookupResult() { this.Success = false; } public PageLookupResult(PageLookupItem item, IReadOnlyList<PageLookupItem> viewStartEntries) { this.ViewEntry = item; this.ViewStartEntries = viewStartEntries; this.Success = true; } public bool Success { get; } public PageLookupItem ViewEntry { get; } public IReadOnlyList<PageLookupItem> ViewStartEntries { get; } } } ```
d4bbc011-6b68-45a3-819f-56de5ca5411d
{ "language": "C#" }
```c# using System; namespace Microsoft.Build.Logging.StructuredLogger { public class TimedNode : NamedNode { public int Id { get; set; } public int NodeId { get; set; } /// <summary> /// Unique index of the node in the build tree, can be used as a /// "URL" to node /// </summary> public int Index { get; set; } public DateTime StartTime { get; set; } public DateTime EndTime { get; set; } public TimeSpan Duration { get { if (EndTime >= StartTime) { return EndTime - StartTime; } return TimeSpan.Zero; } } public string DurationText => TextUtilities.DisplayDuration(Duration); public override string TypeName => nameof(TimedNode); public string GetTimeAndDurationText(bool fullPrecision = false) { var duration = DurationText; if (string.IsNullOrEmpty(duration)) { duration = "0"; } return $@"Start: {TextUtilities.Display(StartTime, displayDate: true, fullPrecision)} End: {TextUtilities.Display(EndTime, displayDate: true, fullPrecision)} Duration: {duration}"; } public override string ToolTip => GetTimeAndDurationText(); } } ``` Add XML doc comments on Id and NodeId
```c# using System; namespace Microsoft.Build.Logging.StructuredLogger { public class TimedNode : NamedNode { /// <summary> /// The Id of a Project, ProjectEvaluation, Target and Task. /// Corresponds to ProjectStartedEventsArgs.ProjectId, TargetStartedEventArgs.TargetId, etc. /// </summary> public int Id { get; set; } /// <summary> /// Corresponds to BuildEventArgs.BuildEventContext.NodeId, /// which is the id of the MSBuild.exe node process that built the current project or /// executed the given target or task. /// </summary> public int NodeId { get; set; } /// <summary> /// Unique index of the node in the build tree, can be used as a /// "URL" to node /// </summary> public int Index { get; set; } public DateTime StartTime { get; set; } public DateTime EndTime { get; set; } public TimeSpan Duration { get { if (EndTime >= StartTime) { return EndTime - StartTime; } return TimeSpan.Zero; } } public string DurationText => TextUtilities.DisplayDuration(Duration); public override string TypeName => nameof(TimedNode); public string GetTimeAndDurationText(bool fullPrecision = false) { var duration = DurationText; if (string.IsNullOrEmpty(duration)) { duration = "0"; } return $@"Start: {TextUtilities.Display(StartTime, displayDate: true, fullPrecision)} End: {TextUtilities.Display(EndTime, displayDate: true, fullPrecision)} Duration: {duration}"; } public override string ToolTip => GetTimeAndDurationText(); } } ```
a878d9d9-5b9e-49e7-8ace-9b2cf102f499
{ "language": "C#" }
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Configuration; using osu.Framework.Graphics; namespace osu.Game.Overlays.Settings.Sections.Debug { public class GeneralSettings : SettingsSubsection { protected override string Header => "General"; [BackgroundDependencyLoader] private void load(FrameworkDebugConfigManager config, FrameworkConfigManager frameworkConfig) { Children = new Drawable[] { new SettingsCheckbox { LabelText = "Bypass caching", Bindable = config.GetBindable<bool>(DebugSetting.BypassCaching) }, new SettingsCheckbox { LabelText = "Debug logs", Bindable = frameworkConfig.GetBindable<bool>(FrameworkSetting.ShowLogOverlay) } }; } } } ``` Add setting to toggle performance logging
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Configuration; using osu.Framework.Graphics; namespace osu.Game.Overlays.Settings.Sections.Debug { public class GeneralSettings : SettingsSubsection { protected override string Header => "General"; [BackgroundDependencyLoader] private void load(FrameworkDebugConfigManager config, FrameworkConfigManager frameworkConfig) { Children = new Drawable[] { new SettingsCheckbox { LabelText = "Show log overlay", Bindable = frameworkConfig.GetBindable<bool>(FrameworkSetting.ShowLogOverlay) }, new SettingsCheckbox { LabelText = "Performance logging", Bindable = frameworkConfig.GetBindable<bool>(FrameworkSetting.PerformanceLogging) }, new SettingsCheckbox { LabelText = "Bypass caching (slow)", Bindable = config.GetBindable<bool>(DebugSetting.BypassCaching) }, }; } } } ```
cd37bf3c-3106-4c72-9916-09dedc229913
{ "language": "C#" }
```c# #pragma warning disable CS1591 using System; using Newtonsoft.Json; namespace Discord.API { internal class Embed { [JsonProperty("title")] public string Title { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("url")] public string Url { get; set; } [JsonProperty("color")] public uint? Color { get; set; } [JsonProperty("type")] public EmbedType Type { get; set; } [JsonProperty("timestamp")] public DateTimeOffset? Timestamp { get; set; } [JsonProperty("author")] public Optional<EmbedAuthor> Author { get; set; } [JsonProperty("footer")] public Optional<EmbedFooter> Footer { get; set; } [JsonProperty("video")] public Optional<EmbedVideo> Video { get; set; } [JsonProperty("thumbnail")] public Optional<EmbedThumbnail> Thumbnail { get; set; } [JsonProperty("image")] public Optional<EmbedImage> Image { get; set; } [JsonProperty("provider")] public Optional<EmbedProvider> Provider { get; set; } [JsonProperty("fields")] public Optional<EmbedField[]> Fields { get; set; } } } ``` Use StringEnum converter in API model
```c# #pragma warning disable CS1591 using System; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Discord.API { internal class Embed { [JsonProperty("title")] public string Title { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("url")] public string Url { get; set; } [JsonProperty("color")] public uint? Color { get; set; } [JsonProperty("type"), JsonConverter(typeof(StringEnumConverter))] public EmbedType Type { get; set; } [JsonProperty("timestamp")] public DateTimeOffset? Timestamp { get; set; } [JsonProperty("author")] public Optional<EmbedAuthor> Author { get; set; } [JsonProperty("footer")] public Optional<EmbedFooter> Footer { get; set; } [JsonProperty("video")] public Optional<EmbedVideo> Video { get; set; } [JsonProperty("thumbnail")] public Optional<EmbedThumbnail> Thumbnail { get; set; } [JsonProperty("image")] public Optional<EmbedImage> Image { get; set; } [JsonProperty("provider")] public Optional<EmbedProvider> Provider { get; set; } [JsonProperty("fields")] public Optional<EmbedField[]> Fields { get; set; } } } ```
f6a52a02-c351-4e6a-b815-057a4f429390
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.Framework.DependencyInjection; using Microsoft.AspNet.FileProviders; using Microsoft.Dnx.Runtime; using MakingSense.AspNet.Documentation; namespace MakingSense.AspNet.HypermediaApi.Seed { public class Startup { // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { } public void Configure(IApplicationBuilder app, IApplicationEnvironment appEnv) { app.UseStaticFiles(); UseDocumentation(app, appEnv); app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); } private static void UseDocumentation(IApplicationBuilder app, IApplicationEnvironment appEnv) { var documentationFilesProvider = new PhysicalFileProvider(appEnv.ApplicationBasePath); app.UseDocumentation(new DocumentationOptions() { DefaultFileName = "index", RequestPath = "/docs", NotFoundHtmlFile = documentationFilesProvider.GetFileInfo("DocumentationTemplates\\NotFound.html"), LayoutFile = documentationFilesProvider.GetFileInfo("DocumentationTemplates\\Layout.html") }); } } } ``` Add NotFound and ErrorHandling middlewares
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.Framework.DependencyInjection; using Microsoft.AspNet.FileProviders; using Microsoft.Dnx.Runtime; using MakingSense.AspNet.Documentation; using MakingSense.AspNet.HypermediaApi.Formatters; using MakingSense.AspNet.HypermediaApi.ValidationFilters; namespace MakingSense.AspNet.HypermediaApi.Seed { public class Startup { // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.OutputFormatters.Clear(); options.OutputFormatters.Add(new HypermediaApiJsonOutputFormatter()); options.InputFormatters.Clear(); options.InputFormatters.Add(new HypermediaApiJsonInputFormatter()); options.Filters.Add(new PayloadValidationFilter()); options.Filters.Add(new RequiredPayloadFilter()); }); } public void Configure(IApplicationBuilder app, IApplicationEnvironment appEnv) { app.UseApiErrorHandler(); app.UseMvc(); app.UseStaticFiles(); UseDocumentation(app, appEnv); app.UseNotFoundHandler(); } private static void UseDocumentation(IApplicationBuilder app, IApplicationEnvironment appEnv) { var documentationFilesProvider = new PhysicalFileProvider(appEnv.ApplicationBasePath); app.UseDocumentation(new DocumentationOptions() { DefaultFileName = "index", RequestPath = "/docs", NotFoundHtmlFile = documentationFilesProvider.GetFileInfo("DocumentationTemplates\\NotFound.html"), LayoutFile = documentationFilesProvider.GetFileInfo("DocumentationTemplates\\Layout.html") }); } } } ```
e521da76-7d44-458f-a847-dd65b888f835
{ "language": "C#" }
```c# using CupCake.Core.Log; using CupCake.Messages.Receive; using CupCake.Players; namespace CupCake.Server.Muffins { public class LogMuffin : CupCakeMuffin { protected override void Enable() { this.Events.Bind<SayPlayerEvent>(this.OnSay); this.Events.Bind<WriteReceiveEvent>(this.OnWrite); this.Events.Bind<InfoReceiveEvent>(this.OnInfo); this.Events.Bind<UpgradeReceiveEvent>(this.OnUpgrade); } private void OnUpgrade(object sender, UpgradeReceiveEvent e) { this.Logger.Log(LogPriority.Message, "The game has been updated."); } private void OnInfo(object sender, InfoReceiveEvent e) { this.Logger.LogPlatform.Log(e.Title, LogPriority.Message, e.Text); } private void OnWrite(object sender, WriteReceiveEvent e) { this.Logger.LogPlatform.Log(e.Title, LogPriority.Message, e.Text); } private void OnSay(object sender, SayPlayerEvent e) { this.Logger.LogPlatform.Log(e.Player.Username, LogPriority.Message, e.Player.Say); } } }``` Make info messages look better
```c# using CupCake.Core.Log; using CupCake.Messages.Receive; using CupCake.Players; namespace CupCake.Server.Muffins { public class LogMuffin : CupCakeMuffin { protected override void Enable() { this.Events.Bind<SayPlayerEvent>(this.OnSay); this.Events.Bind<WriteReceiveEvent>(this.OnWrite); this.Events.Bind<InfoReceiveEvent>(this.OnInfo); this.Events.Bind<UpgradeReceiveEvent>(this.OnUpgrade); } private void OnUpgrade(object sender, UpgradeReceiveEvent e) { this.Logger.Log(LogPriority.Message, "The game has been updated."); } private void OnInfo(object sender, InfoReceiveEvent e) { this.Logger.Log(LogPriority.Message, e.Title); this.Logger.Log(LogPriority.Message, e.Text); } private void OnWrite(object sender, WriteReceiveEvent e) { this.Logger.LogPlatform.Log(e.Title, LogPriority.Message, e.Text); } private void OnSay(object sender, SayPlayerEvent e) { this.Logger.LogPlatform.Log(e.Player.Username, LogPriority.Message, e.Player.Say); } } }```
0832b508-ebab-4997-98e7-7a4aa5b09945
{ "language": "C#" }
```c# using UnityEngine; using System.Collections.Generic; using System; [RequireComponent(typeof(RoomGenerator))] public class MainRoomSelector : MonoBehaviour { public float aboveMeanWidthFactor = 1.25f; public float aboveMeanLengthFactor = 1.25f; [HideInInspector] public List<Room> mainRooms; [HideInInspector] public List<Room> sideRooms; Room[] _rooms; public void Run() { var generator = this.GetComponent<RoomGenerator> (); _rooms = generator.generatedRooms; float meanWidth = 0f; float meanLength = 0f; foreach (var room in _rooms) { meanWidth += room.width; meanLength += room.length; } meanWidth /= _rooms.Length; meanLength /= _rooms.Length; foreach (var room in _rooms) { if (room.width >= meanWidth * aboveMeanWidthFactor && room.length >= meanLength * aboveMeanLengthFactor) { mainRooms.Add (room); room.isMainRoom = true; } else { sideRooms.Add (room); room.isMainRoom = false; } } } } ``` Reset list of main and side rooms on every selection
```c# using UnityEngine; using System.Collections.Generic; using System; [RequireComponent(typeof(RoomGenerator))] public class MainRoomSelector : MonoBehaviour { public float aboveMeanWidthFactor = 1.25f; public float aboveMeanLengthFactor = 1.25f; [HideInInspector] public List<Room> mainRooms; [HideInInspector] public List<Room> sideRooms; Room[] _rooms; public void Run() { mainRooms = new List<Room>(); sideRooms = new List<Room>(); var generator = this.GetComponent<RoomGenerator> (); _rooms = generator.generatedRooms; float meanWidth = 0f; float meanLength = 0f; foreach (var room in _rooms) { meanWidth += room.width; meanLength += room.length; } meanWidth /= _rooms.Length; meanLength /= _rooms.Length; foreach (var room in _rooms) { if (room.width >= meanWidth * aboveMeanWidthFactor && room.length >= meanLength * aboveMeanLengthFactor) { mainRooms.Add (room); room.isMainRoom = true; } else { sideRooms.Add (room); room.isMainRoom = false; } } } } ```
9a4b3c06-f67c-48ba-9075-dd6c7d3b4e2d
{ "language": "C#" }
```c# using System.Collections.Generic; namespace Mollie.Api.Models.Order { public class OrderRefundRequest { /// <summary> /// An array of objects containing the order line details you want to create a refund for. If you send /// an empty array, the entire order will be refunded. /// </summary> public IEnumerable<OrderLineRequest> Lines { get; set; } /// <summary> /// The description of the refund you are creating. This will be shown to the consumer on their card or /// bank statement when possible. Max. 140 characters. /// </summary> public string Description { get; set; } } } ``` Fix for Order Lines in Order Refund
```c# using System.Collections.Generic; namespace Mollie.Api.Models.Order { public class OrderRefundRequest { /// <summary> /// An array of objects containing the order line details you want to create a refund for. If you send /// an empty array, the entire order will be refunded. /// </summary> public IEnumerable<OrderLineDetails> Lines { get; set; } /// <summary> /// The description of the refund you are creating. This will be shown to the consumer on their card or /// bank statement when possible. Max. 140 characters. /// </summary> public string Description { get; set; } } } ```
c621e421-b84b-4c4a-bfc9-7f78f5571f44
{ "language": "C#" }
```c# namespace TraktApiSharp.Example.UWP { using Services.SettingsServices; using System.Threading.Tasks; using Template10.Controls; using Windows.ApplicationModel.Activation; using Windows.UI.Xaml; using Windows.UI.Xaml.Data; [Bindable] sealed partial class App : Template10.Common.BootStrapper { public App() { InitializeComponent(); SplashFactory = (e) => new Views.Splash(e); var settings = SettingsService.Instance; RequestedTheme = settings.AppTheme; CacheMaxDuration = settings.CacheMaxDuration; ShowShellBackButton = settings.UseShellBackButton; } public override async Task OnInitializeAsync(IActivatedEventArgs args) { if (Window.Current.Content as ModalDialog == null) { // create a new frame var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include); // create modal root Window.Current.Content = new ModalDialog { DisableBackButtonWhenModal = true, Content = new Views.Shell(nav), ModalContent = new Views.Busy(), }; } await Task.CompletedTask; } public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { NavigationService.Navigate(typeof(Views.MainPage)); await Task.CompletedTask; } } } ``` Save authorization information, when app is suspended.
```c# namespace TraktApiSharp.Example.UWP { using Services.SettingsServices; using Services.TraktService; using System.Threading.Tasks; using Template10.Controls; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.UI.Xaml; using Windows.UI.Xaml.Data; [Bindable] sealed partial class App : Template10.Common.BootStrapper { public App() { InitializeComponent(); SplashFactory = (e) => new Views.Splash(e); var settings = SettingsService.Instance; RequestedTheme = settings.AppTheme; CacheMaxDuration = settings.CacheMaxDuration; ShowShellBackButton = settings.UseShellBackButton; } public override async Task OnInitializeAsync(IActivatedEventArgs args) { if (Window.Current.Content as ModalDialog == null) { // create a new frame var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include); // create modal root Window.Current.Content = new ModalDialog { DisableBackButtonWhenModal = true, Content = new Views.Shell(nav), ModalContent = new Views.Busy(), }; } await Task.CompletedTask; } public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { NavigationService.Navigate(typeof(Views.MainPage)); await Task.CompletedTask; } public override async Task OnSuspendingAsync(object s, SuspendingEventArgs e, bool prelaunchActivated) { var authorization = TraktServiceProvider.Instance.Client.Authorization; SettingsService.Instance.TraktClientAuthorization = authorization; await Task.CompletedTask; } } } ```
424a262f-d1ce-4742-9019-1577fef06acc
{ "language": "C#" }
```c# // Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System.Collections.Specialized; namespace CefSharp { public interface IRequest { string Url { get; set; } string Method { get; } string Body { get; } NameValueCollection Headers { get; set; } TransitionType TransitionType { get; } } } ``` Add xml comment to TransitionType
```c# // Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System.Collections.Specialized; namespace CefSharp { public interface IRequest { string Url { get; set; } string Method { get; } string Body { get; } NameValueCollection Headers { get; set; } /// <summary> /// Get the transition type for this request. /// Applies to requests that represent a main frame or sub-frame navigation. /// </summary> TransitionType TransitionType { get; } } } ```
7acdefdd-1997-4777-8bc0-6414b005dc5d
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using live.asp.net.Data; using live.asp.net.Services; using live.asp.net.ViewModels; using Microsoft.AspNet.Authorization; using Microsoft.AspNet.Mvc; using Microsoft.Data.Entity; namespace live.asp.net.Controllers { public class HomeController : Controller { private readonly AppDbContext _db; private readonly IShowsService _showsService; public HomeController(IShowsService showsService, AppDbContext dbContext) { _showsService = showsService; _db = dbContext; } [Route("/")] public async Task<IActionResult> Index(bool? disableCache, bool? useDesignData) { var liveShowDetails = await _db.LiveShowDetails.FirstOrDefaultAsync(); var showList = await _showsService.GetRecordedShowsAsync(User, disableCache ?? false, useDesignData ?? false); return View(new HomeViewModel { AdminMessage = liveShowDetails?.AdminMessage, NextShowDate = liveShowDetails?.NextShowDate, LiveShowEmbedUrl = liveShowDetails?.LiveShowEmbedUrl, PreviousShows = showList.Shows, MoreShowsUrl = showList.MoreShowsUrl }); } [HttpGet("error")] public IActionResult Error() { return View(); } } } ``` Fix home page next show time
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using live.asp.net.Data; using live.asp.net.Services; using live.asp.net.ViewModels; using Microsoft.AspNet.Authorization; using Microsoft.AspNet.Mvc; using Microsoft.Data.Entity; namespace live.asp.net.Controllers { public class HomeController : Controller { private readonly AppDbContext _db; private readonly IShowsService _showsService; public HomeController(IShowsService showsService, AppDbContext dbContext) { _showsService = showsService; _db = dbContext; } [Route("/")] public async Task<IActionResult> Index(bool? disableCache, bool? useDesignData) { var liveShowDetails = await _db.LiveShowDetails.FirstOrDefaultAsync(); var showList = await _showsService.GetRecordedShowsAsync(User, disableCache ?? false, useDesignData ?? false); DateTimeOffset? nextShowDateOffset = null; if (liveShowDetails != null) { nextShowDateOffset= TimeZoneInfo.ConvertTimeBySystemTimeZoneId(liveShowDetails.NextShowDate.Value, "Pacific Standard Time"); } return View(new HomeViewModel { AdminMessage = liveShowDetails?.AdminMessage, NextShowDate = nextShowDateOffset, LiveShowEmbedUrl = liveShowDetails?.LiveShowEmbedUrl, PreviousShows = showList.Shows, MoreShowsUrl = showList.MoreShowsUrl }); } [HttpGet("error")] public IActionResult Error() { return View(); } } } ```
3be54806-f01b-480a-8e37-e2812f15b95a
{ "language": "C#" }
```c# using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace T4TS.Tests { [TestClass] public class MemberOutputAppenderTests { [TestMethod] public void MemberOutputAppenderRespectsCompatibilityVersion() { var sb = new StringBuilder(); var member = new TypeScriptInterfaceMember { Name = "Foo", //FullName = "Foo", Type = new BoolType() }; var settings = new Settings(); var appender = new MemberOutputAppender(sb, 0, settings); settings.CompatibilityVersion = new Version(0, 8, 3); appender.AppendOutput(member); Assert.IsTrue(sb.ToString().Contains("bool")); Assert.IsFalse(sb.ToString().Contains("boolean")); sb.Clear(); settings.CompatibilityVersion = new Version(0, 9, 0); appender.AppendOutput(member); Assert.IsTrue(sb.ToString().Contains("boolean")); sb.Clear(); settings.CompatibilityVersion = null; appender.AppendOutput(member); Assert.IsTrue(sb.ToString().Contains("boolean")); } } } ``` Split MemberOutputTests to separate asserts
```c# using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace T4TS.Tests { [TestClass] public class MemberOutputAppenderTests { [TestMethod] public void TypescriptVersion083YieldsBool() { var sb = new StringBuilder(); var member = new TypeScriptInterfaceMember { Name = "Foo", Type = new BoolType() }; var appender = new MemberOutputAppender(sb, 0, new Settings { CompatibilityVersion = new Version(0, 8, 3) }); appender.AppendOutput(member); Assert.AreEqual("Foo: bool;", sb.ToString().Trim()); } [TestMethod] public void TypescriptVersion090YieldsBoolean() { var sb = new StringBuilder(); var member = new TypeScriptInterfaceMember { Name = "Foo", Type = new BoolType() }; var appender = new MemberOutputAppender(sb, 0, new Settings { CompatibilityVersion = new Version(0, 9, 0) }); appender.AppendOutput(member); Assert.AreEqual("Foo: boolean;", sb.ToString().Trim()); } [TestMethod] public void DefaultTypescriptVersionYieldsBoolean() { var sb = new StringBuilder(); var member = new TypeScriptInterfaceMember { Name = "Foo", Type = new BoolType() }; var appender = new MemberOutputAppender(sb, 0, new Settings { CompatibilityVersion = null }); appender.AppendOutput(member); Assert.AreEqual("Foo: boolean;", sb.ToString().Trim()); } } } ```
b376d506-2a51-4d0d-92e7-fb043effe066
{ "language": "C#" }
```c# namespace TestMoya.Runner.Runners { using System; using System.Reflection; using System.Threading; using Moq; using Moya.Models; using Moya.Runner.Runners; using Xunit; public class TimerDecoratorTests { private readonly Mock<ITestRunner> testRunnerMock; private readonly TimerDecorator timerDecorator; public TimerDecoratorTests() { testRunnerMock = new Mock<ITestRunner>(); timerDecorator = new TimerDecorator(testRunnerMock.Object); } [Fact] public void TimerDecoratorExecuteRunsMethod() { bool methodRun = false; MethodInfo method = ((Action)(() => methodRun = true)).Method; testRunnerMock .Setup(x => x.Execute(method)) .Callback(() => methodRun = true) .Returns(new TestResult()); timerDecorator.Execute(method); Assert.True(methodRun); } [Fact] public void TimerDecoratorExecuteAddsDurationToResult() { bool methodRun = false; MethodInfo method = ((Action)(() => Thread.Sleep(1))).Method; testRunnerMock .Setup(x => x.Execute(method)) .Callback(() => methodRun = true) .Returns(new TestResult()); var result = timerDecorator.Execute(method); Assert.True(result.Duration > 0); } } }``` Update timerdecorator test to prevent failed test
```c# namespace TestMoya.Runner.Runners { using System; using System.Reflection; using Moq; using Moya.Attributes; using Moya.Models; using Moya.Runner.Runners; using Xunit; public class TimerDecoratorTests { private readonly Mock<ITestRunner> testRunnerMock; private TimerDecorator timerDecorator; public TimerDecoratorTests() { testRunnerMock = new Mock<ITestRunner>(); } [Fact] public void TimerDecoratorExecuteRunsMethod() { timerDecorator = new TimerDecorator(testRunnerMock.Object); bool methodRun = false; MethodInfo method = ((Action)(() => methodRun = true)).Method; testRunnerMock .Setup(x => x.Execute(method)) .Callback(() => methodRun = true) .Returns(new TestResult()); timerDecorator.Execute(method); Assert.True(methodRun); } [Fact] public void TimerDecoratorExecuteAddsDurationToResult() { MethodInfo method = ((Action)TestClass.MethodWithMoyaAttribute).Method; timerDecorator = new TimerDecorator(new StressTestRunner()); var result = timerDecorator.Execute(method); Assert.True(result.Duration > 0); } public class TestClass { [Stress] public static void MethodWithMoyaAttribute() { } } } }```
60f6ba81-5b48-4c0d-a97e-a38fe4afda22
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using CupCake.Protocol; namespace CupCake.Client.Settings { public class Settings { public Settings() : this(false) { } public Settings(bool isNew) { this.Accounts = new List<Account>(); this.Profiles = new List<Profile>(); this.RecentWorlds = new List<RecentWorld>(); this.Databases = new List<Database>(); if (isNew) { this.Profiles.Add(new Profile { Id = SettingsManager.DefaultId, Name = SettingsManager.DefaultString, Folder = SettingsManager.ProfilesPath }); this.Databases.Add(new Database { Id = SettingsManager.DefaultId, Name = SettingsManager.DefaultString, Type = DatabaseType.SQLite, ConnectionString = String.Format(Database.SQLiteFormat, SettingsManager.DefaultDatabasePath) }); } } public List<Account> Accounts { get; set; } public List<Profile> Profiles { get; set; } public List<RecentWorld> RecentWorlds { get; set; } public List<Database> Databases { get; set; } public int LastProfileId { get; set; } public int LastAccountId { get; set; } public int LastRecentWorldId { get; set; } public int LastDatabaseId { get; set; } public string LastAttachAddress { get; set; } public string LastAttachPin { get; set; } } }``` Fix default database is not set properly the first time
```c# using System; using System.Collections.Generic; using CupCake.Protocol; namespace CupCake.Client.Settings { public class Settings { public Settings() : this(false) { } public Settings(bool isNew) { this.Accounts = new List<Account>(); this.Profiles = new List<Profile>(); this.RecentWorlds = new List<RecentWorld>(); this.Databases = new List<Database>(); if (isNew) { this.Profiles.Add(new Profile { Id = SettingsManager.DefaultId, Name = SettingsManager.DefaultString, Folder = SettingsManager.ProfilesPath, Database = SettingsManager.DefaultId }); this.Databases.Add(new Database { Id = SettingsManager.DefaultId, Name = SettingsManager.DefaultString, Type = DatabaseType.SQLite, ConnectionString = String.Format(Database.SQLiteFormat, SettingsManager.DefaultDatabasePath) }); } } public List<Account> Accounts { get; set; } public List<Profile> Profiles { get; set; } public List<RecentWorld> RecentWorlds { get; set; } public List<Database> Databases { get; set; } public int LastProfileId { get; set; } public int LastAccountId { get; set; } public int LastRecentWorldId { get; set; } public int LastDatabaseId { get; set; } public string LastAttachAddress { get; set; } public string LastAttachPin { get; set; } } }```
436c8b76-3662-4d09-9c1c-a64d7e32f6e6
{ "language": "C#" }
```c# 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("DNSAgent")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DNSAgent")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8424ad23-98aa-4697-a9e7-cb6d5b450c6c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.*")] [assembly: AssemblyFileVersion("1.0.0.0")]``` Change version number to 1.0.
```c# 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("DNSAgent")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DNSAgent")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8424ad23-98aa-4697-a9e7-cb6d5b450c6c")] // 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.*")] [assembly: AssemblyFileVersion("1.0.0.0")]```
e2919fa4-ce4d-43f7-9e68-924c228ac82f
{ "language": "C#" }
```c# // 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.Framework.Graphics.Containers; using osu.Framework.Platform; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Overlays.Dashboard.Home.News { public class NewsTitleLink : OsuHoverContainer { private readonly APINewsPost post; public NewsTitleLink(APINewsPost post) { this.post = post; RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; } [BackgroundDependencyLoader] private void load(GameHost host) { Child = new TextFlowContainer(t => { t.Font = OsuFont.GetFont(weight: FontWeight.Bold); }) { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Text = post.Title }; TooltipText = "view in browser"; Action = () => host.OpenUrlExternally("https://osu.ppy.sh/home/news/" + post.Slug); } } } ``` Change hover colour for news title
```c# // 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.Framework.Graphics.Containers; using osu.Framework.Platform; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Overlays.Dashboard.Home.News { public class NewsTitleLink : OsuHoverContainer { private readonly APINewsPost post; public NewsTitleLink(APINewsPost post) { this.post = post; RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; } [BackgroundDependencyLoader] private void load(GameHost host, OverlayColourProvider colourProvider) { Child = new TextFlowContainer(t => { t.Font = OsuFont.GetFont(weight: FontWeight.Bold); }) { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Text = post.Title }; HoverColour = colourProvider.Light1; TooltipText = "view in browser"; Action = () => host.OpenUrlExternally("https://osu.ppy.sh/home/news/" + post.Slug); } } } ```
56baac4a-d5a4-4c55-9831-1703284785e9
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CK.Glouton.Lucene; using Microsoft.AspNetCore.Mvc; namespace CK.Glouton.Web.Controllers { [Route("api/stats")] public class StatisticsController : Controller { LuceneStatistics luceneStatistics; public StatisticsController() { } } }``` Add api point to controller.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CK.Glouton.Lucene; using CK.Glouton.Model.Lucene; using Microsoft.AspNetCore.Mvc; namespace CK.Glouton.Web.Controllers { [Route("api/stats")] public class StatisticsController : Controller { private readonly ILuceneStatisticsService _luceneStatistics; public StatisticsController(ILuceneStatisticsService luceneStatistics) { _luceneStatistics = luceneStatistics; } [HttpGet("logperappname")] public Dictionary<string, int> LogPerAppName() { return _luceneStatistics.GetLogByAppName(); } [HttpGet("exceptionperappname")] public Dictionary<string, int> ExceptionPerAppName() { return _luceneStatistics.GetExceptionByAppName(); } [HttpGet("Log")] public int AllLogCount() => _luceneStatistics.AllLogCount(); [HttpGet("AppName")] public int AppNameCount() => _luceneStatistics.AppNameCount; [HttpGet("Exception")] public int AllException() => _luceneStatistics.AllExceptionCount; [HttpGet("AppNames")] public IEnumerable<string> AppNames() => _luceneStatistics.GetAppNames; } }```
c95c6e09-fd4f-4d2d-b076-11d0960ee2c2
{ "language": "C#" }
```c# using NSubstitute; using Ploeh.AutoFixture.Xunit; using TeamCityApi.Domain; using TeamCityConsole.Tests.Helpers; using TeamCityConsole.Utils; using Xunit.Extensions; namespace TeamCityConsole.Tests.Utils { public class FileDownloaderTests { [Theory] [AutoNSubstituteData] public void Should_unzip_when_double_star_used([Frozen]IFileSystem fileSystem, FileDownloader downloader) { var file = new File() { Name = "web.zip!**", ContentHref = ""}; string tempFile = @"c:\temp\abc.tmp"; fileSystem.CreateTempFile().Returns(tempFile); downloader.Download(@"c:\temp", file).Wait(); fileSystem.Received().ExtractToDirectory(tempFile, @"c:\temp"); } [Theory] [AutoNSubstituteData] public void Should_delete_target_directory_when_unziping([Frozen]IFileSystem fileSystem, FileDownloader downloader) { var file = new File() { Name = "web.zip!**", ContentHref = "" }; var destPath = @"c:\temp"; fileSystem.DirectoryExists(destPath).Returns(true); downloader.Download(destPath, file).Wait(); fileSystem.Received().DeleteDirectory(destPath, true); } } }``` Remove invalid test as the directory should not be deleted since multiple artifacts / dependencies maybe be unzipping into a folder or a child folder.
```c# using NSubstitute; using Ploeh.AutoFixture.Xunit; using TeamCityApi.Domain; using TeamCityConsole.Tests.Helpers; using TeamCityConsole.Utils; using Xunit.Extensions; namespace TeamCityConsole.Tests.Utils { public class FileDownloaderTests { [Theory] [AutoNSubstituteData] public void Should_unzip_when_double_star_used([Frozen]IFileSystem fileSystem, FileDownloader downloader) { var file = new File() { Name = "web.zip!**", ContentHref = ""}; string tempFile = @"c:\temp\abc.tmp"; fileSystem.CreateTempFile().Returns(tempFile); downloader.Download(@"c:\temp", file).Wait(); fileSystem.Received().ExtractToDirectory(tempFile, @"c:\temp"); } } }```
64903b2c-e6da-49d2-b941-2d77176f8a8b
{ "language": "C#" }
```c# using System.ComponentModel; using DesktopWidgets.Classes; namespace DesktopWidgets.Widgets.Search { public class Settings : WidgetSettingsBase { public Settings() { Width = 150; } [Category("General")] [DisplayName("Base URL")] public string BaseUrl { get; set; } [Category("General")] [DisplayName("URL Suffix")] public string URLSuffix { get; set; } } }``` Change "Search" widget "Base URL" default value
```c# using System.ComponentModel; using DesktopWidgets.Classes; namespace DesktopWidgets.Widgets.Search { public class Settings : WidgetSettingsBase { public Settings() { Width = 150; } [Category("General")] [DisplayName("URL Prefix")] public string BaseUrl { get; set; } = "http://"; [Category("General")] [DisplayName("URL Suffix")] public string URLSuffix { get; set; } } }```
1ac1ec53-747e-42f6-9df9-deaaa2bdc8c5
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; public class TriggerSound : MonoBehaviour { public string tagName1=""; public string tagName2 = ""; public AudioClip triggerSound; public float soundVolume = 1.0f; private AudioSource triggerAudioSource; void Awake() { InitSound(out triggerAudioSource, triggerSound, soundVolume, false); } void InitSound(out AudioSource myAudioSource, AudioClip myClip, float myVolume, bool looping) { myAudioSource = gameObject.AddComponent("AudioSource") as AudioSource; myAudioSource.playOnAwake = false; myAudioSource.clip = myClip; myAudioSource.loop = looping; myAudioSource.volume = myVolume; //myAudioSource.rolloffMode = AudioRolloffMode.Linear; } void OnTriggerEnter(Collider other) { //if (other.gameObject.tag == tagName1 || other.gameObject.tag == tagName2) //2013-08-02 if (other.gameObject.CompareTag(tagName1) || other.gameObject.CompareTag(tagName2)) //2013-08-02 { if (other.gameObject.layer != 2) //2011-12-27 triggerAudioSource.Play(); } } } ``` Update shadows. Update results screen. Update throttling speed modifier within safe range.
```c# using UnityEngine; using System.Collections; public class TriggerSound : MonoBehaviour { public string tagName1 = ""; public string tagName2 = ""; public AudioClip triggerSound; public float soundVolume = 1.0f; private AudioSource triggerAudioSource; void Awake() { InitSound(out triggerAudioSource, triggerSound, soundVolume, false); } void InitSound(out AudioSource audioSource, AudioClip clip, float volume, bool looping) { audioSource = gameObject.AddComponent("AudioSource") as AudioSource; audioSource.playOnAwake = false; audioSource.clip = clip; audioSource.loop = looping; audioSource.volume = (float)GameProfiles.Current.GetAudioEffectsVolume(); //myAudioSource.rolloffMode = AudioRolloffMode.Linear; } void OnTriggerEnter(Collider other) { //if (other.gameObject.tag == tagName1 || other.gameObject.tag == tagName2) //2013-08-02 if (other.gameObject.CompareTag(tagName1) || other.gameObject.CompareTag(tagName2)) { //2013-08-02 if (other.gameObject.layer != 2) //2011-12-27 triggerAudioSource.Play(); } } } ```
df0e4a09-f9e3-4a9c-b26a-599c723b870d
{ "language": "C#" }
```c# // Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/ using System.Management.Automation.Host; using System.Xml.Schema; using Pash.Implementation; namespace System.Management.Automation.Internal { public abstract class InternalCommand { internal CommandInfo CommandInfo { get; set; } internal PSHost PSHostInternal { get; private set; } internal PSObject CurrentPipelineObject { get; set; } internal SessionState State { get; private set; } internal ICommandRuntime CommandRuntime { get; set; } private ExecutionContext _executionContext; internal ExecutionContext ExecutionContext { get { return _executionContext; } set { _executionContext = value; State = new SessionState(_executionContext.SessionState.SessionStateGlobal); PSHostInternal = _executionContext.LocalHost; } } internal bool IsStopping { get { return ((PipelineCommandRuntime)CommandRuntime).IsStopping; } } internal InternalCommand() { } internal virtual void DoBeginProcessing() { } internal virtual void DoEndProcessing() { } internal virtual void DoProcessRecord() { } internal virtual void DoStopProcessing() { } internal void ThrowIfStopping() { } } } ``` Allow the CommandRuntime to be set for a cmdlet.
```c# // Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/ using System.Management.Automation.Host; using System.Xml.Schema; using Pash.Implementation; namespace System.Management.Automation.Internal { public abstract class InternalCommand { internal CommandInfo CommandInfo { get; set; } internal PSHost PSHostInternal { get; private set; } internal PSObject CurrentPipelineObject { get; set; } internal SessionState State { get; private set; } public ICommandRuntime CommandRuntime { get; set; } private ExecutionContext _executionContext; internal ExecutionContext ExecutionContext { get { return _executionContext; } set { _executionContext = value; State = new SessionState(_executionContext.SessionState.SessionStateGlobal); PSHostInternal = _executionContext.LocalHost; } } internal bool IsStopping { get { return ((PipelineCommandRuntime)CommandRuntime).IsStopping; } } internal InternalCommand() { } internal virtual void DoBeginProcessing() { } internal virtual void DoEndProcessing() { } internal virtual void DoProcessRecord() { } internal virtual void DoStopProcessing() { } internal void ThrowIfStopping() { } } } ```
72573ea0-09bd-4207-949d-b4b28de0916a
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using RepoZ.Api.IO; namespace RepoZ.Api.Mac { public class MacPathActionProvider : IPathActionProvider { public IEnumerable<PathAction> GetFor(string path) { yield return createPathAction("Open", "nil"); } private PathAction createPathAction(string name, string command) { return new PathAction() { Name = name, Action = (sender, args) => sender = null }; } private PathAction createDefaultPathAction(string name, string command) { var action = createPathAction(name, command); action.IsDefault = true; return action; } } } ``` Add default path action provider for Mac
```c# using System.Diagnostics; using System.Collections.Generic; using RepoZ.Api.IO; namespace RepoZ.Api.Mac { public class MacPathActionProvider : IPathActionProvider { public IEnumerable<PathAction> GetFor(string path) { yield return createDefaultPathAction("Open in Finder", path); } private PathAction createPathAction(string name, string command) { return new PathAction() { Name = name, Action = (sender, args) => startProcess(command) }; } private PathAction createDefaultPathAction(string name, string command) { var action = createPathAction(name, command); action.IsDefault = true; return action; } private void startProcess(string command) { Process.Start(command); } } } ```
16bdafb6-674d-4728-b66b-83c56c0065ff
{ "language": "C#" }
```c# namespace Nancy.AttributeRouting { using System; using System.Reflection; /// <summary> /// The View attribute indicates the view path to render from request. /// </summary> /// <example> /// The following code will render <c>View/index.html</c> with routing instance. /// <code> /// View('View/index.html') /// </code> /// </example> [AttributeUsage(AttributeTargets.Method)] public class ViewAttribute : Attribute { private readonly string path; /// <summary> /// Initializes a new instance of the <see cref="ViewAttribute"/> class. /// </summary> /// <param name="path">The view path for rendering.</param> public ViewAttribute(string path) { this.path = path.Trim('/'); } internal static string GetPath(MethodBase method) { var attr = method.GetCustomAttribute<ViewAttribute>(false); if (attr == null) { return string.Empty; } string prefix = ViewPrefixAttribute.GetPrefix(method.DeclaringType); string path = string.Format("{0}/{1}", prefix, attr.path); return path; } } } ``` Fix the failing test case.
```c# namespace Nancy.AttributeRouting { using System; using System.Reflection; /// <summary> /// The View attribute indicates the view path to render from request. /// </summary> /// <example> /// The following code will render <c>View/index.html</c> with routing instance. /// <code> /// View('View/index.html') /// </code> /// </example> [AttributeUsage(AttributeTargets.Method)] public class ViewAttribute : Attribute { private readonly string path; /// <summary> /// Initializes a new instance of the <see cref="ViewAttribute"/> class. /// </summary> /// <param name="path">The view path for rendering.</param> public ViewAttribute(string path) { this.path = path.Trim('/'); } internal static string GetPath(MethodBase method) { var attr = method.GetCustomAttribute<ViewAttribute>(false); if (attr == null) { return string.Empty; } string prefix = ViewPrefixAttribute.GetPrefix(method.DeclaringType); string path = string.Format("{0}/{1}", prefix, attr.path).Trim('/'); return path; } } } ```
7e6e048b-b52d-44c4-bc76-bd77936f8f03
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using WindowsInput; namespace TargetClicker { /// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void clickButtonClick(object sender, RoutedEventArgs e) { var sim = new InputSimulator(); sim.Mouse.MoveMouseTo(0, 0); sim.Mouse.RightButtonClick(); } } } ``` Add right click by a short cut key comination
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using WindowsInput; using NHotkey; using NHotkey.Wpf; namespace TargetClicker { /// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); HotkeyManager.Current.AddOrReplace("clickTarget", Key.D1 , ModifierKeys.Control | ModifierKeys.Alt, clickTarget); } private void clickButtonClick(object sender, RoutedEventArgs e) { var sim = new InputSimulator(); sim.Mouse.MoveMouseTo(0, 0); sim.Mouse.RightButtonClick(); } private void clickTarget(object sender, HotkeyEventArgs e) { var sim = new InputSimulator(); sim.Mouse.MoveMouseTo(0, 0); sim.Mouse.RightButtonClick(); } } } ```
051cfe61-7495-4c4a-b6fd-50c1f4cdab93
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using AgateLib; namespace Tests { class Launcher { [STAThread] public static void Main(string[] args) { AgateFileProvider.Assemblies.AddPath("../Drivers"); AgateFileProvider.Images.AddPath("Data"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmLauncher()); } } } ``` Fix test launcher to not use Drivers directory.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using AgateLib; namespace Tests { class Launcher { [STAThread] public static void Main(string[] args) { AgateFileProvider.Images.AddPath("Data"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmLauncher()); } } } ```
5c8b43c3-5c73-46bc-bd00-4eed54268b22
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace Schedutalk.Logic { class HttpRequestor { public async Task<string> getHttpRequestAsString(Func<string, HttpRequestMessage> requestTask, string input) { HttpClient httpClient = new HttpClient(); HttpRequestMessage request = requestTask(input); var response = httpClient.SendAsync(request); var result = await response.Result.Content.ReadAsStringAsync(); return result; } } } ``` Implement utlity for requesting JSON as string
```c# using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace Schedutalk.Logic { class HttpRequestor { public async Task<string> getHttpRequestAsString(Func<string, HttpRequestMessage> requestTask, string input) { HttpClient httpClient = new HttpClient(); HttpRequestMessage request = requestTask(input); var response = httpClient.SendAsync(request); var result = await response.Result.Content.ReadAsStringAsync(); return result; } public string getJSONAsString(Func<string, HttpRequestMessage> requestTask, string placeName) { Task<string> task = getHttpRequestAsString(requestTask, "E2"); task.Wait(); //Format string string replacement = task.Result; if (0 == replacement[0].CompareTo('[')) replacement = replacement.Substring(1); if (0 == replacement[replacement.Length - 1].CompareTo(']')) replacement = replacement.Remove(replacement.Length - 1); return replacement; } } } ```
960cf93c-fbd0-4536-9f27-94cb94426f97
{ "language": "C#" }
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Net.Http { /// <summary> /// Defines default values for http handler properties which is meant to be re-used across WinHttp & UnixHttp Handlers /// </summary> internal static class HttpHandlerDefaults { public const int DefaultMaxAutomaticRedirections = 50; public const DecompressionMethods DefaultAutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; public const bool DefaultAutomaticRedirection = true; public const bool DefaultUseCookies = true; public const bool DefaultPreAuthenticate = false; } }``` Fix XML docs containing an ampersand
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Net.Http { /// <summary> /// Defines default values for http handler properties which is meant to be re-used across WinHttp and UnixHttp Handlers /// </summary> internal static class HttpHandlerDefaults { public const int DefaultMaxAutomaticRedirections = 50; public const DecompressionMethods DefaultAutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; public const bool DefaultAutomaticRedirection = true; public const bool DefaultUseCookies = true; public const bool DefaultPreAuthenticate = false; } } ```
4bdd3a71-f026-495a-a7a3-70278d526bc7
{ "language": "C#" }
```c# //****************************************************************************************************** // Setting.cs - Gbtc // // Copyright © 2021, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this // file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 06/09/2021 - Billy Ernest // Generated original version of source code. // //****************************************************************************************************** using GSF.Data.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SystemCenter.Model { [ConfigFileTableNamePrefix, TableName("SystemCenter.Setting"), UseEscapedName, AllowSearch] [PostRoles("Administrator")] [DeleteRoles("Administrator")] [PatchRoles("Administrator")] public class Setting: openXDA.Model.Setting {} } ``` Remove configfile prefix from settings file and let tablename drive naming.
```c# //****************************************************************************************************** // Setting.cs - Gbtc // // Copyright © 2021, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this // file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 06/09/2021 - Billy Ernest // Generated original version of source code. // //****************************************************************************************************** using GSF.Data.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SystemCenter.Model { [TableName("SystemCenter.Setting"), UseEscapedName, AllowSearch] [PostRoles("Administrator")] [DeleteRoles("Administrator")] [PatchRoles("Administrator")] public class Setting: openXDA.Model.Setting {} } ```
dfb0fa2b-b977-4caa-a4eb-d4c1815aa1be
{ "language": "C#" }
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Configuration; using osu.Game.Rulesets.Mania.Configuration; using osu.Game.Rulesets.UI.Scrolling; namespace osu.Game.Rulesets.Mania.UI { public class ManiaScrollingInfo : IScrollingInfo { private readonly Bindable<ManiaScrollingDirection> configDirection = new Bindable<ManiaScrollingDirection>(); public readonly Bindable<ScrollingDirection> Direction = new Bindable<ScrollingDirection>(); IBindable<ScrollingDirection> IScrollingInfo.Direction => Direction; public ManiaScrollingInfo(ManiaConfigManager config) { config.BindWith(ManiaSetting.ScrollDirection, configDirection); configDirection.BindValueChanged(v => Direction.Value = (ScrollingDirection)v); } } } ``` Fix mania scroll direction not being read from database
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Configuration; using osu.Game.Rulesets.Mania.Configuration; using osu.Game.Rulesets.UI.Scrolling; namespace osu.Game.Rulesets.Mania.UI { public class ManiaScrollingInfo : IScrollingInfo { private readonly Bindable<ManiaScrollingDirection> configDirection = new Bindable<ManiaScrollingDirection>(); public readonly Bindable<ScrollingDirection> Direction = new Bindable<ScrollingDirection>(); IBindable<ScrollingDirection> IScrollingInfo.Direction => Direction; public ManiaScrollingInfo(ManiaConfigManager config) { config.BindWith(ManiaSetting.ScrollDirection, configDirection); configDirection.BindValueChanged(v => Direction.Value = (ScrollingDirection)v, true); } } } ```
894bdf66-2415-447f-a834-09baf8678164
{ "language": "C#" }
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Game.Rulesets.Osu.Difficulty.Preprocessing; namespace osu.Game.Rulesets.Osu.Difficulty.Skills { /// <summary> /// Represents the skill required to press keys with regards to keeping up with the speed at which objects need to be hit. /// </summary> public class Speed : Skill { protected override double SkillMultiplier => 1400; protected override double StrainDecayBase => 0.3; protected override double StrainValueOf(OsuDifficultyHitObject current) { double distance = Math.Min(SINGLE_SPACING_THRESHOLD, current.TravelDistance + current.JumpDistance); return (0.95 + Math.Pow(distance / SINGLE_SPACING_THRESHOLD, 4)) / current.StrainTime; } } } ``` Add the [200 .. 300] bpm speed bonus
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Game.Rulesets.Osu.Difficulty.Preprocessing; namespace osu.Game.Rulesets.Osu.Difficulty.Skills { /// <summary> /// Represents the skill required to press keys with regards to keeping up with the speed at which objects need to be hit. /// </summary> public class Speed : Skill { protected override double SkillMultiplier => 1400; protected override double StrainDecayBase => 0.3; private const double min_speed_bonus = 75; // ~200BPM private const double max_speed_bonus = 45; // ~330BPM private const double speed_balancing_factor = 40; protected override double StrainValueOf(OsuDifficultyHitObject current) { double distance = Math.Min(SINGLE_SPACING_THRESHOLD, current.TravelDistance + current.JumpDistance); double deltaTime = Math.Max(max_speed_bonus, current.DeltaTime); double speedBonus = 1.0; if (deltaTime < min_speed_bonus) speedBonus = 1 + Math.Pow((min_speed_bonus - deltaTime) / speed_balancing_factor, 2); return speedBonus * (0.95 + Math.Pow(distance / SINGLE_SPACING_THRESHOLD, 4)) / current.StrainTime; } } } ```
14741a3e-f074-4c6e-b0d2-907a7787d52c
{ "language": "C#" }
```c# using System; using UnityEngine; using System.Collections; public class GroundCheck : MonoBehaviour { public bool IsOnGround { get; private set; } public void OnTriggerEnter(Collider other) { var geometry = other.gameObject.GetComponent<LevelGeometry>(); if (geometry != null) { IsOnGround = true; } } public void OnTriggerExit(Collider other) { var geometry = other.gameObject.GetComponent<LevelGeometry>(); if (geometry != null) { IsOnGround = false; } } } ``` Fix landing on the ground not working occasionally
```c# using System; using UnityEngine; using System.Collections; public class GroundCheck : MonoBehaviour { public bool IsOnGround { get; private set; } public void OnTriggerStay(Collider other) { var geometry = other.gameObject.GetComponent<LevelGeometry>(); if (geometry != null) { IsOnGround = true; } } public void OnTriggerExit(Collider other) { var geometry = other.gameObject.GetComponent<LevelGeometry>(); if (geometry != null) { IsOnGround = false; } } } ```
3c1e8039-0e85-4fee-a96a-0c4cab244420
{ "language": "C#" }
```c# // 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.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using osu.Framework.Platform; using osu.Game.Database; namespace osu.Game.IPC { public class ArchiveImportIPCChannel : IpcChannel<ArchiveImportMessage> { private readonly ICanAcceptFiles importer; public ArchiveImportIPCChannel(IIpcHost host, ICanAcceptFiles importer = null) : base(host) { this.importer = importer; MessageReceived += msg => { Debug.Assert(importer != null); ImportAsync(msg.Path).ContinueWith(t => { if (t.Exception != null) throw t.Exception; }, TaskContinuationOptions.OnlyOnFaulted); }; } public async Task ImportAsync(string path) { if (importer == null) { // we want to contact a remote osu! to handle the import. await SendMessageAsync(new ArchiveImportMessage { Path = path }).ConfigureAwait(false); return; } if (importer.HandledExtensions.Contains(Path.GetExtension(path)?.ToLowerInvariant())) await importer.Import(path).ConfigureAwait(false); } } public class ArchiveImportMessage { public string Path; } } ``` Return null IPC response for archive imports
```c# // 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.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using osu.Framework.Platform; using osu.Game.Database; namespace osu.Game.IPC { public class ArchiveImportIPCChannel : IpcChannel<ArchiveImportMessage> { private readonly ICanAcceptFiles importer; public ArchiveImportIPCChannel(IIpcHost host, ICanAcceptFiles importer = null) : base(host) { this.importer = importer; MessageReceived += msg => { Debug.Assert(importer != null); ImportAsync(msg.Path).ContinueWith(t => { if (t.Exception != null) throw t.Exception; }, TaskContinuationOptions.OnlyOnFaulted); return null; }; } public async Task ImportAsync(string path) { if (importer == null) { // we want to contact a remote osu! to handle the import. await SendMessageAsync(new ArchiveImportMessage { Path = path }).ConfigureAwait(false); return; } if (importer.HandledExtensions.Contains(Path.GetExtension(path)?.ToLowerInvariant())) await importer.Import(path).ConfigureAwait(false); } } public class ArchiveImportMessage { public string Path; } } ```
ced1e394-29ec-412a-a915-c385b384c238
{ "language": "C#" }
```c# // 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 System.Collections.Generic; using osu.Framework.Allocation; using osu.Game.Rulesets; using osu.Game.Screens.Edit; using osu.Game.Tests.Beatmaps; namespace osu.Game.Tests.Visual { public abstract class EditorTestCase : ScreenTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(Editor), typeof(EditorScreen) }; private readonly Ruleset ruleset; protected EditorTestCase(Ruleset ruleset) { this.ruleset = ruleset; } [BackgroundDependencyLoader] private void load() { Beatmap.Value = new TestWorkingBeatmap(ruleset.RulesetInfo, Clock); LoadComponentAsync(new Editor(), LoadScreen); } } } ``` Fix one more test regression
```c# // 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 System.Collections.Generic; using osu.Framework.Allocation; using osu.Game.Rulesets; using osu.Game.Screens.Edit; using osu.Game.Tests.Beatmaps; namespace osu.Game.Tests.Visual { public abstract class EditorTestCase : ScreenTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(Editor), typeof(EditorScreen) }; private readonly Ruleset ruleset; protected EditorTestCase(Ruleset ruleset) { this.ruleset = ruleset; } [BackgroundDependencyLoader] private void load() { Beatmap.Value = new TestWorkingBeatmap(ruleset.RulesetInfo, null); LoadComponentAsync(new Editor(), LoadScreen); } } } ```
87268c8e-611b-4d23-8b3d-7767e5f27039
{ "language": "C#" }
```c# // Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved. // The Apache v2. See License.txt in the project root for license information. using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing.Matching; namespace Wangkanai.Detection.Hosting { internal class ResponsivePageMatcherPolicy : MatcherPolicy, IEndpointComparerPolicy, IEndpointSelectorPolicy { public ResponsivePageMatcherPolicy() => Comparer = EndpointMetadataComparer<IResponsiveMetadata>.Default; public IComparer<Endpoint> Comparer { get; } public override int Order => 10000; public bool AppliesToEndpoints(IReadOnlyList<Endpoint> endpoints) { for (var i = 0; i < endpoints.Count; i++) if (endpoints[i].Metadata.GetMetadata<IResponsiveMetadata>() != null) return true; return false; } public Task ApplyAsync(HttpContext httpContext, CandidateSet candidates) { var device = httpContext.GetDevice(); for (var i = 0; i < candidates.Count; i++) { var endpoint = candidates[i].Endpoint; var metadata = endpoint.Metadata.GetMetadata<IResponsiveMetadata>(); if (metadata?.Device != null && device != metadata.Device) { // This endpoint is not a match for the selected device. candidates.SetValidity(i, false); } } return Task.CompletedTask; } } }``` Change for to foreach in endpoints list
```c# // Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved. // The Apache v2. See License.txt in the project root for license information. using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing.Matching; namespace Wangkanai.Detection.Hosting { internal class ResponsivePageMatcherPolicy : MatcherPolicy, IEndpointComparerPolicy, IEndpointSelectorPolicy { public ResponsivePageMatcherPolicy() => Comparer = EndpointMetadataComparer<IResponsiveMetadata>.Default; public IComparer<Endpoint> Comparer { get; } public override int Order => 10000; public bool AppliesToEndpoints(IReadOnlyList<Endpoint> endpoints) { foreach (var endpoint in endpoints) if (endpoint?.Metadata.GetMetadata<IResponsiveMetadata>() != null) return true; return false; } public Task ApplyAsync(HttpContext httpContext, CandidateSet candidates) { var device = httpContext.GetDevice(); for (var i = 0; i < candidates.Count; i++) { var endpoint = candidates[i].Endpoint; var metadata = endpoint.Metadata.GetMetadata<IResponsiveMetadata>(); if (metadata?.Device != null && device != metadata.Device) { // This endpoint is not a match for the selected device. candidates.SetValidity(i, false); } } return Task.CompletedTask; } } }```
21ef8863-71f4-49d6-a6fa-fc7d6acca1b3
{ "language": "C#" }
```c# using System; namespace StateMechanic { /// <summary> /// Exception thrown when a transition could not be created from a state on an event, because the state and event do not belong to the same state machine /// </summary> public class InvalidEventTransitionException : Exception { /// <summary> /// Gets the state from which the transition could not be created /// </summary> public IState From { get; private set; } /// <summary> /// Gets the event on which the transition could not be created /// </summary> public IEvent Event { get; private set; } internal InvalidEventTransitionException(IState from, IEvent @event) : base(String.Format("Unable to create from state {0} on event {1}, as state {0} does not belong to the same state machine as event {1}, or to a child state machine of event {1}", from.Name, @event.Name)) { this.From = from; this.Event = @event; } } } ``` Fix typo in exception message
```c# using System; namespace StateMechanic { /// <summary> /// Exception thrown when a transition could not be created from a state on an event, because the state and event do not belong to the same state machine /// </summary> public class InvalidEventTransitionException : Exception { /// <summary> /// Gets the state from which the transition could not be created /// </summary> public IState From { get; private set; } /// <summary> /// Gets the event on which the transition could not be created /// </summary> public IEvent Event { get; private set; } internal InvalidEventTransitionException(IState from, IEvent @event) : base(String.Format("Unable to create transition from state {0} on event {1}, as state {0} does not belong to the same state machine as event {1}, or to a child state machine of event {1}", from.Name, @event.Name)) { this.From = from; this.Event = @event; } } } ```
9d0e0490-4164-4136-8078-07070bf5bb2a
{ "language": "C#" }
```c# using System.IO; using System.Linq; using FluentAssertions; using NUnit.Framework; using SlothUnitParser; /* TODO */ namespace SlothUnit.Parser.Test { [TestFixture] class ClangWrapperShould : FileSystemTest { [Test] public void retrieve_the_name_of_a_cursor() { var filePath = Path.Combine(TestProjectDir, "ClangWrapperShould.h"); var clangWrapper = new ClangWrapper(); var classCursor = clangWrapper.GetClassCursorsIn(filePath).Single(); ClangWrapper.GetCursorName(classCursor).Should().Be("ClangWrapperShould"); } [Test] public void retrieve_the_line_of_a_cursor() { var filePath = Path.Combine(TestProjectDir, "ClangWrapperShould.h"); var clangWrapper = new ClangWrapper(); var classCursor = clangWrapper.GetClassCursorsIn(filePath).Single(); ClangWrapper.GetCursorLine(classCursor).Should().Be(6); } [Test] public void retrieve_the_filepath_for_the_file_a_cursor_is_in() { var filePath = Path.Combine(TestProjectDir, "ClangWrapperShould.h"); var clangWrapper = new ClangWrapper(); var classCursor = clangWrapper.GetClassCursorsIn(filePath).Single(); ClangWrapper.GetCursorFilePath(classCursor).Should().Be(filePath); } } } ``` Refactor introduce SetUp in test
```c# using System.IO; using System.Linq; using ClangSharp; using FluentAssertions; using NUnit.Framework; using SlothUnitParser; /* TODO */ namespace SlothUnit.Parser.Test { [TestFixture] class ClangWrapperShould : FileSystemTest { private CXCursor ClassCursor { get; set; } private string FilePath { get; set; } [SetUp] public void given_a_class_cursor_in_a_file() { FilePath = Path.Combine(TestProjectDir, "ClangWrapperShould.h"); ClassCursor = new ClangWrapper().GetClassCursorsIn(FilePath).Single(); } [Test] public void retrieve_the_filepath_for_the_file_a_cursor_is_in() { ClangWrapper.GetCursorFilePath(ClassCursor).Should().Be(FilePath); } [Test] public void retrieve_the_name_of_a_cursor() { ClangWrapper.GetCursorName(ClassCursor).Should().Be("ClangWrapperShould"); } [Test] public void retrieve_the_line_of_a_cursor() { ClangWrapper.GetCursorLine(ClassCursor).Should().Be(6); } } } ```
bd6060a4-9831-41bc-9124-48a07de13172
{ "language": "C#" }
```c# using System; using System.Linq; using Android.App; using Android.OS; using Android.Views; using Android.Widget; using Toggl.Joey.UI.Adapters; namespace Toggl.Joey.UI.Fragments { public class LogTimeEntriesListFragment : ListFragment { public override void OnViewCreated (View view, Bundle savedInstanceState) { base.OnViewCreated (view, savedInstanceState); ListAdapter = new LogTimeEntriesAdapter (); } public override void OnListItemClick (ListView l, View v, int position, long id) { var adapter = l.Adapter as LogTimeEntriesAdapter; if (adapter == null) return; var model = adapter.GetModel (position); if (model == null) return; model.Continue (); } } } ``` Fix continuing historic time entries.
```c# using System; using System.Linq; using Android.App; using Android.OS; using Android.Views; using Android.Widget; using Toggl.Joey.UI.Adapters; namespace Toggl.Joey.UI.Fragments { public class LogTimeEntriesListFragment : ListFragment { public override void OnViewCreated (View view, Bundle savedInstanceState) { base.OnViewCreated (view, savedInstanceState); ListAdapter = new LogTimeEntriesAdapter (); } public override void OnListItemClick (ListView l, View v, int position, long id) { var adapter = l.Adapter as LogTimeEntriesAdapter; if (adapter == null) return; var model = adapter.GetModel (position); if (model == null) return; model.IsPersisted = true; model.Continue (); } } } ```
0319073d-5b72-4703-9188-89091fa47902
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using Cosmos.Build.Common; using Cosmos.TestRunner.Core; namespace Cosmos.TestRunner.Full { public class DefaultEngineConfiguration : IEngineConfiguration { public virtual int AllowedSecondsInKernel => 6000; public virtual IEnumerable<RunTargetEnum> RunTargets { get { yield return RunTargetEnum.Bochs; //yield return RunTargetEnum.VMware; //yield return RunTargetEnum.HyperV; //yield return RunTargetEnum.Qemu; } } public virtual bool RunWithGDB => true; public virtual bool StartBochsDebugGUI => true; public virtual bool DebugIL2CPU => true; public virtual string KernelPkg => String.Empty; public virtual TraceAssemblies TraceAssembliesLevel => TraceAssemblies.User; public virtual bool EnableStackCorruptionChecks => true; public virtual StackCorruptionDetectionLevel StackCorruptionDetectionLevel => StackCorruptionDetectionLevel.MethodFooters; public virtual DebugMode DebugMode => DebugMode.Source; public virtual IEnumerable<string> KernelAssembliesToRun { get { foreach (var xKernelType in TestKernelSets.GetKernelTypesToRun()) { yield return xKernelType.Assembly.Location; } } } } } ``` Disable DebugIL2CPU to test all kernels
```c# using System; using System.Collections.Generic; using Cosmos.Build.Common; using Cosmos.TestRunner.Core; namespace Cosmos.TestRunner.Full { public class DefaultEngineConfiguration : IEngineConfiguration { public virtual int AllowedSecondsInKernel => 6000; public virtual IEnumerable<RunTargetEnum> RunTargets { get { yield return RunTargetEnum.Bochs; //yield return RunTargetEnum.VMware; //yield return RunTargetEnum.HyperV; //yield return RunTargetEnum.Qemu; } } public virtual bool RunWithGDB => true; public virtual bool StartBochsDebugGUI => true; public virtual bool DebugIL2CPU => false; public virtual string KernelPkg => String.Empty; public virtual TraceAssemblies TraceAssembliesLevel => TraceAssemblies.User; public virtual bool EnableStackCorruptionChecks => true; public virtual StackCorruptionDetectionLevel StackCorruptionDetectionLevel => StackCorruptionDetectionLevel.MethodFooters; public virtual DebugMode DebugMode => DebugMode.Source; public virtual IEnumerable<string> KernelAssembliesToRun { get { foreach (var xKernelType in TestKernelSets.GetKernelTypesToRun()) { yield return xKernelType.Assembly.Location; } } } } } ```
bd12f5c3-e672-4784-a477-cc6daae0d18f
{ "language": "C#" }
```c# using System; using System.Diagnostics; using System.Globalization; namespace Octokit { /// <summary> /// Describes a new deployment key to create. /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public class NewDeployKey { public string Title { get; set; } public string Key { get; set; } internal string DebuggerDisplay { get { return String.Format(CultureInfo.InvariantCulture, "Key: {0}, Title: {1}", Key, Title); } } } } ``` Add the ability to create a readonly deploy key
```c# using System; using System.Diagnostics; using System.Globalization; namespace Octokit { /// <summary> /// Describes a new deployment key to create. /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public class NewDeployKey { public string Title { get; set; } public string Key { get; set; } /// <summary> /// Gets or sets a value indicating whether the key will only be able to read repository contents. Otherwise, /// the key will be able to read and write. /// </summary> /// <value> /// <c>true</c> if [read only]; otherwise, <c>false</c>. /// </value> public bool ReadOnly { get; set; } internal string DebuggerDisplay { get { return String.Format(CultureInfo.InvariantCulture, "Key: {0}, Title: {1}", Key, Title); } } } } ```
91b578a8-cd7b-47cd-ab36-971dd90302c4
{ "language": "C#" }
```c# using System.Linq; using System.ServiceModel.Syndication; namespace Firehose.Web.Extensions { public static class SyndicationItemExtensions { public static bool ApplyDefaultFilter(this SyndicationItem item) { if (item == null) return false; var hasPowerShellCategory = false; var hasPowerShellKeywords = false; if (item.Categories.Count > 0) { hasPowerShellCategory = item.Categories.Any(category => category.Name.ToLowerInvariant().Contains("powershell")); } if (item.ElementExtensions.Count > 0) { var element = item.ElementExtensions.FirstOrDefault(e => e.OuterName == "keywords"); if (element != null) { var keywords = element.GetObject<string>(); hasPowerShellKeywords = keywords.ToLowerInvariant().Contains("powershell"); } } var hasPowerShellTitle = item.Title?.Text.ToLowerInvariant().Contains("powershell") ?? false; return hasPowerShellTitle || hasPowerShellCategory || hasPowerShellKeywords; } public static string ToHtml(this SyndicationContent content) { var textSyndicationContent = content as TextSyndicationContent; if (textSyndicationContent != null) { return textSyndicationContent.Text; } return content.ToString(); } } }``` Update filter to support PWSH
```c# using System.Linq; using System.ServiceModel.Syndication; namespace Firehose.Web.Extensions { public static class SyndicationItemExtensions { public static bool ApplyDefaultFilter(this SyndicationItem item) { if (item == null) return false; var hasPowerShellCategory = false; var hasPowerShellKeywords = false; var hasPWSHCategory = false; var hasPWSHKeywords = false; if (item.Categories.Count > 0) { hasPowerShellCategory = item.Categories.Any(category => category.Name.ToLowerInvariant().Contains("powershell")); hasPWSHCategory = item.Categories.Any(category => category.Name.ToLowerInvariant().Contains("pwsh")); } if (item.ElementExtensions.Count > 0) { var element = item.ElementExtensions.FirstOrDefault(e => e.OuterName == "keywords"); if (element != null) { var keywords = element.GetObject<string>(); hasPowerShellKeywords = keywords.ToLowerInvariant().Contains("powershell"); hasPWSHKeywords = keywords.ToLowerInvariant().Contains("pwsh"); } } var hasPowerShellTitle = item.Title?.Text.ToLowerInvariant().Contains("powershell") ?? false; var hasPWSHTitle = item.Title?.Text.ToLowerInvariant().Contains("pwsh") ?? false; return hasPowerShellTitle || hasPowerShellCategory || hasPowerShellKeywords || hasPWSHTitle || hasPWSHCategory || hasPWSHKeywords; } public static string ToHtml(this SyndicationContent content) { var textSyndicationContent = content as TextSyndicationContent; if (textSyndicationContent != null) { return textSyndicationContent.Text; } return content.ToString(); } } }```
7fcf3f9d-0ac9-4b2b-8814-96ab8952d675
{ "language": "C#" }
```c# using SkiResort.XamarinApp.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SkiResort.XamarinApp { public static class Config { public const string API_URL = "__SERVERURI__/api"; public const double USER_DEFAULT_POSITION_LATITUDE = 40.7201013; public const double USER_DEFAULT_POSITION_LONGITUDE = -74.0101931; public static Color BAR_COLOR_BLACK = Color.FromHex("#141414"); } } ``` Fix an issue with the default URI
```c# using SkiResort.XamarinApp.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SkiResort.XamarinApp { public static class Config { public const string API_URL = "__SERVERURI__"; public const double USER_DEFAULT_POSITION_LATITUDE = 40.7201013; public const double USER_DEFAULT_POSITION_LONGITUDE = -74.0101931; public static Color BAR_COLOR_BLACK = Color.FromHex("#141414"); } } ```
9ea21164-639e-4112-bb58-1b32e10a19ba
{ "language": "C#" }
```c# using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Networking; public static class UnityUtils { public static bool IsAnyKeyUp(KeyCode[] keys) { foreach (KeyCode key in keys) { if (Input.GetKeyUp(key)) return true; } return false; } public static bool IsAnyKeyDown(KeyCode[] keys) { foreach (KeyCode key in keys) { if (Input.GetKeyDown(key)) return true; } return false; } public static bool IsHeadless() { return SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null; } public static bool TryGetByNetId<T>(NetworkInstanceId targetNetId, out T output) where T : Component { output = null; GameObject foundObject = ClientScene.FindLocalObject(targetNetId); if (foundObject == null) return false; output = foundObject.GetComponent<T>(); if (output == null) return false; return true; } } ``` Add Is any key function
```c# using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Networking; public static class UnityUtils { public static bool IsAnyKeyUp(KeyCode[] keys) { foreach (KeyCode key in keys) { if (Input.GetKeyUp(key)) return true; } return false; } public static bool IsAnyKeyDown(KeyCode[] keys) { foreach (KeyCode key in keys) { if (Input.GetKeyDown(key)) return true; } return false; } public static bool IsAnyKey(KeyCode[] keys) { foreach (KeyCode key in keys) { if (Input.GetKey(key)) return true; } return false; } public static bool IsHeadless() { return SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null; } public static bool TryGetByNetId<T>(NetworkInstanceId targetNetId, out T output) where T : Component { output = null; GameObject foundObject = ClientScene.FindLocalObject(targetNetId); if (foundObject == null) return false; output = foundObject.GetComponent<T>(); if (output == null) return false; return true; } } ```
30ba2867-9e8e-4ca9-996f-8d9482072dfd
{ "language": "C#" }
```c# @{ ViewBag.Title = "Contact"; } <h2>@ViewBag.Title.</h2> <h3>@ViewBag.Message</h3> <address> One Microsoft Way<br /> Redmond, WA 98052-6399<br /> <abbr title="Phone">P:</abbr> 425.555.0100 </address> <address> <strong>Support:</strong> <a href="mailto:Support@example.com">Support@wechangedthis.com</a><br /> <strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a> <strong>Batman:</strong> <a href="mailto:Batman@batman.com">Batman@batman.com</a> <strong>Peter Parker</strong> <a href="mailto:spiderman@spiderman.com">Spiderman@spiderman.com</a> </address>``` Add Travis to contact page.
```c# @{ ViewBag.Title = "Contact"; } <h2>@ViewBag.Title.</h2> <h3>@ViewBag.Message</h3> <address> One Microsoft Way<br /> Redmond, WA 98052-6399<br /> <abbr title="Phone">P:</abbr> 425.555.0100 </address> <address> <strong>Support:</strong> <a href="mailto:Support@example.com">Support@wechangedthis.com</a><br /> <strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a> <strong>Batman:</strong> <a href="mailto:Batman@batman.com">Batman@batman.com</a> <strong>Peter Parker</strong> <a href="mailto:spiderman@spiderman.com">Spiderman@spiderman.com</a> <strong>Travis Elkins</strong> </address>```
71901d4a-ba5f-4c0d-99cd-025c98d2295c
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using CommandLine.OptParse; using Sep.Git.Tfs.Core; using Sep.Git.Tfs.Core.TfsInterop; using StructureMap; namespace Sep.Git.Tfs.Commands { [Pluggable("unshelve")] [Description("unshelve [options] (-l | shelveset-name destination-branch)")] [RequiresValidGitRepository] public class Unshelve : GitTfsCommand { private readonly Globals _globals; public Unshelve(Globals globals) { _globals = globals; } [OptDef(OptValType.ValueReq)] [ShortOptionName('u')] [LongOptionName("user")] [UseNameAsLongOption(false)] [Description("Shelveset owner (default is the current user; 'all' means all users)")] public string Owner { get; set; } public IEnumerable<IOptionResults> ExtraOptions { get { return this.MakeNestedOptionResults(); } } public int Run(IList<string> args) { // TODO -- let the remote be specified on the command line. var remote = _globals.Repository.ReadAllTfsRemotes().First(); return remote.Tfs.Unshelve(this, remote, args); } } } ``` Fix the TODO item in Ushelve so it can support multiple TFS remotes
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Text.RegularExpressions; using CommandLine.OptParse; using Sep.Git.Tfs.Core; using StructureMap; namespace Sep.Git.Tfs.Commands { [Pluggable("unshelve")] [Description("unshelve [options] (-l | shelveset-name destination-branch)")] [RequiresValidGitRepository] public class Unshelve : GitTfsCommand { private readonly Globals _globals; public Unshelve(Globals globals) { _globals = globals; } [OptDef(OptValType.ValueReq)] [ShortOptionName('u')] [LongOptionName("user")] [UseNameAsLongOption(false)] [Description("Shelveset owner (default is the current user; 'all' means all users)")] public string Owner { get; set; } public IEnumerable<IOptionResults> ExtraOptions { get { return this.MakeNestedOptionResults(); } } public int Run(IList<string> args) { var remote = _globals.Repository.ReadTfsRemote(_globals.RemoteId); return remote.Tfs.Unshelve(this, remote, args); } } } ```
558d49e8-c9ab-4921-8706-bf0295dfe0f7
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Game.Beatmaps; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Edit.Checks.Components; using osu.Game.Rulesets.Osu.Edit.Checks; namespace osu.Game.Rulesets.Osu.Edit { public class OsuChecker : Checker { public readonly List<Check> beatmapChecks = new List<Check> { new CheckOffscreenObjects() }; public override IEnumerable<Issue> Run(IBeatmap beatmap) { // Also run mode-invariant checks. foreach (var issue in base.Run(beatmap)) yield return issue; foreach (var issue in beatmapChecks.SelectMany(check => check.Run(beatmap))) yield return issue; } } } ``` Fix field name and accessibility
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Game.Beatmaps; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Edit.Checks.Components; using osu.Game.Rulesets.Osu.Edit.Checks; namespace osu.Game.Rulesets.Osu.Edit { public class OsuChecker : Checker { private readonly List<Check> checks = new List<Check> { new CheckOffscreenObjects() }; public override IEnumerable<Issue> Run(IBeatmap beatmap) { // Also run mode-invariant checks. foreach (var issue in base.Run(beatmap)) yield return issue; foreach (var issue in checks.SelectMany(check => check.Run(beatmap))) yield return issue; } } } ```
caa9ca0c-f5c7-451e-870c-7a40df1f2fbb
{ "language": "C#" }
```c# #load nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease Environment.SetVariableNames(); BuildParameters.SetParameters(context: Context, buildSystem: BuildSystem, sourceDirectoryPath: "./", title: "Cake.FileHelpers", repositoryOwner: "cake-contrib", repositoryName: "Cake.FileHelpers", appVeyorAccountName: "cakecontrib", shouldRunDupFinder: false, shouldRunInspectCode: false); BuildParameters.PrintParameters(Context); ToolSettings.SetToolSettings(context: Context, dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/Cake.FileHelpers.Tests/*.cs" }, testCoverageFilter: "+[*]* -[xunit.*]* -[Cake.Core]* -[Cake.Testing]* -[*.Tests]* -[FakeItEasy]*", testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*", testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs"); Build.RunDotNetCore(); ``` Fix source dir path (doesn't like "./")
```c# #load nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease Environment.SetVariableNames(); BuildParameters.SetParameters(context: Context, buildSystem: BuildSystem, sourceDirectoryPath: Context.Environment.WorkingDirectory, title: "Cake.FileHelpers", repositoryOwner: "cake-contrib", repositoryName: "Cake.FileHelpers", appVeyorAccountName: "cakecontrib", shouldRunDupFinder: false, shouldRunInspectCode: false); BuildParameters.PrintParameters(Context); ToolSettings.SetToolSettings(context: Context, dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/Cake.FileHelpers.Tests/*.cs" }, testCoverageFilter: "+[*]* -[xunit.*]* -[Cake.Core]* -[Cake.Testing]* -[*.Tests]* -[FakeItEasy]*", testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*", testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs"); Build.RunDotNetCore(); ```
5fc132bd-8728-4d54-96bc-f88e9c7dfb85
{ "language": "C#" }
```c# using System; namespace xFunc.Library.Maths.Expressions { public class AssignMathExpression : IMathExpression { private VariableMathExpression variable; private IMathExpression value; public AssignMathExpression() : this(null, null) { } public AssignMathExpression(VariableMathExpression variable, IMathExpression value) { this.variable = variable; this.value = value; } public double Calculate(MathParameterCollection parameters) { if (parameters == null) throw new ArgumentNullException("parameters"); parameters.Add(variable.Variable, value.Calculate(parameters)); return double.NaN; } public IMathExpression Derivative() { throw new NotSupportedException(); } public IMathExpression Derivative(VariableMathExpression variable) { throw new NotSupportedException(); } public VariableMathExpression Variable { get { return variable; } set { variable = value; } } public IMathExpression Value { get { return this.value; } set { this.value = value; } } public IMathExpression Parent { get { return null; } set { } } } } ``` Fix bug with reassigning the variable.
```c# using System; namespace xFunc.Library.Maths.Expressions { public class AssignMathExpression : IMathExpression { private VariableMathExpression variable; private IMathExpression value; public AssignMathExpression() : this(null, null) { } public AssignMathExpression(VariableMathExpression variable, IMathExpression value) { this.variable = variable; this.value = value; } public double Calculate(MathParameterCollection parameters) { if (parameters == null) throw new ArgumentNullException("parameters"); parameters[variable.Variable] = value.Calculate(parameters); return double.NaN; } public IMathExpression Derivative() { throw new NotSupportedException(); } public IMathExpression Derivative(VariableMathExpression variable) { throw new NotSupportedException(); } public VariableMathExpression Variable { get { return variable; } set { variable = value; } } public IMathExpression Value { get { return this.value; } set { this.value = value; } } public IMathExpression Parent { get { return null; } set { } } } } ```
2e1b3ef4-bcbc-430c-81d6-9324a9f59c58
{ "language": "C#" }
```c# 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.Name; 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]; } } } ``` Use fullname for sure that it will not duplicate with other
```c# 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]; } } } ```
b7bd8ded-5f17-4172-8d81-7ed8f5874131
{ "language": "C#" }
```c# using System.Linq; using NUnit.Framework; namespace Ploeh.AutoFixture.NUnit3.UnitTest { [TestFixture] public class DependencyConstraints { [TestCase("Moq")] [TestCase("Rhino.Mocks")] public void AutoFixtureNUnit3DoesNotReference(string assemblyName) { // Fixture setup // Exercise system var references = typeof(AutoDataAttribute).Assembly.GetReferencedAssemblies(); // Verify outcome Assert.False(references.Any(an => an.Name == assemblyName)); // Teardown } [TestCase("Moq")] [TestCase("Rhino.Mocks")] public void AutoFixtureNUnit3UnitTestsDoNotReference(string assemblyName) { // Fixture setup // Exercise system var references = this.GetType().Assembly.GetReferencedAssemblies(); // Verify outcome Assert.False(references.Any(an => an.Name == assemblyName)); // Teardown } } } ``` Add other mocking libs in dependency contraints
```c# using System.Linq; using NUnit.Framework; namespace Ploeh.AutoFixture.NUnit3.UnitTest { [TestFixture] public class DependencyConstraints { [TestCase("FakeItEasy")] [TestCase("Foq")] [TestCase("FsCheck")] [TestCase("Moq")] [TestCase("NSubstitute")] [TestCase("Rhino.Mocks")] [TestCase("Unquote")] [TestCase("xunit")] [TestCase("xunit.extensions")] public void AutoFixtureNUnit3DoesNotReference(string assemblyName) { // Fixture setup // Exercise system var references = typeof(AutoDataAttribute).Assembly.GetReferencedAssemblies(); // Verify outcome Assert.False(references.Any(an => an.Name == assemblyName)); // Teardown } [TestCase("FakeItEasy")] [TestCase("Foq")] [TestCase("FsCheck")] [TestCase("Moq")] [TestCase("NSubstitute")] [TestCase("Rhino.Mocks")] [TestCase("Unquote")] [TestCase("xunit")] [TestCase("xunit.extensions")] public void AutoFixtureNUnit3UnitTestsDoNotReference(string assemblyName) { // Fixture setup // Exercise system var references = this.GetType().Assembly.GetReferencedAssemblies(); // Verify outcome Assert.False(references.Any(an => an.Name == assemblyName)); // Teardown } } } ```