doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
3cb6d394-50d3-41f5-90b6-656f34604c1e
{ "language": "C#" }
```c# using System.IO; using System.Xml; namespace VanillaTransformer.PostTransformations.XML { public class ReFormatXMLTransformation:IPostTransformation { public string Name { get { return "ReFormatXML"; } } public string Execute(string configContent) { var settings = new XmlWriterSettings() { Indent = true, IndentChars = " ", NewLineChars = "\r\n", NewLineHandling = NewLineHandling.Replace, }; var xDocument = new XmlDocument(); xDocument.LoadXml(configContent); using (var textWriter = new StringWriter()) { using (var writer = XmlWriter.Create(textWriter,settings)) { xDocument.WriteTo(writer); } return textWriter.ToString(); } } } } ``` Set line ending according to the enviroment in ReFormatXML
```c# using System; using System.IO; using System.Xml; namespace VanillaTransformer.PostTransformations.XML { public class ReFormatXMLTransformation:IPostTransformation { public string Name { get { return "ReFormatXML"; } } public string Execute(string configContent) { var settings = new XmlWriterSettings() { Indent = true, IndentChars = " ", NewLineChars = Environment.NewLine, NewLineHandling = NewLineHandling.Replace, }; var xDocument = new XmlDocument(); xDocument.LoadXml(configContent); using (var textWriter = new StringWriter()) { using (var writer = XmlWriter.Create(textWriter,settings)) { xDocument.WriteTo(writer); } return textWriter.ToString(); } } } } ```
b6008e6e-3444-4047-9cf2-c799f5d916f7
{ "language": "C#" }
```c# using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using NServiceBus; using SFA.DAS.EmployerFinance.Messages.Commands; namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs { public class ImportLevyDeclarationsJob { private readonly IMessageSession _messageSession; public ImportLevyDeclarationsJob(IMessageSession messageSession) { _messageSession = messageSession; } public Task Run([TimerTrigger("0 0 15 20 * *")] TimerInfo timer, ILogger logger) { return _messageSession.Send(new ImportLevyDeclarationsCommand()); } } }``` Update Timer for Levy to 23rd
```c# using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using NServiceBus; using SFA.DAS.EmployerFinance.Messages.Commands; namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs { public class ImportLevyDeclarationsJob { private readonly IMessageSession _messageSession; public ImportLevyDeclarationsJob(IMessageSession messageSession) { _messageSession = messageSession; } public Task Run([TimerTrigger("0 0 15 23 * *")] TimerInfo timer, ILogger logger) { return _messageSession.Send(new ImportLevyDeclarationsCommand()); } } }```
76dd0b57-aeea-47ad-b3c7-e3870d33bd85
{ "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.Platform; using osu.Framework.Testing; namespace osu.Game.Configuration { [ExcludeFromDynamicCompile] public class DevelopmentOsuConfigManager : OsuConfigManager { protected override string Filename => base.Filename.Replace(".ini", ".dev.ini"); public DevelopmentOsuConfigManager(Storage storage) : base(storage) { LookupKeyBindings = _ => "unknown"; LookupSkinName = _ => "unknown"; } } } ``` Revert "Fix potential crash in tests when attempting to lookup key bindings in cases the lookup is not available"
```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.Platform; using osu.Framework.Testing; namespace osu.Game.Configuration { [ExcludeFromDynamicCompile] public class DevelopmentOsuConfigManager : OsuConfigManager { protected override string Filename => base.Filename.Replace(".ini", ".dev.ini"); public DevelopmentOsuConfigManager(Storage storage) : base(storage) { } } } ```
0c5d03ab-78b4-449c-a49e-5511530bce1f
{ "language": "C#" }
```c# namespace PcscDotNet { /// <summary> /// Indicates whether other applications may form connections to the card. /// </summary> public enum SCardShare { /// <summary> /// This application demands direct control of the reader, so it is not available to other applications. /// </summary> Direct = 3, /// <summary> /// This application is not willing to share this card with other applications. /// </summary> Exclusive = 1, /// <summary> /// This application is willing to share this card with other applications. /// </summary> Shared = 2, /// <summary> /// Share mode is undefined, can not be used to connect to card/reader. /// </summary> Undefined = 0 } }``` Append new line at EOF
```c# namespace PcscDotNet { /// <summary> /// Indicates whether other applications may form connections to the card. /// </summary> public enum SCardShare { /// <summary> /// This application demands direct control of the reader, so it is not available to other applications. /// </summary> Direct = 3, /// <summary> /// This application is not willing to share this card with other applications. /// </summary> Exclusive = 1, /// <summary> /// This application is willing to share this card with other applications. /// </summary> Shared = 2, /// <summary> /// Share mode is undefined, can not be used to connect to card/reader. /// </summary> Undefined = 0 } } ```
aa15c2cc-a097-409b-b55a-86e1d4b6744d
{ "language": "C#" }
```c# using System.ComponentModel.DataAnnotations; namespace TM.Shared { public class AuthorBadge { [StringLength(400)] public string ImageSiteUrl { get; set; } [StringLength(100)] public string ImageName { get; set; } [StringLength(400)] public string Link { get; set; } [StringLength(100)] public string HoverText { get; set; } public bool IsEmpty { get { return string.IsNullOrWhiteSpace(Link); } } } }``` Increase AuthorBage.HoverText db table column length
```c# using System.ComponentModel.DataAnnotations; namespace TM.Shared { public class AuthorBadge { [StringLength(400)] public string ImageSiteUrl { get; set; } [StringLength(100)] public string ImageName { get; set; } [StringLength(400)] public string Link { get; set; } [StringLength(400)] public string HoverText { get; set; } public bool IsEmpty { get { return string.IsNullOrWhiteSpace(Link); } } } }```
128a6936-7510-4b6d-a74e-16a66e6e9827
{ "language": "C#" }
```c# using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace IF.Lastfm.Core.Api.Helpers { public static class ApiExtensions { public static T GetAttribute<T>(this Enum enumValue) where T : Attribute { return enumValue .GetType() .GetTypeInfo() .GetDeclaredField(enumValue.ToString()) .GetCustomAttribute<T>(); } public static string GetApiName(this Enum enumValue) { var attribute = enumValue.GetAttribute<ApiNameAttribute>(); return (attribute != null && !string.IsNullOrWhiteSpace(attribute.Text)) ? attribute.Text : enumValue.ToString(); } public static int ToUnixTimestamp(this DateTime dt) { var d = (dt - new DateTime(1970, 1, 1).ToUniversalTime()).TotalSeconds; return Convert.ToInt32(d); } public static DateTime ToDateTimeUtc(this double stamp) { var d = new DateTime(1970, 1, 1).ToUniversalTime(); d = d.AddSeconds(stamp); return d; } public static int CountOrDefault<T>(this IEnumerable<T> enumerable) { return enumerable != null ? enumerable.Count() : 0; } } }``` Fix time bug with scrobbles
```c# using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace IF.Lastfm.Core.Api.Helpers { public static class ApiExtensions { public static T GetAttribute<T>(this Enum enumValue) where T : Attribute { return enumValue .GetType() .GetTypeInfo() .GetDeclaredField(enumValue.ToString()) .GetCustomAttribute<T>(); } public static string GetApiName(this Enum enumValue) { var attribute = enumValue.GetAttribute<ApiNameAttribute>(); return (attribute != null && !string.IsNullOrWhiteSpace(attribute.Text)) ? attribute.Text : enumValue.ToString(); } public static int ToUnixTimestamp(this DateTime dt) { var d = (dt - new DateTime(1970, 1, 1)).TotalSeconds; return Convert.ToInt32(d); } public static DateTime ToDateTimeUtc(this double stamp) { var d = new DateTime(1970, 1, 1).ToUniversalTime(); d = d.AddSeconds(stamp); return d; } public static int CountOrDefault<T>(this IEnumerable<T> enumerable) { return enumerable != null ? enumerable.Count() : 0; } } }```
fc411ad7-bb14-4e13-a7d1-d11dbab208c2
{ "language": "C#" }
```c# using System; using Xamarin.Forms; using System.Collections.Generic; namespace FreshMvvm { public class FreshTabbedNavigationContainer : TabbedPage, IFreshNavigationService { public FreshTabbedNavigationContainer () { RegisterNavigation (); } protected void RegisterNavigation () { FreshIOC.Container.Register<IFreshNavigationService> (this); } public virtual Page AddTab<T> (string title, string icon, object data = null) where T : FreshBasePageModel { var page = FreshPageModelResolver.ResolvePageModel<T> (data); var navigationContainer = CreateContainerPage (page); navigationContainer.Title = title; navigationContainer.Icon = icon; Children.Add (navigationContainer); return navigationContainer; } protected virtual Page CreateContainerPage (Page page) { return new NavigationPage (page); } public async System.Threading.Tasks.Task PushPage (Xamarin.Forms.Page page, FreshBasePageModel model, bool modal = false) { if (modal) await this.CurrentPage.Navigation.PushModalAsync (CreateContainerPage (page)); else await this.CurrentPage.Navigation.PushAsync (page); } public async System.Threading.Tasks.Task PopPage (bool modal = false) { if (modal) await this.CurrentPage.Navigation.PopModalAsync (); else await this.CurrentPage.Navigation.PopAsync (); } } } ``` Fix issue with nulll image icon in tabbed navigation container
```c# using System; using Xamarin.Forms; using System.Collections.Generic; namespace FreshMvvm { public class FreshTabbedNavigationContainer : TabbedPage, IFreshNavigationService { public FreshTabbedNavigationContainer () { RegisterNavigation (); } protected void RegisterNavigation () { FreshIOC.Container.Register<IFreshNavigationService> (this); } public virtual Page AddTab<T> (string title, string icon, object data = null) where T : FreshBasePageModel { var page = FreshPageModelResolver.ResolvePageModel<T> (data); var navigationContainer = CreateContainerPage (page); navigationContainer.Title = title; if (!string.IsNullOrWhiteSpace(icon)) navigationContainer.Icon = icon; Children.Add (navigationContainer); return navigationContainer; } protected virtual Page CreateContainerPage (Page page) { return new NavigationPage (page); } public async System.Threading.Tasks.Task PushPage (Xamarin.Forms.Page page, FreshBasePageModel model, bool modal = false) { if (modal) await this.CurrentPage.Navigation.PushModalAsync (CreateContainerPage (page)); else await this.CurrentPage.Navigation.PushAsync (page); } public async System.Threading.Tasks.Task PopPage (bool modal = false) { if (modal) await this.CurrentPage.Navigation.PopModalAsync (); else await this.CurrentPage.Navigation.PopAsync (); } } } ```
ce5f9f2c-b4c6-4ce7-99d1-7188afe18f32
{ "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. using System.IdentityModel.Claims; using System.Runtime; using System.Security.Principal; namespace System.ServiceModel { public class SpnEndpointIdentity : EndpointIdentity { private static TimeSpan _spnLookupTime = TimeSpan.FromMinutes(1); public SpnEndpointIdentity(string spnName) { if (spnName == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("spnName"); base.Initialize(Claim.CreateSpnClaim(spnName)); } public SpnEndpointIdentity(Claim identity) { if (identity == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("identity"); if (!identity.ClaimType.Equals(ClaimTypes.Spn)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.Format(SR.UnrecognizedClaimTypeForIdentity, identity.ClaimType, ClaimTypes.Spn)); base.Initialize(identity); } public static TimeSpan SpnLookupTime { get { return _spnLookupTime; } set { if (value.Ticks < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("value", value.Ticks, SR.Format(SR.ValueMustBeNonNegative))); } _spnLookupTime = value; } } } } ``` Implement supported parts of Spn/UpnEndpointIdentity
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IdentityModel.Claims; using System.Runtime; using System.Security.Principal; namespace System.ServiceModel { public class SpnEndpointIdentity : EndpointIdentity { private static TimeSpan _spnLookupTime = TimeSpan.FromMinutes(1); public SpnEndpointIdentity(string spnName) { if (spnName == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("spnName"); base.Initialize(Claim.CreateSpnClaim(spnName)); } public SpnEndpointIdentity(Claim identity) { if (identity == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("identity"); if (!identity.ClaimType.Equals(ClaimTypes.Spn)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.Format(SR.UnrecognizedClaimTypeForIdentity, identity.ClaimType, ClaimTypes.Spn)); base.Initialize(identity); } public static TimeSpan SpnLookupTime { get { return _spnLookupTime; } set { if (value.Ticks < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("value", value.Ticks, SR.Format(SR.ValueMustBeNonNegative))); } _spnLookupTime = value; } } } } ```
ee145463-0062-47ae-8908-4e16603c58fc
{ "language": "C#" }
```c# // Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. namespace SixLabors.Fonts { /// <summary> /// Extension methods for <see cref="IFontCollection"/>. /// </summary> public static class FontCollectionExtensions { /// <summary> /// Adds the fonts from the <see cref="SystemFonts"/> collection to this <see cref="FontCollection"/>. /// </summary> /// <param name="collection">The font collection.</param> /// <returns>The <see cref="FontCollection"/> containing the system fonts.</returns> public static FontCollection AddSystemFonts(this FontCollection collection) { // This cast is safe because our underlying SystemFontCollection implements // both interfaces separately. foreach (FontMetrics? metric in (IReadOnlyFontMetricsCollection)SystemFonts.Collection) { ((IFontMetricsCollection)collection).AddMetrics(metric); } return collection; } } } ``` Add an overload of `AddSystemFonts`
```c# // Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using System; namespace SixLabors.Fonts { /// <summary> /// Extension methods for <see cref="IFontCollection"/>. /// </summary> public static class FontCollectionExtensions { /// <summary> /// Adds the fonts from the <see cref="SystemFonts"/> collection to this <see cref="FontCollection"/>. /// </summary> /// <param name="collection">The font collection.</param> /// <returns>The <see cref="FontCollection"/> containing the system fonts.</returns> public static FontCollection AddSystemFonts(this FontCollection collection) { // This cast is safe because our underlying SystemFontCollection implements // both interfaces separately. foreach (FontMetrics metric in (IReadOnlyFontMetricsCollection)SystemFonts.Collection) { ((IFontMetricsCollection)collection).AddMetrics(metric); } return collection; } /// <summary> /// Adds the fonts from the <see cref="SystemFonts"/> collection to this <see cref="FontCollection"/>. /// </summary> /// <param name="collection">The font collection.</param> /// <param name="match">The System.Predicate delegate that defines the conditions of <see cref="FontMetrics"/> to add into the font collection.</param> /// <returns>The <see cref="FontCollection"/> containing the system fonts.</returns> public static FontCollection AddSystemFonts(this FontCollection collection, Predicate<FontMetrics> match) { foreach (FontMetrics metric in (IReadOnlyFontMetricsCollection)SystemFonts.Collection) { if (match(metric)) { ((IFontMetricsCollection)collection).AddMetrics(metric); } } return collection; } } } ```
95564e8f-3438-4d80-bd72-59a687dd4938
{ "language": "C#" }
```c# @model Portal.CMS.Web.Areas.Admin.ViewModels.Settings.EditViewModel @{ Layout = ""; } @using (Html.BeginForm("Edit", "Settings", FormMethod.Post)) { @Html.AntiForgeryToken() @Html.HiddenFor(x => x.SettingId) @Html.ValidationMessage("SettingName") <div class="control-group float-container"> @Html.LabelFor(x => x.SettingName) @if (Model.SettingName != "Website Name") { @Html.TextBoxFor(x => x.SettingName, new { placeholder = "Setting Name" }) } else { @Html.TextBoxFor(x => x.SettingName, new { placeholder = "Setting Name", @readonly="true" }) } </div> <div class="control-group float-container"> @Html.LabelFor(x => x.SettingValue) @Html.TextBoxFor(x => x.SettingValue, new { placeholder = "Setting Value" }) </div> <br /> <div class="footer"> <button class="btn primary">Save</button> @if (Model.SettingName != "Website Name") { <a href="@Url.Action("Delete", "Settings", new { settingId = Model.SettingId })" class="btn delete">Delete</a> } <button class="btn" data-dismiss="modal">Cancel</button> </div> }``` Remove ViewLogic Validation on Edit Settings Screen
```c# @model Portal.CMS.Web.Areas.Admin.ViewModels.Settings.EditViewModel @{ Layout = ""; } @using (Html.BeginForm("Edit", "Settings", FormMethod.Post)) { @Html.AntiForgeryToken() @Html.HiddenFor(x => x.SettingId) @Html.ValidationMessage("SettingName") <div class="control-group float-container"> @Html.LabelFor(x => x.SettingName) @Html.TextBoxFor(x => x.SettingName, new { placeholder = "Setting Name" }) </div> <div class="control-group float-container"> @Html.LabelFor(x => x.SettingValue) @Html.TextBoxFor(x => x.SettingValue, new { placeholder = "Setting Value" }) </div> <br /> <div class="footer"> <button class="btn primary">Save</button> <a href="@Url.Action("Delete", "Settings", new { settingId = Model.SettingId })" class="btn delete">Delete</a> <button class="btn" data-dismiss="modal">Cancel</button> </div> }```
3408d9cd-4985-481d-8609-a450c02c4b08
{ "language": "C#" }
```c# using System; using System.Collections; using System.Collections.Generic; using TSQLLint.Lib.Rules.RuleViolations; namespace TSQLLint.Tests.Helpers { public class RuleViolationComparer : IComparer, IComparer<RuleViolation> { public int Compare(object x, object y) { if (!(x is RuleViolation lhs) || !(y is RuleViolation rhs)) { throw new InvalidOperationException("cannot compare null object"); } return Compare(lhs, rhs); } public int Compare(RuleViolation left, RuleViolation right) { if (right != null && left != null && left.Line != right.Line) { return -1; } if (right != null && left != null && left.Column != right.Column) { return -1; } if (right != null && left != null && left.RuleName != right.RuleName) { return -1; } return 0; } } } ``` Exclude test utility from coverage
```c# using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using TSQLLint.Lib.Rules.RuleViolations; namespace TSQLLint.Tests.Helpers { [ExcludeFromCodeCoverage] public class RuleViolationComparer : IComparer, IComparer<RuleViolation> { public int Compare(object x, object y) { if (!(x is RuleViolation lhs) || !(y is RuleViolation rhs)) { throw new InvalidOperationException("cannot compare null object"); } return Compare(lhs, rhs); } public int Compare(RuleViolation left, RuleViolation right) { if (right != null && left != null && left.Line != right.Line) { return -1; } if (right != null && left != null && left.Column != right.Column) { return -1; } if (right != null && left != null && left.RuleName != right.RuleName) { return -1; } return 0; } } } ```
52947723-725c-403f-af89-ff31d545c409
{ "language": "C#" }
```c# using System; using System.Linq; using Abp.Dependency; using Castle.Core; using Castle.MicroKernel; namespace Abp.Auditing { internal class AuditingInterceptorRegistrar { private readonly IAuditingConfiguration _auditingConfiguration; private readonly IIocManager _iocManager; public AuditingInterceptorRegistrar(IIocManager iocManager) { _auditingConfiguration = _iocManager.Resolve<IAuditingConfiguration>(); _iocManager = iocManager; } public void Initialize() { if (!_auditingConfiguration.IsEnabled) { return; } _iocManager.IocContainer.Kernel.ComponentRegistered += Kernel_ComponentRegistered; } private void Kernel_ComponentRegistered(string key, IHandler handler) { if (ShouldIntercept(handler.ComponentModel.Implementation)) { handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(AuditingInterceptor))); } } private bool ShouldIntercept(Type type) { if (_auditingConfiguration.Selectors.Any(selector => selector.Predicate(type))) { return true; } if (type.IsDefined(typeof(AuditedAttribute), true)) //TODO: true or false? { return true; } if (type.GetMethods().Any(m => m.IsDefined(typeof(AuditedAttribute), true))) //TODO: true or false? { return true; } return false; } } }``` Fix for previous minor refactoring.
```c# using System; using System.Linq; using Abp.Dependency; using Castle.Core; using Castle.MicroKernel; namespace Abp.Auditing { internal class AuditingInterceptorRegistrar { private readonly IIocManager _iocManager; private readonly IAuditingConfiguration _auditingConfiguration; public AuditingInterceptorRegistrar(IIocManager iocManager) { _iocManager = iocManager; _auditingConfiguration = _iocManager.Resolve<IAuditingConfiguration>(); } public void Initialize() { if (!_auditingConfiguration.IsEnabled) { return; } _iocManager.IocContainer.Kernel.ComponentRegistered += Kernel_ComponentRegistered; } private void Kernel_ComponentRegistered(string key, IHandler handler) { if (ShouldIntercept(handler.ComponentModel.Implementation)) { handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(AuditingInterceptor))); } } private bool ShouldIntercept(Type type) { if (_auditingConfiguration.Selectors.Any(selector => selector.Predicate(type))) { return true; } if (type.IsDefined(typeof(AuditedAttribute), true)) //TODO: true or false? { return true; } if (type.GetMethods().Any(m => m.IsDefined(typeof(AuditedAttribute), true))) //TODO: true or false? { return true; } return false; } } }```
9d0f3a30-d5aa-4a04-8dd3-e2a5a908ef1b
{ "language": "C#" }
```c# // vimage - http://torrunt.net/vimage // Corey Zeke Womack (Torrunt) - me@torrunt.net using System; namespace vimage { class Program { static void Main(string[] args) { string file; if (args.Length == 0) { #if DEBUG //file = @"C:\Users\Corey\Pictures\Test Images\Beaver_Transparent.png"; //file = @"C:\Users\Corey\Pictures\Test Images\AdventureTime_TransparentAnimation.gif"; //file = @"C:\Users\Corey\Pictures\Test Images\AnimatedGif.gif"; file = @"G:\Misc\Desktop Backgrounds\0diHF.jpg"; #else return; #endif } else file = args[0]; ImageViewer ImageViewer = new ImageViewer(file); } } } ``` Load only if the file given exists
```c# // vimage - http://torrunt.net/vimage // Corey Zeke Womack (Torrunt) - me@torrunt.net using System; namespace vimage { class Program { static void Main(string[] args) { string file; if (args.Length == 0) return; else file = args[0]; if (System.IO.File.Exists(file)) { ImageViewer imageViewer = new ImageViewer(file); } } } } ```
bb76cdc5-c3d9-4ea5-9d74-7f6a0e2da0e6
{ "language": "C#" }
```c# // Copyright 2013-2021 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (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.imagemagick.org/script/license.php // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. using System.IO; namespace ImageMagick.Configuration { internal sealed class ConfigurationFile : IConfigurationFile { public ConfigurationFile(string fileName) { FileName = fileName; Data = LoadData(); } public string FileName { get; } public string Data { get; set; } private string LoadData() { using (Stream stream = TypeHelper.GetManifestResourceStream(typeof(ConfigurationFile), "ImageMagick.Resources.Xml", FileName)) { using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } } }``` Patch delegates.xml for non Windows platform.
```c# // Copyright 2013-2021 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (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.imagemagick.org/script/license.php // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. using System.IO; namespace ImageMagick.Configuration { internal sealed class ConfigurationFile : IConfigurationFile { public ConfigurationFile(string fileName) { FileName = fileName; Data = LoadData(); } public string FileName { get; } public string Data { get; set; } private string LoadData() { using (Stream stream = TypeHelper.GetManifestResourceStream(typeof(ConfigurationFile), "ImageMagick.Resources.Xml", FileName)) { using (var reader = new StreamReader(stream)) { var data = reader.ReadToEnd(); data = UpdateDelegatesXml(data); return data; } } } private string UpdateDelegatesXml(string data) { if (OperatingSystem.IsWindows || FileName != "delegates.xml") return data; return data.Replace("@PSDelegate@", "gs"); } } }```
29cd827d-ac4f-4247-928c-5956f6e9c1f6
{ "language": "C#" }
```c# #region using System.Collections.Generic; #endregion namespace Snooze { public static class ResourceFormatters { static readonly IList<IResourceFormatter> _formatters = new List<IResourceFormatter>(); static ResourceFormatters() { // The order of formatters matters. // Browsers like Chrome will ask for "text/xml, application/xhtml+xml, ..." // But we don't want to use the XML formatter by default // - which would happen since "text/xml" appears first in the list. // So we add an explicitly typed ViewFormatter first. _formatters.Add(new ViewFormatter("application/xhtml+xml")); _formatters.Add(new ViewFormatter("*/*")); // similar reason for this. _formatters.Add(new JsonFormatter()); _formatters.Add(new XmlFormatter()); _formatters.Add(new ViewFormatter()); _formatters.Add(new StringFormatter()); _formatters.Add(new ByteArrayFormatter()); } public static IList<IResourceFormatter> Formatters { get { return _formatters; } } } }``` Add text/html as first content type, should possible detect IE..
```c# #region using System.Collections.Generic; #endregion namespace Snooze { public static class ResourceFormatters { static readonly IList<IResourceFormatter> _formatters = new List<IResourceFormatter>(); static ResourceFormatters() { // The order of formatters matters. // Browsers like Chrome will ask for "text/xml, application/xhtml+xml, ..." // But we don't want to use the XML formatter by default // - which would happen since "text/xml" appears first in the list. // So we add an explicitly typed ViewFormatter first. _formatters.Add(new ViewFormatter("text/html")); _formatters.Add(new ViewFormatter("application/xhtml+xml")); _formatters.Add(new ViewFormatter("*/*")); // similar reason for this. _formatters.Add(new JsonFormatter()); _formatters.Add(new XmlFormatter()); _formatters.Add(new ViewFormatter()); _formatters.Add(new StringFormatter()); _formatters.Add(new ByteArrayFormatter()); } public static IList<IResourceFormatter> Formatters { get { return _formatters; } } } }```
252611bd-80a0-4007-a0c4-1850f56e42b6
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Griddly.Mvc { public class GriddlyContext { public string Name { get; set; } public bool IsDefaultSkipped { get; set; } public bool IsDeepLink { get; set; } public GriddlyFilterCookieData CookieData { get; set; } public string CookieName => "gf_" + Name; public Dictionary<string, object> Defaults { get; set; } = new Dictionary<string, object>(); public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>(); public int PageNumber { get; set; } public int PageSize { get; set; } public GriddlyExportFormat? ExportFormat { get; set; } public SortField[] SortFields { get; set; } } public class GriddlyFilterCookieData { public Dictionary<string, string[]> Values { get; set; } public SortField[] SortFields { get; set; } } } ``` Make griddly defaults and parameters case insensitive
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Griddly.Mvc { public class GriddlyContext { public string Name { get; set; } public bool IsDefaultSkipped { get; set; } public bool IsDeepLink { get; set; } public GriddlyFilterCookieData CookieData { get; set; } public string CookieName => "gf_" + Name; public Dictionary<string, object> Defaults { get; set; } = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); public int PageNumber { get; set; } public int PageSize { get; set; } public GriddlyExportFormat? ExportFormat { get; set; } public SortField[] SortFields { get; set; } } public class GriddlyFilterCookieData { public Dictionary<string, string[]> Values { get; set; } public SortField[] SortFields { get; set; } } } ```
2452bc46-ef8a-47a1-ab3a-53ae0d4ddddb
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SlackAPI { [RequestPath("conversations.open")] public class ConversationsOpenResponse : Response { public string no_op; public string already_open; public Channel channel; } } ``` Add field for error responses
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SlackAPI { [RequestPath("conversations.open")] public class ConversationsOpenResponse : Response { public string no_op; public string already_open; public Channel channel; public string error; } ```
dda9f15f-1338-47cd-b687-94ac27863677
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CefSharp.Wpf.Example.Handlers { public class MenuHandler : IMenuHandler { public bool OnBeforeContextMenu(IWebBrowser browser, IContextMenuParams parameters) { Console.WriteLine("Context menu opened"); Console.WriteLine(parameters.MisspelledWord); return true; } } } ``` Add license disclaimer Cleanup formatting
```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; namespace CefSharp.Wpf.Example.Handlers { public class MenuHandler : IMenuHandler { public bool OnBeforeContextMenu(IWebBrowser browser, IContextMenuParams parameters) { Console.WriteLine("Context menu opened"); Console.WriteLine(parameters.MisspelledWord); return true; } } } ```
14af7759-9b94-41a0-8ec2-794880d2575a
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Fatec.Treinamento.Model.DTO { public class DetalhesCurso { public int Id { get; set; } public string Nome { get; set; } public string Assunto { get; set; } public string Autor { get; set; } public DateTime DataCriacao { get; set; } public int Classificacao { get; set; } } } ``` Add property 'Descricao' to class 'DetalheCurso'
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Fatec.Treinamento.Model.DTO { public class DetalhesCurso { public int Id { get; set; } public string Nome { get; set; } public string Assunto { get; set; } public string Autor { get; set; } public DateTime DataCriacao { get; set; } public int Classificacao { get; set; } //public string Descricao { get; set; } } } ```
c0b8c49f-abbf-4576-968a-3c724abc32ee
{ "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> </address>``` Add Peter Parker 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> </address>```
53f323ae-7c38-4618-bb81-a36176a8e99d
{ "language": "C#" }
```c# // // Image.cs // // Author: // Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com> // // Copyright (c) 2015 Benito Palacios Sánchez (c) 2015 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; namespace Deblocus.Entities { public class Image { private string name; public Image() { Name = DefaultName; } public static string DefaultName { get { return "No Title"; } } public virtual int Id { get; protected set; } public virtual byte[] Data { get; set; } public virtual string Name { get { return name; } set { name = string.IsNullOrEmpty(value) ? DefaultName : value; } } public virtual string Description { get; set; } } } ``` Fix default name for images
```c# // // Image.cs // // Author: // Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com> // // Copyright (c) 2015 Benito Palacios Sánchez (c) 2015 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; namespace Deblocus.Entities { public class Image { private string name; public Image() { Name = DefaultName; } public static string DefaultName { get { return "No Name"; } } public virtual int Id { get; protected set; } public virtual byte[] Data { get; set; } public virtual string Name { get { return name; } set { name = string.IsNullOrEmpty(value) ? DefaultName : value; } } public virtual string Description { get; set; } } } ```
3af90e00-bf71-4241-b77b-561bbc2e15f7
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace AppStudio.Uwp.Html { public sealed class HtmlText : HtmlFragment { public string Content { get; set; } public HtmlText() { Name = "text"; } public HtmlText(string doc, int startIndex, int endIndex) : this() { if (!string.IsNullOrEmpty(doc) && endIndex - startIndex > 0) { Content = WebUtility.HtmlDecode(doc.Substring(startIndex, endIndex - startIndex)); } } public override string ToString() { return Content; } internal static HtmlText Create(string doc, HtmlTag startTag, HtmlTag endTag) { var startIndex = 0; if (startTag != null) { startIndex = startTag.StartIndex + startTag.Length; } var endIndex = doc.Length; if (endTag != null) { endIndex = endTag.StartIndex; } var text = new HtmlText(doc, startIndex, endIndex); if (text != null && !string.IsNullOrEmpty(text.Content)) { return text; } return null; } } } ``` Fix html enconded characters in plain text
```c# using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace AppStudio.Uwp.Html { public sealed class HtmlText : HtmlFragment { private string _content; public string Content { get { return _content; } set { _content = WebUtility.HtmlDecode(value); } } public HtmlText() { Name = "text"; } public HtmlText(string doc, int startIndex, int endIndex) : this() { if (!string.IsNullOrEmpty(doc) && endIndex - startIndex > 0) { Content = doc.Substring(startIndex, endIndex - startIndex); } } public override string ToString() { return Content; } internal static HtmlText Create(string doc, HtmlTag startTag, HtmlTag endTag) { var startIndex = 0; if (startTag != null) { startIndex = startTag.StartIndex + startTag.Length; } var endIndex = doc.Length; if (endTag != null) { endIndex = endTag.StartIndex; } var text = new HtmlText(doc, startIndex, endIndex); if (text != null && !string.IsNullOrEmpty(text.Content)) { return text; } return null; } } } ```
8b187646-cd79-4d39-aca0-e564dedcc5cc
{ "language": "C#" }
```c# namespace Halcyon.HAL { public interface IHALModelConfig { string LinkBase { get; } bool ForceHAL { get; } } }``` Allow model config to be modified
```c# namespace Halcyon.HAL { public interface IHALModelConfig { string LinkBase { get; set; } bool ForceHAL { get; set; } } }```
9002a3e9-d66f-4f17-9fc8-342055bed131
{ "language": "C#" }
```c# using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; namespace LoveSeat { public interface IObjectSerializer<T> { T Deserialize(string json); string Serialize(object obj); } public class ObjectSerializer<T> : IObjectSerializer<T> { protected readonly JsonSerializerSettings settings; public ObjectSerializer() { settings = new JsonSerializerSettings(); var converters = new List<JsonConverter> { new IsoDateTimeConverter() }; settings.Converters = converters; settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); settings.NullValueHandling = NullValueHandling.Ignore; } public virtual T Deserialize(string json) { return JsonConvert.DeserializeObject<T>(json.Replace("_id", "id").Replace("_rev", "rev"), settings); } public virtual string Serialize(object obj) { return JsonConvert.SerializeObject(obj, Formatting.Indented, settings).Replace("id", "_id").Replace("rev", "_rev"); } } }``` Change the behavior of the object serializer so that objects are initialized with values instead of Nulls
```c# using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; namespace LoveSeat { public interface IObjectSerializer<T> { T Deserialize(string json); string Serialize(object obj); } public class ObjectSerializer<T> : IObjectSerializer<T> { protected readonly JsonSerializerSettings settings; public ObjectSerializer() { settings = new JsonSerializerSettings(); var converters = new List<JsonConverter> { new IsoDateTimeConverter() }; settings.Converters = converters; settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); settings.NullValueHandling = NullValueHandling.Include; } public virtual T Deserialize(string json) { return JsonConvert.DeserializeObject<T>(json.Replace("_id", "id").Replace("_rev", "rev"), settings); } public virtual string Serialize(object obj) { return JsonConvert.SerializeObject(obj, Formatting.Indented, settings).Replace("id", "_id").Replace("rev", "_rev"); } } }```
b3dbbba3-5097-436b-8ddb-b59bf9cf3afb
{ "language": "C#" }
```c# using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using VasysRomanNumeralsKata; namespace VasysRomanNumeralsKataTest { [TestClass] public class ToRomanNumeralsTest { [TestMethod] public void WhenRomanNumeralExtensionIsPassedTenItReturnsX() { int ten = 10; Assert.IsTrue(ten.ToRomanNumeral() == "X"); } [TestMethod] public void WhenRomanNumeralExtensionIsPassedNumbersDivisibleByOneHundredItReturnsARomanNumeral() { int oneThousand = 1000; Assert.IsTrue(oneThousand.ToRomanNumeral() == "M"); int nineHundred = 900; Assert.IsTrue(nineHundred.ToRomanNumeral() == "CM"); int fiveHundred = 500; Assert.IsTrue(fiveHundred.ToRomanNumeral() == "D"); int fourHundred = 400; Assert.IsTrue(fourHundred.ToRomanNumeral() == "CD"); int oneHundred = 100; Assert.IsTrue(oneHundred.ToRomanNumeral() == "C"); int twoHundred = 200; Assert.IsTrue(twoHundred.ToRomanNumeral() == "CC"); int threeHundred = 300; Assert.IsTrue(threeHundred.ToRomanNumeral() == "CCC"); } } } ``` Add test for 2000 (MM) - this should have been done before adding loop for M.
```c# using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using VasysRomanNumeralsKata; namespace VasysRomanNumeralsKataTest { [TestClass] public class ToRomanNumeralsTest { [TestMethod] public void WhenRomanNumeralExtensionIsPassedTenItReturnsX() { int ten = 10; Assert.IsTrue(ten.ToRomanNumeral() == "X"); } [TestMethod] public void WhenRomanNumeralExtensionIsPassedNumbersDivisibleByOneHundredItReturnsARomanNumeral() { int oneThousand = 1000; Assert.IsTrue(oneThousand.ToRomanNumeral() == "M"); int nineHundred = 900; Assert.IsTrue(nineHundred.ToRomanNumeral() == "CM"); int fiveHundred = 500; Assert.IsTrue(fiveHundred.ToRomanNumeral() == "D"); int fourHundred = 400; Assert.IsTrue(fourHundred.ToRomanNumeral() == "CD"); int oneHundred = 100; Assert.IsTrue(oneHundred.ToRomanNumeral() == "C"); int twoHundred = 200; Assert.IsTrue(twoHundred.ToRomanNumeral() == "CC"); int threeHundred = 300; Assert.IsTrue(threeHundred.ToRomanNumeral() == "CCC"); int twoThousand = 2000; Assert.IsTrue(twoThousand.ToRomanNumeral() == "MM"); } } } ```
1eef1d80-79ae-4d9c-8f25-74dd04402fd7
{ "language": "C#" }
```c# using System.Web.Mvc; using System.Web.Routing; using SFA.DAS.EAS.Account.Api.Client; using SFA.DAS.EAS.Account.Api.Types; namespace SFA.DAS.EmployerFinance.Web.Filters { public class LevyEmployerTypeOnly : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { var hashedAccountId = filterContext.ActionParameters["HashedAccountId"].ToString(); var accountApi = DependencyResolver.Current.GetService<IAccountApiClient>(); var account = accountApi.GetAccount(hashedAccountId).Result; if (account.ApprenticeshipEmployerType == "1") { base.OnActionExecuting(filterContext); } else { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary( new { controller = "AccessDenied", action = "Index", })); } } } }``` Handle failed Api call within Action Filter
```c# using System; using System.Web.Mvc; using System.Web.Routing; using SFA.DAS.EAS.Account.Api.Client; using SFA.DAS.EmployerFinance.Web.Helpers; namespace SFA.DAS.EmployerFinance.Web.Filters { public class LevyEmployerTypeOnly : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { try { var hashedAccountId = filterContext.ActionParameters["HashedAccountId"].ToString(); var accountApi = DependencyResolver.Current.GetService<IAccountApiClient>(); var task = accountApi.GetAccount(hashedAccountId); task.RunSynchronously(); var account = task.Result; if (account.ApprenticeshipEmployerType == "1") { base.OnActionExecuting(filterContext); } else { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary( new { controller = ControllerConstants.AccessDeniedControllerName, action = "Index", })); } } catch (Exception ex) { filterContext.Result = new ViewResult { ViewName = ControllerConstants.BadRequestViewName }; } } } }```
a138439c-9537-43c9-8ede-0f8745e23d23
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Globalization; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; namespace GogoKit.Http { public class UserAgentHandler : DelegatingHandler { private readonly IReadOnlyList<ProductInfoHeaderValue> _userAgentHeaderValues; public UserAgentHandler(ProductHeaderValue product) { Requires.ArgumentNotNull(product, nameof(product)); _userAgentHeaderValues = GetUserAgentHeaderValues(product); } private IReadOnlyList<ProductInfoHeaderValue> GetUserAgentHeaderValues(ProductHeaderValue product) { return new List<ProductInfoHeaderValue> { new ProductInfoHeaderValue(product), //new ProductInfoHeaderValue($"({CultureInfo.CurrentCulture.Name}; GogoKit {AssemblyVersionInformation.Version})") }; } protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { foreach (var product in _userAgentHeaderValues) { request.Headers.UserAgent.Add(product); } return base.SendAsync(request, cancellationToken); } } } ``` Include GogoKit version in User-Agent header
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Threading; using System.Threading.Tasks; namespace GogoKit.Http { public class UserAgentHandler : DelegatingHandler { private static readonly ProductInfoHeaderValue GogoKitVersionHeaderValue = new ProductInfoHeaderValue( "GogoKit", FileVersionInfo.GetVersionInfo(typeof(UserAgentHandler).Assembly.Location).ProductVersion); private readonly IReadOnlyList<ProductInfoHeaderValue> _userAgentHeaderValues; public UserAgentHandler(ProductHeaderValue product) { Requires.ArgumentNotNull(product, nameof(product)); _userAgentHeaderValues = GetUserAgentHeaderValues(product); } private IReadOnlyList<ProductInfoHeaderValue> GetUserAgentHeaderValues(ProductHeaderValue product) { return new List<ProductInfoHeaderValue> { new ProductInfoHeaderValue(product), GogoKitVersionHeaderValue }; } protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { foreach (var product in _userAgentHeaderValues) { request.Headers.UserAgent.Add(product); } return base.SendAsync(request, cancellationToken); } } } ```
4701d1c2-bc27-499e-be2c-9d8301ba3b05
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to) { foreach (var instruction in instructions) { var method = instruction.operand as MethodBase; if (method == from) instruction.operand = to; yield return instruction; } } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } // more added soon } }``` Make MethodReplacer change opcode to CALL as default
```c# using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to, OpCode? callOpcode = null) { foreach (var instruction in instructions) { var method = instruction.operand as MethodBase; if (method == from) { instruction.opcode = callOpcode ?? OpCodes.Call; instruction.operand = to; } yield return instruction; } } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } // more added soon } }```
09fcba79-0c0c-4c55-b935-ab88fa88a679
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FluentValidation; using PlanetWars.Shared; namespace PlanetWars.Validators { public class LogonRequestValidator : AbstractValidator<LogonRequest> { public LogonRequestValidator() { RuleFor(logon => logon.AgentName) .NotEmpty().WithMessage("Please use a non empty agent name, logon failed") .Length(1, 20).WithMessage("Please use an agent name between 1-20 characters, logon failed"); RuleFor(logon => logon.MapGeneration) .Must(x => x == MapGenerationOption.Basic || x == MapGenerationOption.Random).WithMessage("Please use a valid Map Generation Option"); } } }``` Update agent name to only allow 18 characters so that it looks good on the screen
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FluentValidation; using PlanetWars.Shared; namespace PlanetWars.Validators { public class LogonRequestValidator : AbstractValidator<LogonRequest> { public LogonRequestValidator() { RuleFor(logon => logon.AgentName) .NotEmpty().WithMessage("Please use a non empty agent name, logon failed") .Length(1, 18).WithMessage("Please use an agent name between 1-18 characters, logon failed"); RuleFor(logon => logon.MapGeneration) .Must(x => x == MapGenerationOption.Basic || x == MapGenerationOption.Random).WithMessage("Please use a valid Map Generation Option"); } } }```
e347d303-0a90-4f36-9aac-b18fdcb86667
{ "language": "C#" }
```c# using System; using engine.core; namespace engine.rules { public class PercentageDiscount : Rule { private readonly string m_ApplicableItemName; private readonly int m_Percentage; public PercentageDiscount(string applicableItemName, int percentage) { m_ApplicableItemName = applicableItemName; m_Percentage = percentage; } public override Basket Apply(Basket basket) { var discountedBasket = new Basket(); foreach (var item in basket) { discountedBasket.Add(item); if (item.Name.Equals(m_ApplicableItemName) && !item.UsedInOffer) { var discountToApply = -(int) Math.Ceiling(item.Price * ((double) m_Percentage / 100)); discountedBasket.Add(string.Format("{0}:{1}% discount", m_ApplicableItemName, m_Percentage), discountToApply); } } return discountedBasket; } } }``` Change this to a double so that we don't have to always cast.
```c# using System; using engine.core; namespace engine.rules { public class PercentageDiscount : Rule { private readonly string m_ApplicableItemName; private readonly double m_Percentage; public PercentageDiscount(string applicableItemName, int percentage) { m_ApplicableItemName = applicableItemName; m_Percentage = percentage; } public override Basket Apply(Basket basket) { var discountedBasket = new Basket(); foreach (var item in basket) { discountedBasket.Add(item); if (item.Name.Equals(m_ApplicableItemName) && !item.UsedInOffer) { var discountToApply = -(int) Math.Ceiling(item.Price * (m_Percentage / 100)); discountedBasket.Add(string.Format("{0}:{1}% discount", m_ApplicableItemName, m_Percentage), discountToApply); } } return discountedBasket; } } }```
397e5db5-6bf8-4133-ba4b-718e2c591074
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Threading; namespace Ensconce.Console { /// <summary> /// Retry logic applied from this Stack Overflow thread /// http://stackoverflow.com/questions/1563191/c-sharp-cleanest-way-to-write-retry-logic /// </summary> public static class Retry { public static void Do(Action action, TimeSpan retryInterval, int retryCount = 3) { Do<object>(() => { action(); return null; }, retryInterval, retryCount); } public static T Do<T>(Func<T> action, TimeSpan retryInterval, int retryCount = 3) { var exceptions = new List<Exception>(); for (var retry = 0; retry < retryCount; retry++) { try { return action(); } catch (Exception ex) { System.Console.Out.WriteLine("Something went wrong, but we're going to try again..."); System.Console.Out.WriteLine(ex.Message); exceptions.Add(ex); Thread.Sleep(retryInterval); } } throw new AggregateException(exceptions); } } } ``` Improve logging in retry logic & increase to 5 tries
```c# using System; using System.Collections.Generic; using System.Threading; namespace Ensconce.Console { /// <summary> /// Retry logic applied from this Stack Overflow thread /// http://stackoverflow.com/questions/1563191/c-sharp-cleanest-way-to-write-retry-logic /// </summary> public static class Retry { private static readonly int retryCount = 5; public static void Do(Action action, TimeSpan retryInterval) { Do<object>(() => { action(); return null; }, retryInterval); } public static T Do<T>(Func<T> action, TimeSpan retryInterval) { var exceptions = new List<Exception>(); for (var retry = 0; retry < retryCount; retry++) { try { return action(); } catch (Exception ex) when (retry + 1 < retryCount) { System.Console.Out.WriteLine($"Something went wrong on attempt {retry + 1} of {retryCount}, but we're going to try again in {retryInterval.TotalMilliseconds}ms..."); exceptions.Add(ex); Thread.Sleep(retryInterval); } catch (Exception ex) { exceptions.Add(ex); System.Console.Out.WriteLine($"Something went wrong on attempt {retry + 1} of {retryCount}, throwing all {exceptions.Count} exceptions..."); } } throw new AggregateException(exceptions); } } } ```
edd1fd26-cfa7-464c-a22c-8b395e73a20c
{ "language": "C#" }
```c# using AxoCover.Models.Extensions; using AxoCover.Properties; using System; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; namespace AxoCover.Models { public abstract class TelemetryManager : ITelemetryManager { protected IEditorContext _editorContext; public bool IsTelemetryEnabled { get { return Settings.Default.IsTelemetryEnabled; } set { Settings.Default.IsTelemetryEnabled = value; } } public TelemetryManager(IEditorContext editorContext) { _editorContext = editorContext; Application.Current.DispatcherUnhandledException += OnDispatcherUnhandledException; } private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { var description = e.Exception.GetDescription(); if (description.Contains(nameof(AxoCover))) { _editorContext.WriteToLog(Resources.ExceptionEncountered); _editorContext.WriteToLog(description); UploadExceptionAsync(e.Exception); e.Handled = true; } } public abstract Task<bool> UploadExceptionAsync(Exception exception); } } ``` Make telemetry break execution if debugger is attached instead of pushing report
```c# using AxoCover.Models.Extensions; using AxoCover.Properties; using System; using System.Diagnostics; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; namespace AxoCover.Models { public abstract class TelemetryManager : ITelemetryManager { protected IEditorContext _editorContext; public bool IsTelemetryEnabled { get { return Settings.Default.IsTelemetryEnabled; } set { Settings.Default.IsTelemetryEnabled = value; } } public TelemetryManager(IEditorContext editorContext) { _editorContext = editorContext; Application.Current.DispatcherUnhandledException += OnDispatcherUnhandledException; } private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { var description = e.Exception.GetDescription(); if (description.Contains(nameof(AxoCover))) { _editorContext.WriteToLog(Resources.ExceptionEncountered); _editorContext.WriteToLog(description); if (Debugger.IsAttached) { Debugger.Break(); } else { UploadExceptionAsync(e.Exception); } e.Handled = true; } } public abstract Task<bool> UploadExceptionAsync(Exception exception); } } ```
80c9dda8-c318-4f91-9f63-a2a47c0b1f63
{ "language": "C#" }
```c# using MultiMiner.Engine; using MultiMiner.Utility.Serialization; using System.Collections.Generic; using System.IO; namespace MultiMiner.Win.Data.Configuration { public class NetworkDevices { public class NetworkDevice { public string IPAddress { get; set; } public int Port { get; set; } } public List<NetworkDevice> Devices { get; set; } private static string NetworkDevicesConfigurationFileName() { return Path.Combine(ApplicationPaths.AppDataPath(), "NetworkDevicesConfiguration.xml"); } public void SaveNetworkDevicesConfiguration() { ConfigurationReaderWriter.WriteConfiguration(Devices, NetworkDevicesConfigurationFileName()); } public void LoadNetworkDevicesConfiguration() { Devices = ConfigurationReaderWriter.ReadConfiguration<List<NetworkDevice>>(NetworkDevicesConfigurationFileName()); } } } ``` Fix a null ref error submitting MobileMiner stats without Network Devices
```c# using MultiMiner.Engine; using MultiMiner.Utility.Serialization; using System.Collections.Generic; using System.IO; namespace MultiMiner.Win.Data.Configuration { public class NetworkDevices { public class NetworkDevice { public string IPAddress { get; set; } public int Port { get; set; } } public List<NetworkDevice> Devices { get; set; } public NetworkDevices() { //set a default - null ref errors if submitting MobileMiner stats before scan is completed Devices = new List<NetworkDevice>(); } private static string NetworkDevicesConfigurationFileName() { return Path.Combine(ApplicationPaths.AppDataPath(), "NetworkDevicesConfiguration.xml"); } public void SaveNetworkDevicesConfiguration() { ConfigurationReaderWriter.WriteConfiguration(Devices, NetworkDevicesConfigurationFileName()); } public void LoadNetworkDevicesConfiguration() { Devices = ConfigurationReaderWriter.ReadConfiguration<List<NetworkDevice>>(NetworkDevicesConfigurationFileName()); } } } ```
ac857ad2-7c3b-4282-8ced-5637127b1b36
{ "language": "C#" }
```c# <!DOCTYPE html> <html lang="en-gb"> <head> <title>@SettingHelper.Get("Website Name"): @ViewBag.Title</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" /> <meta name="description" content="@SettingHelper.Get("Description Meta Tag")"> @RenderSection("Styles", false) @Styles.Render("~/Resources/CSS/Bootstrap") @Styles.Render("~/Resources/CSS/FontAwesome") @Styles.Render("~/Resources/CSS/Administration/Framework") @Styles.Render("~/Resources/CSS/PageBuilder/Framework") @Styles.Render("~/Resources/CSS/Framework") @Scripts.Render("~/Resources/JavaScript/JQuery") @Scripts.Render("~/Resources/JavaScript/JQueryUI") @RenderSection("HEADScripts", false) @Html.Partial("_Analytics") </head> <body> @Html.Partial("_NavBar") @Html.Partial("_Administration") @RenderBody() @if (UserHelper.IsAdmin) { @Styles.Render("~/Resources/CSS/Bootstrap/Tour") @Styles.Render("~/Resources/CSS/PageBuilder/Framework/Administration") } <link href="@Url.Action("Render", "Theme", new { area = "Builder" })" rel="stylesheet" type="text/css" /> @Html.Partial("_DOMScripts") @RenderSection("DOMScripts", false) </body> </html>``` Change Order of Loading Styles
```c# <!DOCTYPE html> <html lang="en-gb"> <head> <title>@SettingHelper.Get("Website Name"): @ViewBag.Title</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" /> <meta name="description" content="@SettingHelper.Get("Description Meta Tag")"> @RenderSection("Styles", false) @Styles.Render("~/Resources/CSS/Bootstrap") @Styles.Render("~/Resources/CSS/FontAwesome") @Styles.Render("~/Resources/CSS/Administration/Framework") @Styles.Render("~/Resources/CSS/PageBuilder/Framework") @Styles.Render("~/Resources/CSS/Framework") @if (UserHelper.IsAdmin) { @Styles.Render("~/Resources/CSS/Bootstrap/Tour") @Styles.Render("~/Resources/CSS/PageBuilder/Framework/Administration") } <link href="@Url.Action("Render", "Theme", new { area = "Builder" })" rel="stylesheet" type="text/css" /> @Scripts.Render("~/Resources/JavaScript/JQuery") @Scripts.Render("~/Resources/JavaScript/JQueryUI") @RenderSection("HEADScripts", false) @Html.Partial("_Analytics") </head> <body> @Html.Partial("_NavBar") @Html.Partial("_Administration") @RenderBody() @Html.Partial("_DOMScripts") @RenderSection("DOMScripts", false) </body> </html>```
eb335412-b243-45a8-91b7-6358f6ebbcf7
{ "language": "C#" }
```c# using static MyOwnSearchEngine.HtmlFactory; namespace MyOwnSearchEngine { public class Hex : IProcessor { public string GetResult(Query query) { var integer = query.TryGetStructure<Integer>(); if (integer != null) { return GetResult(integer.Value); } var separatedList = query.TryGetStructure<SeparatedList>(); if (separatedList != null && separatedList.Count >= 2) { var number = separatedList.TryGetStructure<Integer>(0); if (number != null) { var keyword1 = separatedList.TryGetStructure<Keyword>(1); if (keyword1 != null) { if (keyword1 == "hex" && separatedList.Count == 2) { return GetResult(number.Value); } if (separatedList.Count == 3 && (keyword1 == "in" || keyword1 == "to") && separatedList.TryGetStructure<Keyword>(2) == "hex") { return GetResult(number.Value); } } } } return null; } private string GetResult(int value) { return Div(Escape($"{value} = 0x{value.ToString("X")}")); } } } ``` Allow syntax like "hex 56"
```c# using static MyOwnSearchEngine.HtmlFactory; namespace MyOwnSearchEngine { public class Hex : IProcessor { public string GetResult(Query query) { var integer = query.TryGetStructure<Integer>(); if (integer != null) { return GetResult(integer.Value); } var separatedList = query.TryGetStructure<SeparatedList>(); if (separatedList != null && separatedList.Count >= 2) { var number = separatedList.TryGetStructure<Integer>(0); if (number != null) { var keyword1 = separatedList.TryGetStructure<Keyword>(1); if (keyword1 != null) { if (keyword1 == "hex" && separatedList.Count == 2) { return GetResult(number.Value); } if (separatedList.Count == 3 && (keyword1 == "in" || keyword1 == "to") && separatedList.TryGetStructure<Keyword>(2) == "hex") { return GetResult(number.Value); } } } else { number = separatedList.TryGetStructure<Integer>(1); var keyword1 = separatedList.TryGetStructure<Keyword>(0); if (number != null && keyword1 != null && keyword1 == "hex" && separatedList.Count == 2) { return GetResult(number.Value); } } } return null; } private string GetResult(int value) { return Div(Escape($"{value} = 0x{value.ToString("X")}")); } } } ```
38ac5339-7d68-48ac-8296-c57ad195aeb9
{ "language": "C#" }
```c# using System; using DesktopWidgets.Classes; namespace DesktopWidgets.Widgets.CountdownClock { public class Settings : WidgetClockSettingsBase { public DateTime EndDateTime { get; set; } = DateTime.Now; } }``` Change "Countdown" widget default "TimeFormat"
```c# using System; using DesktopWidgets.Classes; namespace DesktopWidgets.Widgets.CountdownClock { public class Settings : WidgetClockSettingsBase { public Settings() { TimeFormat = "dd:hh:mm:ss"; } public DateTime EndDateTime { get; set; } = DateTime.Now; } }```
1aaede98-6c8e-43f9-913a-b31a2e1aa373
{ "language": "C#" }
```c# public class Conditional : DecoratorTask { private ConditionalDelegate conditionalDelegate; public Conditional(string name, ConditionalDelegate conditionalDelegate) : base(name) { this.conditionalDelegate = conditionalDelegate; } public override ReturnCode Update() { var value = conditionalDelegate(); if (value) { return ReturnCode.Succeed; } else { return ReturnCode.Fail; } } } public delegate bool ConditionalDelegate();``` Change conditional from decorator to a task
```c# public class Conditional : Task { private ConditionalDelegate conditionalDelegate; public Conditional(string name, ConditionalDelegate conditionalDelegate) : base(name) { this.conditionalDelegate = conditionalDelegate; } public override ReturnCode Update() { var value = conditionalDelegate(); if (value) { return ReturnCode.Succeed; } else { return ReturnCode.Fail; } } } public delegate bool ConditionalDelegate();```
d5fcc9c9-3462-4392-a760-2771e205d390
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Text; namespace SharpConfig { public interface ITypeStringConverter { string ConvertToString(object value); object ConvertFromString(string value, Type hint); Type ConvertibleType { get; } } public abstract class TypeStringConverter<T> : ITypeStringConverter { public abstract string ConvertToString(object value); public abstract object ConvertFromString(string value, Type hint); public Type ConvertibleType { get { return typeof(T); } } } } ``` Add type string converter documentation.
```c# using System; using System.Collections.Generic; using System.Text; namespace SharpConfig { /// <summary> /// Defines a type-to-string and string-to-type converter /// that is used for the conversion of setting values. /// </summary> public interface ITypeStringConverter { /// <summary> /// Converts an object to its string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>The object's string representation.</returns> string ConvertToString(object value); /// <summary> /// Converts a string value to an object of this converter's type. /// </summary> /// <param name="value"></param> /// <param name="hint"> /// A type hint. This is used rarely, such as in the enum converter. /// The enum converter's official type is Enum, whereas the type hint /// represents the underlying enum type. /// This parameter can be safely ignored for custom converters. /// </param> /// <returns>The converted object.</returns> object ConvertFromString(string value, Type hint); /// <summary> /// The type that this converter is able to convert to and from a string. /// </summary> Type ConvertibleType { get; } } /// <summary> /// Represents a type-to-string and string-to-type converter /// that is used for the conversion of setting values. /// </summary> /// <typeparam name="T">The type that this converter is able to convert.</typeparam> public abstract class TypeStringConverter<T> : ITypeStringConverter { /// <summary> /// Converts an object to its string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>The object's string representation.</returns> public abstract string ConvertToString(object value); /// <summary> /// Converts a string value to an object of this converter's type. /// </summary> /// <param name="value"></param> /// <param name="hint"> /// A type hint. This is used rarely, such as in the enum converter. /// The enum converter's official type is Enum, whereas the type hint /// represents the underlying enum type. /// This parameter can be safely ignored for custom converters. /// </param> /// <returns>The converted object.</returns> public abstract object ConvertFromString(string value, Type hint); /// <summary> /// The type that this converter is able to convert to and from a string. /// </summary> public Type ConvertibleType { get { return typeof(T); } } } } ```
f5cb247d-5df8-4d95-9c80-8972ea4f3152
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Text; namespace Camunda.Api.Client.Identity { public class IdentityVerifiedUser { /// <summary> /// The id of the user /// </summary> public string AuthenticatedUser; /// <summary> /// Verification successful or not /// </summary> public bool IsAuthenticated; } } ``` Fix isAuthenticated -> authenticated to get it working - Camunda docs error
```c# using System; using System.Collections.Generic; using System.Text; namespace Camunda.Api.Client.Identity { public class IdentityVerifiedUser { /// <summary> /// The id of the user /// </summary> public string AuthenticatedUser; /// <summary> /// Verification successful or not /// </summary> public bool Authenticated; } } ```
9358d863-0b88-4b58-9592-68592c0d4fc0
{ "language": "C#" }
```c# 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; return type != null && type.Namespace == ns.ToString(); } } }``` Fix namespace function not using top level types
```c# 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(); } } }```
cc5af6e5-f5de-4ffc-a49d-aad8be76d434
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Text.RegularExpressions; using Rant.Stringes; using Rant.Stringes.Tokens; namespace Rant.Vocabulary { internal static class Dic2Lexer { private const RegexOptions DicRegexOptions = RegexOptions.Compiled; private static readonly LexerRules<DicTokenType> Rules; static Dic2Lexer() { Rules = new LexerRules<DicTokenType> { {new Regex(@"\#\s*(?<value>[^\r]*)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Directive, 2}, {new Regex(@"\|\s*(?<value>[^\r]*)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Property, 2}, {new Regex(@"\>\s*(?<value>[^\r]*)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Entry, 2}, {new Regex(@"\s+"), DicTokenType.Ignore} }; Rules.AddEndToken(DicTokenType.EOF); Rules.IgnoreRules.Add(DicTokenType.Ignore); } public static IEnumerable<Token<DicTokenType>> Tokenize(string data) { Token<DicTokenType> token; var reader = new StringeReader(data); while ((token = reader.ReadToken(Rules)).Identifier != DicTokenType.EOF) { yield return token; } } } internal enum DicTokenType { Directive, Entry, Property, Ignore, EOF } }``` Fix Dic2 lexer regexes to work properly on Linux
```c# using System.Collections.Generic; using System.Text.RegularExpressions; using Rant.Stringes; using Rant.Stringes.Tokens; namespace Rant.Vocabulary { internal static class Dic2Lexer { private const RegexOptions DicRegexOptions = RegexOptions.Compiled; private static readonly LexerRules<DicTokenType> Rules; static Dic2Lexer() { Rules = new LexerRules<DicTokenType> { {new Regex(@"\#\s*(?<value>.*?)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Directive, 2}, {new Regex(@"\|\s*(?<value>.*?)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Property, 2}, {new Regex(@"\>\s*(?<value>.*?)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Entry, 2}, {new Regex(@"\s+"), DicTokenType.Ignore} }; Rules.AddEndToken(DicTokenType.EOF); Rules.IgnoreRules.Add(DicTokenType.Ignore); } public static IEnumerable<Token<DicTokenType>> Tokenize(string data) { Token<DicTokenType> token; var reader = new StringeReader(data); while ((token = reader.ReadToken(Rules)).Identifier != DicTokenType.EOF) { yield return token; } } } internal enum DicTokenType { Directive, Entry, Property, Ignore, EOF } }```
9f67f922-4410-4df0-9ba4-29bd069ed6db
{ "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 NUnit.Framework; using osu.Framework.Testing; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; using osu.Game.Screens.Play.HUD; namespace osu.Game.Tests.Visual.Gameplay { public class TestSceneSkinnableScoreCounter : SkinnableTestScene { private IEnumerable<SkinnableScoreCounter> scoreCounters => CreatedDrawables.OfType<SkinnableScoreCounter>(); protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset(); [SetUpSteps] public void SetUpSteps() { AddStep("Create combo counters", () => SetContents(() => { var comboCounter = new SkinnableScoreCounter(); comboCounter.Current.Value = 1; return comboCounter; })); } [Test] public void TestScoreCounterIncrementing() { AddStep(@"Reset all", delegate { foreach (var s in scoreCounters) s.Current.Value = 0; }); AddStep(@"Hit! :D", delegate { foreach (var s in scoreCounters) s.Current.Value += 300; }); } } } ``` Add test coverage for score counter alignment
```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 NUnit.Framework; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Testing; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; using osu.Game.Screens.Play.HUD; namespace osu.Game.Tests.Visual.Gameplay { public class TestSceneSkinnableScoreCounter : SkinnableTestScene { private IEnumerable<SkinnableScoreCounter> scoreCounters => CreatedDrawables.OfType<SkinnableScoreCounter>(); protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset(); [SetUpSteps] public void SetUpSteps() { AddStep("Create combo counters", () => SetContents(() => { var comboCounter = new SkinnableScoreCounter(); comboCounter.Current.Value = 1; return comboCounter; })); } [Test] public void TestScoreCounterIncrementing() { AddStep(@"Reset all", delegate { foreach (var s in scoreCounters) s.Current.Value = 0; }); AddStep(@"Hit! :D", delegate { foreach (var s in scoreCounters) s.Current.Value += 300; }); } [Test] public void TestVeryLargeScore() { AddStep("set large score", () => scoreCounters.ForEach(counter => counter.Current.Value = 1_00_000_000)); } } } ```
5a29f057-e831-4951-af49-31704ec41227
{ "language": "C#" }
```c# // Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.AdventOfCode.Puzzles.Y2016 { using Xunit; /// <summary> /// A class containing tests for the <see cref="Day18"/> class. This class cannot be inherited. /// </summary> public static class Day18Tests { [Theory] [InlineData("..^^.", 3, 6)] [InlineData(".^^.^.^^^^", 10, 38)] public static void Y2016_Day18_FindSafeTileCount_Returns_Correct_Solution(string firstRowTiles, int rows, int expected) { // Act int actual = Day18.FindSafeTileCount(firstRowTiles, rows); // Assert Assert.Equal(expected, actual); } [Theory] [InlineData("40", 1987)] public static void Y2016_Day18_Solve_Returns_Correct_Solution(string rows, int expected) { // Arrange string[] args = new[] { rows }; // Act var puzzle = PuzzleTestHelpers.SolvePuzzle<Day18>(args); // Assert Assert.Equal(expected, puzzle.SafeTileCount); } } } ``` Add test for day 18 part 2
```c# // Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.AdventOfCode.Puzzles.Y2016 { using Xunit; /// <summary> /// A class containing tests for the <see cref="Day18"/> class. This class cannot be inherited. /// </summary> public static class Day18Tests { [Theory] [InlineData("..^^.", 3, 6)] [InlineData(".^^.^.^^^^", 10, 38)] public static void Y2016_Day18_FindSafeTileCount_Returns_Correct_Solution(string firstRowTiles, int rows, int expected) { // Act int actual = Day18.FindSafeTileCount(firstRowTiles, rows); // Assert Assert.Equal(expected, actual); } [Theory] [InlineData("40", 1987)] [InlineData("400000", 19984714)] public static void Y2016_Day18_Solve_Returns_Correct_Solution(string rows, int expected) { // Arrange string[] args = new[] { rows }; // Act var puzzle = PuzzleTestHelpers.SolvePuzzle<Day18>(args); // Assert Assert.Equal(expected, puzzle.SafeTileCount); } } } ```
2bbf8130-0e3b-4fa1-ad24-eb80b0f055fb
{ "language": "C#" }
```c# using System; using System.Linq; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Diploms.Core; using System.Collections.Generic; namespace Diploms.DataLayer { public static class DiplomContentSystemExtensions { public static void EnsureSeedData(this DiplomContext context) { if (context.AllMigrationsApplied()) { if (!context.Roles.Any()) { context.Roles.AddRange(Role.Admin, Role.Owner, Role.Student, Role.Teacher); context.SaveChanges(); } if(!context.Users.Any()) { context.Users.Add(new User{ Id = 1, Login = "admin", PasswordHash = @"WgHWgYQpzkpETS0VemCGE15u2LNPjTbtocMdxtqLll8=", Roles = new List<UserRole> { new UserRole { UserId = 1, RoleId = 1 } } }); } } } private static bool AllMigrationsApplied(this DiplomContext context) { var applied = context.GetService<IHistoryRepository>() .GetAppliedMigrations() .Select(m => m.MigrationId); var total = context.GetService<IMigrationsAssembly>() .Migrations .Select(m => m.Key); return !total.Except(applied).Any(); } } }``` Fix saving changes when seeding data
```c# using System; using System.Linq; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Diploms.Core; using System.Collections.Generic; namespace Diploms.DataLayer { public static class DiplomContentSystemExtensions { public static void EnsureSeedData(this DiplomContext context) { if (context.AllMigrationsApplied()) { if (!context.Roles.Any()) { context.Roles.AddRange(Role.Admin, Role.Owner, Role.Student, Role.Teacher); context.SaveChanges(); } if(!context.Users.Any()) { context.Users.Add(new User{ Id = 1, Login = "admin", PasswordHash = @"WgHWgYQpzkpETS0VemCGE15u2LNPjTbtocMdxtqLll8=", Roles = new List<UserRole> { new UserRole { UserId = 1, RoleId = 1 } } }); } context.SaveChanges(); } } private static bool AllMigrationsApplied(this DiplomContext context) { var applied = context.GetService<IHistoryRepository>() .GetAppliedMigrations() .Select(m => m.MigrationId); var total = context.GetService<IMigrationsAssembly>() .Migrations .Select(m => m.Key); return !total.Except(applied).Any(); } } }```
42df65e9-8bf1-42c9-8f6d-a75643754c35
{ "language": "C#" }
```c# #region using System.Linq; using System.Management; using UlteriusServer.TaskServer.Api.Models; using UlteriusServer.TaskServer.Api.Serialization; using vtortola.WebSockets; #endregion namespace UlteriusServer.TaskServer.Api.Controllers.Impl { internal class GpuController : ApiController { private readonly WebSocket client; private readonly Packets packet; private readonly ApiSerializator serializator = new ApiSerializator(); public GpuController(WebSocket client, Packets packet) { this.client = client; this.packet = packet; } public void GetGpuInformation() { var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_VideoController"); var gpus = (from ManagementBaseObject mo in searcher.Get() select new GpuInformation { Name = mo["Name"]?.ToString(), ScreenInfo = mo["VideoModeDescription"]?.ToString(), DriverVersion = mo["DriverVersion"]?.ToString(), RefreshRate = int.Parse(mo["CurrentRefreshRate"]?.ToString()), AdapterRam = mo["AdapterRAM"]?.ToString(), VideoArchitecture = int.Parse(mo["VideoArchitecture"]?.ToString()), VideoMemoryType = int.Parse(mo["VideoMemoryType"]?.ToString()), InstalledDisplayDrivers = mo["InstalledDisplayDrivers"]?.ToString()?.Split(','), AdapterCompatibility = mo["AdapterCompatibility"]?.ToString() }).ToList(); var data = new { gpus }; serializator.Serialize(client, packet.endpoint, packet.syncKey, data); } } }``` Set to 0 if null
```c# #region using System.Linq; using System.Management; using UlteriusServer.TaskServer.Api.Models; using UlteriusServer.TaskServer.Api.Serialization; using vtortola.WebSockets; #endregion namespace UlteriusServer.TaskServer.Api.Controllers.Impl { internal class GpuController : ApiController { private readonly WebSocket client; private readonly Packets packet; private readonly ApiSerializator serializator = new ApiSerializator(); public GpuController(WebSocket client, Packets packet) { this.client = client; this.packet = packet; } public void GetGpuInformation() { var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_VideoController"); var gpus = (from ManagementBaseObject mo in searcher.Get() select new GpuInformation { Name = mo["Name"]?.ToString(), ScreenInfo = mo["VideoModeDescription"]?.ToString(), DriverVersion = mo["DriverVersion"]?.ToString(), RefreshRate = int.Parse(mo["CurrentRefreshRate"]?.ToString() ?? "0"), AdapterRam = mo["AdapterRAM"]?.ToString(), VideoArchitecture = int.Parse(mo["VideoArchitecture"]?.ToString() ?? "0"), VideoMemoryType = int.Parse(mo["VideoMemoryType"]?.ToString() ?? "0"), InstalledDisplayDrivers = mo["InstalledDisplayDrivers"]?.ToString()?.Split(','), AdapterCompatibility = mo["AdapterCompatibility"]?.ToString() }).ToList(); var data = new { gpus }; serializator.Serialize(client, packet.endpoint, packet.syncKey, data); } } }```
d44d5e21-a0cd-4b18-a830-c9b8fb16dac6
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; public class PlateformerManager : MonoBehaviour { public float MoveSpeed; public float JumpForce; public float Gravity; public float TimerForDifficulty; float timeUntilEndGame; public static PlateformerManager Instance; void Awake () { PlateformerManager.Instance = this; } // Use this for initialization void Start () { this.timeUntilEndGame = Time.time + TimerForDifficulty; Physics2D.gravity = new Vector2(0f, this.Gravity); } // Update is called once per frame void Update () { if(Time.time > this.timeUntilEndGame) { if(GameObject.FindGameObjectWithTag("Player").GetComponent<PlateformerCharacter>().LockMove) { GameManager.Instance.LevelEnd(true); } else { GameManager.Instance.LevelEnd(false); } } } public float GetJumpForce () { return this.JumpForce; } public float GetMoveSpeed () { return this.MoveSpeed; } public float GetGravity () { return this.Gravity; } } ``` Update plateformer gravity at fixed update
```c# using UnityEngine; using System.Collections; public class PlateformerManager : MonoBehaviour { public float MoveSpeed; public float JumpForce; public float Gravity; public float TimerForDifficulty; float timeUntilEndGame; public static PlateformerManager Instance; void Awake () { PlateformerManager.Instance = this; } // Use this for initialization void Start () { this.timeUntilEndGame = Time.time + TimerForDifficulty; } // Update is called once per frame void Update () { if(Time.time > this.timeUntilEndGame) { if(GameObject.FindGameObjectWithTag("Player").GetComponent<PlateformerCharacter>().LockMove) { GameManager.Instance.LevelEnd(true); } else { GameManager.Instance.LevelEnd(false); } } } void FixedUpdate () { Physics2D.gravity = new Vector2(0f, this.Gravity); } public float GetJumpForce () { return this.JumpForce; } public float GetMoveSpeed () { return this.MoveSpeed; } public float GetGravity () { return this.Gravity; } } ```
1a4cc44a-ed4f-4587-a42f-156886c77a01
{ "language": "C#" }
```c# // Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System.Reflection; using System.Runtime.CompilerServices; //[assembly: AssemblyVersion("0.0.0.*")] [assembly: AssemblyTitle ("NDesk.DBus")] [assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")] [assembly: AssemblyCopyright ("Copyright (C) Alp Toker")] [assembly: AssemblyCompany ("NDesk")] [assembly: InternalsVisibleTo ("dbus-sharp-glib")] [assembly: InternalsVisibleTo ("dbus-monitor")] [assembly: InternalsVisibleTo ("dbus-daemon")] ``` Use the correct strong name for dbus-sharp-glib friend assembly
```c# // Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System.Reflection; using System.Runtime.CompilerServices; //[assembly: AssemblyVersion("0.0.0.*")] [assembly: AssemblyTitle ("NDesk.DBus")] [assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")] [assembly: AssemblyCopyright ("Copyright (C) Alp Toker")] [assembly: AssemblyCompany ("NDesk")] [assembly: InternalsVisibleTo ("NDesk.DBus.GLib")] [assembly: InternalsVisibleTo ("dbus-monitor")] [assembly: InternalsVisibleTo ("dbus-daemon")] ```
370c9c9d-468b-4585-bd70-18e1f2504ab5
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Security.Cryptography; using Jose; namespace Nexmo.Api { internal class Jwt { internal static string CreateToken(string appId, string privateKeyFile) { var tokenData = new byte[64]; var rng = RandomNumberGenerator.Create(); rng.GetBytes(tokenData); var jwtTokenId = Convert.ToBase64String(tokenData); var payload = new Dictionary<string, object> { { "iat", (long) (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds }, { "application_id", appId }, { "jti", jwtTokenId } }; var pemContents = File.ReadAllText(privateKeyFile); var rsa = PemParse.DecodePEMKey(pemContents); return JWT.Encode(payload, rsa, JwsAlgorithm.RS256); } } }``` Remove IO dependency; expect contents of private key and not path to key
```c# using System; using System.Collections.Generic; using System.Security.Cryptography; using Jose; namespace Nexmo.Api { internal class Jwt { internal static string CreateToken(string appId, string privateKey) { var tokenData = new byte[64]; var rng = RandomNumberGenerator.Create(); rng.GetBytes(tokenData); var jwtTokenId = Convert.ToBase64String(tokenData); var payload = new Dictionary<string, object> { { "iat", (long) (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds }, { "application_id", appId }, { "jti", jwtTokenId } }; var rsa = PemParse.DecodePEMKey(privateKey); return JWT.Encode(payload, rsa, JwsAlgorithm.RS256); } } }```
360cfbdd-07fb-4902-9f05-990ab198824c
{ "language": "C#" }
```c# using System; using System.Xml.Linq; namespace Buildalyzer.Construction { public class PackageReference : IPackageReference { public string Name { get; } public string Version { get; } internal PackageReference(XElement packageReferenceElement) { this.Name = packageReferenceElement.GetAttributeValue("Include"); this.Version = packageReferenceElement.GetAttributeValue("Version"); } } } ``` Add support for update property
```c# using System; using System.Xml.Linq; namespace Buildalyzer.Construction { public class PackageReference : IPackageReference { public string Name { get; } public string Version { get; } internal PackageReference(XElement packageReferenceElement) { this.Name = packageReferenceElement.GetAttributeValue("Include") ?? packageReferenceElement.GetAttributeValue("Update"); this.Version = packageReferenceElement.GetAttributeValue("Version"); } } } ```
a189cd91-1fa5-4be0-9b78-6b3a61aba3bc
{ "language": "C#" }
```c# using System; namespace GUtils.IO { public static class FileSizes { public const UInt64 B = 1024; public const UInt64 KiB = 1024 * B; public const UInt64 MiB = 1024 * KiB; public const UInt64 GiB = 1024 * MiB; public const UInt64 TiB = 1024 * GiB; public const UInt64 PiB = 1024 * TiB; private static readonly String[] _suffixes = new[] { "B", "KiB", "MiB", "GiB", "TiB", "PiB" }; public static String Format ( UInt64 Size ) { var i = ( Int32 ) Math.Round ( Math.Log ( Size, 1024 ) ); return $"{Size / ( Math.Pow ( B, i ) )} {_suffixes[i]}"; } } } ``` Use floor for better file sizes
```c# using System; namespace GUtils.IO { public static class FileSizes { public const UInt64 B = 1024; public const UInt64 KiB = 1024 * B; public const UInt64 MiB = 1024 * KiB; public const UInt64 GiB = 1024 * MiB; public const UInt64 TiB = 1024 * GiB; public const UInt64 PiB = 1024 * TiB; private static readonly String[] _suffixes = new[] { "B", "KiB", "MiB", "GiB", "TiB", "PiB" }; public static String Format ( UInt64 Size ) { var i = ( Int32 ) Math.Floor ( Math.Log ( Size, 1024 ) ); return $"{Size / ( Math.Pow ( B, i ) )} {_suffixes[i]}"; } } } ```
1908f02f-e061-4d41-b7d3-04782b0100e7
{ "language": "C#" }
```c# namespace Mapsui; public class MRect2 { public MPoint Max { get; } public MPoint Min { get; } public double MaxX => Max.X; public double MaxY => Max.Y; public double MinX => Min.X; public double MinY => Min.Y; public MPoint Centroid => new MPoint(Max.X - Min.X, Max.Y - Min.Y); public double Width => Max.X - MinX; public double Height => Max.Y - MinY; public double Bottom => Min.Y; public double Left => Min.X; public double Top => Max.Y; public double Right => Max.X; public MPoint TopLeft => new MPoint(Left, Top); public MPoint TopRight => new MPoint(Right, Top); public MPoint BottomLeft => new MPoint(Left, Bottom); public MPoint BottomRight => new MPoint(Right, Bottom); //IEnumerable<MPoint> Vertices { get; } //MRect Clone(); //bool Contains(MPoint? p); //bool Contains(MRect r); //bool Equals(MRect? other); //double GetArea(); //MRect Grow(double amount); //MRect Grow(double amountInX, double amountInY); //bool Intersects(MRect? box); //MRect Join(MRect? box); //MRect Multiply(double factor); //MQuad Rotate(double degrees); } ``` Add our own Vertices method
```c# using System.Collections.Generic; namespace Mapsui; public class MRect2 { public MPoint Max { get; } public MPoint Min { get; } public double MaxX => Max.X; public double MaxY => Max.Y; public double MinX => Min.X; public double MinY => Min.Y; public MPoint Centroid => new MPoint(Max.X - Min.X, Max.Y - Min.Y); public double Width => Max.X - MinX; public double Height => Max.Y - MinY; public double Bottom => Min.Y; public double Left => Min.X; public double Top => Max.Y; public double Right => Max.X; public MPoint TopLeft => new MPoint(Left, Top); public MPoint TopRight => new MPoint(Right, Top); public MPoint BottomLeft => new MPoint(Left, Bottom); public MPoint BottomRight => new MPoint(Right, Bottom); /// <summary> /// Returns the vertices in clockwise order from bottom left around to bottom right /// </summary> public IEnumerable<MPoint> Vertices { get { yield return BottomLeft; yield return TopLeft; yield return TopRight; yield return BottomRight; } } //MRect Clone(); //bool Contains(MPoint? p); //bool Contains(MRect r); //bool Equals(MRect? other); //double GetArea(); //MRect Grow(double amount); //MRect Grow(double amountInX, double amountInY); //bool Intersects(MRect? box); //MRect Join(MRect? box); //MRect Multiply(double factor); //MQuad Rotate(double degrees); } ```
997289a0-66a7-4f44-88d4-17367c910635
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using twitch_tv_viewer.Models; namespace twitch_tv_viewer.Services { public class TwitchChannelService : ITwitchChannelService { public async Task<string> PlayVideo(TwitchChannel channel, string quality) { var startInfo = new ProcessStartInfo { FileName = "livestreamer", Arguments = $"--http-query-param client_id=spyiu9jqdnfjtwv6l1xjk5zgt8qb91l twitch.tv/{channel.Name} {quality}", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true }; var process = new Process { StartInfo = startInfo }; process.Start(); return await process.StandardOutput.ReadToEndAsync(); } public async Task<string> PlayVideo(TwitchChannel twitchChannel) => await PlayVideo(twitchChannel, "source"); public void OpenChat(TwitchChannel channel) { Process.Start($"http://twitch.tv/{channel.Name}/chat?popout="); } } } ``` Use settings repository in twitch channel service
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using twitch_tv_viewer.Models; using twitch_tv_viewer.Repositories; namespace twitch_tv_viewer.Services { public class TwitchChannelService : ITwitchChannelService { public TwitchChannelService() { Settings = new SettingsRepository(); } public ISettingsRepository Settings { get; set; } public async Task<string> PlayVideo(TwitchChannel channel, string quality) { var startInfo = new ProcessStartInfo { FileName = "livestreamer", Arguments = $"--http-query-param client_id=spyiu9jqdnfjtwv6l1xjk5zgt8qb91l twitch.tv/{channel.Name} {quality}", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true }; var process = new Process { StartInfo = startInfo }; process.Start(); return await process.StandardOutput.ReadToEndAsync(); } public async Task<string> PlayVideo(TwitchChannel twitchChannel) => await PlayVideo(twitchChannel, Settings.Quality); public void OpenChat(TwitchChannel channel) { Process.Start($"http://twitch.tv/{channel.Name}/chat?popout="); } } } ```
52d1d1e4-8f98-4cd3-a326-1398f594febb
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using BatteryCommander.Web.Models; using MediatR; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace BatteryCommander.Web.Queries { public class GetSUTARequests : IRequest<IEnumerable<SUTA>> { [FromRoute] public int Unit { get; set; } // Search by Soldier, Status, Dates private class Handler : IRequestHandler<GetSUTARequests, IEnumerable<SUTA>> { private readonly Database db; public Handler(Database db) { this.db = db; } public async Task<IEnumerable<SUTA>> Handle(GetSUTARequests request, CancellationToken cancellationToken) { return await AsQueryable(db) .Where(suta => suta.Soldier.UnitId == request.Unit) .ToListAsync(cancellationToken); } } public static IQueryable<SUTA> AsQueryable(Database db) { return db .SUTAs .Include(suta => suta.Soldier) .ThenInclude(soldier => soldier.Unit) .Include(suta => suta.Supervisor) .Include(suta => suta.Events); } } } ``` Order by start date by default
```c# using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using BatteryCommander.Web.Models; using MediatR; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace BatteryCommander.Web.Queries { public class GetSUTARequests : IRequest<IEnumerable<SUTA>> { [FromRoute] public int Unit { get; set; } // Search by Soldier, Status, Dates private class Handler : IRequestHandler<GetSUTARequests, IEnumerable<SUTA>> { private readonly Database db; public Handler(Database db) { this.db = db; } public async Task<IEnumerable<SUTA>> Handle(GetSUTARequests request, CancellationToken cancellationToken) { return await AsQueryable(db) .Where(suta => suta.Soldier.UnitId == request.Unit) .OrderBy(suta => suta.StartDate) .ToListAsync(cancellationToken); } } public static IQueryable<SUTA> AsQueryable(Database db) { return db .SUTAs .Include(suta => suta.Soldier) .ThenInclude(soldier => soldier.Unit) .Include(suta => suta.Supervisor) .Include(suta => suta.Events); } } } ```
476b13b8-1760-46b7-8f8d-45c29f8d38f6
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using FizzBuzz.ConsoleApp; using TechTalk.SpecFlow; namespace FizzBuzz.Specification.AutomationLayer { [Binding] public class StepDefinitions { private int currentNumber; private string currentResult; [Given(@"the current number is '(.*)'")] public void GivenTheCurrentNumberIs(int currentNumber) { this.currentNumber = currentNumber; } [When(@"I print the number")] public void WhenIPrintTheNumber() { this.currentResult = new FizzBuzzer().Print(this.currentNumber); } [Then(@"the result is '(.*)'")] public void ThenTheResultIs(int p0) { ScenarioContext.Current.Pending(); } } } ``` Implement third step of automation layer
```c# using System; using FizzBuzz.ConsoleApp; using NFluent; using TechTalk.SpecFlow; namespace FizzBuzz.Specification.AutomationLayer { [Binding] public class StepDefinitions { private int currentNumber; private string currentResult; [Given(@"the current number is '(.*)'")] public void GivenTheCurrentNumberIs(int currentNumber) { this.currentNumber = currentNumber; } [When(@"I print the number")] public void WhenIPrintTheNumber() { this.currentResult = new FizzBuzzer().Print(this.currentNumber); } [Then(@"the result is '(.*)'")] public void ThenTheResultIs(string expectedResult) { Check.That(this.currentResult).IsEqualTo(expectedResult); } } } ```
54953ce1-207d-406e-ae84-2f0cc65d8b07
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; [SelectionBase] [DisallowMultipleComponent] public class Unit : MonoBehaviour { [SerializeField] string faction; [SerializeField] int maxHeath = 100; [SerializeField] int health; // This function is called on Component Placement/Replacement void Reset() { } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } } ``` Test for CRLF line ending bug
```c# using UnityEngine; using System.Collections; [SelectionBase] [DisallowMultipleComponent] public class Unit : MonoBehaviour { [SerializeField] string faction; [SerializeField] int maxHeath = 100; [SerializeField] int health; // This function is called on Component Placement/Replacement void Reset() { } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } //Called every frame in editor void OnDrawGizmos() { } } ```
ed3df0bd-3021-4c85-8fae-c89e31a92751
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Serilog; namespace Commencement.Jobs.Common.Logging { public static class LogHelper { private static bool _loggingSetup = false; public static void ConfigureLogging() { if (_loggingSetup) return; //only setup logging once Log.Logger = new LoggerConfiguration() .WriteTo.Stackify() .WriteTo.Console() .CreateLogger(); AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) => Log.Fatal(eventArgs.ExceptionObject as Exception, eventArgs.ExceptionObject.ToString()); _loggingSetup = true; } } } ``` Add it to the job log too.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Serilog; using Serilog.Exceptions.Destructurers; namespace Commencement.Jobs.Common.Logging { public static class LogHelper { private static bool _loggingSetup = false; public static void ConfigureLogging() { if (_loggingSetup) return; //only setup logging once Log.Logger = new LoggerConfiguration() .WriteTo.Stackify() .WriteTo.Console() .Enrich.With<ExceptionEnricher>() .CreateLogger(); AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) => Log.Fatal(eventArgs.ExceptionObject as Exception, eventArgs.ExceptionObject.ToString()); _loggingSetup = true; } } } ```
bd7c04b3-7c15-4294-8c28-5818f38de18a
{ "language": "C#" }
```c# using System; using System.ComponentModel; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace Tgstation.Server.Host.IO { /// <summary> /// <see cref="ISymlinkFactory"/> for windows systems /// </summary> sealed class WindowsSymlinkFactory : ISymlinkFactory { /// <inheritdoc /> public Task CreateSymbolicLink(string targetPath, string linkPath, CancellationToken cancellationToken) => Task.Factory.StartNew(() => { if (targetPath == null) throw new ArgumentNullException(nameof(targetPath)); if (linkPath == null) throw new ArgumentNullException(nameof(linkPath)); //check if its not a file var flags = File.Exists(targetPath) ? 0 : 3; //SYMBOLIC_LINK_FLAG_DIRECTORY | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE on win10 1607+ developer mode cancellationToken.ThrowIfCancellationRequested(); if (!NativeMethods.CreateSymbolicLink(linkPath, targetPath, flags)) throw new Win32Exception(Marshal.GetLastWin32Error()); }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current); } } ``` Fix unprivileged file symlink creation
```c# using System; using System.ComponentModel; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace Tgstation.Server.Host.IO { /// <summary> /// <see cref="ISymlinkFactory"/> for windows systems /// </summary> sealed class WindowsSymlinkFactory : ISymlinkFactory { /// <inheritdoc /> public Task CreateSymbolicLink(string targetPath, string linkPath, CancellationToken cancellationToken) => Task.Factory.StartNew(() => { if (targetPath == null) throw new ArgumentNullException(nameof(targetPath)); if (linkPath == null) throw new ArgumentNullException(nameof(linkPath)); //check if its not a file var flags = File.Exists(targetPath) ? 2 : 3; //SYMBOLIC_LINK_FLAG_DIRECTORY and SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE on win10 1607+ developer mode cancellationToken.ThrowIfCancellationRequested(); if (!NativeMethods.CreateSymbolicLink(linkPath, targetPath, flags)) throw new Win32Exception(Marshal.GetLastWin32Error()); }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current); } } ```
806e6bcf-bf0c-4164-996b-d81da6f83893
{ "language": "C#" }
```c# using System; using System.Collections.Generic; namespace FisherYates { public static class FisherYates { /* ** http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle */ static readonly Random Rand = new Random(); public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> list) { var rand = Rand; var enumerable = list as T[] ?? list.ToArray(); for (var i = enumerable.Length; i > 1; i--) { // First step : Pick random element to swap. var j = rand.Next(i); // Second step : Swap. var tmp = enumerable[j]; enumerable[j] = enumerable[i - 1]; enumerable[i - 1] = tmp; } return enumerable; } } } ``` Remove whitespace and add using
```c# using System; using System.Collections.Generic; using System.Linq; namespace FisherYates { public static class FisherYates { /* ** http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle */ static readonly Random Rand = new Random(); public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> list) { var rand = Rand; var enumerable = list as T[] ?? list.ToArray(); for (var i = enumerable.Length; i > 1; i--) { // First step : Pick random element to swap. var j = rand.Next(i); // Second step : Swap. var tmp = enumerable[j]; enumerable[j] = enumerable[i - 1]; enumerable[i - 1] = tmp; } return enumerable; } } } ```
b0edd03e-fe8f-4db8-bae6-0329031aeb66
{ "language": "C#" }
```c# using NUnit.Framework; using System; using Microsoft.Boogie; using Microsoft.Basetypes; using System.IO; using symbooglix; namespace SymbooglixLibTests { [TestFixture()] public class Literal { public Literal() { SymbooglixTest.setupDebug(); } [Test()] public void bitvector() { var literal = new LiteralExpr(Token.NoToken, BigNum.FromInt(19), 32); // 19bv32 checkLiteral(literal, "(_ bv19 32)"); } [Test()] public void Bools() { checkLiteral(Expr.True, "true"); checkLiteral(Expr.False, "false"); } private void checkLiteral(LiteralExpr e, string expected) { using (var writer = new StringWriter()) { var printer = new SMTLIBQueryPrinter(writer); printer.Traverse(e); Assert.IsTrue(writer.ToString() == expected); } } } } ``` Move the ExprSMTLIB test cases (there's only one right now) into their own namespace.
```c# using NUnit.Framework; using System; using Microsoft.Boogie; using Microsoft.Basetypes; using System.IO; using symbooglix; namespace ExprSMTLIBTest { [TestFixture()] public class Literal { public Literal() { SymbooglixLibTests.SymbooglixTest.setupDebug(); } [Test()] public void bitvector() { var literal = new LiteralExpr(Token.NoToken, BigNum.FromInt(19), 32); // 19bv32 checkLiteral(literal, "(_ bv19 32)"); } [Test()] public void Bools() { checkLiteral(Expr.True, "true"); checkLiteral(Expr.False, "false"); } private void checkLiteral(LiteralExpr e, string expected) { using (var writer = new StringWriter()) { var printer = new SMTLIBQueryPrinter(writer); printer.Traverse(e); Assert.IsTrue(writer.ToString() == expected); } } } } ```
1b2d55ce-daa3-40c3-9220-a6c2ab365d5c
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; using Microsoft.Practices.Unity; using UI.AddComponent; namespace UI { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); this.MainWindow = new MainWindow(); var compManager = new MEF_CompositionManager(); compManager.ComposeParts(); var container = new UnityContainer(); foreach (var component in compManager.ImportedComponents) { container.RegisterType(component.Provider.Key, component.Provider.Value); container.RegisterType(typeof(WorkspaceViewModel), component.Workspace, component.Workspace.Name); } container.RegisterType<IWorkspaceService, WorkspaceService>(); this.MainWindow.DataContext = container.Resolve<CalculatorViewModel>(); this.MainWindow.Show(); } } public interface IWorkspaceService { IEnumerable<WorkspaceViewModel> GetWorkspaces(); } public class WorkspaceService : IWorkspaceService { private readonly IUnityContainer container; public WorkspaceService(IUnityContainer container) { this.container = container; } public IEnumerable<WorkspaceViewModel> GetWorkspaces() { return container.ResolveAll<WorkspaceViewModel>().ToArray();; } } } ``` Add Guid as name for workspace registration
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; using Microsoft.Practices.Unity; using UI.AddComponent; namespace UI { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); this.MainWindow = new MainWindow(); var compManager = new MEF_CompositionManager(); compManager.ComposeParts(); var container = new UnityContainer(); foreach (var component in compManager.ImportedComponents) { container.RegisterType(component.Provider.Key, component.Provider.Value); container.RegisterType(typeof(WorkspaceViewModel), component.Workspace, Guid.NewGuid().ToString()); } container.RegisterType<IWorkspaceService, WorkspaceService>(); this.MainWindow.DataContext = container.Resolve<CalculatorViewModel>(); this.MainWindow.Show(); } } public interface IWorkspaceService { IEnumerable<WorkspaceViewModel> GetWorkspaces(); } public class WorkspaceService : IWorkspaceService { private readonly IUnityContainer container; public WorkspaceService(IUnityContainer container) { this.container = container; } public IEnumerable<WorkspaceViewModel> GetWorkspaces() { return container.ResolveAll<WorkspaceViewModel>().ToArray(); } } } ```
ea976085-48d0-4c65-bbe4-328b94cc3947
{ "language": "C#" }
```c# using EvoSim; using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace EvoCommand { class Program { static void Main(string[] args) { Simulation sim = new Simulation(); sim.Initialize(sim); DateTime startTime = DateTime.UtcNow; DateTime lastUpdate; DateTime lastSerializationTime = DateTime.UtcNow; long i = 0; while (true) { lastUpdate = DateTime.UtcNow; update(new GameTime(DateTime.UtcNow - startTime, lastUpdate - lastUpdate)); i++; if (i % 1000000 == 1) Console.WriteLine("Programm still active - " + DateTime.Now.ToString()); // Save progress every minute if ((DateTime.UtcNow - lastSerializationTime).TotalSeconds > 10) { lastSerializationTime = DateTime.UtcNow; sim.TileMap.SerializeToFile("tilemap.dat"); sim.CreatureManager.Serialize("creatures.dat", "graveyard/graveyard"); Console.WriteLine("Save everything."); } } } public static void update(GameTime gametime) { } } } ``` Update now actually does things in EvoCommand
```c# using EvoSim; using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace EvoCommand { class Program { static void Main(string[] args) { Simulation sim = new Simulation(); sim.Initialize(sim); DateTime startTime = DateTime.UtcNow; DateTime lastUpdate; DateTime lastSerializationTime = DateTime.UtcNow; long i = 0; while (true) { lastUpdate = DateTime.UtcNow; sim.NotifyTick(new GameTime(DateTime.UtcNow - startTime, lastUpdate - lastUpdate)); i++; if (i % 1000000 == 1) Console.WriteLine("Programm still active - " + DateTime.Now.ToString()); // Save progress every minute if ((DateTime.UtcNow - lastSerializationTime).TotalSeconds > 10) { lastSerializationTime = DateTime.UtcNow; sim.TileMap.SerializeToFile("tilemap.dat"); sim.CreatureManager.Serialize("creatures.dat", "graveyard/graveyard"); Console.WriteLine("Save everything."); } } } } } ```
d8e233fc-5741-40cd-aff8-46de7d9b268d
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace netcore.Controllers { [Route("api/[controller]")] public class ValuesController : Controller { // GET api/values [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public string Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody]string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } } ``` Add Value object with Id and Text
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace netcore.Controllers { [Route("api/[controller]")] public class ValuesController : Controller { // GET api/values [HttpGet] public IEnumerable<Value> Get() { return new Value[] { new Value { Id = 1, Text = "value1"}, new Value { Id = 2, Text = "value2"} }; } // GET api/values/5 [HttpGet("{id:int}")] public Value Get(int id) { return new Value { Id = id, Text = "value" }; } // POST api/values [HttpPost] public void Post([FromBody]string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } public class Value { public int Id { get; set; } public string Text { get; set; } } } ```
113d7b5f-e23b-481f-8339-032ae58c09b9
{ "language": "C#" }
```c# using System; using System.Threading.Tasks; using SoraBot.Data.Repositories.Interfaces; using SoraBot.Services.Cache; namespace SoraBot.Services.Guilds { public class PrefixService : IPrefixService { public const string CACHE_PREFIX = "prfx:"; public const short CACHE_TTL_MINS = 60; private readonly ICacheService _cacheService; private readonly IGuildRepository _guildRepo; public PrefixService(ICacheService cacheService, IGuildRepository guildRepo) { _cacheService = cacheService; _guildRepo = guildRepo; } public async Task<string> GetPrefix(ulong id) { string idStr = CACHE_PREFIX + id.ToString(); return await _cacheService.GetOrSetAndGetAsync(idStr, async () => await _guildRepo.GetGuildPrefix(id).ConfigureAwait(false) ?? "$", TimeSpan.FromMinutes(CACHE_TTL_MINS)).ConfigureAwait(false); } public async Task<bool> SetPrefix(ulong id, string prefix) { // Let's set it in the DB. And if it succeeds we'll also add it to our cache if (!await _guildRepo.SetGuildPrefix(id, prefix).ConfigureAwait(false)) return false; // Update the Cache string idStr = CACHE_PREFIX + id.ToString(); _cacheService.Set(idStr, prefix, TimeSpan.FromMinutes(CACHE_TTL_MINS)); return true; } } }``` Set TTL for prefix to infinity rn
```c# using System; using System.Threading.Tasks; using SoraBot.Data.Repositories.Interfaces; using SoraBot.Services.Cache; namespace SoraBot.Services.Guilds { public class PrefixService : IPrefixService { public const string CACHE_PREFIX = "prfx:"; // public const short CACHE_TTL_MINS = 60; private readonly ICacheService _cacheService; private readonly IGuildRepository _guildRepo; public PrefixService(ICacheService cacheService, IGuildRepository guildRepo) { _cacheService = cacheService; _guildRepo = guildRepo; } public async Task<string> GetPrefix(ulong id) { string idStr = CACHE_PREFIX + id.ToString(); return await _cacheService.GetOrSetAndGetAsync(idStr, async () => await _guildRepo.GetGuildPrefix(id).ConfigureAwait(false) ?? "$" ).ConfigureAwait(false); } public async Task<bool> SetPrefix(ulong id, string prefix) { // Let's set it in the DB. And if it succeeds we'll also add it to our cache if (!await _guildRepo.SetGuildPrefix(id, prefix).ConfigureAwait(false)) return false; // Update the Cache string idStr = CACHE_PREFIX + id.ToString(); _cacheService.Set(idStr, prefix); return true; } } }```
6032e2c2-51fa-464e-beaf-8692d68ff1f3
{ "language": "C#" }
```c# using System; using System.Diagnostics; using HandlebarsDotNet.Collections; using HandlebarsDotNet.EqualityComparers; using HandlebarsDotNet.Runtime; namespace HandlebarsDotNet { [DebuggerDisplay("undefined")] public class UndefinedBindingResult : IEquatable<UndefinedBindingResult> { private static readonly LookupSlim<string, GcDeferredValue<string, UndefinedBindingResult>, StringEqualityComparer> Cache = new LookupSlim<string, GcDeferredValue<string, UndefinedBindingResult>, StringEqualityComparer>(new StringEqualityComparer(StringComparison.OrdinalIgnoreCase)); public static UndefinedBindingResult Create(string value) => Cache.GetOrAdd(value, ValueFactory).Value; private static readonly Func<string, GcDeferredValue<string, UndefinedBindingResult>> ValueFactory = s => { return new GcDeferredValue<string, UndefinedBindingResult>(s, v => new UndefinedBindingResult(v)); }; public readonly string Value; private UndefinedBindingResult(string value) => Value = value; public override string ToString() => Value; public bool Equals(UndefinedBindingResult other) => Value == other?.Value; public override bool Equals(object obj) => obj is UndefinedBindingResult other && Equals(other); public override int GetHashCode() => Value != null ? Value.GetHashCode() : 0; } } ``` Use case sensitive cache for Undefined result
```c# using System; using System.Diagnostics; using HandlebarsDotNet.Collections; using HandlebarsDotNet.EqualityComparers; using HandlebarsDotNet.Runtime; namespace HandlebarsDotNet { [DebuggerDisplay("undefined")] public class UndefinedBindingResult : IEquatable<UndefinedBindingResult> { private static readonly LookupSlim<string, GcDeferredValue<string, UndefinedBindingResult>, StringEqualityComparer> Cache = new LookupSlim<string, GcDeferredValue<string, UndefinedBindingResult>, StringEqualityComparer>(new StringEqualityComparer(StringComparison.Ordinal)); public static UndefinedBindingResult Create(string value) => Cache.GetOrAdd(value, ValueFactory).Value; private static readonly Func<string, GcDeferredValue<string, UndefinedBindingResult>> ValueFactory = s => { return new GcDeferredValue<string, UndefinedBindingResult>(s, v => new UndefinedBindingResult(v)); }; public readonly string Value; private UndefinedBindingResult(string value) => Value = value; public override string ToString() => Value; public bool Equals(UndefinedBindingResult other) => Value == other?.Value; public override bool Equals(object obj) => obj is UndefinedBindingResult other && Equals(other); public override int GetHashCode() => Value != null ? Value.GetHashCode() : 0; } } ```
26b9b3b1-d961-4445-8430-1292881930f1
{ "language": "C#" }
```c# using System.Threading.Tasks; using Basic.Models; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using MR.AspNetCore.Jobs; namespace Basic { public class Program { public static async Task Main(string[] args) { var host = CreateWebHostBuilder(args).Build(); await host.StartJobsAsync(); using (var scope = host.Services.CreateScope()) { var context = scope.ServiceProvider.GetService<AppDbContext>(); await context.Database.MigrateAsync(); } host.Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } } ``` Use generic host in sample
```c# using System.Threading.Tasks; using Basic.Models; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using MR.AspNetCore.Jobs; namespace Basic { public class Program { public static async Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); await host.StartJobsAsync(); using (var scope = host.Services.CreateScope()) { var context = scope.ServiceProvider.GetService<AppDbContext>(); await context.Database.MigrateAsync(); } host.Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } } ```
5d7894b7-43de-47c9-9ce9-45a2e9276589
{ "language": "C#" }
```c# using System; using System.Web; using System.Web.Hosting; using System.Configuration; namespace NuGet.Server.Infrastructure { public class PackageUtility { internal static string PackagePhysicalPath; private static string DefaultPackagePhysicalPath = HostingEnvironment.MapPath("~/Packages"); static PackageUtility() { string packagePath = ConfigurationManager.AppSettings["NuGetPackagePath"]; if (string.IsNullOrEmpty(packagePath)) { PackagePhysicalPath = DefaultPackagePhysicalPath; } else { PackagePhysicalPath = packagePath; } } public static Uri GetPackageUrl(string path, Uri baseUri) { return new Uri(baseUri, GetPackageDownloadUrl(path)); } private static string GetPackageDownloadUrl(string path) { return VirtualPathUtility.ToAbsolute("~/Packages/" + path); } } } ``` Check if the specified path is a physical or a virtual path
```c# using System; using System.Web; using System.Web.Hosting; using System.Configuration; using System.IO; namespace NuGet.Server.Infrastructure { public class PackageUtility { internal static string PackagePhysicalPath; private static string DefaultPackagePhysicalPath = HostingEnvironment.MapPath("~/Packages"); static PackageUtility() { string packagePath = ConfigurationManager.AppSettings["NuGetPackagePath"]; if (string.IsNullOrEmpty(packagePath)) { PackagePhysicalPath = DefaultPackagePhysicalPath; } else { if (Path.IsPathRooted(packagePath)) { PackagePhysicalPath = packagePath; } else { PackagePhysicalPath = HostingEnvironment.MapPath(packagePath); } } } public static Uri GetPackageUrl(string path, Uri baseUri) { return new Uri(baseUri, GetPackageDownloadUrl(path)); } private static string GetPackageDownloadUrl(string path) { return VirtualPathUtility.ToAbsolute("~/Packages/" + path); } } } ```
1b3fd6b5-afbc-41b4-aad1-470de45d7211
{ "language": "C#" }
```c# namespace NTwitch { public interface IEntity { ITwitchClient Client { get; } uint Id { get; } } } ``` Change id type from uint to ulong
```c# namespace NTwitch { public interface IEntity { ITwitchClient Client { get; } ulong Id { get; } } } ```
238e88be-1ffa-414b-926b-76aea2c754e8
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Booma.Proxy { /// <summary> /// The collection of network players that are known about. /// </summary> public interface INetworkPlayerCollection : IEnumerable<INetworkPlayer> { /// <summary> /// The local player. /// </summary> INetworkPlayer Local { get; } /// <summary> /// The networked players. /// </summary> IEnumerable<INetworkPlayer> Players { get; } /// <summary> /// The networked player's excluding the <see cref="Local"/> player. /// </summary> IEnumerable<INetworkPlayer> ExcludingLocal { get; } /// <summary> /// Returns the <see cref="INetworkPlayer"/> with the id. /// Or null if the player doesn't exist. /// </summary> /// <param name="id">The id to check for.</param> /// <returns>The <see cref="INetworkPlayer"/> with the id or null.</returns> INetworkPlayer this[int id] { get; } /// <summary> /// Indicates if it contains the <see cref="id"/> key value. /// </summary> /// <param name="id">The id to check for.</param> /// <returns>True if the collection contains the ID.</returns> bool ContainsId(int id); } } ``` Remove uneeded player collection methods
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Booma.Proxy { /// <summary> /// The collection of network players that are known about. /// </summary> public interface INetworkPlayerCollection : IEnumerable<INetworkPlayer> { /// <summary> /// The networked players. /// </summary> IEnumerable<INetworkPlayer> Players { get; } /// <summary> /// Returns the <see cref="INetworkPlayer"/> with the id. /// Or null if the player doesn't exist. /// </summary> /// <param name="id">The id to check for.</param> /// <returns>The <see cref="INetworkPlayer"/> with the id or null.</returns> INetworkPlayer this[int id] { get; } /// <summary> /// Indicates if it contains the <see cref="id"/> key value. /// </summary> /// <param name="id">The id to check for.</param> /// <returns>True if the collection contains the ID.</returns> bool ContainsId(int id); } } ```
d28c6970-d236-45e9-bbe4-85c182936d8e
{ "language": "C#" }
```c# // Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Gax; using System; using System.Linq; using Xunit; namespace Google.Monitoring.V3 { [Collection(nameof(MonitoringFixture))] public class GroupServiceClientSnippets { private readonly MonitoringFixture _fixture; public GroupServiceClientSnippets(MonitoringFixture fixture) { _fixture = fixture; } [Fact] public void ListGroups() { string projectId = _fixture.ProjectId; // Snippet: ListGroups GroupServiceClient client = GroupServiceClient.Create(); string projectName = MetricServiceClient.FormatProjectName(projectId); IPagedEnumerable<ListGroupsResponse, Group> groups = client.ListGroups(projectName, "", "", ""); foreach (Group group in groups.Take(10)) { Console.WriteLine($"{group.Name}: {group.DisplayName}"); } // End snippet } } } ``` Comment out non-compiling test while we don't flatten ListGroups
```c# // Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Gax; using System; using System.Linq; using Xunit; namespace Google.Monitoring.V3 { [Collection(nameof(MonitoringFixture))] public class GroupServiceClientSnippets { private readonly MonitoringFixture _fixture; public GroupServiceClientSnippets(MonitoringFixture fixture) { _fixture = fixture; } /* TODO: Reinstate when ListGroups is present again. [Fact] public void ListGroups() { string projectId = _fixture.ProjectId; // Snippet: ListGroups GroupServiceClient client = GroupServiceClient.Create(); string projectName = MetricServiceClient.FormatProjectName(projectId); IPagedEnumerable<ListGroupsResponse, Group> groups = client.ListGroups(projectName, "", "", ""); foreach (Group group in groups.Take(10)) { Console.WriteLine($"{group.Name}: {group.DisplayName}"); } // End snippet } */ } } ```
73c42592-861b-46c1-bcc4-b43c03d34d3c
{ "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.Rulesets.Osu.Skinning { public enum OsuSkinConfiguration { HitCirclePrefix, HitCircleOverlap, SliderBorderSize, SliderPathRadius, AllowSliderBallTint, CursorExpand, CursorRotate, HitCircleOverlayAboveNumber, HitCircleOverlayAboveNumer, // Some old skins will have this typo SpinnerFrequencyModulate } } ``` Replace accidental tab with spaces
```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.Rulesets.Osu.Skinning { public enum OsuSkinConfiguration { HitCirclePrefix, HitCircleOverlap, SliderBorderSize, SliderPathRadius, AllowSliderBallTint, CursorExpand, CursorRotate, HitCircleOverlayAboveNumber, HitCircleOverlayAboveNumer, // Some old skins will have this typo SpinnerFrequencyModulate } } ```
d600b088-99c7-4e9b-91f5-40d7c27aad9f
{ "language": "C#" }
```c# // // Query.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2016 Roman M. Yagodin // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.Linq; using R7.University.Models; namespace R7.University.Queries { public class Query<TEntity> where TEntity: class { private readonly IModelContext modelContext; public Query (IModelContext modelContext) { this.modelContext = modelContext; } public IEnumerable<TEntity> Execute () { return modelContext.Query<TEntity> ().ToList (); } } } ``` Add execute method overload with ordering
```c# // // Query.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2016 Roman M. Yagodin // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.Linq; using R7.University.Models; namespace R7.University.Queries { public class Query<TEntity> where TEntity: class { private readonly IModelContext modelContext; public Query (IModelContext modelContext) { this.modelContext = modelContext; } public IList<TEntity> Execute () { return modelContext.Query<TEntity> ().ToList (); } public IList<TEntity> Execute<TKey> (Func<TEntity,TKey> keySelector) { return modelContext.Query<TEntity> ().OrderBy (keySelector).ToList (); } } } ```
392b2987-cd7c-4ff5-a415-803daf24a836
{ "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 osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Graphics; using osu.Game.Online.Multiplayer; using osuTK; namespace osu.Game.Screens.Multi.Match.Components { public class Footer : CompositeDrawable { public const float HEIGHT = 100; public Action OnStart; public readonly Bindable<PlaylistItem> SelectedItem = new Bindable<PlaylistItem>(); private readonly Drawable background; public Footer() { RelativeSizeAxes = Axes.X; Height = HEIGHT; InternalChildren = new[] { background = new Box { RelativeSizeAxes = Axes.Both }, new ReadyButton { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(600, 50), SelectedItem = { BindTarget = SelectedItem }, Action = () => OnStart?.Invoke() } }; } [BackgroundDependencyLoader] private void load(OsuColour colours) { background.Colour = Color4Extensions.FromHex(@"28242d"); } } } ``` Reduce footer height to match back button
```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 osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Graphics; using osu.Game.Online.Multiplayer; using osuTK; namespace osu.Game.Screens.Multi.Match.Components { public class Footer : CompositeDrawable { public const float HEIGHT = 50; public Action OnStart; public readonly Bindable<PlaylistItem> SelectedItem = new Bindable<PlaylistItem>(); private readonly Drawable background; public Footer() { RelativeSizeAxes = Axes.X; Height = HEIGHT; InternalChildren = new[] { background = new Box { RelativeSizeAxes = Axes.Both }, new ReadyButton { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(600, 50), SelectedItem = { BindTarget = SelectedItem }, Action = () => OnStart?.Invoke() } }; } [BackgroundDependencyLoader] private void load(OsuColour colours) { background.Colour = Color4Extensions.FromHex(@"28242d"); } } } ```
68970d1e-ad03-4df5-8831-fd1553c2e45c
{ "language": "C#" }
```c# using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace Tiesmaster.Dcc { public class Startup { public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(); if(env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Run(async (context) => { await context.Response.WriteAsync("Hello from DCC ;)"); }); } } }``` Change hello world implementation to using the
```c# using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Logging; namespace Tiesmaster.Dcc { public class Startup { public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(); if(env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.RunProxy(new ProxyOptions { Host = "jsonplaceholder.typicode.com" }); } } }```
4994039d-04f7-47ed-8994-1207b499edf8
{ "language": "C#" }
```c# namespace BmpListener.Bgp { internal class PathAttributeMultiExitDisc : PathAttribute { public int? Metric { get; private set; } public override void Decode(byte[] data, int offset) { //Array.Reverse(data, offset, 0); //Metric = BitConverter.ToInt32(data, 0); } } }``` Add multi-exit discriminator (MED) support
```c# using BmpListener.Utilities; namespace BmpListener.Bgp { internal class PathAttributeMultiExitDisc : PathAttribute { public uint Metric { get; private set; } public override void Decode(byte[] data, int offset) { Metric = EndianBitConverter.Big.ToUInt32(data, offset); } } }```
255dae95-1319-4ca9-8ad9-eebf8c9f799e
{ "language": "C#" }
```c# using System; using System.Data; namespace Gigobyte.Daterpillar.Data { public class MySQLSchemaAggregator : SchemaAggregatorBase { public MySQLSchemaAggregator(IDbConnection connection) : base(connection) { } protected override string GetColumnInfoQuery(string tableName) { throw new NotImplementedException(); } protected override string GetForeignKeyInfoQuery(string tableName) { throw new NotImplementedException(); } protected override string GetIndexColumnsQuery(string indexIdentifier) { throw new NotImplementedException(); } protected override string GetIndexInfoQuery(string tableName) { throw new NotImplementedException(); } protected override string GetTableInfoQuery() { throw new NotImplementedException(); } } }``` Add implementation details to MySQLScheamAggregator.cs
```c# using System; using System.Data; namespace Gigobyte.Daterpillar.Data { public class MySQLSchemaAggregator : SchemaAggregatorBase { public MySQLSchemaAggregator(IDbConnection connection) : base(connection) { } protected override string GetColumnInfoQuery(string tableName) { return $"SELECT c.`COLUMN_NAME` AS `Name`, c.DATA_TYPE AS `Type`, if(c.CHARACTER_MAXIMUM_LENGTH IS NULL, if(c.NUMERIC_PRECISION IS NULL, 0, c.NUMERIC_PRECISION), c.CHARACTER_MAXIMUM_LENGTH) AS `Scale`, if(c.NUMERIC_SCALE IS NULL, 0, c.NUMERIC_SCALE) AS `Precision`, c.IS_NULLABLE AS `Nullable`, c.COLUMN_DEFAULT AS `Default`, if(c.EXTRA = 'auto_increment', 1, 0) AS `Auto`, c.COLUMN_COMMENT AS `Comment` FROM information_schema.`COLUMNS` c WHERE c.TABLE_SCHEMA = '{Schema.Name}' AND c.`TABLE_NAME` = '{tableName}';"; } protected override string GetForeignKeyInfoQuery(string tableName) { return $"SELECT rc.`CONSTRAINT_NAME` AS `Name`, fc.FOR_COL_NAME AS `Column`, rc.REFERENCED_TABLE_NAME AS `Referecne_Table`, fc.REF_COL_NAME AS `Reference_Column`, rc.UPDATE_RULE AS `On_Update`, rc.DELETE_RULE AS `On_Delete`, rc.MATCH_OPTION AS `On_Match` FROM information_schema.REFERENTIAL_CONSTRAINTS rc JOIN information_schema.INNODB_SYS_FOREIGN_COLS fc ON fc.ID = concat(rc.`CONSTRAINT_SCHEMA`, '/', rc.`CONSTRAINT_NAME`) WHERE rc.`CONSTRAINT_SCHEMA` = '{Schema.Name}' AND rc.`TABLE_NAME` = '{tableName}';"; } protected override string GetIndexColumnsQuery(string indexIdentifier) { throw new NotImplementedException(); } protected override string GetIndexInfoQuery(string tableName) { throw new NotImplementedException(); } protected override string GetTableInfoQuery() { return $"SELECT t.TABLE_NAME AS `Name`, t.TABLE_COMMENT AS `Comment` FROM information_schema.TABLES t WHERE t.TABLE_SCHEMA = '{Schema.Name}';"; } } }```
fd0e67ef-a672-47ad-9f42-3f061cf9b324
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Xml.Serialization; namespace SevenDigital.Api.Schema.Playlists.Response { [Serializable] public class PlaylistLocation : UserBasedUpdatableItem { [XmlAttribute("id")] public string Id { get; set; } [XmlElement("name")] public string Name { get; set; } [XmlArray("links")] [XmlArrayItem("link")] public List<Link> Links { get; set; } [XmlElement("trackCount")] public int TrackCount { get; set; } [XmlElement("visibility")] public PlaylistVisibilityType Visibility { get; set; } [XmlElement("status")] public PlaylistStatusType Status { get; set; } [XmlArray("tags")] [XmlArrayItem("tag")] public List<Tag> Tags { get; set; } public override string ToString() { return string.Format("{0}: {1}", Id, Name); } } }``` Add image and description to playlist location
```c# using System; using System.Collections.Generic; using System.Xml.Serialization; namespace SevenDigital.Api.Schema.Playlists.Response { [Serializable] public class PlaylistLocation : UserBasedUpdatableItem { [XmlAttribute("id")] public string Id { get; set; } [XmlElement("name")] public string Name { get; set; } [XmlArray("links")] [XmlArrayItem("link")] public List<Link> Links { get; set; } [XmlElement("trackCount")] public int TrackCount { get; set; } [XmlElement("visibility")] public PlaylistVisibilityType Visibility { get; set; } [XmlElement("description")] public string Description { get; set; } [XmlElement("image")] public string Image { get; set; } [XmlElement("status")] public PlaylistStatusType Status { get; set; } [XmlArray("tags")] [XmlArrayItem("tag")] public List<Tag> Tags { get; set; } public override string ToString() { return string.Format("{0}: {1}", Id, Name); } } }```
61c14c90-55db-480e-887c-768dca09f32d
{ "language": "C#" }
```c# using AvalonStudio.MainMenu; using AvalonStudio.Menus; using System; using System.Collections.Generic; using System.Composition; using System.Text; namespace WalletWasabi.Gui.Shell.MainMenu { internal class ToolsMainMenuItems { private IMenuItemFactory _menuItemFactory; [ImportingConstructor] public ToolsMainMenuItems(IMenuItemFactory menuItemFactory) { _menuItemFactory = menuItemFactory; } #region MainMenu [ExportMainMenuItem("Tools")] [DefaultOrder(1)] public IMenuItem Tools => _menuItemFactory.CreateHeaderMenuItem("Tools", null); #endregion MainMenu #region Group [ExportMainMenuDefaultGroup("Tools", "Wallet")] [DefaultOrder(0)] public object WalletGroup => null; [ExportMainMenuDefaultGroup("Tools", "Settings")] [DefaultOrder(1)] public object SettingsGroup => null; #endregion Group #region MenuItem [ExportMainMenuItem("Tools", "Wallet")] [DefaultOrder(0)] [DefaultGroup("Wallet")] public IMenuItem GenerateWallet => _menuItemFactory.CreateCommandMenuItem("Tools.WalletManager"); [ExportMainMenuItem("Tools", "Settings")] [DefaultOrder(1)] [DefaultGroup("Settings")] public IMenuItem Settings => _menuItemFactory.CreateCommandMenuItem("Tools.Settings"); #endregion MenuItem } } ``` Rename Wallets group to Managers group
```c# using AvalonStudio.MainMenu; using AvalonStudio.Menus; using System; using System.Collections.Generic; using System.Composition; using System.Text; namespace WalletWasabi.Gui.Shell.MainMenu { internal class ToolsMainMenuItems { private IMenuItemFactory _menuItemFactory; [ImportingConstructor] public ToolsMainMenuItems(IMenuItemFactory menuItemFactory) { _menuItemFactory = menuItemFactory; } #region MainMenu [ExportMainMenuItem("Tools")] [DefaultOrder(1)] public IMenuItem Tools => _menuItemFactory.CreateHeaderMenuItem("Tools", null); #endregion MainMenu #region Group [ExportMainMenuDefaultGroup("Tools", "Managers")] [DefaultOrder(0)] public object ManagersGroup => null; [ExportMainMenuDefaultGroup("Tools", "Settings")] [DefaultOrder(1)] public object SettingsGroup => null; #endregion Group #region MenuItem [ExportMainMenuItem("Tools", "Wallet Manager")] [DefaultOrder(0)] [DefaultGroup("Managers")] public IMenuItem GenerateWallet => _menuItemFactory.CreateCommandMenuItem("Tools.WalletManager"); [ExportMainMenuItem("Tools", "Settings")] [DefaultOrder(1)] [DefaultGroup("Settings")] public IMenuItem Settings => _menuItemFactory.CreateCommandMenuItem("Tools.Settings"); #endregion MenuItem } } ```
295972c8-4abe-4ab8-bb8f-d00fe9a184be
{ "language": "C#" }
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using Android.App; using Android.OS; using Android.Content.PM; using Android.Views; namespace SampleGame.Android { [Activity(Label = "SampleGame", ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, MainLauncher = true, Theme = "@android:style/Theme.NoTitleBar")] public class MainActivity : Activity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Window.AddFlags(WindowManagerFlags.Fullscreen); Window.AddFlags(WindowManagerFlags.KeepScreenOn); SetContentView(new SampleGameView(this)); } } } ``` Remove the label as you can not see it when running the app
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using Android.App; using Android.OS; using Android.Content.PM; using Android.Views; namespace SampleGame.Android { [Activity(ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, MainLauncher = true, Theme = "@android:style/Theme.NoTitleBar")] public class MainActivity : Activity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Window.AddFlags(WindowManagerFlags.Fullscreen); Window.AddFlags(WindowManagerFlags.KeepScreenOn); SetContentView(new SampleGameView(this)); } } } ```
d519223d-06be-4807-a268-1a46f8732060
{ "language": "C#" }
```c# #if !DEBUG using System; using System.IO; #endif using System.Threading; using YGOSharp.OCGWrapper; namespace YGOSharp { public class Program { public static uint ClientVersion = 0x133D; public static void Main(string[] args) { #if !DEBUG try { #endif Config.Load(args); BanlistManager.Init(Config.GetString("BanlistFile", "lflist.conf")); Api.Init(Config.GetString("RootPath", "."), Config.GetString("ScriptDirectory", "script"), Config.GetString("DatabaseFile", "cards.cdb")); ClientVersion = Config.GetUInt("ClientVersion", ClientVersion); CoreServer server = new CoreServer(); server.Start(); while (server.IsRunning) { server.Tick(); Thread.Sleep(1); } #if !DEBUG } catch (Exception ex) { File.WriteAllText("crash_" + DateTime.UtcNow.ToString("yyyy-MM-dd_HH-mm-ss") + ".txt", ex.ToString()); } #endif } } } ``` Bump the protocol version to 0x1343
```c# #if !DEBUG using System; using System.IO; #endif using System.Threading; using YGOSharp.OCGWrapper; namespace YGOSharp { public class Program { public static uint ClientVersion = 0x1343; public static void Main(string[] args) { #if !DEBUG try { #endif Config.Load(args); BanlistManager.Init(Config.GetString("BanlistFile", "lflist.conf")); Api.Init(Config.GetString("RootPath", "."), Config.GetString("ScriptDirectory", "script"), Config.GetString("DatabaseFile", "cards.cdb")); ClientVersion = Config.GetUInt("ClientVersion", ClientVersion); CoreServer server = new CoreServer(); server.Start(); while (server.IsRunning) { server.Tick(); Thread.Sleep(1); } #if !DEBUG } catch (Exception ex) { File.WriteAllText("crash_" + DateTime.UtcNow.ToString("yyyy-MM-dd_HH-mm-ss") + ".txt", ex.ToString()); } #endif } } } ```
21b3d86e-ee06-437c-ac14-21cf1dc7465b
{ "language": "C#" }
```c# using System; using NUnit.Framework; using RethinkDb; using System.Net; using System.Linq; using System.Threading.Tasks; using RethinkDb.Configuration; namespace RethinkDb.Test { public class TestBase { protected IConnection connection; [TestFixtureSetUp] public virtual void TestFixtureSetUp() { try { DoTestFixtureSetUp().Wait(); } catch (Exception e) { Console.WriteLine("TestFixtureSetUp failed: {0}", e); throw; } } private async Task DoTestFixtureSetUp() { connection = ConfigConnectionFactory.Instance.Get("testCluster"); connection.Logger = new DefaultLogger(LoggingCategory.Debug, Console.Out); await connection.ConnectAsync(); try { var dbList = await connection.RunAsync(Query.DbList()); if (dbList.Contains("test")) await connection.RunAsync(Query.DbDrop("test")); } catch (Exception) { } } } } ``` Reduce unit test logger verbosity
```c# using System; using NUnit.Framework; using RethinkDb; using System.Net; using System.Linq; using System.Threading.Tasks; using RethinkDb.Configuration; namespace RethinkDb.Test { public class TestBase { protected IConnection connection; [TestFixtureSetUp] public virtual void TestFixtureSetUp() { try { DoTestFixtureSetUp().Wait(); } catch (Exception e) { Console.WriteLine("TestFixtureSetUp failed: {0}", e); throw; } } private async Task DoTestFixtureSetUp() { connection = ConfigConnectionFactory.Instance.Get("testCluster"); connection.Logger = new DefaultLogger(LoggingCategory.Warning, Console.Out); await connection.ConnectAsync(); try { var dbList = await connection.RunAsync(Query.DbList()); if (dbList.Contains("test")) await connection.RunAsync(Query.DbDrop("test")); } catch (Exception) { } } } } ```
22014cb1-e483-4aaf-a368-45560cad787f
{ "language": "C#" }
```c# using Livet; namespace Anne.Foundation.Mvvm { public class ViewModelBase : ViewModel { public ViewModelBase() { DisposableChecker.Add(this); } protected override void Dispose(bool disposing) { DisposableChecker.Remove(this); base.Dispose(disposing); } } }``` Fix multiple dispose check problem
```c# using Livet; namespace Anne.Foundation.Mvvm { public class ViewModelBase : ViewModel { public ViewModelBase() { DisposableChecker.Add(this); } protected override void Dispose(bool disposing) { if (disposing) DisposableChecker.Remove(this); base.Dispose(disposing); } } }```
91f19da3-fa8c-4868-b39d-5c7aa29ad3ec
{ "language": "C#" }
```c# using System.Linq; using UniRx; using UniRx.Triggers; using UnityEngine; public class WaveformRenderer : MonoBehaviour { [SerializeField] Color color; void Awake() { var model = NotesEditorModel.Instance; var waveData = new float[500000]; var skipSamples = 50; var lines = Enumerable.Range(0, waveData.Length / skipSamples) .Select(_ => new Line(Vector3.zero, Vector3.zero, color)) .ToArray(); this.LateUpdateAsObservable() .Where(_ => model.WaveformDisplayEnabled.Value) .SkipWhile(_ => model.Audio.clip == null) .Subscribe(_ => { model.Audio.clip.GetData(waveData, model.Audio.timeSamples); var x = (model.CanvasWidth.Value / model.Audio.clip.samples) / 2f; var offsetX = model.CanvasOffsetX.Value; var offsetY = 200; for (int li = 0, wi = skipSamples / 2, l = waveData.Length; wi < l; li++, wi += skipSamples) { lines[li].start.x = lines[li].end.x = wi * x + offsetX; lines[li].end.y = waveData[wi] * 45 - offsetY; lines[li].start.y = waveData[wi - skipSamples / 2] * 45 - offsetY; } GLLineRenderer.RenderLines("waveform", lines); }); } } ``` Fix offset samples for GetData
```c# using System.Linq; using UniRx; using UniRx.Triggers; using UnityEngine; public class WaveformRenderer : MonoBehaviour { [SerializeField] Color color; void Awake() { var model = NotesEditorModel.Instance; var waveData = new float[500000]; var skipSamples = 50; var lines = Enumerable.Range(0, waveData.Length / skipSamples) .Select(_ => new Line(Vector3.zero, Vector3.zero, color)) .ToArray(); this.LateUpdateAsObservable() .Where(_ => model.WaveformDisplayEnabled.Value) .SkipWhile(_ => model.Audio.clip == null) .Subscribe(_ => { var timeSamples = Mathf.Min(model.Audio.timeSamples, model.Audio.clip.samples - 1); model.Audio.clip.GetData(waveData, timeSamples); var x = (model.CanvasWidth.Value / model.Audio.clip.samples) / 2f; var offsetX = model.CanvasOffsetX.Value; var offsetY = 200; for (int li = 0, wi = skipSamples / 2, l = waveData.Length; wi < l; li++, wi += skipSamples) { lines[li].start.x = lines[li].end.x = wi * x + offsetX; lines[li].end.y = waveData[wi] * 45 - offsetY; lines[li].start.y = waveData[wi - skipSamples / 2] * 45 - offsetY; } GLLineRenderer.RenderLines("waveform", lines); }); } } ```
8ead474d-d273-4da5-86bb-f74d5fd7c33c
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using ContractsWindow.Unity.Unity; using UnityEngine; using UnityEngine.UI; namespace ContractsWindow.Unity.Interfaces { public interface ICW_Window { bool HideTooltips { get; set; } bool BlizzyAvailable { get; } bool StockToolbar { get; set; } bool ReplaceToolbar { get; set; } bool LargeFont { get; set; } bool IgnoreScale { get; set; } float Scale { get; set; } float MasterScale { get; set; } string Version { get; } IList<IMissionSection> GetMissions { get; } IMissionSection GetCurrentMission { get; } void Rebuild(); void NewMission(string title, Guid id); void SetWindowPosition(Rect r); } } ``` Fix UI scale; add Canvas property
```c# using System; using System.Collections.Generic; using ContractsWindow.Unity.Unity; using UnityEngine; using UnityEngine.UI; namespace ContractsWindow.Unity.Interfaces { public interface ICW_Window { bool HideTooltips { get; set; } bool BlizzyAvailable { get; } bool StockToolbar { get; set; } bool ReplaceToolbar { get; set; } bool LargeFont { get; set; } bool IgnoreScale { get; set; } float Scale { get; set; } float MasterScale { get; } string Version { get; } Canvas MainCanvas { get; } IList<IMissionSection> GetMissions { get; } IMissionSection GetCurrentMission { get; } void Rebuild(); void NewMission(string title, Guid id); void SetWindowPosition(Rect r); } } ```
08eeb6de-2acd-4232-b513-ed7598a702a8
{ "language": "C#" }
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(GridPositionComponent))] [RequireComponent(typeof(ResourceSink))] public class GridOutput : MonoBehaviour { private ResourceStorage ItemDestination; private ResourceSink ItemSource; // Use this for initialization void Start () { ItemDestination = GetComponentInParent<ResourceStorage>(); ItemSource = GetComponent<ResourceSink>(); ItemSource.DeliverItem = (item) => { Debug.Log(new System.Diagnostics.StackTrace()); Debug.Log(ItemDestination); Debug.Log(item); ItemDestination.AddResource(item.ResourceType, 1); // TODO destroy the in-game item return true; }; } // Update is called once per frame void Update () { } } ``` Destroy factory items when moving them to stockpile
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(GridPositionComponent))] [RequireComponent(typeof(ResourceSink))] public class GridOutput : MonoBehaviour { private ResourceStorage ItemDestination; private ResourceSink ItemSource; // Use this for initialization void Start () { ItemDestination = GetComponentInParent<ResourceStorage>(); ItemSource = GetComponent<ResourceSink>(); ItemSource.DeliverItem = (item) => { Debug.Log(new System.Diagnostics.StackTrace()); Debug.Log(ItemDestination); Debug.Log(item); ItemDestination.AddResource(item.ResourceType, 1); Destroy(item.gameObject); return true; }; } // Update is called once per frame void Update () { } } ```
dada2a30-a968-4738-bd9d-d3c0d1b88405
{ "language": "C#" }
```c# // Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using EndlessClient.GameExecution; using EndlessClient.Rendering.Factories; using EOLib.IO.Repositories; namespace EndlessClient { //todo: move this to a different namespace public class TestModeLauncher : ITestModeLauncher { private readonly IEndlessGameProvider _endlessGameProvider; private readonly ICharacterRendererFactory _characterRendererFactory; private readonly IEIFFileProvider _eifFileProvider; private readonly IGameStateProvider _gameStateProvider; public TestModeLauncher(IEndlessGameProvider endlessGameProvider, ICharacterRendererFactory characterRendererFactory, IEIFFileProvider eifFileProvider, IGameStateProvider gameStateProvider) { _endlessGameProvider = endlessGameProvider; _characterRendererFactory = characterRendererFactory; _eifFileProvider = eifFileProvider; _gameStateProvider = gameStateProvider; } public void LaunchTestMode() { if (_gameStateProvider.CurrentState != GameStates.Initial) return; var testMode = new CharacterStateTest( _endlessGameProvider.Game, _characterRendererFactory, _eifFileProvider); _endlessGameProvider.Game.Components.Clear(); _endlessGameProvider.Game.Components.Add(testMode); } } public interface ITestModeLauncher { void LaunchTestMode(); } } ``` Fix bug where test mode wouldn't launch
```c# // Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using EndlessClient.GameExecution; using EndlessClient.Rendering.Factories; using EOLib.IO.Repositories; namespace EndlessClient { //todo: move this to a different namespace public class TestModeLauncher : ITestModeLauncher { private readonly IEndlessGameProvider _endlessGameProvider; private readonly ICharacterRendererFactory _characterRendererFactory; private readonly IEIFFileProvider _eifFileProvider; private readonly IGameStateProvider _gameStateProvider; public TestModeLauncher(IEndlessGameProvider endlessGameProvider, ICharacterRendererFactory characterRendererFactory, IEIFFileProvider eifFileProvider, IGameStateProvider gameStateProvider) { _endlessGameProvider = endlessGameProvider; _characterRendererFactory = characterRendererFactory; _eifFileProvider = eifFileProvider; _gameStateProvider = gameStateProvider; } public void LaunchTestMode() { if (_gameStateProvider.CurrentState != GameStates.None) return; var testMode = new CharacterStateTest( _endlessGameProvider.Game, _characterRendererFactory, _eifFileProvider); _endlessGameProvider.Game.Components.Clear(); _endlessGameProvider.Game.Components.Add(testMode); } } public interface ITestModeLauncher { void LaunchTestMode(); } } ```
b0fca065-90ec-4838-b325-ae4b88704206
{ "language": "C#" }
```c# //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34003 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Extras.EnterpriseLibraryConfigurator 3.0.0")] ``` Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0.
```c# //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18051 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Extras.EnterpriseLibraryConfigurator 3.0.0")] ```
0a595ea3-57bb-4fce-b5a0-f48ca19f438f
{ "language": "C#" }
```c# //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-02-22 14:39")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] ``` Build script now creates individual zip file packages to align with the NuGet packages and semantic versioning.
```c# //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-02-28 02:03")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] ```
1b94b4e2-58aa-4874-b096-a6751a01ea42
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ItemCollage { public static class Helper { public static IEnumerable<int> Range(int start, int end, int step = 1) { if (start > end && step > 0 || start < end && step < 0 || step == 0) throw new ArgumentException("Impossible range"); int steps = (end - start) / step; int i, s; for (i = start, s = 0; s <= steps; i += step, s++) { yield return i; } } } } ``` Make Range report invalid arguments when throwing
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ItemCollage { public static class Helper { public static IEnumerable<int> Range(int start, int end, int step = 1) { if (start > end && step > 0 || start < end && step < 0 || step == 0) throw new ArgumentException(string.Format( "Impossible range: {0} to {1} with step {2}", start, end, step)); int steps = (end - start) / step; int i, s; for (i = start, s = 0; s <= steps; i += step, s++) { yield return i; } } } } ```
c19dd808-aaf9-43e3-a9cc-109580e4d255
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("ChangeLoadingImage_beta")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")] ``` Change assembly version for release
```c# using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("ChangeLoadingImage1.0")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")] ```
0b4279ab-0497-49ff-9173-980c6451ba76
{ "language": "C#" }
```c# using System; using System.Runtime.Serialization; [DataContract] class TellEntry { [DataMember] public readonly string From; [DataMember] public readonly string Message; [DataMember] public readonly DateTimeOffset SentDate; public TimeSpan ElapsedTime { get { return DateTimeOffset.Now - SentDate; } } public TellEntry(string from, string message) { From = from; Message = message; SentDate = DateTimeOffset.Now; } }``` Store sent date in UTC
```c# using System; using System.Runtime.Serialization; [DataContract] class TellEntry { [DataMember] public readonly string From; [DataMember] public readonly string Message; [DataMember] public readonly DateTime SentDateUtc; public TimeSpan ElapsedTime { get { return DateTime.UtcNow - SentDateUtc; } } public TellEntry(string from, string message) { From = from; Message = message; SentDateUtc = DateTime.UtcNow; } }```
5ab4c3a7-4681-4ded-800a-4e16f3eee7e7
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle("Spring.Core Tests")] [assembly: AssemblyDescription("Unit tests for Spring.Core assembly")] ``` Add 'side by side' support in Framework .NET 4.0
```c# using System.Reflection; using System.Runtime.CompilerServices; #if NET_4_0 [assembly: System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)] #endif [assembly: AssemblyTitle("Spring.Core Tests")] [assembly: AssemblyDescription("Unit tests for Spring.Core assembly")] ```
5815431b-782c-4ba3-9ee4-e2f829ad48eb
{ "language": "C#" }
```c# using System; using System.IO; using Digipost.Signature.Api.Client.Core.Internal.Asice; using Digipost.Signature.Api.Client.Core.Internal.Extensions; namespace Digipost.Signature.Api.Client.Core { public class Document : IAsiceAttachable { public Document(string title, FileType fileType, string documentPath) : this(title, fileType, File.ReadAllBytes(documentPath)) { } public Document(string title, FileType fileType, byte[] documentBytes) { Title = title; FileName = $"{title}{fileType.GetExtension()}"; MimeType = fileType.ToMimeType(); Bytes = documentBytes; Id = "Id_" + Guid.NewGuid(); } public string Title { get; } public string FileName { get; } public string Id { get; } public string MimeType { get; } public byte[] Bytes { get; } public override string ToString() { return $"Title: {Title}, Id: {Id}, MimeType: {MimeType}"; } } } ``` Make sure filename / href in document bundle are unique
```c# using System; using System.IO; using Digipost.Signature.Api.Client.Core.Internal.Asice; using Digipost.Signature.Api.Client.Core.Internal.Extensions; namespace Digipost.Signature.Api.Client.Core { public class Document : IAsiceAttachable { public Document(string title, FileType fileType, string documentPath) : this(title, fileType, File.ReadAllBytes(documentPath)) { } public Document(string title, FileType fileType, byte[] documentBytes) { Title = title; FileName = $"{Guid.NewGuid()}{fileType.GetExtension()}"; MimeType = fileType.ToMimeType(); Bytes = documentBytes; Id = "Id_" + Guid.NewGuid(); } public string Title { get; } public string FileName { get; } public string Id { get; } public string MimeType { get; } public byte[] Bytes { get; } public override string ToString() { return $"Title: {Title}, Id: {Id}, MimeType: {MimeType}"; } } } ```
a287feca-313b-4884-b563-42909cd480fc
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using NuGet.Packaging.Core; using NuGet.Versioning; namespace NuKeeper.RepositoryInspection { public class PackageUpdateSet { public PackageUpdateSet(PackageIdentity newPackage, IEnumerable<PackageInProject> currentPackages) { if (newPackage == null) { throw new ArgumentNullException(nameof(newPackage)); } if (currentPackages == null) { throw new ArgumentNullException(nameof(currentPackages)); } if (!currentPackages.Any()) { throw new ArgumentException($"{nameof(currentPackages)} is empty"); } if (currentPackages.Any(p => p.Id != newPackage.Id)) { throw new ArgumentException($"Updates must all be for package {newPackage.Id}"); } NewPackage = newPackage; CurrentPackages = currentPackages.ToList(); } public PackageIdentity NewPackage { get; } public List<PackageInProject> CurrentPackages { get; } public string PackageId => NewPackage.Id; public NuGetVersion NewVersion => NewPackage.Version; } }``` Enumerate once, make it readonly
```c# using System; using System.Collections.Generic; using System.Linq; using NuGet.Packaging.Core; using NuGet.Versioning; namespace NuKeeper.RepositoryInspection { public class PackageUpdateSet { public PackageUpdateSet(PackageIdentity newPackage, IEnumerable<PackageInProject> currentPackages) { if (newPackage == null) { throw new ArgumentNullException(nameof(newPackage)); } if (currentPackages == null) { throw new ArgumentNullException(nameof(currentPackages)); } var currentPackagesList = currentPackages.ToList(); if (!currentPackagesList.Any()) { throw new ArgumentException($"{nameof(currentPackages)} is empty"); } if (currentPackagesList.Any(p => p.Id != newPackage.Id)) { throw new ArgumentException($"Updates must all be for package {newPackage.Id}"); } NewPackage = newPackage; CurrentPackages = currentPackagesList; } public PackageIdentity NewPackage { get; } public IReadOnlyCollection<PackageInProject> CurrentPackages { get; } public string PackageId => NewPackage.Id; public NuGetVersion NewVersion => NewPackage.Version; } }```
05c4dcfe-8983-454b-8ff6-b687c54cb56b
{ "language": "C#" }
```c# using System; using LandauMedia.Telemetry.Internal; namespace LandauMedia.Telemetry { public class Counter : ITelemeter { readonly Lazy<string> _lazyName; Action<Lazy<string>, int> _decrement; Action<Lazy<string>> _decrementByOne; Action<Lazy<string>, int> _icnremnent; Action<Lazy<string>> _increamentByOne; internal Counter(LazyName lazyName) { _lazyName = lazyName.Get(this); } void ITelemeter.ChangeImplementation(ITelemeterImpl impl) { _increamentByOne = impl.GetCounterIncrementByOne(); _icnremnent = impl.GetCounterIncrement(); _decrement = impl.GetCounterDecrement(); _decrementByOne = impl.GetCounterDecrementByOne(); } public void Increment() { _increamentByOne(_lazyName); } public void Increment(int count) { _icnremnent(_lazyName, count); } public void Decrement() { _decrementByOne(_lazyName); } public void Decrement(int count) { _decrement(_lazyName, count); } } }``` Increment and Decrement with 0 does not send any data.
```c# using System; using LandauMedia.Telemetry.Internal; namespace LandauMedia.Telemetry { public class Counter : ITelemeter { readonly Lazy<string> _lazyName; Action<Lazy<string>, int> _decrement; Action<Lazy<string>> _decrementByOne; Action<Lazy<string>, int> _icnremnent; Action<Lazy<string>> _increamentByOne; internal Counter(LazyName lazyName) { _lazyName = lazyName.Get(this); } void ITelemeter.ChangeImplementation(ITelemeterImpl impl) { _increamentByOne = impl.GetCounterIncrementByOne(); _icnremnent = impl.GetCounterIncrement(); _decrement = impl.GetCounterDecrement(); _decrementByOne = impl.GetCounterDecrementByOne(); } public void Increment() { _increamentByOne(_lazyName); } public void Increment(int count) { if(count==0) return; _icnremnent(_lazyName, count); } public void Decrement() { _decrementByOne(_lazyName); } public void Decrement(int count) { if(count==0) return; _decrement(_lazyName, count); } } }```
0732680b-e748-483b-8c30-7efa480f4b68
{ "language": "C#" }
```c# using System; using CSharpTraining; using MonoBrickFirmware.Movement; namespace XUnitSample.Tests { /// <summary> /// Sample test class /// </summary> /// <remarks> /// It was described below URL how to use XUnit /// https://xunit.github.io/docs/comparisons.html /// </remarks> public class MainClassTests { [Xunit.Fact(DisplayName = "We can describe test summary by this attribute."), Xunit.Trait("Category", "Sample")] public void MainTest() { Xunit.Assert.True(true); Xunit.Assert.Equal(10, MainClass.SampleMethod()); var foo = new Motor(MotorPort.OutA); var same = foo; Xunit.Assert.Same(foo, same); // Verify their variables are same object. } [Xunit.Fact(Skip="If you want to ignore test case, you set this attribute to the test case.")] public void IgnoreTest() { Xunit.Assert.True(false, "Expected this test case does not be executed."); MainClass.Main(new string[] { "" }); Motor dummy = new Motor(MotorPort.OutA); dummy.GetSpeed(); } } } ``` Change instance from Motor to Object in test case
```c# using System; using CSharpTraining; using MonoBrickFirmware.Movement; namespace XUnitSample.Tests { /// <summary> /// Sample test class /// </summary> /// <remarks> /// It was described below URL how to use XUnit /// https://xunit.github.io/docs/comparisons.html /// </remarks> public class MainClassTests { [Xunit.Fact(DisplayName = "We can describe test summary by this attribute."), Xunit.Trait("Category", "Sample")] public void MainTest() { Xunit.Assert.True(true); Xunit.Assert.Equal(10, MainClass.SampleMethod()); var foo = new Object(); var same = foo; Xunit.Assert.Same(foo, same); // Verify their variables are same object. } [Xunit.Fact(Skip="If you want to ignore test case, you set this attribute to the test case.")] public void IgnoreTest() { Xunit.Assert.True(false, "Expected this test case does not be executed."); MainClass.Main(new string[] { "" }); Motor dummy = new Motor(MotorPort.OutA); dummy.GetSpeed(); } } } ```
e1e033c6-fd28-4a8e-8111-47cfccba83d0
{ "language": "C#" }
```c# #region Copyright (c) 2016 Atif Aziz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion namespace WebLinq.Zip { using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; public static class ZipQuery { public static IEnumerable<HttpFetch<Zip>> DownloadZip(this IEnumerable<HttpFetch<HttpContent>> query) => from fetch in query select fetch.WithContent(new Zip(DownloadZip(fetch.Content))); static string DownloadZip(HttpContent content) { var path = Path.GetTempFileName(); using (var output = File.Create(path)) content.CopyToAsync(output).Wait(); return path; } } } ``` Fix zip download to be non-blocking
```c# #region Copyright (c) 2016 Atif Aziz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion namespace WebLinq.Zip { using System; using System.IO; using System.Net.Http; using System.Reactive.Linq; using System.Threading.Tasks; public static class ZipQuery { public static IObservable<HttpFetch<Zip>> DownloadZip(this IObservable<HttpFetch<HttpContent>> query) => from fetch in query from path in DownloadZip(fetch.Content) select fetch.WithContent(new Zip(path)); static async Task<string> DownloadZip(HttpContent content) { var path = Path.GetTempFileName(); using (var output = File.Create(path)) await content.CopyToAsync(output); return path; } } } ```
a02c50a8-9c9e-408d-8bd3-5ad5e1dbbe21
{ "language": "C#" }
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Input; using OpenTK; using OpenTK.Input; namespace osu.Game.Screens.Play { public class KeyCounterMouse : KeyCounter { public MouseButton Button { get; } public KeyCounterMouse(MouseButton button) : base(button.ToString()) { Button = button; } public override bool Contains(Vector2 screenSpacePos) => true; protected override bool OnMouseDown(InputState state, MouseDownEventArgs args) { if (args.Button == Button) IsLit = true; return base.OnMouseDown(state, args); } protected override bool OnMouseUp(InputState state, MouseUpEventArgs args) { if (args.Button == Button) IsLit = false; return base.OnMouseUp(state, args); } } } ``` Fix KeyCounter M1 M2 display.
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Input; using OpenTK; using OpenTK.Input; namespace osu.Game.Screens.Play { public class KeyCounterMouse : KeyCounter { public MouseButton Button { get; } public KeyCounterMouse(MouseButton button) : base(getStringRepresentation(button)) { Button = button; } private static string getStringRepresentation(MouseButton button) { switch (button) { default: return button.ToString(); case MouseButton.Left: return @"M1"; case MouseButton.Right: return @"M2"; } } public override bool Contains(Vector2 screenSpacePos) => true; protected override bool OnMouseDown(InputState state, MouseDownEventArgs args) { if (args.Button == Button) IsLit = true; return base.OnMouseDown(state, args); } protected override bool OnMouseUp(InputState state, MouseUpEventArgs args) { if (args.Button == Button) IsLit = false; return base.OnMouseUp(state, args); } } } ```
ad3ffafa-2da9-4c70-989d-f3b0a68724b0
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace Sample.Forms.UWP { public sealed partial class MainPage { public MainPage() { this.InitializeComponent(); LoadApplication(new Sample.Forms.App()); } } } ``` Add platform init calls for UWP
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace Sample.Forms.UWP { public sealed partial class MainPage { public MainPage() { this.InitializeComponent(); LoadApplication(new Sample.Forms.App()); ZXing.Net.Mobile.Forms.WindowsUniversal.ZXingScannerViewRenderer.Init(); ZXing.Net.Mobile.Forms.WindowsUniversal.ZXingBarcodeImageViewRenderer.Init(); } } } ```
a454ec46-d6b7-46f4-b9ff-405889d43372
{ "language": "C#" }
```c# using CK.Glouton.Model.Server.Handlers.Implementation; using CK.Glouton.Model.Services; using Microsoft.AspNetCore.Mvc; namespace CK.Glouton.Web.Controllers { [Route( "api/alert" )] public class AlertController : Controller { private readonly IAlertService _alertService; public AlertController( IAlertService alertService ) { _alertService = alertService; } [HttpPost( "add" )] public object AddAlert( [FromBody] AlertExpressionModel alertExpressionModel ) { if( _alertService.NewAlertRequest( alertExpressionModel ) ) return Ok(); return BadRequest(); } [HttpGet( "configuration/{key}" )] public object GetConfiguration( string key ) { if( _alertService.TryGetConfiguration( key, out var configuration ) ) return configuration; return BadRequest(); } [HttpGet( "configuration" )] public string[] GetAllConfiguration() { return _alertService.AvailableConfiguration; } [HttpGet( "all" )] public object GetAllAlerts() { return _alertService.GetAllAlerts(); } } }``` Fix issues with endpoint add of alert controller.
```c# using CK.Glouton.Model.Server.Handlers.Implementation; using CK.Glouton.Model.Services; using Microsoft.AspNetCore.Mvc; namespace CK.Glouton.Web.Controllers { [Route( "api/alert" )] public class AlertController : Controller { private readonly IAlertService _alertService; public AlertController( IAlertService alertService ) { _alertService = alertService; } [HttpPost( "add" )] public object AddAlert( [FromBody] AlertExpressionModel alertExpressionModel ) { if( _alertService.NewAlertRequest( alertExpressionModel ) ) return NoContent(); return BadRequest(); } [HttpGet( "configuration/{key}" )] public object GetConfiguration( string key ) { if( _alertService.TryGetConfiguration( key, out var configuration ) ) return configuration; return BadRequest(); } [HttpGet( "configuration" )] public string[] GetAllConfiguration() { return _alertService.AvailableConfiguration; } [HttpGet( "all" )] public object GetAllAlerts() { return _alertService.GetAllAlerts(); } } }```
69a2a968-259d-4a90-9f56-15ccd2ef31ca
{ "language": "C#" }
```c# // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommentSelection; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; using VSCommanding = Microsoft.VisualStudio.Commanding; namespace Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection { /* TODO - Modify these once the toggle block comment handler is added. [Export(typeof(VSCommanding.ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [Name(PredefinedCommandHandlerNames.CommentSelection)]*/ internal class ToggleBlockCommentCommandHandler : AbstractToggleBlockCommentBase { [ImportingConstructor] internal ToggleBlockCommentCommandHandler( ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService) : base(undoHistoryRegistry, editorOperationsFactoryService) { } /// <summary> /// Gets the default text based document data provider for block comments. /// </summary> protected override async Task<IToggleBlockCommentDocumentDataProvider> GetBlockCommentDocumentDataProvider(Document document, ITextSnapshot snapshot, CommentSelectionInfo commentInfo, CancellationToken cancellationToken) { return new ToggleBlockCommentDocumentDataProvider(snapshot, commentInfo); } } } ``` Fix async warning in toggle block comment.
```c# // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommentSelection; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; using VSCommanding = Microsoft.VisualStudio.Commanding; namespace Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection { /* TODO - Modify these once the toggle block comment handler is added. [Export(typeof(VSCommanding.ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [Name(PredefinedCommandHandlerNames.CommentSelection)]*/ internal class ToggleBlockCommentCommandHandler : AbstractToggleBlockCommentBase { [ImportingConstructor] internal ToggleBlockCommentCommandHandler( ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService) : base(undoHistoryRegistry, editorOperationsFactoryService) { } /// <summary> /// Gets the default text based document data provider for block comments. /// </summary> protected override Task<IToggleBlockCommentDocumentDataProvider> GetBlockCommentDocumentDataProvider(Document document, ITextSnapshot snapshot, CommentSelectionInfo commentInfo, CancellationToken cancellationToken) { IToggleBlockCommentDocumentDataProvider provider = new ToggleBlockCommentDocumentDataProvider(snapshot, commentInfo); return Task.FromResult(provider); } } } ```