Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix failing test by setting the host object | using System;
using System.IO;
using System.Text;
using Microsoft.TemplateEngine.Core.Contracts;
using Xunit;
namespace Microsoft.TemplateEngine.Core.UnitTests
{
public abstract class TestBase
{
protected static void RunAndVerify(string originalValue, string expectedValue, IProcessor processor, int bufferSize, bool? changeOverride = null)
{
byte[] valueBytes = Encoding.UTF8.GetBytes(originalValue);
MemoryStream input = new MemoryStream(valueBytes);
MemoryStream output = new MemoryStream();
bool changed = processor.Run(input, output, bufferSize);
Verify(Encoding.UTF8, output, changed, originalValue, expectedValue, changeOverride);
}
protected static void Verify(Encoding encoding, Stream output, bool changed, string source, string expected, bool? changeOverride = null)
{
output.Position = 0;
byte[] resultBytes = new byte[output.Length];
output.Read(resultBytes, 0, resultBytes.Length);
string actual = encoding.GetString(resultBytes);
Assert.Equal(expected, actual);
bool expectedChange = changeOverride ?? !string.Equals(expected, source, StringComparison.Ordinal);
string modifier = expectedChange ? "" : "not ";
if (expectedChange ^ changed)
{
Assert.False(true, $"Expected value to {modifier} be changed");
}
}
}
}
| using System;
using System.IO;
using System.Text;
using Microsoft.TemplateEngine.Core.Contracts;
using Microsoft.TemplateEngine.Utils;
using Xunit;
namespace Microsoft.TemplateEngine.Core.UnitTests
{
public abstract class TestBase
{
protected TestBase()
{
EngineEnvironmentSettings.Host = new DefaultTemplateEngineHost("TestRunner", Version.Parse("1.0.0.0"), "en-US");
}
protected static void RunAndVerify(string originalValue, string expectedValue, IProcessor processor, int bufferSize, bool? changeOverride = null)
{
byte[] valueBytes = Encoding.UTF8.GetBytes(originalValue);
MemoryStream input = new MemoryStream(valueBytes);
MemoryStream output = new MemoryStream();
bool changed = processor.Run(input, output, bufferSize);
Verify(Encoding.UTF8, output, changed, originalValue, expectedValue, changeOverride);
}
protected static void Verify(Encoding encoding, Stream output, bool changed, string source, string expected, bool? changeOverride = null)
{
output.Position = 0;
byte[] resultBytes = new byte[output.Length];
output.Read(resultBytes, 0, resultBytes.Length);
string actual = encoding.GetString(resultBytes);
Assert.Equal(expected, actual);
bool expectedChange = changeOverride ?? !string.Equals(expected, source, StringComparison.Ordinal);
string modifier = expectedChange ? "" : "not ";
if (expectedChange ^ changed)
{
Assert.False(true, $"Expected value to {modifier} be changed");
}
}
}
}
|
Add /GET for a single website resource | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using GeoToast.Data;
using GeoToast.Data.Models;
using GeoToast.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace GeoToast.Controllers
{
//[Authorize]
[Route("api/[controller]")]
public class WebsiteController : Controller
{
private readonly GeoToastDbContext _dbContext;
private readonly IMapper _mapper;
public WebsiteController(GeoToastDbContext dbContext, IMapper mapper)
{
_dbContext = dbContext;
_mapper = mapper;
}
[HttpGet]
public IEnumerable<WebsiteReadModel> Get()
{
// TODO: Only select websites for current User
return _mapper.Map<List<WebsiteReadModel>>(_dbContext.Websites);
}
[HttpPost]
public async Task<IActionResult> Post([FromBody]WebsiteCreateModel model)
{
if (ModelState.IsValid)
{
// TODO: Set User ID
var website = _mapper.Map<Website>(model);
_dbContext.Websites.Add(website);
await _dbContext.SaveChangesAsync();
return CreatedAtAction("Get", website.Id);
}
return BadRequest();
}
}
} | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using GeoToast.Data;
using GeoToast.Data.Models;
using GeoToast.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace GeoToast.Controllers
{
//[Authorize]
[Route("api/website")]
public class WebsiteController : Controller
{
private readonly GeoToastDbContext _dbContext;
private readonly IMapper _mapper;
public WebsiteController(GeoToastDbContext dbContext, IMapper mapper)
{
_dbContext = dbContext;
_mapper = mapper;
}
[HttpGet]
public IEnumerable<WebsiteReadModel> Get()
{
// TODO: Only select websites for current User
return _mapper.Map<List<WebsiteReadModel>>(_dbContext.Websites);
}
[HttpGet("{id}")]
public async Task<IActionResult> Get(int id)
{
var website = await _dbContext.Websites.FirstOrDefaultAsync(w => w.Id == id);
if (website == null)
return NotFound();
return Ok(_mapper.Map<WebsiteReadModel>(website));
}
[HttpPost]
public async Task<IActionResult> Post([FromBody]WebsiteCreateModel model)
{
if (ModelState.IsValid)
{
// TODO: Set User ID
var website = _mapper.Map<Website>(model);
_dbContext.Websites.Add(website);
await _dbContext.SaveChangesAsync();
return CreatedAtAction("Get", new { id = website.Id }, _mapper.Map<WebsiteReadModel>(website));
}
return BadRequest();
}
}
} |
Allow statically bound Razor templates to be output cached | using System.Web.UI;
using Sitecore.Web.UI;
using Blade.Razor;
using Blade.Utility;
using Sitecore.Diagnostics;
namespace Blade.Views
{
/// <summary>
/// Allows statically binding a Razor template as if it were a WebControl
/// </summary>
public class RazorTemplate : WebControl
{
/// <summary>
/// Virtual path to the Razor file to render
/// </summary>
public string Path { get; set; }
/// <summary>
/// The Model for the Razor view. The model will be null if this is unset.
/// </summary>
public object Model { get; set; }
protected override void DoRender(HtmlTextWriter output)
{
using (new RenderingDiagnostics(output, Path + " (statically bound)", Cacheable, VaryByData, VaryByDevice, VaryByLogin, VaryByParm, VaryByQueryString, VaryByUser, ClearOnIndexUpdate, GetCachingID()))
{
Assert.IsNotNull(Path, "Path was null or empty, and must point to a valid virtual path to a Razor rendering.");
var renderer = new ViewRenderer();
var result = renderer.RenderPartialViewToString(Path, Model);
output.Write(result);
}
}
}
}
| using System.Web.UI;
using Sitecore.Web.UI;
using Blade.Razor;
using Blade.Utility;
using Sitecore.Diagnostics;
namespace Blade.Views
{
/// <summary>
/// Allows statically binding a Razor template as if it were a WebControl
/// </summary>
public class RazorTemplate : WebControl
{
/// <summary>
/// Virtual path to the Razor file to render
/// </summary>
public string Path { get; set; }
/// <summary>
/// The Model for the Razor view. The model will be null if this is unset.
/// </summary>
public object Model { get; set; }
protected override void DoRender(HtmlTextWriter output)
{
using (new RenderingDiagnostics(output, Path + " (statically bound)", Cacheable, VaryByData, VaryByDevice, VaryByLogin, VaryByParm, VaryByQueryString, VaryByUser, ClearOnIndexUpdate, GetCachingID()))
{
Assert.IsNotNull(Path, "Path was null or empty, and must point to a valid virtual path to a Razor rendering.");
var renderer = new ViewRenderer();
var result = renderer.RenderPartialViewToString(Path, Model);
output.Write(result);
}
}
protected override string GetCachingID()
{
return Path;
}
}
}
|
Implement RunServerCompilation in portable build task | // 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 Microsoft.CodeAnalysis.CommandLine;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.BuildTasks
{
internal static class BuildClientShim
{
public static Task<BuildResponse> RunServerCompilation(
RequestLanguage language,
List<string> arguments,
BuildPaths buildPaths,
string keepAlive,
string libEnvVariable,
CancellationToken cancellationToken)
{
throw new NotSupportedException();
}
}
}
| // 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 Microsoft.CodeAnalysis.CommandLine;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.BuildTasks
{
internal static class BuildClientShim
{
public static Task<BuildResponse> RunServerCompilation(
RequestLanguage language,
List<string> arguments,
BuildPaths buildPaths,
string keepAlive,
string libEnvVariable,
CancellationToken cancellationToken) => Task.FromResult<BuildResponse>(null);
}
}
|
Fix copy/paste bug related to changeset a06f6c6cd5ab | using System;
using System.Collections.Generic;
using System.Net.Mail;
using Composite.C1Console.Workflow;
namespace CompositeC1Contrib.Email.C1Console.Workflows
{
[AllowPersistingWorkflow(WorkflowPersistingType.Idle)]
public sealed class EditConfigurableSystemNetMailClientQueueWorkflow : EditMailQueueWorkflow
{
public EditConfigurableSystemNetMailClientQueueWorkflow() : base("\\InstalledPackages\\CompositeC1Contrib.Email\\EditConfigurableSystemNetMailClientQueue.xml") { }
public static IEnumerable<string> GetNetworkDeliveryOptions()
{
return Enum.GetNames(typeof(SmtpDeliveryMethod));
}
}
}
| using System;
using System.Collections.Generic;
using System.Net.Mail;
namespace CompositeC1Contrib.Email.C1Console.Workflows
{
public sealed class EditConfigurableSystemNetMailClientQueueWorkflow : EditMailQueueWorkflow
{
public EditConfigurableSystemNetMailClientQueueWorkflow() : base("\\InstalledPackages\\CompositeC1Contrib.Email\\EditConfigurableSystemNetMailClientQueue.xml") { }
public static IEnumerable<string> GetNetworkDeliveryOptions()
{
return Enum.GetNames(typeof(SmtpDeliveryMethod));
}
}
}
|
Update class that was missed in the last commit |
namespace Glimpse.Agent.AspNet.Mvc.Messages
{
public class ActionInvokedMessage
{
public string ActionId { get; set; }
public Timing Timing { get; set; }
}
} |
namespace Glimpse.Agent.AspNet.Mvc.Messages
{
public class AfterActionMessage
{
public string ActionId { get; set; }
public Timing Timing { get; set; }
}
} |
Fix feature FootprintY having FootprintX value | namespace Mappy.Data
{
using Mappy.Util;
using TAUtil.Tdf;
public class FeatureRecord
{
public string Name { get; set; }
public string World { get; set; }
public string Category { get; set; }
public int FootprintX { get; set; }
public int FootprintY { get; set; }
public string AnimFileName { get; set; }
public string SequenceName { get; set; }
public string ObjectName { get; set; }
public static FeatureRecord FromTdfNode(TdfNode n)
{
return new FeatureRecord
{
Name = n.Name,
World = n.Entries.GetOrDefault("world", string.Empty),
Category = n.Entries.GetOrDefault("category", string.Empty),
FootprintX = TdfConvert.ToInt32(n.Entries.GetOrDefault("footprintx", "0")),
FootprintY = TdfConvert.ToInt32(n.Entries.GetOrDefault("footprintx", "0")),
AnimFileName = n.Entries.GetOrDefault("filename", string.Empty),
SequenceName = n.Entries.GetOrDefault("seqname", string.Empty),
ObjectName = n.Entries.GetOrDefault("object", string.Empty)
};
}
}
}
| namespace Mappy.Data
{
using Mappy.Util;
using TAUtil.Tdf;
public class FeatureRecord
{
public string Name { get; set; }
public string World { get; set; }
public string Category { get; set; }
public int FootprintX { get; set; }
public int FootprintY { get; set; }
public string AnimFileName { get; set; }
public string SequenceName { get; set; }
public string ObjectName { get; set; }
public static FeatureRecord FromTdfNode(TdfNode n)
{
return new FeatureRecord
{
Name = n.Name,
World = n.Entries.GetOrDefault("world", string.Empty),
Category = n.Entries.GetOrDefault("category", string.Empty),
FootprintX = TdfConvert.ToInt32(n.Entries.GetOrDefault("footprintx", "0")),
FootprintY = TdfConvert.ToInt32(n.Entries.GetOrDefault("footprintz", "0")),
AnimFileName = n.Entries.GetOrDefault("filename", string.Empty),
SequenceName = n.Entries.GetOrDefault("seqname", string.Empty),
ObjectName = n.Entries.GetOrDefault("object", string.Empty)
};
}
}
}
|
Add missing '.' to /// comment | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="ErrorController.cs" company="https://martincostello.com/">
// Martin Costello (c) 2016
// </copyright>
// <summary>
// ErrorController.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace MartinCostello.Api.Controllers
{
using Microsoft.AspNetCore.Mvc;
/// <summary>
/// A class representing the controller for the <c>/error</c> resource.
/// </summary>
public class ErrorController : Controller
{
/// <summary>
/// Gets the view for the error page.
/// </summary>
/// <param name="id">The optional HTTP status code associated with the error</param>
/// <returns>
/// The view for the error page.
/// </returns>
[HttpGet]
public IActionResult Index(int? id) => View("Error", id ?? 500);
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="ErrorController.cs" company="https://martincostello.com/">
// Martin Costello (c) 2016
// </copyright>
// <summary>
// ErrorController.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace MartinCostello.Api.Controllers
{
using Microsoft.AspNetCore.Mvc;
/// <summary>
/// A class representing the controller for the <c>/error</c> resource.
/// </summary>
public class ErrorController : Controller
{
/// <summary>
/// Gets the view for the error page.
/// </summary>
/// <param name="id">The optional HTTP status code associated with the error.</param>
/// <returns>
/// The view for the error page.
/// </returns>
[HttpGet]
public IActionResult Index(int? id) => View("Error", id ?? 500);
}
}
|
Set environment variable configuration to the passed in parameter | using System;
namespace AppHarbor.Commands
{
public class LoginCommand : ICommand
{
private readonly AppHarborApi _appHarborApi;
private readonly EnvironmentVariableConfiguration _environmentVariableConfiguration;
public LoginCommand(AppHarborApi appHarborApi, EnvironmentVariableConfiguration environmentVariableConfiguration)
{
_appHarborApi = appHarborApi;
_environmentVariableConfiguration = _environmentVariableConfiguration;
}
public void Execute(string[] arguments)
{
Console.WriteLine("Username:");
var username = Console.ReadLine();
Console.WriteLine("Password:");
var password = Console.ReadLine();
}
}
}
| using System;
namespace AppHarbor.Commands
{
public class LoginCommand : ICommand
{
private readonly AppHarborApi _appHarborApi;
private readonly EnvironmentVariableConfiguration _environmentVariableConfiguration;
public LoginCommand(AppHarborApi appHarborApi, EnvironmentVariableConfiguration environmentVariableConfiguration)
{
_appHarborApi = appHarborApi;
_environmentVariableConfiguration = environmentVariableConfiguration;
}
public void Execute(string[] arguments)
{
Console.WriteLine("Username:");
var username = Console.ReadLine();
Console.WriteLine("Password:");
var password = Console.ReadLine();
}
}
}
|
Resolve compiler warnings from BenchmarkDotNet upgrade | // Copyright (c) Andrew Arnott. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Nerdbank.Streams.Benchmark
{
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Jobs;
internal class BenchmarkConfig : ManualConfig
{
public BenchmarkConfig()
{
this.Add(DefaultConfig.Instance.With(MemoryDiagnoser.Default));
}
}
}
| // Copyright (c) Andrew Arnott. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Nerdbank.Streams.Benchmark
{
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Jobs;
internal class BenchmarkConfig : ManualConfig
{
public BenchmarkConfig()
{
this.Add(DefaultConfig.Instance.AddDiagnoser(MemoryDiagnoser.Default));
}
}
}
|
Use HostConstants in the extensions. | namespace SignalR.Abstractions
{
public static class HostContextExtensions
{
public static T GetValue<T>(this HostContext context, string key)
{
object value;
if (context.Items.TryGetValue(key, out value))
{
return (T)value;
}
return default(T);
}
public static bool IsDebuggingEnabled(this HostContext context)
{
return context.GetValue<bool>("debugMode");
}
public static bool SupportsWebSockets(this HostContext context)
{
return context.GetValue<bool>("supportsWebSockets");
}
}
}
| namespace SignalR.Abstractions
{
public static class HostContextExtensions
{
public static T GetValue<T>(this HostContext context, string key)
{
object value;
if (context.Items.TryGetValue(key, out value))
{
return (T)value;
}
return default(T);
}
public static bool IsDebuggingEnabled(this HostContext context)
{
return context.GetValue<bool>(HostConstants.DebugMode);
}
public static bool SupportsWebSockets(this HostContext context)
{
return context.GetValue<bool>(HostConstants.SupportsWebSockets);
}
}
}
|
Update feed uri, blog platform transition | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class JoshKing : IAmACommunityMember, IFilterMyBlogPosts
{
public string FirstName => "Josh";
public string LastName => "King";
public string ShortBioOrTagLine => "Geek, Father, Walking Helpdesk";
public string StateOrRegion => "Hawke's Bay, NZ";
public string EmailAddress => "joshua@king.geek.nz";
public string TwitterHandle => "WindosNZ";
public string GitHubHandle => "Windos";
public string GravatarHash => "fafdbc410c9adf8c4d2235d37470859a";
public GeoPosition Position => new GeoPosition(-39.4928, 176.9120);
public Uri WebSite => new Uri("https://king.geek.nz/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://king.geek.nz/feed.xml"); } }
public bool Filter(SyndicationItem item)
{
return item.Categories.Where(i => i.Name.Equals("powershell", StringComparison.OrdinalIgnoreCase)).Any();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class JoshKing : IAmACommunityMember
{
public string FirstName => "Josh";
public string LastName => "King";
public string ShortBioOrTagLine => "Geek, Father, Walking Helpdesk";
public string StateOrRegion => "Hawke's Bay, NZ";
public string EmailAddress => "joshua@king.geek.nz";
public string TwitterHandle => "WindosNZ";
public string GitHubHandle => "Windos";
public string GravatarHash => "fafdbc410c9adf8c4d2235d37470859a";
public GeoPosition Position => new GeoPosition(-39.4928, 176.9120);
public Uri WebSite => new Uri("https://king.geek.nz/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://king.geek.nz/tag/powershell/rss/"); } }
}
}
|
Check for forum notifications more often. | namespace Mitternacht.Common {
public class TimeConstants {
public const int WaitForForum = 500;
public const int TeamUpdate = 3 * 60 * 1000;
public const int Birthday = 60 * 1000;
public const int ForumNotification = 1 * 60 * 1000;
}
}
| namespace Mitternacht.Common {
public class TimeConstants {
public const int WaitForForum = 500;
public const int TeamUpdate = 3 * 60 * 1000;
public const int Birthday = 60 * 1000;
public const int ForumNotification = 30 * 1000;
}
}
|
Update the test runner to use the new parser interface. | using System;
using System.IO;
using Cxxi;
using Cxxi.Types;
namespace Generator.Tests
{
public class HeaderTestFixture
{
protected Library library;
protected TypeMapDatabase database;
private const string TestsDirectory = @"..\..\..\tests\Native";
protected void ParseLibrary(string file)
{
ParseLibrary(TestsDirectory, file);
}
protected void ParseLibrary(string dir, string file)
{
database = new TypeMapDatabase();
database.SetupTypeMaps();
var options = new DriverOptions();
var path = Path.Combine(Directory.GetCurrentDirectory(), dir);
options.IncludeDirs.Add(path);
var parser = new Parser(options);
var result = parser.ParseHeader(file);
if (!result.Success)
throw new Exception("Could not parse file: " + file);
library = result.Library;
foreach (var diag in result.Diagnostics)
Console.WriteLine(diag.Message);
}
}
}
| using System;
using System.IO;
using Cxxi;
using Cxxi.Types;
namespace Generator.Tests
{
public class HeaderTestFixture
{
protected Library library;
protected TypeMapDatabase database;
private const string TestsDirectory = @"..\..\..\tests\Native";
protected void ParseLibrary(string file)
{
ParseLibrary(TestsDirectory, file);
}
protected void ParseLibrary(string dir, string file)
{
database = new TypeMapDatabase();
database.SetupTypeMaps();
var options = new DriverOptions();
var path = Path.Combine(Directory.GetCurrentDirectory(), dir);
options.IncludeDirs.Add(path);
var parser = new Parser(options);
var result = parser.ParseHeader(file);
if (result.Kind != ParserResultKind.Success)
throw new Exception("Could not parse file: " + file);
library = result.Library;
foreach (var diag in result.Diagnostics)
Console.WriteLine(diag.Message);
}
}
}
|
Add missing unit tests for Range equality. | using System;
using NUnit.Framework;
namespace FindRandomNumber.Common {
[TestFixture]
public class RangeTests {
[TestFixture]
public class Construction : RangeTests {
[Test]
public void GivenMaximumLessThanMinimum_Throws() {
Assert.Throws<ArgumentOutOfRangeException>(() => new Range(100, 99));
}
[Test]
public void GivenMaximumEqualToMinimum_DoesNotThrow() {
var actual = new Range(100, 100);
Assert.That(actual.Minimum, Is.EqualTo(100));
Assert.That(actual.Maximum, Is.EqualTo(100));
}
[Test]
public void GivenMaximumGreaterThanMinimum_DoesNotThrow() {
var actual = new Range(100, 200);
Assert.That(actual.Minimum, Is.EqualTo(100));
Assert.That(actual.Maximum, Is.EqualTo(200));
}
}
}
} | using System;
using NUnit.Framework;
namespace FindRandomNumber.Common {
[TestFixture]
public class RangeTests {
[TestFixture]
public class Construction : RangeTests {
[Test]
public void GivenMaximumLessThanMinimum_Throws() {
Assert.Throws<ArgumentOutOfRangeException>(() => new Range(100, 99));
}
[Test]
public void GivenMaximumEqualToMinimum_DoesNotThrow() {
var actual = new Range(100, 100);
Assert.That(actual.Minimum, Is.EqualTo(100));
Assert.That(actual.Maximum, Is.EqualTo(100));
}
[Test]
public void GivenMaximumGreaterThanMinimum_DoesNotThrow() {
var actual = new Range(100, 200);
Assert.That(actual.Minimum, Is.EqualTo(100));
Assert.That(actual.Maximum, Is.EqualTo(200));
}
}
[TestFixture]
public class Equality : RangeTests {
[Test]
public void EmptyInstances_AreEqual() {
var obj1 = new Range();
var obj2 = new Range();
Assert.That(obj1.Equals(obj2));
Assert.That(obj1.GetHashCode(), Is.EqualTo(obj2.GetHashCode()));
Assert.That(obj1 == obj2);
}
[Test]
public void ObjectsWithEqualValues_AreEqual() {
var obj1 = new Range(321, 456);
var obj2 = new Range(321, 456);
Assert.That(obj1.Equals(obj2));
Assert.That(obj1 == obj2);
Assert.That(obj1.GetHashCode(), Is.EqualTo(obj2.GetHashCode()));
}
[Test]
public void ObjectsWithDifferentValues_AreNotEqual() {
var obj1 = new Range(1, 123);
var obj2 = new Range(1, 124);
var obj3 = new Range(0, 123);
Assert.That(!obj1.Equals(obj2));
Assert.That(obj1 != obj2);
Assert.That(!obj2.Equals(obj3));
Assert.That(obj2 != obj3);
Assert.That(!obj1.Equals(obj3));
Assert.That(obj1 != obj3);
}
}
}
} |
Comment the security check so it's obvious what its for. | using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace NuGetGallery
{
public partial class PagesController : Controller
{
public IContentService ContentService { get; protected set; }
protected PagesController() { }
public PagesController(IContentService contentService)
{
ContentService = contentService;
}
// This will let you add 'static' cshtml pages to the site under View/Pages or Branding/Views/Pages
public virtual ActionResult Page(string pageName)
{
if (pageName == null || pageName.Any(c => !Char.IsLetterOrDigit(c)))
{
return HttpNotFound();
}
return View(pageName);
}
public virtual ActionResult Contact()
{
return View();
}
public virtual async Task<ActionResult> Home()
{
if (ContentService != null)
{
ViewBag.Content = await ContentService.GetContentItemAsync(
Constants.ContentNames.Home,
TimeSpan.FromMinutes(1));
}
return View();
}
public virtual async Task<ActionResult> Terms()
{
if (ContentService != null)
{
ViewBag.Content = await ContentService.GetContentItemAsync(
Constants.ContentNames.TermsOfUse,
TimeSpan.FromDays(1));
}
return View();
}
public virtual async Task<ActionResult> Privacy()
{
if (ContentService != null)
{
ViewBag.Content = await ContentService.GetContentItemAsync(
Constants.ContentNames.PrivacyPolicy,
TimeSpan.FromDays(1));
}
return View();
}
}
} | using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace NuGetGallery
{
public partial class PagesController : Controller
{
public IContentService ContentService { get; protected set; }
protected PagesController() { }
public PagesController(IContentService contentService)
{
ContentService = contentService;
}
// This will let you add 'static' cshtml pages to the site under View/Pages or Branding/Views/Pages
public virtual ActionResult Page(string pageName)
{
// Prevent traversal attacks and serving non-pages by disallowing ., /, %, and more!
if (pageName == null || pageName.Any(c => !Char.IsLetterOrDigit(c)))
{
return HttpNotFound();
}
return View(pageName);
}
public virtual ActionResult Contact()
{
return View();
}
public virtual async Task<ActionResult> Home()
{
if (ContentService != null)
{
ViewBag.Content = await ContentService.GetContentItemAsync(
Constants.ContentNames.Home,
TimeSpan.FromMinutes(1));
}
return View();
}
public virtual async Task<ActionResult> Terms()
{
if (ContentService != null)
{
ViewBag.Content = await ContentService.GetContentItemAsync(
Constants.ContentNames.TermsOfUse,
TimeSpan.FromDays(1));
}
return View();
}
public virtual async Task<ActionResult> Privacy()
{
if (ContentService != null)
{
ViewBag.Content = await ContentService.GetContentItemAsync(
Constants.ContentNames.PrivacyPolicy,
TimeSpan.FromDays(1));
}
return View();
}
}
} |
Split a really long WriteLine into a Write & WriteLine. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cheers
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello there! What's your name?");
string name = Console.ReadLine();
foreach (char letter in name.ToLower())
{
if (Char.IsLetter(letter))
{
string aOrAn = "a... ";
foreach (char nonvoiced in "halfnorsemix")
{
if (letter == nonvoiced)
{
aOrAn = "an... ";
}
}
Console.WriteLine("Give me " + aOrAn + letter);
}
}
Console.WriteLine(name.ToUpper() + "'s just GRAND!");
Console.WriteLine("Hey, " + name + ", what’s your birthday ? (MM/DD)");
string birthday = Console.ReadLine();
DateTime convertedBirthday = Convert.ToDateTime(birthday);
DateTime today = DateTime.Today;
if (convertedBirthday.Equals(today))
{
Console.WriteLine("Happy Birthday!!");
}
else
{
if (convertedBirthday < today)
{
convertedBirthday = convertedBirthday.AddYears(1);
}
Console.WriteLine("Awesome! Your birthday is in " + convertedBirthday.Subtract(today).Days + " days! Happy Birthday in advance!");
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cheers
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello there! What's your name?");
string name = Console.ReadLine();
foreach (char letter in name.ToLower())
{
if (Char.IsLetter(letter))
{
string aOrAn = "a... ";
foreach (char nonvoiced in "halfnorsemix")
{
if (letter == nonvoiced)
{
aOrAn = "an... ";
}
}
Console.WriteLine("Give me " + aOrAn + letter);
}
}
Console.WriteLine(name.ToUpper() + "'s just GRAND!");
Console.WriteLine("Hey, " + name + ", what’s your birthday ? (MM/DD)");
string birthday = Console.ReadLine();
DateTime convertedBirthday = Convert.ToDateTime(birthday);
DateTime today = DateTime.Today;
if (convertedBirthday.Equals(today))
{
Console.WriteLine("Happy Birthday!!");
}
else
{
if (convertedBirthday < today)
{
convertedBirthday = convertedBirthday.AddYears(1);
}
Console.Write("Awesome! Your birthday is in " + convertedBirthday.Subtract(today).Days);
Console.WriteLine(" days! Happy Birthday in advance!");
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
|
Hide comment form if user not signed in. | @model CompetitionPlatform.Models.ProjectViewModels.ProjectCommentPartialViewModel
<form asp-controller="ProjectDetails" asp-action="AddComment" enctype="multipart/form-data">
<div class="form-group">
@Html.Hidden("projectId", Model.ProjectId)
<input asp-for="@Model.ProjectId" type="hidden" />
<textarea asp-for="@Model.Comment" rows="5" class="form-control" placeholder="Enter your comment here..."></textarea>
</div>
<input type="submit" value="Post Comment" class="btn btn-primary pull-right" />
</form>
<div class="project-details-comments">
@foreach (var comment in Model.Comments)
{
<div class="container">
<div class="row">
<div class="project-comments-avatar inline">
<img src="~/images/avatar.svg"
alt="@Model.FullName"
asp-append-version="true" />
</div>
<p class="project-comment-author bold-text inline">
@comment.FullName
@if (Model.UserId == comment.UserId)
{
<span class="label label-primary">CREATOR</span>
}
</p>
<small class="inline text-muted">@comment.LastModified.ToString("hh:mm tt MMMM dd, yyyy")</small>
</div>
<div class="project-comment col-md-9">
<p class="project-comment-text">@comment.Comment</p>
</div>
</div>
}
</div> | @using System.Threading.Tasks
@using CompetitionPlatform.Helpers
@model CompetitionPlatform.Models.ProjectViewModels.ProjectCommentPartialViewModel
<form asp-controller="ProjectDetails" asp-action="AddComment" enctype="multipart/form-data">
@if (ClaimsHelper.GetUser(User.Identity).Email != null)
{
<div class="form-group">
@Html.Hidden("projectId", Model.ProjectId)
<input asp-for="@Model.ProjectId" type="hidden" />
<textarea asp-for="@Model.Comment" rows="5" class="form-control" placeholder="Enter your comment here..."></textarea>
</div>
<input type="submit" value="Post Comment" class="btn btn-primary pull-right" />
}
</form>
<div class="project-details-comments">
@foreach (var comment in Model.Comments)
{
<div class="container">
<div class="row">
<div class="project-comments-avatar inline">
<img src="~/images/avatar.svg"
alt="@Model.FullName"
asp-append-version="true" />
</div>
<p class="project-comment-author bold-text inline">
@comment.FullName
@if (Model.UserId == comment.UserId)
{
<span class="label label-primary">CREATOR</span>
}
</p>
<small class="inline text-muted">@comment.LastModified.ToString("hh:mm tt MMMM dd, yyyy")</small>
</div>
<div class="project-comment col-md-9">
<p class="project-comment-text">@comment.Comment</p>
</div>
</div>
}
</div> |
Rename the test class and method | using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace VersionOne.Bugzilla.BugzillaAPI.Testss
{
[TestClass()]
public class given_a_Bug
{
private IBug _bug;
private string _expectedReassignToPayload;
[TestInitialize()]
public void SetContext()
{
_bug = new Bug();
_expectedReassignToPayload = "{\r\n \"assigned_to\": \"denise@denise.com\",\r\n \"status\": \"CONFIRMED\",\r\n \"token\": \"terry.densmore@versionone.com\"\r\n}";
}
[TestMethod]
public void it_should_give_appropriate_reassigneto_payloads()
{
var integrationUser = "terry.densmore@versionone.com";
_bug.AssignedTo = "denise@denise.com";
Assert.IsTrue(_expectedReassignToPayload == _bug.GetReassignBugPayload(integrationUser));
}
}
}
| using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace VersionOne.Bugzilla.BugzillaAPI.Testss
{
[TestClass()]
public class Given_A_Bug
{
private IBug _bug;
private string _expectedReassignToPayload;
[TestInitialize()]
public void SetContext()
{
_bug = new Bug();
_expectedReassignToPayload = "{\r\n \"assigned_to\": \"denise@denise.com\",\r\n \"status\": \"CONFIRMED\",\r\n \"token\": \"terry.densmore@versionone.com\"\r\n}";
}
[TestMethod]
public void it_should_give_appropriate_reassignto_payloads()
{
var integrationUser = "terry.densmore@versionone.com";
_bug.AssignedTo = "denise@denise.com";
Assert.IsTrue(_expectedReassignToPayload == _bug.GetReassignBugPayload(integrationUser));
}
}
}
|
Use switch statement instead of an array | // 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.Bindables;
using osu.Framework.Graphics.Textures;
using osu.Game.Rulesets.Catch.Objects.Drawables;
namespace osu.Game.Rulesets.Catch.Skinning.Legacy
{
internal class LegacyFruitPiece : LegacyCatchHitObjectPiece
{
public readonly Bindable<FruitVisualRepresentation> VisualRepresentation = new Bindable<FruitVisualRepresentation>();
private readonly string[] lookupNames =
{
"fruit-pear", "fruit-grapes", "fruit-apple", "fruit-orange"
};
protected override void LoadComplete()
{
base.LoadComplete();
var fruit = (DrawableFruit)DrawableHitObject;
if (fruit != null)
VisualRepresentation.BindTo(fruit.VisualRepresentation);
VisualRepresentation.BindValueChanged(visual => setTexture(visual.NewValue), true);
}
private void setTexture(FruitVisualRepresentation visualRepresentation)
{
Texture texture = Skin.GetTexture(lookupNames[(int)visualRepresentation]);
Texture overlayTexture = Skin.GetTexture(lookupNames[(int)visualRepresentation] + "-overlay");
SetTexture(texture, overlayTexture);
}
}
}
| // 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.Bindables;
using osu.Game.Rulesets.Catch.Objects.Drawables;
namespace osu.Game.Rulesets.Catch.Skinning.Legacy
{
internal class LegacyFruitPiece : LegacyCatchHitObjectPiece
{
public readonly Bindable<FruitVisualRepresentation> VisualRepresentation = new Bindable<FruitVisualRepresentation>();
protected override void LoadComplete()
{
base.LoadComplete();
var fruit = (DrawableFruit)DrawableHitObject;
if (fruit != null)
VisualRepresentation.BindTo(fruit.VisualRepresentation);
VisualRepresentation.BindValueChanged(visual => setTexture(visual.NewValue), true);
}
private void setTexture(FruitVisualRepresentation visualRepresentation)
{
switch (visualRepresentation)
{
case FruitVisualRepresentation.Pear:
SetTexture(Skin.GetTexture("fruit-pear"), Skin.GetTexture("fruit-pear-overlay"));
break;
case FruitVisualRepresentation.Grape:
SetTexture(Skin.GetTexture("fruit-grapes"), Skin.GetTexture("fruit-grapes-overlay"));
break;
case FruitVisualRepresentation.Pineapple:
SetTexture(Skin.GetTexture("fruit-apple"), Skin.GetTexture("fruit-apple-overlay"));
break;
case FruitVisualRepresentation.Raspberry:
SetTexture(Skin.GetTexture("fruit-orange"), Skin.GetTexture("fruit-orange-overlay"));
break;
}
}
}
}
|
Change Error class to internal | namespace Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.Implementation
{
using System.Runtime.Serialization;
[DataContract]
internal class BackendResponse
{
[DataMember(Name = "itemsReceived")]
public int ItemsReceived { get; set; }
[DataMember(Name = "itemsAccepted")]
public int ItemsAccepted { get; set; }
[DataMember(Name = "errors")]
public Error[] Errors { get; set; }
[DataContract]
public class Error
{
[DataMember(Name = "index")]
public int Index { get; set; }
[DataMember(Name = "statusCode")]
public int StatusCode { get; set; }
[DataMember(Name = "message")]
public string Message { get; set; }
}
}
}
| namespace Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.Implementation
{
using System.Runtime.Serialization;
[DataContract]
internal class BackendResponse
{
[DataMember(Name = "itemsReceived")]
public int ItemsReceived { get; set; }
[DataMember(Name = "itemsAccepted")]
public int ItemsAccepted { get; set; }
[DataMember(Name = "errors")]
public Error[] Errors { get; set; }
[DataContract]
internal class Error
{
[DataMember(Name = "index")]
public int Index { get; set; }
[DataMember(Name = "statusCode")]
public int StatusCode { get; set; }
[DataMember(Name = "message")]
public string Message { get; set; }
}
}
}
|
Fix failing multiplayer player test | // 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.Linq;
using NUnit.Framework;
using osu.Framework.Testing;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.OnlinePlay.Multiplayer;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestSceneMultiplayerPlayer : MultiplayerTestScene
{
private MultiplayerPlayer player;
[SetUpSteps]
public override void SetUpSteps()
{
base.SetUpSteps();
AddStep("set beatmap", () =>
{
Beatmap.Value = CreateWorkingBeatmap(new OsuRuleset().RulesetInfo);
});
AddStep("initialise gameplay", () =>
{
Stack.Push(player = new MultiplayerPlayer(Client.APIRoom, Client.CurrentMatchPlayingItem.Value, Client.Room?.Users.ToArray()));
});
}
[Test]
public void TestGameplay()
{
AddUntilStep("wait for gameplay start", () => player.LocalUserPlaying.Value);
}
}
}
| // 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.Linq;
using NUnit.Framework;
using osu.Framework.Screens;
using osu.Framework.Testing;
using osu.Game.Online.Multiplayer;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.OnlinePlay.Multiplayer;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestSceneMultiplayerPlayer : MultiplayerTestScene
{
private MultiplayerPlayer player;
[SetUpSteps]
public override void SetUpSteps()
{
base.SetUpSteps();
AddStep("set beatmap", () =>
{
Beatmap.Value = CreateWorkingBeatmap(new OsuRuleset().RulesetInfo);
});
AddStep("initialise gameplay", () =>
{
Stack.Push(player = new MultiplayerPlayer(Client.APIRoom, Client.CurrentMatchPlayingItem.Value, Client.Room?.Users.ToArray()));
});
AddUntilStep("wait for player to be current", () => player.IsCurrentScreen() && player.IsLoaded);
AddStep("start gameplay", () => ((IMultiplayerClient)Client).MatchStarted());
}
[Test]
public void TestGameplay()
{
AddUntilStep("wait for gameplay start", () => player.LocalUserPlaying.Value);
}
}
}
|
Fix bulk alias unit tests | namespace Nest
{
/// <summary>
/// Marker interface for alias operation
/// </summary>
public interface IAliasAction { }
}
| using Utf8Json;
using Utf8Json.Internal;
namespace Nest
{
/// <summary>
/// Marker interface for alias operation
/// </summary>
[JsonFormatter(typeof(AliasActionFormatter))]
public interface IAliasAction { }
public class AliasActionFormatter : IJsonFormatter<IAliasAction>
{
private static readonly AutomataDictionary Actions = new AutomataDictionary
{
{ "add", 0 },
{ "remove", 1 },
{ "remove_index", 2 },
};
public IAliasAction Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
var token = reader.GetCurrentJsonToken();
if (token == JsonToken.Null)
return null;
var segment = reader.ReadNextBlockSegment();
var segmentReader = new JsonReader(segment.Array, segment.Offset);
segmentReader.ReadIsBeginObjectWithVerify();
var action = segmentReader.ReadPropertyNameSegmentRaw();
IAliasAction aliasAction = null;
segmentReader = new JsonReader(segment.Array, segment.Offset);
if (Actions.TryGetValue(action, out var value))
{
switch (value)
{
case 0:
aliasAction = Deserialize<AliasAddAction>(ref segmentReader, formatterResolver);
break;
case 1:
aliasAction = Deserialize<AliasRemoveAction>(ref segmentReader, formatterResolver);
break;
case 2:
aliasAction = Deserialize<AliasRemoveIndexAction>(ref segmentReader, formatterResolver);
break;
}
}
return aliasAction;
}
public void Serialize(ref JsonWriter writer, IAliasAction value, IJsonFormatterResolver formatterResolver)
{
if (value == null)
{
writer.WriteNull();
return;
}
switch (value)
{
case IAliasAddAction addAction:
Serialize(ref writer, addAction, formatterResolver);
break;
case IAliasRemoveAction removeAction:
Serialize(ref writer, removeAction, formatterResolver);
break;
case IAliasRemoveIndexAction removeIndexAction:
Serialize(ref writer, removeIndexAction, formatterResolver);
break;
default:
// TODO: Should we handle some other way?
writer.WriteNull();
break;
}
}
private static void Serialize<TAliasAction>(ref JsonWriter writer, TAliasAction action,
IJsonFormatterResolver formatterResolver
) where TAliasAction : IAliasAction
{
var formatter = formatterResolver.GetFormatter<TAliasAction>();
formatter.Serialize(ref writer, action, formatterResolver);
}
private static TAliasAction Deserialize<TAliasAction>(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
where TAliasAction : IAliasAction
{
var formatter = formatterResolver.GetFormatter<TAliasAction>();
return formatter.Deserialize(ref reader, formatterResolver);
}
}
}
|
Improve test method name for clarity. | using Fixie.Execution;
using Fixie.Internal;
namespace Fixie.Tests.Execution
{
public class RunnerAppDomainCommunicationTests
{
public void ShouldAllowRunnersInOtherAppDomainsToProvideTheirOwnListeners()
{
typeof(Listener).ShouldBeSafeAppDomainCommunicationInterface();
}
public void ShouldAllowRunnersToPerformTestDiscoveryAndExecutionThroughExecutionProxy()
{
typeof(ExecutionProxy).ShouldBeSafeAppDomainCommunicationInterface();
}
}
} | using Fixie.Execution;
using Fixie.Internal;
namespace Fixie.Tests.Execution
{
public class RunnerAppDomainCommunicationTests
{
public void ShouldAllowRunnersInOtherAppDomainsToProvideTheirOwnListeners()
{
typeof(Listener).ShouldBeSafeAppDomainCommunicationInterface();
}
public void ShouldAllowRunnersInOtherAppDomainsToPerformTestDiscoveryAndExecutionThroughExecutionProxy()
{
typeof(ExecutionProxy).ShouldBeSafeAppDomainCommunicationInterface();
}
}
} |
Update anti forgery helper as extension methods | namespace GeekLearning.Test.Integration.Helpers
{
using System;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
// http://www.stefanhendriks.com/2016/05/11/integration-testing-your-asp-net-core-app-dealing-with-anti-request-forgery-csrf-formdata-and-cookies/
public class AntiForgeryHelper
{
public static string ExtractAntiForgeryToken(string htmlResponseText)
{
if (htmlResponseText == null) throw new ArgumentNullException("htmlResponseText");
System.Text.RegularExpressions.Match match = Regex.Match(htmlResponseText, @"\<input name=""__RequestVerificationToken"" type=""hidden"" value=""([^""]+)"" \/\>");
return match.Success ? match.Groups[1].Captures[0].Value : null;
}
public static async Task<string> ExtractAntiForgeryToken(HttpResponseMessage response)
{
string responseAsString = await response.Content.ReadAsStringAsync();
return await Task.FromResult(ExtractAntiForgeryToken(responseAsString));
}
}
}
| namespace GeekLearning.Test.Integration.Helpers
{
using System;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
// http://www.stefanhendriks.com/2016/05/11/integration-testing-your-asp-net-core-app-dealing-with-anti-request-forgery-csrf-formdata-and-cookies/
public static class AntiForgeryHelper
{
public static string ExtractAntiForgeryToken(string htmlResponseText)
{
if (htmlResponseText == null) throw new ArgumentNullException("htmlResponseText");
System.Text.RegularExpressions.Match match = Regex.Match(htmlResponseText, @"\<input name=""__RequestVerificationToken"" type=""hidden"" value=""([^""]+)"" \/\>");
return match.Success ? match.Groups[1].Captures[0].Value : null;
}
public static async Task<string> ExtractAntiForgeryTokenAsync(this HttpResponseMessage response)
{
string responseAsString = await response.Content.ReadAsStringAsync();
return await Task.FromResult(ExtractAntiForgeryToken(responseAsString));
}
}
}
|
Add ResolveByName attribute to TargetControl property | using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Xaml.Interactivity;
namespace Avalonia.Xaml.Interactions.Custom;
/// <summary>
/// A behavior that allows to hide control on lost focus event.
/// </summary>
public class HideOnLostFocusBehavior : Behavior<Control>
{
/// <summary>
/// Identifies the <seealso cref="TargetControl"/> avalonia property.
/// </summary>
public static readonly StyledProperty<Control?> TargetControlProperty =
AvaloniaProperty.Register<HideOnLostFocusBehavior, Control?>(nameof(TargetControl));
/// <summary>
/// Gets or sets the target control. This is a avalonia property.
/// </summary>
public Control? TargetControl
{
get => GetValue(TargetControlProperty);
set => SetValue(TargetControlProperty, value);
}
/// <inheritdoc />
protected override void OnAttachedToVisualTree()
{
AssociatedObject?.AddHandler(InputElement.LostFocusEvent, AssociatedObject_LostFocus, RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
}
/// <inheritdoc />
protected override void OnDetachedFromVisualTree()
{
AssociatedObject?.RemoveHandler(InputElement.LostFocusEvent, AssociatedObject_LostFocus);
}
private void AssociatedObject_LostFocus(object? sender, RoutedEventArgs e)
{
if (TargetControl is { })
{
TargetControl.IsVisible = false;
}
}
}
| using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Xaml.Interactivity;
namespace Avalonia.Xaml.Interactions.Custom;
/// <summary>
/// A behavior that allows to hide control on lost focus event.
/// </summary>
public class HideOnLostFocusBehavior : Behavior<Control>
{
/// <summary>
/// Identifies the <seealso cref="TargetControl"/> avalonia property.
/// </summary>
public static readonly StyledProperty<Control?> TargetControlProperty =
AvaloniaProperty.Register<HideOnLostFocusBehavior, Control?>(nameof(TargetControl));
/// <summary>
/// Gets or sets the target control. This is a avalonia property.
/// </summary>
[ResolveByName]
public Control? TargetControl
{
get => GetValue(TargetControlProperty);
set => SetValue(TargetControlProperty, value);
}
/// <inheritdoc />
protected override void OnAttachedToVisualTree()
{
AssociatedObject?.AddHandler(InputElement.LostFocusEvent, AssociatedObject_LostFocus, RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
}
/// <inheritdoc />
protected override void OnDetachedFromVisualTree()
{
AssociatedObject?.RemoveHandler(InputElement.LostFocusEvent, AssociatedObject_LostFocus);
}
private void AssociatedObject_LostFocus(object? sender, RoutedEventArgs e)
{
if (TargetControl is { })
{
TargetControl.IsVisible = false;
}
}
}
|
Set new assembly version for release 1.1.0.0 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AsterNET.ARI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AsterNET.ARI")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0d0c4e4f-1ff2-427b-9027-d010b0edd456")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AsterNET.ARI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AsterNET.ARI")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0d0c4e4f-1ff2-427b-9027-d010b0edd456")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
|
Enable cors request from everywhere. | using CloudConfVarnaEdition4._0.Entities;
using CloudConfVarnaEdition4._0.Repositories;
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Cors;
namespace CloudConfVarnaEdition4._0_RestAPI.Controllers
{
[EnableCors(origins: "http://cloudconfvarnamicroservices.azurewebsites.net", headers: "*", methods: "*")]
public class MatchesController : ApiController
{
private static readonly MongoDbMatchRepository _repository = new MongoDbMatchRepository();
// GET api/matches
public IEnumerable<Match> Get()
{
// Add Dummy records to database
_repository.AddDummyMatches();
return _repository.GetAllEntities();
}
}
}
| using CloudConfVarnaEdition4._0.Entities;
using CloudConfVarnaEdition4._0.Repositories;
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Cors;
namespace CloudConfVarnaEdition4._0_RestAPI.Controllers
{
// Allow CORS for all origins. (Caution!)
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class MatchesController : ApiController
{
private static readonly MongoDbMatchRepository _repository = new MongoDbMatchRepository();
// GET api/matches
public IEnumerable<Match> Get()
{
// Add Dummy records to database
_repository.AddDummyMatches();
return _repository.GetAllEntities();
}
}
}
|
Use the new valid rename field tag id in integration tests | // 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 Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess
{
public class InlineRenameDialog_OutOfProc : OutOfProcComponent
{
private const string ChangeSignatureDialogAutomationId = "InlineRenameDialog";
public string ValidRenameTag => "RoslynRenameValidTag";
public InlineRenameDialog_OutOfProc(VisualStudioInstance visualStudioInstance)
: base(visualStudioInstance)
{
}
public void Invoke()
{
VisualStudioInstance.ExecuteCommand("Refactor.Rename");
VisualStudioInstance.Workspace.WaitForAsyncOperations(FeatureAttribute.Rename);
}
public void ToggleIncludeComments()
{
VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.C, ShiftState.Alt));
VisualStudioInstance.Workspace.WaitForAsyncOperations(FeatureAttribute.Rename);
}
public void ToggleIncludeStrings()
{
VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.S, ShiftState.Alt));
VisualStudioInstance.Workspace.WaitForAsyncOperations(FeatureAttribute.Rename);
}
public void ToggleIncludeOverloads()
{
VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.O, ShiftState.Alt));
VisualStudioInstance.Workspace.WaitForAsyncOperations(FeatureAttribute.Rename);
}
}
}
| // 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 Microsoft.CodeAnalysis.Editor.Implementation.InlineRename.HighlightTags;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess
{
public class InlineRenameDialog_OutOfProc : OutOfProcComponent
{
private const string ChangeSignatureDialogAutomationId = "InlineRenameDialog";
public string ValidRenameTag => RenameFieldBackgroundAndBorderTag.TagId;
public InlineRenameDialog_OutOfProc(VisualStudioInstance visualStudioInstance)
: base(visualStudioInstance)
{
}
public void Invoke()
{
VisualStudioInstance.ExecuteCommand("Refactor.Rename");
VisualStudioInstance.Workspace.WaitForAsyncOperations(FeatureAttribute.Rename);
}
public void ToggleIncludeComments()
{
VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.C, ShiftState.Alt));
VisualStudioInstance.Workspace.WaitForAsyncOperations(FeatureAttribute.Rename);
}
public void ToggleIncludeStrings()
{
VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.S, ShiftState.Alt));
VisualStudioInstance.Workspace.WaitForAsyncOperations(FeatureAttribute.Rename);
}
public void ToggleIncludeOverloads()
{
VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.O, ShiftState.Alt));
VisualStudioInstance.Workspace.WaitForAsyncOperations(FeatureAttribute.Rename);
}
}
}
|
Make sure there is an error code available | using System;
using System.Runtime.InteropServices;
namespace Eavesdrop
{
internal static class NativeMethods
{
[DllImport("wininet.dll")]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
}
} | using System;
using System.Runtime.InteropServices;
namespace Eavesdrop
{
internal static class NativeMethods
{
[DllImport("wininet.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
}
} |
Set default back to Chrome driver. | using System.Collections.Generic;
using BoDi;
using Coypu;
using Coypu.Drivers;
using TechTalk.SpecFlow;
namespace WebSpecs.Support
{
[Binding]
public class Hooks
{
private readonly IObjectContainer objectContainer;
private BrowserSession browser;
private readonly List<Page> pages = new List<Page>();
public Hooks(IObjectContainer objectContainer)
{
this.objectContainer = objectContainer;
}
[BeforeScenario]
public void Before()
{
var configuration = new SessionConfiguration
{
// Uncomment the Browser you want
//Browser = Browser.Firefox,
//Browser = Browser.Chrome,
//Browser = Browser.InternetExplorer,
Browser = Browser.PhantomJS,
};
browser = new PageBrowserSession(configuration);
objectContainer.RegisterInstanceAs(browser);
objectContainer.RegisterInstanceAs(pages);
}
[AfterScenario]
public void DisposeSites()
{
browser.Dispose();
}
}
} | using System.Collections.Generic;
using BoDi;
using Coypu;
using Coypu.Drivers;
using TechTalk.SpecFlow;
namespace WebSpecs.Support
{
[Binding]
public class Hooks
{
private readonly IObjectContainer objectContainer;
private BrowserSession browser;
private readonly List<Page> pages = new List<Page>();
public Hooks(IObjectContainer objectContainer)
{
this.objectContainer = objectContainer;
}
[BeforeScenario]
public void Before()
{
var configuration = new SessionConfiguration
{
// Uncomment the Browser you want
Browser = Browser.Firefox,
//Browser = Browser.Chrome,
//Browser = Browser.InternetExplorer,
//Browser = Browser.PhantomJS,
};
browser = new PageBrowserSession(configuration);
objectContainer.RegisterInstanceAs(browser);
objectContainer.RegisterInstanceAs(pages);
}
[AfterScenario]
public void DisposeSites()
{
browser.Dispose();
}
}
} |
Set sink version to match Serilog version. | using System.Reflection;
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.1.1.1")]
[assembly: AssemblyInformationalVersion("1.0.0")]
| using System.Reflection;
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.4.204.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
|
Correct negative values under arm64 | /* Copyright © 2018 Jeremy Herbison
This file is part of AudioWorks.
AudioWorks is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public
License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
version.
AudioWorks 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 Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along with AudioWorks. If not, see
<https://www.gnu.org/licenses/>. */
using System.Runtime.InteropServices;
namespace AudioWorks.Extensibility
{
[StructLayout(LayoutKind.Sequential)]
readonly struct Int24
{
readonly byte _byte1;
readonly byte _byte2;
readonly byte _byte3;
internal Int24(float value)
{
_byte1 = (byte) value;
_byte2 = (byte) (((uint) value >> 8) & 0xFF);
_byte3 = (byte) (((uint) value >> 16) & 0xFF);
}
public static implicit operator int(Int24 value) =>
value._byte1 | value._byte2 << 8 | ((sbyte) value._byte3 << 16);
}
} | /* Copyright © 2018 Jeremy Herbison
This file is part of AudioWorks.
AudioWorks is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public
License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
version.
AudioWorks 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 Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along with AudioWorks. If not, see
<https://www.gnu.org/licenses/>. */
using System.Runtime.InteropServices;
namespace AudioWorks.Extensibility
{
[StructLayout(LayoutKind.Sequential)]
readonly struct Int24
{
readonly byte _byte1;
readonly byte _byte2;
readonly byte _byte3;
internal Int24(float value)
{
_byte1 = (byte) value;
_byte2 = (byte) (((int) value >> 8) & 0xFF);
_byte3 = (byte) (((int) value >> 16) & 0xFF);
}
public static implicit operator int(Int24 value) =>
value._byte1 | value._byte2 << 8 | ((sbyte) value._byte3 << 16);
}
} |
Read from log stream and use a simple filter | using System;
using Amazon.CloudWatchLogs;
using Amazon.Lambda.Core;
namespace LogParser {
//--- Classes ---
public class CloudWatchLogsEvent {
//--- Properties ---
public Awslogs awslogs { get; set; }
}
public class Awslogs {
//--- Properties ---
public string data { get; set; }
}
public class Function {
//--- Fields ---
private readonly IAmazonCloudWatchLogs _cloudWatchClient;
//--- Methods ---
public Function() {
_cloudWatchClient = new AmazonCloudWatchLogsClient();
}
[LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
public void Handler(CloudWatchLogsEvent cloudWatchLogsEvent, ILambdaContext context) {
Console.WriteLine(cloudWatchLogsEvent.awslogs.data);
}
}
}
| using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text.RegularExpressions;
using Amazon.CloudWatchLogs;
using Amazon.Lambda.Core;
using LogParser.Model;
using Newtonsoft.Json;
namespace LogParser {
public class Function {
//--- Fields ---
private readonly IAmazonCloudWatchLogs _cloudWatchClient;
private const string FILTER = @"^(\[[A-Z ]+\])";
private static readonly Regex filter = new Regex(FILTER, RegexOptions.Compiled | RegexOptions.CultureInvariant);
//--- Constructors ---
public Function() {
_cloudWatchClient = new AmazonCloudWatchLogsClient();
}
//--- Methods ---
[LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
public void Handler(CloudWatchLogsEvent cloudWatchLogsEvent, ILambdaContext context) {
// Level One
Console.WriteLine($"THIS IS THE DATA: {cloudWatchLogsEvent.AwsLogs.Data}");
var data = DecompressLogData(cloudWatchLogsEvent.AwsLogs.Data);
Console.WriteLine($"THIS IS THE DECODED, UNCOMPRESSED DATA: {data}");
var events = JsonConvert.DeserializeObject<DecompressedEvents>(data).LogEvents;
var filteredEvents = events.Where(x => filter.IsMatch(x.Message)).ToList();
filteredEvents.ForEach(x => Console.WriteLine(x.Message));
}
public static string DecompressLogData(string value) {
var gzip = Convert.FromBase64String(value);
using (GZipStream stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress))
return new StreamReader(stream).ReadToEnd();
}
}
}
|
Fix For Broken Tests For CustomType List | using NUnit.Framework;
using ServiceStack.Common.Tests.Models;
namespace ServiceStack.Redis.Tests.Support
{
public class CustomTypeFactory : ModelFactoryBase<CustomType>
{
public CustomTypeFactory()
{
ModelConfig<CustomType>.Id(x => x.CustomId);
}
public override void AssertIsEqual(CustomType actual, CustomType expected)
{
Assert.AreEqual(actual.CustomId, Is.EqualTo(expected.CustomId));
Assert.AreEqual(actual.CustomName, Is.EqualTo(expected.CustomName));
}
public override CustomType CreateInstance(int i)
{
return new CustomType { CustomId = i, CustomName = "Name" + i };
}
}
} | using NUnit.Framework;
using ServiceStack.Common.Tests.Models;
namespace ServiceStack.Redis.Tests.Support
{
public class CustomTypeFactory : ModelFactoryBase<CustomType>
{
public CustomTypeFactory()
{
ModelConfig<CustomType>.Id(x => x.CustomId);
}
public override void AssertIsEqual(CustomType actual, CustomType expected)
{
Assert.AreEqual(actual.CustomId, expected.CustomId);
Assert.AreEqual(actual.CustomName, expected.CustomName);
}
public override CustomType CreateInstance(int i)
{
return new CustomType { CustomId = i, CustomName = "Name" + i };
}
}
} |
Fix hit explosions not being cleaned up correctly when rewinding | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Pooling;
using osu.Game.Rulesets.Judgements;
using osu.Game.Skinning;
namespace osu.Game.Rulesets.Mania.UI
{
public class PoolableHitExplosion : PoolableDrawable
{
public const double DURATION = 200;
public JudgementResult Result { get; private set; }
private SkinnableDrawable skinnableExplosion;
public PoolableHitExplosion()
{
RelativeSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader]
private void load()
{
InternalChild = skinnableExplosion = new SkinnableDrawable(new ManiaSkinComponent(ManiaSkinComponents.HitExplosion), _ => new DefaultHitExplosion())
{
RelativeSizeAxes = Axes.Both
};
}
public void Apply(JudgementResult result)
{
Result = result;
}
protected override void PrepareForUse()
{
base.PrepareForUse();
(skinnableExplosion?.Drawable as IHitExplosion)?.Animate(Result);
this.Delay(DURATION).Then().Expire();
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Pooling;
using osu.Game.Rulesets.Judgements;
using osu.Game.Skinning;
namespace osu.Game.Rulesets.Mania.UI
{
public class PoolableHitExplosion : PoolableDrawable
{
public const double DURATION = 200;
public JudgementResult Result { get; private set; }
private SkinnableDrawable skinnableExplosion;
public PoolableHitExplosion()
{
RelativeSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader]
private void load()
{
InternalChild = skinnableExplosion = new SkinnableDrawable(new ManiaSkinComponent(ManiaSkinComponents.HitExplosion), _ => new DefaultHitExplosion())
{
RelativeSizeAxes = Axes.Both
};
}
public void Apply(JudgementResult result)
{
Result = result;
}
protected override void PrepareForUse()
{
base.PrepareForUse();
LifetimeStart = Time.Current;
(skinnableExplosion?.Drawable as IHitExplosion)?.Animate(Result);
this.Delay(DURATION).Then().Expire();
}
}
}
|
Add back actually needed change | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.IO.Stores;
using osu.Game.Rulesets;
using osu.Game.Skinning;
namespace osu.Game.Tests.Visual
{
[TestFixture]
public abstract class LegacySkinPlayerTestScene : PlayerTestScene
{
private ISkinSource legacySkinSource;
protected override TestPlayer CreatePlayer(Ruleset ruleset) => new SkinProvidingPlayer(legacySkinSource);
[BackgroundDependencyLoader]
private void load(OsuGameBase game, SkinManager skins)
{
var legacySkin = new DefaultLegacySkin(new NamespacedResourceStore<byte[]>(game.Resources, "Skins/Legacy"), skins);
legacySkinSource = new SkinProvidingContainer(legacySkin);
}
public class SkinProvidingPlayer : TestPlayer
{
[Cached(typeof(ISkinSource))]
private readonly ISkinSource skinSource;
public SkinProvidingPlayer(ISkinSource skinSource)
{
this.skinSource = skinSource;
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.IO.Stores;
using osu.Game.Rulesets;
using osu.Game.Skinning;
namespace osu.Game.Tests.Visual
{
[TestFixture]
public abstract class LegacySkinPlayerTestScene : PlayerTestScene
{
protected LegacySkin LegacySkin { get; private set; }
private ISkinSource legacySkinSource;
protected override TestPlayer CreatePlayer(Ruleset ruleset) => new SkinProvidingPlayer(legacySkinSource);
[BackgroundDependencyLoader]
private void load(OsuGameBase game, SkinManager skins)
{
LegacySkin = new DefaultLegacySkin(new NamespacedResourceStore<byte[]>(game.Resources, "Skins/Legacy"), skins);
legacySkinSource = new SkinProvidingContainer(LegacySkin);
}
public class SkinProvidingPlayer : TestPlayer
{
[Cached(typeof(ISkinSource))]
private readonly ISkinSource skinSource;
public SkinProvidingPlayer(ISkinSource skinSource)
{
this.skinSource = skinSource;
}
}
}
}
|
Use new new syntax for initialized fields | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using LibGit2Sharp;
using static GitNStats.Core.Tooling;
namespace GitNStats.Core
{
/// <summary>
/// Walks the commit graph back to the beginning of time.
/// Guaranteed to only visit a commit once.
/// </summary>
public class CommitVisitor : Visitor
{
/// <summary>
/// Walk the graph from this commit back.
/// </summary>
/// <param name="commit">The commit to start at.</param>
public override void Walk(Commit commit)
{
Walk(commit, new HashSet<string>());
//WithStopWatch(() => Walk(commit, new HashSet<string>()), "Total Time Walking Graph: {0}");
}
private Object padlock = new Object();
private void Walk(Commit commit, ISet<string> visitedCommits)
{
// It's not safe to concurrently write to the Set.
// If two threads hit this at the same time we could visit the same commit twice.
lock(padlock)
{
// If we weren't successful in adding the commit, we've already been here.
if(!visitedCommits.Add(commit.Sha))
return;
}
OnVisited(this, commit);
Parallel.ForEach(commit.Parents, parent =>
{
Walk(parent, visitedCommits);
});
}
}
} | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using LibGit2Sharp;
using static GitNStats.Core.Tooling;
namespace GitNStats.Core
{
/// <summary>
/// Walks the commit graph back to the beginning of time.
/// Guaranteed to only visit a commit once.
/// </summary>
public class CommitVisitor : Visitor
{
/// <summary>
/// Walk the graph from this commit back.
/// </summary>
/// <param name="commit">The commit to start at.</param>
public override void Walk(Commit commit)
{
Walk(commit, new HashSet<string>());
//WithStopWatch(() => Walk(commit, new HashSet<string>()), "Total Time Walking Graph: {0}");
}
private Object padlock = new();
private void Walk(Commit commit, ISet<string> visitedCommits)
{
// It's not safe to concurrently write to the Set.
// If two threads hit this at the same time we could visit the same commit twice.
lock(padlock)
{
// If we weren't successful in adding the commit, we've already been here.
if(!visitedCommits.Add(commit.Sha))
return;
}
OnVisited(this, commit);
Parallel.ForEach(commit.Parents, parent =>
{
Walk(parent, visitedCommits);
});
}
}
} |
Add indexer, IEnumerable, and Add for easier creation of HasArbitraryKey objects | using System.Collections.Generic;
namespace Rollbar {
public abstract class HasArbitraryKeys {
protected HasArbitraryKeys(Dictionary<string, object> additionalKeys) {
AdditionalKeys = additionalKeys ?? new Dictionary<string, object>();
}
public abstract void Normalize();
public abstract Dictionary<string, object> Denormalize();
public Dictionary<string, object> AdditionalKeys { get; private set; }
}
public static class HasArbitraryKeysExtension {
public static T WithKeys<T>(this T has, Dictionary<string, object> otherKeys) where T : HasArbitraryKeys {
foreach (var kvp in otherKeys) {
has.AdditionalKeys.Add(kvp.Key, kvp.Value);
}
return has;
}
}
} | using System.Collections;
using System.Collections.Generic;
namespace Rollbar {
public abstract class HasArbitraryKeys : IEnumerable<KeyValuePair<string, object>> {
protected HasArbitraryKeys(Dictionary<string, object> additionalKeys) {
AdditionalKeys = additionalKeys ?? new Dictionary<string, object>();
}
public abstract void Normalize();
public abstract Dictionary<string, object> Denormalize();
public Dictionary<string, object> AdditionalKeys { get; private set; }
public void Add(string key, object value) {
AdditionalKeys.Add(key, value);
Normalize();
}
public object this[string key] {
get { return Denormalize()[key]; }
set { Add(key, value); }
}
public IEnumerator<KeyValuePair<string, object>> GetEnumerator() {
return Denormalize().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
}
public static class HasArbitraryKeysExtension {
public static T WithKeys<T>(this T has, Dictionary<string, object> otherKeys) where T : HasArbitraryKeys {
foreach (var kvp in otherKeys) {
has.AdditionalKeys.Add(kvp.Key, kvp.Value);
}
return has;
}
}
} |
Save ip after recording, check ip on index, version 1.0 | <div class="span7">
<div id="button" class="tile quadro triple-vertical bg-lightPink bg-active-lightBlue" style="padding:10px; text-align: center;">
Your number is... <br /><br />
<span class="COUNT">@(Model)!!!</span><br /><br />
Click this pink square to record a three second video of you saying
<strong>@Model</strong> in your language of choice.<br /><br />
If you don't like your number please hit refresh.<br /><br />
Make yourself comfortable and get ready to join A Thousand Counts.<br /><br />
3, 2, 1, COUNT!
</div>
</div> | <div class="span7">
<div id="button" class="tile quadro triple-vertical bg-lightPink bg-active-lightBlue" style="padding:10px; text-align: center;">
Your number is... <br /><br />
<span class="COUNT">@(Model)!!!</span><br /><br />
Click this pink square to record a three second video of you saying
<strong>@Model</strong> in your language of choice.<br /><br />
If you don't like your number refresh the page to see what other
counts are left.<br /><br />
Make yourself comfortable and get ready to join A Thousand Counts.<br /><br />
3, 2, 1, COUNT!
</div>
</div> |
Fix Clear-Bitmap disposing cleared bitmap too early. | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
namespace PixelPet {
/// <summary>
/// PixelPet workbench instance.
/// </summary>
public class Workbench {
public IList<Color> Palette { get; }
public Bitmap Bitmap { get; private set; }
public Graphics Graphics { get; private set; }
public MemoryStream Stream { get; private set; }
public Workbench() {
this.Palette = new List<Color>();
ClearBitmap(8, 8);
this.Stream = new MemoryStream();
}
public void ClearBitmap(int width, int height) {
Bitmap bmp = null;
try {
bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);
} finally {
if (bmp != null) {
bmp.Dispose();
}
}
SetBitmap(bmp);
this.Graphics.Clear(Color.Transparent);
this.Graphics.Flush();
}
public void SetBitmap(Bitmap bmp) {
if (this.Graphics != null) {
this.Graphics.Dispose();
}
if (this.Bitmap != null) {
this.Bitmap.Dispose();
}
this.Bitmap = bmp;
this.Graphics = Graphics.FromImage(this.Bitmap);
}
}
}
| using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
namespace PixelPet {
/// <summary>
/// PixelPet workbench instance.
/// </summary>
public class Workbench {
public IList<Color> Palette { get; }
public Bitmap Bitmap { get; private set; }
public Graphics Graphics { get; private set; }
public MemoryStream Stream { get; private set; }
public Workbench() {
this.Palette = new List<Color>();
ClearBitmap(8, 8);
this.Stream = new MemoryStream();
}
public void ClearBitmap(int width, int height) {
Bitmap bmp = null;
try {
bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);
SetBitmap(bmp);
} finally {
if (bmp != null) {
bmp.Dispose();
}
}
this.Graphics.Clear(Color.Transparent);
this.Graphics.Flush();
}
public void SetBitmap(Bitmap bmp) {
if (this.Graphics != null) {
this.Graphics.Dispose();
}
if (this.Bitmap != null) {
this.Bitmap.Dispose();
}
this.Bitmap = bmp;
this.Graphics = Graphics.FromImage(this.Bitmap);
}
}
}
|
Comment out redis queue tests for now. | using System;
using Exceptionless.Core;
using Exceptionless.Core.Queues;
using StackExchange.Redis;
namespace Exceptionless.Api.Tests.Queue {
public class RedisQueueTests : InMemoryQueueTests {
private ConnectionMultiplexer _muxer;
protected override IQueue<SimpleWorkItem> GetQueue(int retries, TimeSpan? workItemTimeout, TimeSpan? retryDelay) {
//if (!Settings.Current.UseAzureServiceBus)
// return;
if (_muxer == null)
_muxer = ConnectionMultiplexer.Connect(Settings.Current.RedisConnectionInfo.ToString());
return new RedisQueue<SimpleWorkItem>(_muxer, workItemTimeout: workItemTimeout, retries: 1);
}
}
} | //using System;
//using Exceptionless.Core;
//using Exceptionless.Core.Queues;
//using StackExchange.Redis;
//namespace Exceptionless.Api.Tests.Queue {
// public class RedisQueueTests : InMemoryQueueTests {
// private ConnectionMultiplexer _muxer;
// protected override IQueue<SimpleWorkItem> GetQueue(int retries, TimeSpan? workItemTimeout, TimeSpan? retryDelay) {
// //if (!Settings.Current.UseAzureServiceBus)
// // return;
// if (_muxer == null)
// _muxer = ConnectionMultiplexer.Connect(Settings.Current.RedisConnectionInfo.ToString());
// return new RedisQueue<SimpleWorkItem>(_muxer, workItemTimeout: workItemTimeout, retries: 1);
// }
// }
//} |
Add IArchiveReader to Autofac configuration. | using Arkivverket.Arkade.Core;
using Arkivverket.Arkade.Identify;
using Autofac;
namespace Arkivverket.Arkade.Util
{
public class ArkadeAutofacModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<ArchiveExtractor>().As<IArchiveExtractor>();
builder.RegisterType<TarCompressionUtility>().As<ICompressionUtility>();
builder.RegisterType<ArchiveExtractionReader>().AsSelf();
builder.RegisterType<ArchiveIdentifier>().As<IArchiveIdentifier>();
builder.RegisterType<TestEngine>().AsSelf().SingleInstance();
}
}
}
| using Arkivverket.Arkade.Core;
using Arkivverket.Arkade.Identify;
using Autofac;
namespace Arkivverket.Arkade.Util
{
public class ArkadeAutofacModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<ArchiveExtractor>().As<IArchiveExtractor>();
builder.RegisterType<TarCompressionUtility>().As<ICompressionUtility>();
builder.RegisterType<ArchiveExtractionReader>().AsSelf();
builder.RegisterType<ArchiveIdentifier>().As<IArchiveIdentifier>();
builder.RegisterType<TestEngine>().AsSelf().SingleInstance();
builder.RegisterType<ArchiveContentReader>().As<IArchiveContentReader>();
}
}
}
|
Fix not pasting stats with no boss name available. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CasualMeter.Common.Helpers;
using Tera.DamageMeter;
namespace CasualMeter.Common.Formatters
{
public class DamageTrackerFormatter : Formatter
{
public DamageTrackerFormatter(DamageTracker damageTracker, FormatHelpers formatHelpers)
{
var placeHolders = new List<KeyValuePair<string, object>>();
placeHolders.Add(new KeyValuePair<string, object>("Boss", damageTracker.Name));
placeHolders.Add(new KeyValuePair<string, object>("Time", formatHelpers.FormatTimeSpan(damageTracker.Duration)));
Placeholders = placeHolders.ToDictionary(x => x.Key, y => y.Value);
FormatProvider = formatHelpers.CultureInfo;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CasualMeter.Common.Helpers;
using Tera.DamageMeter;
namespace CasualMeter.Common.Formatters
{
public class DamageTrackerFormatter : Formatter
{
public DamageTrackerFormatter(DamageTracker damageTracker, FormatHelpers formatHelpers)
{
var placeHolders = new List<KeyValuePair<string, object>>();
placeHolders.Add(new KeyValuePair<string, object>("Boss", damageTracker.Name??string.Empty));
placeHolders.Add(new KeyValuePair<string, object>("Time", formatHelpers.FormatTimeSpan(damageTracker.Duration)));
Placeholders = placeHolders.ToDictionary(x => x.Key, y => y.Value);
FormatProvider = formatHelpers.CultureInfo;
}
}
}
|
Support to specify UTC and offset separately to setCurrentTimeAsync | using System;
using System.Threading.Tasks;
namespace Kazyx.RemoteApi.System
{
public class SystemApiClient : ApiClient
{
/// <summary>
///
/// </summary>
/// <param name="endpoint">Endpoint URL of system service.</param>
public SystemApiClient(Uri endpoint)
: base(endpoint)
{
}
public async Task SetCurrentTimeAsync(DateTimeOffset time)
{
var req = new TimeOffset
{
DateTime = time.ToString("yyyy-MM-ddThh:mm:ssZ"),
TimeZoneOffsetMinute = (int)(time.Offset.TotalMinutes),
DstOffsetMinute = 0
};
await NoValue(RequestGenerator.Serialize("setCurrentTime", ApiVersion.V1_0, req));
}
}
}
| using System;
using System.Threading.Tasks;
namespace Kazyx.RemoteApi.System
{
public class SystemApiClient : ApiClient
{
/// <summary>
///
/// </summary>
/// <param name="endpoint">Endpoint URL of system service.</param>
public SystemApiClient(Uri endpoint)
: base(endpoint)
{
}
public async Task SetCurrentTimeAsync(DateTimeOffset UtcTime, int OffsetInMinute)
{
var req = new TimeOffset
{
DateTime = UtcTime.ToString("yyyy-MM-ddTHH:mm:ssZ"),
TimeZoneOffsetMinute = OffsetInMinute,
DstOffsetMinute = 0
};
await NoValue(RequestGenerator.Serialize("setCurrentTime", ApiVersion.V1_0, req));
}
}
}
|
Trim down data returned from API | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
using AutoMapper;
using Umbraco.Core.Models;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.Models.Mapping;
using Umbraco.Web.Mvc;
using Umbraco.Web.Editors;
namespace Archetype.Umbraco.Api
{
[PluginController("ArchetypeApi")]
public class ArchetypeDataTypeController : UmbracoAuthorizedJsonController
{
//pulled from the Core
public DataTypeDisplay GetById(int id)
{
var dataType = Services.DataTypeService.GetDataTypeDefinitionById(id);
if (dataType == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return Mapper.Map<IDataTypeDefinition, DataTypeDisplay>(dataType);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
using AutoMapper;
using Umbraco.Core.Models;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.Models.Mapping;
using Umbraco.Web.Mvc;
using Umbraco.Web.Editors;
namespace Archetype.Umbraco.Api
{
[PluginController("ArchetypeApi")]
public class ArchetypeDataTypeController : UmbracoAuthorizedJsonController
{
//pulled from the Core
public object GetById(int id)
{
var dataType = Services.DataTypeService.GetDataTypeDefinitionById(id);
if (dataType == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
var dataTypeDisplay = Mapper.Map<IDataTypeDefinition, DataTypeDisplay>(dataType);
return new { selectedEditor = dataTypeDisplay.SelectedEditor, preValues = dataTypeDisplay.PreValues };
}
}
}
|
Rollback mistakenly committed commented lines | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Foundation;
using UIKit;
using Xunit.Runner;
using Xunit.Runners.UI;
using Xunit.Sdk;
namespace Couchbase.Lite.Tests.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public partial class AppDelegate : RunnerAppDelegate
{
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
Couchbase.Lite.Support.iOS.Activate();
// We need this to ensure the execution assembly is part of the app bundle
AddExecutionAssembly(typeof(ExtensibilityPointFactory).Assembly);
// tests can be inside the main assembly
AddTestAssembly(Assembly.GetExecutingAssembly());
//AutoStart = true;
//TerminateAfterExecution = true;
//using (var str = GetType().Assembly.GetManifestResourceStream("result_ip"))
//using (var sr = new StreamReader(str)) {
// Writer = new TcpTextWriter(sr.ReadToEnd().TrimEnd(), 12345);
//}
return base.FinishedLaunching(app, options);
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Foundation;
using UIKit;
using Xunit.Runner;
using Xunit.Runners.UI;
using Xunit.Sdk;
namespace Couchbase.Lite.Tests.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public partial class AppDelegate : RunnerAppDelegate
{
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
Couchbase.Lite.Support.iOS.Activate();
// We need this to ensure the execution assembly is part of the app bundle
AddExecutionAssembly(typeof(ExtensibilityPointFactory).Assembly);
// tests can be inside the main assembly
AddTestAssembly(Assembly.GetExecutingAssembly());
AutoStart = true;
TerminateAfterExecution = true;
using (var str = GetType().Assembly.GetManifestResourceStream("result_ip"))
using (var sr = new StreamReader(str))
{
Writer = new TcpTextWriter(sr.ReadToEnd().TrimEnd(), 12345);
}
return base.FinishedLaunching(app, options);
}
}
} |
Revert "revert logging config causing bug" | using FilterLists.Api.DependencyInjection.Extensions;
using FilterLists.Data.DependencyInjection.Extensions;
using FilterLists.Services.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace FilterLists.Api
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", false, true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.RegisterFilterListsRepositories(Configuration);
services.RegisterFilterListsServices();
services.RegisterFilterListsApi();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvc();
//TODO: maybe move to Startup() per Scott Allen
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
}
}
} | using FilterLists.Api.DependencyInjection.Extensions;
using FilterLists.Data.DependencyInjection.Extensions;
using FilterLists.Services.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace FilterLists.Api
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", false, true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
.AddEnvironmentVariables();
Configuration = builder.Build();
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.RegisterFilterListsRepositories(Configuration);
services.RegisterFilterListsServices();
services.RegisterFilterListsApi();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvc();
}
}
} |
Fix bug when moving between pages executing on UI thread. | using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Linq;
using System.Threading.Tasks;
namespace PackageExplorerViewModel
{
internal abstract class QueryContextBase<T>
{
private int? _totalItemCount;
public int TotalItemCount
{
get
{
return _totalItemCount ?? 0;
}
}
protected bool TotalItemCountReady
{
get
{
return _totalItemCount.HasValue;
}
}
public IQueryable<T> Source { get; private set; }
protected QueryContextBase(IQueryable<T> source)
{
Source = source;
}
protected async Task<IEnumerable<T>> LoadData(IQueryable<T> query)
{
var dataServiceQuery = query as DataServiceQuery<T>;
if (!TotalItemCountReady && dataServiceQuery != null)
{
var queryResponse = (QueryOperationResponse<T>)
await Task.Factory.FromAsync<IEnumerable<T>>(dataServiceQuery.BeginExecute(null, null), dataServiceQuery.EndExecute);
try
{
_totalItemCount = (int)queryResponse.TotalCount;
}
catch (InvalidOperationException)
{
// the server doesn't return $inlinecount value,
// fall back to using $count query
_totalItemCount = Source.Count();
}
return queryResponse;
}
else
{
if (!TotalItemCountReady)
{
_totalItemCount = Source.Count();
}
return query;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Linq;
using System.Threading.Tasks;
namespace PackageExplorerViewModel
{
internal abstract class QueryContextBase<T>
{
private int? _totalItemCount;
public int TotalItemCount
{
get
{
return _totalItemCount ?? 0;
}
}
protected bool TotalItemCountReady
{
get
{
return _totalItemCount.HasValue;
}
}
public IQueryable<T> Source { get; private set; }
protected QueryContextBase(IQueryable<T> source)
{
Source = source;
}
protected async Task<IEnumerable<T>> LoadData(IQueryable<T> query)
{
var dataServiceQuery = query as DataServiceQuery<T>;
if (dataServiceQuery != null)
{
var queryResponse = (QueryOperationResponse<T>)
await Task.Factory.FromAsync<IEnumerable<T>>(dataServiceQuery.BeginExecute(null, null), dataServiceQuery.EndExecute);
try
{
_totalItemCount = (int)queryResponse.TotalCount;
}
catch (InvalidOperationException)
{
if (!TotalItemCountReady)
{
// the server doesn't return $inlinecount value,
// fall back to using $count query
_totalItemCount = Source.Count();
}
}
return queryResponse;
}
else
{
if (!TotalItemCountReady)
{
_totalItemCount = Source.Count();
}
return query;
}
}
}
} |
Add the all-important = sign to make arg passing work | // Copyright 2016-2017 Datalust Pty Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using Datalust.ClefTool.Pipe;
namespace Datalust.ClefTool.Cli.Features
{
class InvalidDataHandlingFeature : CommandFeature
{
public InvalidDataHandling InvalidDataHandling { get; private set; }
public override void Enable(OptionSet options)
{
options.Add("invalid-data",
"Specify how invalid data is handled: fail (default), ignore, or report",
v => InvalidDataHandling = (InvalidDataHandling)Enum.Parse(typeof(InvalidDataHandling), v, ignoreCase: true));
}
}
}
| // Copyright 2016-2017 Datalust Pty Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using Datalust.ClefTool.Pipe;
namespace Datalust.ClefTool.Cli.Features
{
class InvalidDataHandlingFeature : CommandFeature
{
public InvalidDataHandling InvalidDataHandling { get; private set; }
public override void Enable(OptionSet options)
{
options.Add("invalid-data=",
"Specify how invalid data is handled: fail (default), ignore, or report",
v => InvalidDataHandling = (InvalidDataHandling)Enum.Parse(typeof(InvalidDataHandling), v, ignoreCase: true));
}
}
}
|
Make proeprty setters private if they are not being used | using System;
namespace MiniWebDeploy.Deployer.Features.Discovery
{
public class AssemblyDetails
{
public string Path { get; set; }
public string BinaryPath { get; set; }
public Type InstallerType { get; set; }
public AssemblyDetails(string path, string binaryPath, Type installerType)
{
Path = path;
BinaryPath = binaryPath;
InstallerType = installerType;
}
}
} | using System;
namespace MiniWebDeploy.Deployer.Features.Discovery
{
public class AssemblyDetails
{
public string Path { get; private set; }
public string BinaryPath { get; private set; }
public Type InstallerType { get; private set; }
public AssemblyDetails(string path, string binaryPath, Type installerType)
{
Path = path;
BinaryPath = binaryPath;
InstallerType = installerType;
}
}
} |
Add support for metadata on BankAccount creation | namespace Stripe
{
using Newtonsoft.Json;
using Stripe.Infrastructure;
public class BankAccountCreateOptions : BaseOptions
{
/// <summary>
/// REQUIRED. Either a token, like the ones returned by
/// <a href="https://stripe.com/docs/stripe.js">Stripe.js</a>, or a
/// <see cref="SourceBankAccount"/> instance containing a user’s bank account
/// details.
/// </summary>
[JsonProperty("source")]
[JsonConverter(typeof(AnyOfConverter))]
public AnyOf<string, SourceBankAccount> Source { get; set; }
}
}
| namespace Stripe
{
using System.Collections.Generic;
using Newtonsoft.Json;
using Stripe.Infrastructure;
public class BankAccountCreateOptions : BaseOptions, IHasMetadata
{
/// <summary>
/// A set of key/value pairs that you can attach to an object. It can be useful for storing
/// additional information about the object in a structured format.
/// </summary>
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
/// <summary>
/// REQUIRED. Either a token, like the ones returned by
/// <a href="https://stripe.com/docs/stripe.js">Stripe.js</a>, or a
/// <see cref="SourceBankAccount"/> instance containing a user’s bank account
/// details.
/// </summary>
[JsonProperty("source")]
[JsonConverter(typeof(AnyOfConverter))]
public AnyOf<string, SourceBankAccount> Source { get; set; }
}
}
|
Add space to commit again. | @model SvNaum.Web.Models.NewsInputModel
@{
this.ViewBag.Title = "Add news";
}
<h2>Create news:</h2>
@using(Html.BeginForm("NewsAdd", "Admin", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.EditorForModel()
<br />
<br />
<input type="submit" value="Save" />
<input type="button" value="Cancel" onclick="window.location = '/Home/Index';" />
}
@section scripts
{
@Scripts.Render("~/bundles/jqueryval");
} | @model SvNaum.Web.Models.NewsInputModel
@{
this.ViewBag.Title = "Add news";
}
<h2>Create news:</h2>
@using(Html.BeginForm("NewsAdd", "Admin", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.EditorForModel()
<br />
<br />
<input type="submit" value="Save" />
<input type="button" value="Cancel" onclick="window.location = '/Home/Index';" />
}
@section scripts
{
@Scripts.Render("~/bundles/jqueryval");
} |
Switch from record to record class | namespace ApiTemplate
{
using System.Reflection;
public record AssemblyInformation(string Product, string Description, string Version)
{
public static readonly AssemblyInformation Current = new(typeof(AssemblyInformation).Assembly);
public AssemblyInformation(Assembly assembly)
: this(
assembly.GetCustomAttribute<AssemblyProductAttribute>()!.Product,
assembly.GetCustomAttribute<AssemblyDescriptionAttribute>()!.Description,
assembly.GetCustomAttribute<AssemblyFileVersionAttribute>()!.Version)
{
}
}
}
| namespace ApiTemplate
{
using System.Reflection;
public record class AssemblyInformation(string Product, string Description, string Version)
{
public static readonly AssemblyInformation Current = new(typeof(AssemblyInformation).Assembly);
public AssemblyInformation(Assembly assembly)
: this(
assembly.GetCustomAttribute<AssemblyProductAttribute>()!.Product,
assembly.GetCustomAttribute<AssemblyDescriptionAttribute>()!.Description,
assembly.GetCustomAttribute<AssemblyFileVersionAttribute>()!.Version)
{
}
}
}
|
Use TryAdd to add services rather than Add | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Cors;
using Microsoft.AspNet.Cors.Core;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.Internal;
namespace Microsoft.Framework.DependencyInjection
{
/// <summary>
/// The <see cref="IServiceCollection"/> extensions for enabling CORS support.
/// </summary>
public static class CorsServiceCollectionExtensions
{
/// <summary>
/// Can be used to configure services in the <paramref name="serviceCollection"/>.
/// </summary>
/// <param name="serviceCollection">The service collection which needs to be configured.</param>
/// <param name="configure">A delegate which is run to configure the services.</param>
/// <returns></returns>
public static IServiceCollection ConfigureCors(
[NotNull] this IServiceCollection serviceCollection,
[NotNull] Action<CorsOptions> configure)
{
return serviceCollection.Configure(configure);
}
/// <summary>
/// Add services needed to support CORS to the given <paramref name="serviceCollection"/>.
/// </summary>
/// <param name="serviceCollection">The service collection to which CORS services are added.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddCors(this IServiceCollection serviceCollection)
{
serviceCollection.AddOptions();
serviceCollection.AddTransient<ICorsService, CorsService>();
serviceCollection.AddTransient<ICorsPolicyProvider, DefaultCorsPolicyProvider>();
return serviceCollection;
}
}
} | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Cors;
using Microsoft.AspNet.Cors.Core;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.Internal;
namespace Microsoft.Framework.DependencyInjection
{
/// <summary>
/// The <see cref="IServiceCollection"/> extensions for enabling CORS support.
/// </summary>
public static class CorsServiceCollectionExtensions
{
/// <summary>
/// Can be used to configure services in the <paramref name="serviceCollection"/>.
/// </summary>
/// <param name="serviceCollection">The service collection which needs to be configured.</param>
/// <param name="configure">A delegate which is run to configure the services.</param>
/// <returns></returns>
public static IServiceCollection ConfigureCors(
[NotNull] this IServiceCollection serviceCollection,
[NotNull] Action<CorsOptions> configure)
{
return serviceCollection.Configure(configure);
}
/// <summary>
/// Add services needed to support CORS to the given <paramref name="serviceCollection"/>.
/// </summary>
/// <param name="serviceCollection">The service collection to which CORS services are added.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddCors(this IServiceCollection serviceCollection)
{
serviceCollection.AddOptions();
serviceCollection.TryAdd(ServiceDescriptor.Transient<ICorsService, CorsService>());
serviceCollection.TryAdd(ServiceDescriptor.Transient<ICorsPolicyProvider, DefaultCorsPolicyProvider>());
return serviceCollection;
}
}
} |
Change from == null to is null in NodaTime.Testing | // Copyright 2013 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
namespace NodaTime.Testing
{
/// <summary>
/// Helper static methods for argument/state validation. Copied from NodaTime.Utility,
/// as we don't want the Testing assembly to have internal access to NodaTime, but we
/// don't really want to expose Preconditions publically.
/// </summary>
internal static class Preconditions
{
/// <summary>
/// Returns the given argument after checking whether it's null. This is useful for putting
/// nullity checks in parameters which are passed to base class constructors.
/// </summary>
internal static T CheckNotNull<T>(T argument, string paramName) where T : class
{
if (argument == null)
{
throw new ArgumentNullException(paramName);
}
return argument;
}
}
}
| // Copyright 2013 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
namespace NodaTime.Testing
{
/// <summary>
/// Helper static methods for argument/state validation. Copied from NodaTime.Utility,
/// as we don't want the Testing assembly to have internal access to NodaTime, but we
/// don't really want to expose Preconditions publically.
/// </summary>
internal static class Preconditions
{
/// <summary>
/// Returns the given argument after checking whether it's null. This is useful for putting
/// nullity checks in parameters which are passed to base class constructors.
/// </summary>
internal static T CheckNotNull<T>(T argument, string paramName) where T : class
{
if (argument is null)
{
throw new ArgumentNullException(paramName);
}
return argument;
}
}
}
|
Remove setters from Id and Type | using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Telegram.Bot.Types.ReplyMarkups;
namespace Telegram.Bot.Types.InlineQueryResults
{
/// <summary>
/// Base Class for inline results send in response to an <see cref="InlineQuery"/>
/// </summary>
[JsonObject(MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
public abstract class InlineQueryResult
{
/// <summary>
/// </summary>
/// <param name="id"></param>
/// <param name="type"></param>
protected InlineQueryResult(string id, InlineQueryResultType type)
{
Id = id;
Type = type;
}
/// <summary>
/// Unique identifier of this result
/// </summary>
[JsonProperty(Required = Required.Always)]
public string Id { get; set; }
/// <summary>
/// Type of the result
/// </summary>
[JsonProperty(Required = Required.Always)]
public InlineQueryResultType Type { get; protected set; }
/// <summary>
/// Inline keyboard attached to the message
/// </summary>
[JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
public InlineKeyboardMarkup ReplyMarkup { get; set; }
}
}
| using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Telegram.Bot.Types.ReplyMarkups;
namespace Telegram.Bot.Types.InlineQueryResults
{
/// <summary>
/// Base Class for inline results send in response to an <see cref="InlineQuery"/>
/// </summary>
[JsonObject(MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
public abstract class InlineQueryResult
{
/// <summary>
/// </summary>
/// <param name="id"></param>
/// <param name="type"></param>
protected InlineQueryResult(string id, InlineQueryResultType type)
{
Id = id;
Type = type;
}
/// <summary>
/// Unique identifier of this result
/// </summary>
[JsonProperty(Required = Required.Always)]
public string Id { get; }
/// <summary>
/// Type of the result
/// </summary>
[JsonProperty(Required = Required.Always)]
public InlineQueryResultType Type { get; }
/// <summary>
/// Inline keyboard attached to the message
/// </summary>
[JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
public InlineKeyboardMarkup ReplyMarkup { get; set; }
}
}
|
Add a using and set the position of the stream | namespace Pigeon
{
using System.Linq;
using System.Net.Mail;
using Pigeon.Adapters;
public class Mailer
{
private readonly IMailService mailService;
public Mailer(IMailService mailService)
{
this.mailService = mailService;
}
public void SendZip(ZipResult result, string emailAddress, string emailFrom, string subject, string attachmentName)
{
string body;
if (result != null && result.Entries.Any())
{
body = string.Join("\n\r", result.Entries);
}
else
{
body = "No files found for range specified";
}
var mailMessage = new MailMessage()
{
To = { emailAddress },
From = new MailAddress(emailFrom),
Body = body,
Subject = subject
};
if (result?.ZipStream != null)
{
mailMessage.Attachments.Add(new Attachment(result.ZipStream, attachmentName));
}
this.mailService.SendMessage(mailMessage);
}
}
} | namespace Pigeon
{
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Net.Mime;
using Pigeon.Adapters;
public class Mailer
{
private readonly IMailService mailService;
public Mailer(IMailService mailService)
{
this.mailService = mailService;
}
public void SendZip(ZipResult result, string emailAddress, string emailFrom, string subject, string attachmentName)
{
string body;
if (result != null && result.Entries.Any())
{
body = string.Join("\n\r", result.Entries);
}
else
{
body = "No files found for range specified";
}
var mailMessage = new MailMessage()
{
To = { emailAddress },
From = new MailAddress(emailFrom),
Body = body,
Subject = subject
};
using (mailMessage)
{
if (result?.ZipStream != null)
{
result.ZipStream.Position = 0;
Attachment attachment = new Attachment(result.ZipStream, attachmentName + ".zip", MediaTypeNames.Application.Zip);
mailMessage.Attachments.Add(attachment);
}
this.mailService.SendMessage(mailMessage);
}
}
}
} |
Add permissions to sample app | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ComponentSample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ComponentSample")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
// Add some common permissions, these can be removed if not needed
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
| using System.Reflection;
using System.Runtime.InteropServices;
using Android;
using Android.App;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ComponentSample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ComponentSample")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: UsesPermission(Manifest.Permission.AccessFineLocation)]
[assembly: UsesPermission(Manifest.Permission.AccessCoarseLocation)]
[assembly: UsesPermission(Manifest.Permission.AccessWifiState)]
[assembly: UsesPermission(Manifest.Permission.AccessNetworkState)]
[assembly: UsesPermission(Manifest.Permission.Internet)]
[assembly: UsesPermission(Manifest.Permission.WriteExternalStorage)]
|
Add ProvideLanguageExtension to markdown formats | using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.Markdown.Editor.ContentTypes;
using Microsoft.VisualStudio.R.Package.Packages;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.R.Packages.Markdown {
[PackageRegistration(UseManagedResourcesOnly = true)]
[Guid(MdGuidList.MdPackageGuidString)]
[ProvideEditorExtension(typeof(MdEditorFactory), ".md", 0x32, NameResourceID = 107)]
[ProvideEditorExtension(typeof(MdEditorFactory), ".rmd", 0x32, NameResourceID = 107)]
[ProvideEditorExtension(typeof(MdEditorFactory), ".markdown", 0x32, NameResourceID = 107)]
[ProvideLanguageService(typeof(MdLanguageService), MdContentTypeDefinition.LanguageName, 107, ShowSmartIndent = false)]
[ProvideEditorFactory(typeof(MdEditorFactory), 107, CommonPhysicalViewAttributes = 0x2, TrustLevel = __VSEDITORTRUSTLEVEL.ETL_AlwaysTrusted)]
[ProvideEditorLogicalView(typeof(MdEditorFactory), VSConstants.LOGVIEWID.TextView_string)]
internal sealed class MdPackage : BasePackage<MdLanguageService> {
protected override IEnumerable<IVsEditorFactory> CreateEditorFactories() {
yield return new MdEditorFactory(this);
}
}
}
| using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.Markdown.Editor.ContentTypes;
using Microsoft.VisualStudio.R.Package.Packages;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.R.Packages.Markdown {
[PackageRegistration(UseManagedResourcesOnly = true)]
[Guid(MdGuidList.MdPackageGuidString)]
[ProvideLanguageExtension(MdGuidList.MdLanguageServiceGuidString, MdContentTypeDefinition.FileExtension1)]
[ProvideLanguageExtension(MdGuidList.MdLanguageServiceGuidString, MdContentTypeDefinition.FileExtension2)]
[ProvideLanguageExtension(MdGuidList.MdLanguageServiceGuidString, MdContentTypeDefinition.FileExtension3)]
[ProvideEditorExtension(typeof(MdEditorFactory), ".md", 0x32, NameResourceID = 107)]
[ProvideEditorExtension(typeof(MdEditorFactory), ".rmd", 0x32, NameResourceID = 107)]
[ProvideEditorExtension(typeof(MdEditorFactory), ".markdown", 0x32, NameResourceID = 107)]
[ProvideLanguageService(typeof(MdLanguageService), MdContentTypeDefinition.LanguageName, 107, ShowSmartIndent = false)]
[ProvideEditorFactory(typeof(MdEditorFactory), 107, CommonPhysicalViewAttributes = 0x2, TrustLevel = __VSEDITORTRUSTLEVEL.ETL_AlwaysTrusted)]
[ProvideEditorLogicalView(typeof(MdEditorFactory), VSConstants.LOGVIEWID.TextView_string)]
internal sealed class MdPackage : BasePackage<MdLanguageService> {
protected override IEnumerable<IVsEditorFactory> CreateEditorFactories() {
yield return new MdEditorFactory(this);
}
}
}
|
Revert orleans for backwards compatibility. | // ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.Globalization;
#pragma warning disable SA1313 // Parameter names should begin with lower-case letter
namespace Squidex.Infrastructure.Commands
{
public sealed record CommandRequest(IAggregateCommand Command, string Culture, string CultureUI)
{
public static CommandRequest Create(IAggregateCommand command)
{
return new CommandRequest(command,
CultureInfo.CurrentCulture.Name,
CultureInfo.CurrentUICulture.Name);
}
public void ApplyContext()
{
var culture = GetCulture(Culture);
if (culture != null)
{
CultureInfo.CurrentCulture = culture;
}
var uiCulture = GetCulture(CultureUI);
if (uiCulture != null)
{
CultureInfo.CurrentUICulture = uiCulture;
}
}
private static CultureInfo? GetCulture(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return null;
}
try
{
return CultureInfo.GetCultureInfo(name);
}
catch (CultureNotFoundException)
{
return null;
}
}
}
}
| // ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.Globalization;
namespace Squidex.Infrastructure.Commands
{
public sealed class CommandRequest
{
public IAggregateCommand Command { get; }
public string Culture { get; }
public string CultureUI { get; }
public CommandRequest(IAggregateCommand command, string culture, string cultureUI)
{
Command = command;
Culture = culture;
CultureUI = cultureUI;
}
public static CommandRequest Create(IAggregateCommand command)
{
return new CommandRequest(command,
CultureInfo.CurrentCulture.Name,
CultureInfo.CurrentUICulture.Name);
}
public void ApplyContext()
{
var culture = GetCulture(Culture);
if (culture != null)
{
CultureInfo.CurrentCulture = culture;
}
var uiCulture = GetCulture(CultureUI);
if (uiCulture != null)
{
CultureInfo.CurrentUICulture = uiCulture;
}
}
private static CultureInfo? GetCulture(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return null;
}
try
{
return CultureInfo.GetCultureInfo(name);
}
catch (CultureNotFoundException)
{
return null;
}
}
}
}
|
Add bad know-how for NotifyIcon | using System;
using System.Windows.Forms;
namespace COIME.Common.Control
{
public class NotifyIconUtil
{
/// <summary>
/// Setup NotifyIcon.
/// The icon added to the notification area, and then retry until it succeeds.
/// </summary>
/// <param name="notifyIcon"></param>
public static void Setup(NotifyIcon notifyIcon)
{
// setup notify icon
while (true)
{
int tickCount = Environment.TickCount;
notifyIcon.Visible = true;
tickCount = Environment.TickCount - tickCount;
if (tickCount < 4000)
{
// Success if less than 4 seconds
break;
}
// retry
notifyIcon.Visible = false;
}
}
}
}
| using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace COIME.Common.Control
{
public class NotifyIconUtil
{
/*
* for ALT + F4 problem
* see http://d.hatena.ne.jp/hnx8/20131208/1386486457
*/
[DllImport("user32")]
static extern IntPtr GetForegroundWindow();
[System.Runtime.InteropServices.DllImport("user32")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
[System.Runtime.InteropServices.DllImport("user32")]
static extern IntPtr GetDesktopWindow();
/// <summary>
/// Setup NotifyIcon.
/// The icon added to the notification area, and then retry until it succeeds.
/// </summary>
/// <param name="notifyIcon"></param>
public static void Setup(NotifyIcon notifyIcon)
{
AntiAltF4(notifyIcon);
// setup notify icon
while (true)
{
int tickCount = Environment.TickCount;
notifyIcon.Visible = true;
tickCount = Environment.TickCount - tickCount;
if (tickCount < 4000)
{
// Success if less than 4 seconds
break;
}
// retry
notifyIcon.Visible = false;
}
}
private static void AntiAltF4(NotifyIcon notifyIcon)
{
var cms = notifyIcon.ContextMenuStrip;
if (cms != null)
{
cms.PreviewKeyDown += (sender, e) =>
{
if (e.Alt)
{
SetForegroundWindow(GetDesktopWindow());
}
};
cms.Closing += (sender, e) =>
{
FieldInfo fi = typeof(NotifyIcon).GetField("window", BindingFlags.NonPublic | BindingFlags.Instance);
NativeWindow window = fi.GetValue(notifyIcon) as NativeWindow;
IntPtr handle = GetForegroundWindow();
if (handle == window.Handle)
{
SetForegroundWindow(GetDesktopWindow());
}
};
}
}
}
}
|
Update helper for the case when you want to find a node in structured trivia. | // 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.Threading;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class LocationExtensions
{
public static SyntaxToken FindToken(this Location location, CancellationToken cancellationToken)
=> location.SourceTree.GetRoot(cancellationToken).FindToken(location.SourceSpan.Start);
public static SyntaxNode FindNode(this Location location, CancellationToken cancellationToken)
=> location.SourceTree.GetRoot(cancellationToken).FindNode(location.SourceSpan);
public static SyntaxNode FindNode(this Location location, bool getInnermostNodeForTie, CancellationToken cancellationToken)
=> location.SourceTree.GetRoot(cancellationToken).FindNode(location.SourceSpan, getInnermostNodeForTie: getInnermostNodeForTie);
public static bool IsVisibleSourceLocation(this Location loc)
{
if (!loc.IsInSource)
{
return false;
}
var tree = loc.SourceTree;
return !(tree == null || tree.IsHiddenPosition(loc.SourceSpan.Start));
}
}
}
| // 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.Threading;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class LocationExtensions
{
public static SyntaxToken FindToken(this Location location, CancellationToken cancellationToken)
=> location.SourceTree.GetRoot(cancellationToken).FindToken(location.SourceSpan.Start);
public static SyntaxNode FindNode(this Location location, CancellationToken cancellationToken)
=> location.SourceTree.GetRoot(cancellationToken).FindNode(location.SourceSpan);
public static SyntaxNode FindNode(this Location location, bool getInnermostNodeForTie, CancellationToken cancellationToken)
=> location.SourceTree.GetRoot(cancellationToken).FindNode(location.SourceSpan, getInnermostNodeForTie: getInnermostNodeForTie);
public static SyntaxNode FindNode(this Location location, bool findInsideTrivia, bool getInnermostNodeForTie, CancellationToken cancellationToken)
=> location.SourceTree.GetRoot(cancellationToken).FindNode(location.SourceSpan, findInsideTrivia, getInnermostNodeForTie);
public static bool IsVisibleSourceLocation(this Location loc)
{
if (!loc.IsInSource)
{
return false;
}
var tree = loc.SourceTree;
return !(tree == null || tree.IsHiddenPosition(loc.SourceSpan.Start));
}
}
}
|
Fix multi-input controller not adding tilt. | // Copyright 2017 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 UnityEngine;
using System.Collections.Generic;
namespace Hamster.InputControllers {
// Class for compositing multile input sources.
// Useful for normalizing and combining different input sources.
public class MultiInputController : BasePlayerController {
List<BasePlayerController> controllerList;
public MultiInputController() {
controllerList = new List<BasePlayerController>() {
new KeyboardController(),
};
if (CommonData.inVrMode) {
controllerList.Add(new DaydreamTiltController());
} else {
new TiltController();
}
}
public override Vector2 GetInputVector() {
Vector2 result = Vector2.zero;
foreach (BasePlayerController controller in controllerList) {
result += controller.GetInputVector();
}
return result;
}
}
}
| // Copyright 2017 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 UnityEngine;
using System.Collections.Generic;
namespace Hamster.InputControllers {
// Class for compositing multile input sources.
// Useful for normalizing and combining different input sources.
public class MultiInputController : BasePlayerController {
List<BasePlayerController> controllerList;
public MultiInputController() {
controllerList = new List<BasePlayerController>() {
new KeyboardController(),
};
if (CommonData.inVrMode) {
controllerList.Add(new DaydreamTiltController());
} else {
controllerList.Add(new TiltController());
}
}
public override Vector2 GetInputVector() {
Vector2 result = Vector2.zero;
foreach (BasePlayerController controller in controllerList) {
result += controller.GetInputVector();
}
return result;
}
}
}
|
Add sync Run helper to sort fields visitor | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Foundatio.Parsers.LuceneQueries.Extensions;
using Foundatio.Parsers.LuceneQueries.Nodes;
using Foundatio.Parsers.LuceneQueries.Visitors;
using Nest;
namespace Foundatio.Parsers.ElasticQueries.Visitors {
public class GetSortFieldsVisitor : QueryNodeVisitorWithResultBase<IEnumerable<IFieldSort>> {
private readonly List<IFieldSort> _fields = new List<IFieldSort>();
public override void Visit(TermNode node, IQueryVisitorContext context) {
if (String.IsNullOrEmpty(node.Field))
return;
var elasticContext = context as IElasticQueryVisitorContext;
if (elasticContext == null)
throw new ArgumentException("Context must be of type IElasticQueryVisitorContext", nameof(context));
string field = elasticContext.GetNonAnalyzedFieldName(node.Field);
var sort = new SortField { Field = field };
if (node.IsNodeNegated())
sort.Order = SortOrder.Descending;
_fields.Add(sort);
}
public override async Task<IEnumerable<IFieldSort>> AcceptAsync(IQueryNode node, IQueryVisitorContext context) {
await node.AcceptAsync(this, context).ConfigureAwait(false);
return _fields;
}
public static Task<IEnumerable<IFieldSort>> RunAsync(IQueryNode node, IQueryVisitorContext context = null) {
return new GetSortFieldsVisitor().AcceptAsync(node, context);
}
}
}
| using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Foundatio.Parsers.LuceneQueries.Extensions;
using Foundatio.Parsers.LuceneQueries.Nodes;
using Foundatio.Parsers.LuceneQueries.Visitors;
using Nest;
namespace Foundatio.Parsers.ElasticQueries.Visitors {
public class GetSortFieldsVisitor : QueryNodeVisitorWithResultBase<IEnumerable<IFieldSort>> {
private readonly List<IFieldSort> _fields = new List<IFieldSort>();
public override void Visit(TermNode node, IQueryVisitorContext context) {
if (String.IsNullOrEmpty(node.Field))
return;
var elasticContext = context as IElasticQueryVisitorContext;
if (elasticContext == null)
throw new ArgumentException("Context must be of type IElasticQueryVisitorContext", nameof(context));
string field = elasticContext.GetNonAnalyzedFieldName(node.Field);
var sort = new SortField { Field = field };
if (node.IsNodeNegated())
sort.Order = SortOrder.Descending;
_fields.Add(sort);
}
public override async Task<IEnumerable<IFieldSort>> AcceptAsync(IQueryNode node, IQueryVisitorContext context) {
await node.AcceptAsync(this, context).ConfigureAwait(false);
return _fields;
}
public static Task<IEnumerable<IFieldSort>> RunAsync(IQueryNode node, IQueryVisitorContext context = null) {
return new GetSortFieldsVisitor().AcceptAsync(node, context);
}
public static IEnumerable<IFieldSort> Run(IQueryNode node, IQueryVisitorContext context = null) {
return RunAsync(node, context).GetAwaiter().GetResult();
}
}
}
|
Delete scheduled task when content is published | using Orchard.ContentManagement.Handlers;
using Orchard.PublishLater.Models;
using Orchard.PublishLater.Services;
using Orchard.Tasks.Scheduling;
namespace Orchard.PublishLater.Handlers {
public class PublishLaterPartHandler : ContentHandler {
private readonly IPublishLaterService _publishLaterService;
public PublishLaterPartHandler(
IPublishLaterService publishLaterService,
IPublishingTaskManager publishingTaskManager) {
_publishLaterService = publishLaterService;
OnLoading<PublishLaterPart>((context, part) => LazyLoadHandlers(part));
OnVersioning<PublishLaterPart>((context, part, newVersionPart) => LazyLoadHandlers(newVersionPart));
OnRemoved<PublishLaterPart>((context, part) => publishingTaskManager.DeleteTasks(part.ContentItem));
}
protected void LazyLoadHandlers(PublishLaterPart part) {
part.ScheduledPublishUtc.Loader(() => _publishLaterService.GetScheduledPublishUtc(part));
}
}
} | using Orchard.ContentManagement.Handlers;
using Orchard.PublishLater.Models;
using Orchard.PublishLater.Services;
using Orchard.Tasks.Scheduling;
namespace Orchard.PublishLater.Handlers {
public class PublishLaterPartHandler : ContentHandler {
private readonly IPublishLaterService _publishLaterService;
public PublishLaterPartHandler(
IPublishLaterService publishLaterService,
IPublishingTaskManager publishingTaskManager) {
_publishLaterService = publishLaterService;
OnLoading<PublishLaterPart>((context, part) => LazyLoadHandlers(part));
OnVersioning<PublishLaterPart>((context, part, newVersionPart) => LazyLoadHandlers(newVersionPart));
OnRemoved<PublishLaterPart>((context, part) => publishingTaskManager.DeleteTasks(part.ContentItem));
OnPublishing<PublishLaterPart>((context, part) =>
{
var existingPublishTask = publishingTaskManager.GetPublishTask(context.ContentItem);
//Check if there is already and existing publish task for old version.
if (existingPublishTask != null)
{
//If exists remove it in order no to override the latest published version.
publishingTaskManager.DeleteTasks(context.ContentItem);
}
});
}
protected void LazyLoadHandlers(PublishLaterPart part) {
part.ScheduledPublishUtc.Loader(() => _publishLaterService.GetScheduledPublishUtc(part));
}
}
} |
Remove exceptions from character extensions | // 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 System;
using System.Linq;
using EOLib.Domain.Character;
namespace EOLib.Domain.Extensions
{
public static class CharacterRenderPropertiesExtensions
{
public static bool IsFacing(this ICharacterRenderProperties renderProperties, params EODirection[] directions)
{
return directions.Contains(renderProperties.Direction);
}
public static bool IsActing(this ICharacterRenderProperties renderProperties, CharacterActionState action)
{
return renderProperties.CurrentAction == action;
}
public static int GetDestinationX(this ICharacterRenderProperties renderProperties)
{
if (renderProperties.CurrentAction != CharacterActionState.Walking)
throw new ArgumentException("The character is not currently in the walking state.", "renderProperties");
var offset = GetXOffset(renderProperties.Direction);
return renderProperties.MapX + offset;
}
public static int GetDestinationY(this ICharacterRenderProperties renderProperties)
{
if (renderProperties.CurrentAction != CharacterActionState.Walking)
throw new ArgumentException("The character is not currently in the walking state.", "renderProperties");
var offset = GetYOffset(renderProperties.Direction);
return renderProperties.MapY + offset;
}
private static int GetXOffset(EODirection direction)
{
return direction == EODirection.Right ? 1 :
direction == EODirection.Left ? -1 : 0;
}
private static int GetYOffset(EODirection direction)
{
return direction == EODirection.Down ? 1 :
direction == EODirection.Up ? -1 : 0;
}
}
}
| // 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 System;
using System.Linq;
using EOLib.Domain.Character;
namespace EOLib.Domain.Extensions
{
public static class CharacterRenderPropertiesExtensions
{
public static bool IsFacing(this ICharacterRenderProperties renderProperties, params EODirection[] directions)
{
return directions.Contains(renderProperties.Direction);
}
public static bool IsActing(this ICharacterRenderProperties renderProperties, CharacterActionState action)
{
return renderProperties.CurrentAction == action;
}
public static int GetDestinationX(this ICharacterRenderProperties renderProperties)
{
var offset = GetXOffset(renderProperties.Direction);
return renderProperties.MapX + offset;
}
public static int GetDestinationY(this ICharacterRenderProperties renderProperties)
{
var offset = GetYOffset(renderProperties.Direction);
return renderProperties.MapY + offset;
}
private static int GetXOffset(EODirection direction)
{
return direction == EODirection.Right ? 1 :
direction == EODirection.Left ? -1 : 0;
}
private static int GetYOffset(EODirection direction)
{
return direction == EODirection.Down ? 1 :
direction == EODirection.Up ? -1 : 0;
}
}
}
|
Make Search Operator automatically parsed by MVC. | using System;
using System.Web.Mvc;
using TeacherPouch.Models;
using TeacherPouch.Providers;
using TeacherPouch.Repositories;
namespace TeacherPouch.Web.Controllers
{
public partial class SearchController : RepositoryControllerBase
{
public SearchController(IRepository repository)
{
base.Repository = repository;
}
// GET: /Search?q=spring&op=and
public virtual ViewResult Search(string q, string op)
{
if (String.IsNullOrWhiteSpace(q) || q.Length < 2)
return base.View(Views.NoneFound);
ViewBag.SearchTerm = q;
bool allowPrivate = SecurityHelper.UserCanSeePrivateRecords(base.User);
SearchOperator searchOperator = SearchOperator.Or;
if (!String.IsNullOrWhiteSpace(op))
{
SearchOperator parsed;
if (Enum.TryParse(op, true, out parsed))
searchOperator = parsed;
}
if (searchOperator == SearchOperator.Or)
{
var results = base.Repository.SearchOr(q, allowPrivate);
if (results.HasAnyResults)
return base.View(Views.SearchResultsOr, results);
else
return base.View(Views.NoneFound);
}
else if (searchOperator == SearchOperator.And)
{
ViewBag.AndChecked = true;
var results = base.Repository.SearchAnd(q, allowPrivate);
if (results.HasAnyResults)
return base.View(Views.SearchResultsAnd, results);
else
return base.View(Views.NoneFound);
}
else
{
throw new ApplicationException("Search operator not found.");
}
}
}
}
| using System;
using System.ComponentModel;
using System.Web.Mvc;
using TeacherPouch.Models;
using TeacherPouch.Providers;
using TeacherPouch.Repositories;
namespace TeacherPouch.Web.Controllers
{
public partial class SearchController : RepositoryControllerBase
{
public SearchController(IRepository repository)
{
base.Repository = repository;
}
// GET: /Search?q=spring&op=and
public virtual ViewResult Search(string q, SearchOperator op = SearchOperator.Or)
{
if (String.IsNullOrWhiteSpace(q) || q.Length < 2)
return base.View(Views.NoneFound);
ViewBag.SearchTerm = q;
bool allowPrivate = SecurityHelper.UserCanSeePrivateRecords(base.User);
if (op == SearchOperator.Or)
{
var results = base.Repository.SearchOr(q, allowPrivate);
if (results.HasAnyResults)
return base.View(Views.SearchResultsOr, results);
else
return base.View(Views.NoneFound);
}
else if (op == SearchOperator.And)
{
ViewBag.AndChecked = true;
var results = base.Repository.SearchAnd(q, allowPrivate);
if (results.HasAnyResults)
return base.View(Views.SearchResultsAnd, results);
else
return base.View(Views.NoneFound);
}
else
{
throw new InvalidEnumArgumentException("Unknown search operator.");
}
}
}
}
|
Change over usage of IAgentStartup to use IAgentStartupManager instead | using System.Linq;
using Glimpse.Web;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
namespace Glimpse.Agent.Web
{
public static class GlimpseAgentWebExtension
{
public static IApplicationBuilder UseGlimpseAgent(this IApplicationBuilder app)
{
var startups = app.ApplicationServices.GetRequiredService<IExtensionProvider<IAgentStartup>>();
if (startups.Instances.Any())
{
var options = new StartupOptions(app);
foreach (var startup in startups.Instances)
{
startup.Run(options);
}
}
return app.UseMiddleware<GlimpseAgentWebMiddleware>(app);
}
}
} | using System.Linq;
using Glimpse.Web;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
namespace Glimpse.Agent.Web
{
public static class GlimpseAgentWebExtension
{
public static IApplicationBuilder UseGlimpseAgent(this IApplicationBuilder app)
{
var manager = app.ApplicationServices.GetRequiredService<IAgentStartupManager>();
manager.Run(new StartupOptions(app));
return app.UseMiddleware<GlimpseAgentWebMiddleware>(app);
}
}
} |
Stop hover sounds from playing when dragging (scrolling) | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input.Events;
using osu.Game.Configuration;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// Handles debouncing hover sounds at a global level to ensure the effects are not overwhelming.
/// </summary>
public abstract class HoverSampleDebounceComponent : CompositeDrawable
{
/// <summary>
/// Length of debounce for hover sound playback, in milliseconds.
/// </summary>
public double HoverDebounceTime { get; } = 20;
private Bindable<double?> lastPlaybackTime;
[BackgroundDependencyLoader]
private void load(AudioManager audio, SessionStatics statics)
{
lastPlaybackTime = statics.GetBindable<double?>(Static.LastHoverSoundPlaybackTime);
}
protected override bool OnHover(HoverEvent e)
{
bool enoughTimePassedSinceLastPlayback = !lastPlaybackTime.Value.HasValue || Time.Current - lastPlaybackTime.Value >= HoverDebounceTime;
if (enoughTimePassedSinceLastPlayback)
{
PlayHoverSample();
lastPlaybackTime.Value = Time.Current;
}
return false;
}
public abstract void PlayHoverSample();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input.Events;
using osu.Game.Configuration;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// Handles debouncing hover sounds at a global level to ensure the effects are not overwhelming.
/// </summary>
public abstract class HoverSampleDebounceComponent : CompositeDrawable
{
/// <summary>
/// Length of debounce for hover sound playback, in milliseconds.
/// </summary>
public double HoverDebounceTime { get; } = 20;
private Bindable<double?> lastPlaybackTime;
[BackgroundDependencyLoader]
private void load(AudioManager audio, SessionStatics statics)
{
lastPlaybackTime = statics.GetBindable<double?>(Static.LastHoverSoundPlaybackTime);
}
protected override bool OnHover(HoverEvent e)
{
// hover sounds shouldn't be played during scroll operations.
if (e.HasAnyButtonPressed)
return false;
bool enoughTimePassedSinceLastPlayback = !lastPlaybackTime.Value.HasValue || Time.Current - lastPlaybackTime.Value >= HoverDebounceTime;
if (enoughTimePassedSinceLastPlayback)
{
PlayHoverSample();
lastPlaybackTime.Value = Time.Current;
}
return false;
}
public abstract void PlayHoverSample();
}
}
|
Stop all watchers when exiting | using System;
using FSWActions.Core;
using FSWActions.Core.Config;
namespace FSWActions.ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
WatchersConfiguration configuration = WatchersConfiguration.LoadConfigFromPath("watchers.xml");
foreach (WatcherConfig watcherConfig in configuration.Watchers)
{
foreach (ActionConfig action in watcherConfig.ActionsConfig)
{
Console.WriteLine("{0} [{1}]\t{2}: {3}", watcherConfig.Path, watcherConfig.Filter, action.Event, action.Command);
}
Watcher watcher = new Watcher(watcherConfig);
watcher.StartWatching();
}
// Wait for the user to quit the program.
Console.WriteLine("\n\nPress \'q\' to quit\n");
while (Console.Read() != 'q') ;
}
}
}
| using System;
using System.Collections.Generic;
using FSWActions.Core;
using FSWActions.Core.Config;
namespace FSWActions.ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
WatchersConfiguration configuration = WatchersConfiguration.LoadConfigFromPath("watchers.xml");
List<Watcher> watchers = new List<Watcher>(configuration.Watchers.Count);
foreach (WatcherConfig watcherConfig in configuration.Watchers)
{
foreach (ActionConfig action in watcherConfig.ActionsConfig)
{
Console.WriteLine("{0} [{1}]\t{2}: {3}", watcherConfig.Path, watcherConfig.Filter, action.Event, action.Command);
}
Watcher watcher = new Watcher(watcherConfig);
watchers.Add(watcher);
watcher.StartWatching();
}
// Wait for the user to quit the program.
Console.WriteLine("\n\nPress \'q\' to quit\n");
while (Console.Read() != 'q') ;
// Stop all watchers, not really necessary though...
foreach (Watcher watcher in watchers)
{
watcher.StopWatching();
}
}
}
}
|
Use ToString in converter instead of boxing-cast | using Newtonsoft.Json;
using System;
using System.Globalization;
namespace Discord.Net.Converters
{
internal class NullableUInt64Converter : JsonConverter
{
public static readonly NullableUInt64Converter Instance = new NullableUInt64Converter();
public override bool CanConvert(Type objectType) => true;
public override bool CanRead => true;
public override bool CanWrite => true;
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
object value = reader.Value;
if (value != null)
return ulong.Parse((string)value, NumberStyles.None, CultureInfo.InvariantCulture);
else
return null;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value != null)
writer.WriteValue(((ulong?)value).Value.ToString(CultureInfo.InvariantCulture));
else
writer.WriteNull();
}
}
}
| using Newtonsoft.Json;
using System;
using System.Globalization;
namespace Discord.Net.Converters
{
internal class NullableUInt64Converter : JsonConverter
{
public static readonly NullableUInt64Converter Instance = new NullableUInt64Converter();
public override bool CanConvert(Type objectType) => true;
public override bool CanRead => true;
public override bool CanWrite => true;
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
object value = reader.Value;
if (value != null)
return ulong.Parse(value.ToString(), NumberStyles.None, CultureInfo.InvariantCulture);
else
return null;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value != null)
writer.WriteValue(((ulong?)value).Value.ToString(CultureInfo.InvariantCulture));
else
writer.WriteNull();
}
}
}
|
Convert all of these SymbolInfo extensions to ImmutableArray and reduce allocations. | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class SymbolInfoExtensions
{
public static IEnumerable<ISymbol> GetAllSymbols(this SymbolInfo info)
{
return info.Symbol == null && info.CandidateSymbols.Length == 0
? SpecializedCollections.EmptyEnumerable<ISymbol>()
: GetAllSymbolsWorker(info).Distinct();
}
private static IEnumerable<ISymbol> GetAllSymbolsWorker(this SymbolInfo info)
{
if (info.Symbol != null)
{
yield return info.Symbol;
}
foreach (var symbol in info.CandidateSymbols)
{
yield return symbol;
}
}
public static ISymbol GetAnySymbol(this SymbolInfo info)
{
return info.Symbol != null
? info.Symbol
: info.CandidateSymbols.FirstOrDefault();
}
public static IEnumerable<ISymbol> GetBestOrAllSymbols(this SymbolInfo info)
{
if (info.Symbol != null)
{
return SpecializedCollections.SingletonEnumerable(info.Symbol);
}
else if (info.CandidateSymbols.Length > 0)
{
return info.CandidateSymbols;
}
return SpecializedCollections.EmptyEnumerable<ISymbol>();
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
// Note - these methods are called in fairly hot paths in the IDE, so we try to be responsible about allocations.
internal static class SymbolInfoExtensions
{
public static ImmutableArray<ISymbol> GetAllSymbols(this SymbolInfo info)
{
return GetAllSymbolsWorker(info).Distinct();
}
private static ImmutableArray<ISymbol> GetAllSymbolsWorker(this SymbolInfo info)
{
if (info.Symbol == null)
{
return info.CandidateSymbols;
}
else
{
var builder = ImmutableArray.CreateBuilder<ISymbol>(info.CandidateSymbols.Length + 1);
builder.Add(info.Symbol);
builder.AddRange(info.CandidateSymbols);
return builder.ToImmutable();
}
}
public static ISymbol GetAnySymbol(this SymbolInfo info)
{
return info.Symbol != null
? info.Symbol
: info.CandidateSymbols.FirstOrDefault();
}
public static ImmutableArray<ISymbol> GetBestOrAllSymbols(this SymbolInfo info)
{
if (info.Symbol != null)
{
return ImmutableArray.Create(info.Symbol);
}
else if (info.CandidateSymbols.Length > 0)
{
return info.CandidateSymbols;
}
return ImmutableArray<ISymbol>.Empty;
}
}
}
|
Fix for failing mspec test | using System;
using Nancy.ErrorHandling;
namespace Nancy.Testing
{
public class PassThroughErrorHandler : IErrorHandler
{
public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)
{
var exception = context.Items[NancyEngine.ERROR_EXCEPTION] as Exception;
return statusCode == HttpStatusCode.InternalServerError && exception != null;
}
public void Handle(HttpStatusCode statusCode, NancyContext context)
{
throw new Exception("ConfigurableBootstrapper Exception", context.Items[NancyEngine.ERROR_EXCEPTION] as Exception);
}
}
} | using System;
using Nancy.ErrorHandling;
namespace Nancy.Testing
{
public class PassThroughErrorHandler : IErrorHandler
{
public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)
{
if (!context.Items.ContainsKey(NancyEngine.ERROR_EXCEPTION))
{
return false;
}
var exception = context.Items[NancyEngine.ERROR_EXCEPTION] as Exception;
return statusCode == HttpStatusCode.InternalServerError && exception != null;
}
public void Handle(HttpStatusCode statusCode, NancyContext context)
{
throw new Exception("ConfigurableBootstrapper Exception", context.Items[NancyEngine.ERROR_EXCEPTION] as Exception);
}
}
} |
Fix multiple open data readers problem. | using FinancesSharp.Models;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
namespace FinancesSharp.ViewModels
{
public class RulesViewModel
{
public IEnumerable<CategorisationRule> Rules { get; private set; }
public RulesViewModel(FinanceDb db)
{
Rules = db.ActiveRules
.OrderBy(x => x.Category.Id)
.AsEnumerable();
}
}
} | using FinancesSharp.Models;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
namespace FinancesSharp.ViewModels
{
public class RulesViewModel
{
public IEnumerable<CategorisationRule> Rules { get; private set; }
public RulesViewModel(FinanceDb db)
{
Rules = db.ActiveRules
.OrderBy(x => x.Category.Id)
.ToList();
}
}
} |
Change logic in console application to draw game field on console.! | using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Logic.Engine;
using Logic.GameObjects;
namespace FeelTheField
{
class ConsoleAplication
{
static void Main()
{
char ch1 = 'X';
char ch2 = '$';
int row = int.Parse(Console.ReadLine());
int col = int.Parse(Console.ReadLine());
char[,] matrix = new char[row, col];
DrawConsole.FillWithChar(matrix, ch1);
DrawConsole.PrintField(matrix);
var engine = Engine.Instance;
engine.ConfigureGameFieldSize(row, col);
var gameField = engine.Field; // The Matrix
DrawConsole.FillWithChar(matrix,'X');
DrawConsole.PrintField(matrix);
}
}
}
| using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Logic.Engine;
using Logic.Enumerations;
using Logic.GameObjects;
namespace FeelTheField
{
class ConsoleAplication
{
static void Main()
{
char closed = 'X';
char open = '$';
int row = int.Parse(Console.ReadLine());
int col = int.Parse(Console.ReadLine());
Console.Clear();
char[,] matrix = new char[row, col];
var engine = Engine.Instance;
engine.ConfigureGameFieldSize(row, col);
var gameField = engine.Field; // The Matrix
DrawConsole.FillWithChar(matrix,'X');
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
if (gameField.Matrix[i, j].ObjeState == State.Open)
{
matrix[i, j] = open;
//matrix[i, j] = gameField.Matrix[i, j].Body;
}
else
{
matrix[i, j] = closed;
//matrix[i, j] = gameField.Matrix[i, j].Body;
}
}
}
DrawConsole.PrintField(matrix);
}
}
}
|
Test Passes - We can get and set Items on Program | using Kata.GildedRose.CSharp.Console;
using NUnit.Framework;
using System.Collections.Generic;
namespace Kata.GildedRose.CSharp.Unit.Tests
{
[TestFixture]
public class WhenTestTheGildedRoseProgram
{
string _actualName = "+5 Dexterity Vest";
int _actualSellin = 10;
int _actualQuality = 10;
Item _actualStockItem;
IList<Item> _stockItems;
Program GildedRoseProgram;
[SetUp]
public void Init()
{
_actualStockItem = new Item
{
Name = _actualName,
SellIn = _actualSellin,
Quality = _actualQuality
};
GildedRoseProgram = new Program();
_stockItems = new List<Item> { _actualStockItem };
}
[Test]
public void ItShouldAllowUsToSetAndRetrieveTheItemsCorrectly()
{
Assert.AreEqual(_actualStockItem, GildedRoseProgram.Items[0]);
}
}
}
| using Kata.GildedRose.CSharp.Console;
using NUnit.Framework;
using System.Collections.Generic;
namespace Kata.GildedRose.CSharp.Unit.Tests
{
[TestFixture]
public class WhenTestTheGildedRoseProgram
{
string _actualName = "+5 Dexterity Vest";
int _actualSellin = 10;
int _actualQuality = 10;
Item _actualStockItem;
IList<Item> _stockItems;
Program GildedRoseProgram;
[SetUp]
public void Init()
{
_actualStockItem = new Item
{
Name = _actualName,
SellIn = _actualSellin,
Quality = _actualQuality
};
GildedRoseProgram = new Program();
_stockItems = new List<Item> { _actualStockItem };
}
[Test]
public void ItShouldAllowUsToSetAndRetrieveTheItemsCorrectly()
{
GildedRoseProgram.Items = _stockItems;
Assert.AreEqual(_actualStockItem, GildedRoseProgram.Items[0]);
}
}
}
|
Remove unneeded properties from assembly info | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PlayerRank")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PlayerRank")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: InternalsVisibleTo("PlayerRank.UnitTests")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f429a5d5-a386-4b9d-a369-c1ffec7da00b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PlayerRank")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PlayerRank")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: InternalsVisibleTo("PlayerRank.UnitTests")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f429a5d5-a386-4b9d-a369-c1ffec7da00b")]
|
Fix default connection string for MongoDB | namespace InfinniPlatform.DocumentStorage
{
/// <summary>
/// Настройки хранилища документов MongoDB.
/// </summary>
public class MongoDocumentStorageOptions
{
public const string SectionName = "mongodbDocumentStorage";
public static MongoDocumentStorageOptions Default = new MongoDocumentStorageOptions();
public MongoDocumentStorageOptions()
{
ConnectionString = "localhost:27017";
}
/// <summary>
/// Строка подключения.
/// </summary>
/// <remarks>
/// Подробнее см. https://docs.mongodb.com/manual/reference/connection-string..
/// </remarks>
public string ConnectionString { get; set; }
}
} | namespace InfinniPlatform.DocumentStorage
{
/// <summary>
/// Настройки хранилища документов MongoDB.
/// </summary>
public class MongoDocumentStorageOptions
{
public const string SectionName = "mongodbDocumentStorage";
public static MongoDocumentStorageOptions Default = new MongoDocumentStorageOptions();
public MongoDocumentStorageOptions()
{
ConnectionString = "mongodb://localhost:27017";
}
/// <summary>
/// Строка подключения.
/// </summary>
/// <remarks>
/// Подробнее см. https://docs.mongodb.com/manual/reference/connection-string..
/// </remarks>
public string ConnectionString { get; set; }
}
} |
Fix wrong usage of Task.FromException | using Mono.Options;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using WalletWasabi.Helpers;
using WalletWasabi.Gui.CrashReport;
namespace WalletWasabi.Gui.CommandLine
{
internal class CrashReportCommand : Command
{
public CrashReportCommand(CrashReporter crashReporter) : base("crashreport", "Activates the internal crash reporting mechanism.")
{
CrashReporter = Guard.NotNull(nameof(crashReporter), crashReporter);
Options = new OptionSet()
{
{ "attempt=", "Number of attempts at starting the crash reporter.", x => Attempts = x },
{ "exception=", "The serialized exception from the previous crash.", x => ExceptionString = x },
};
}
public CrashReporter CrashReporter { get; }
public string Attempts { get; private set; }
public string ExceptionString { get; private set; }
public override Task<int> InvokeAsync(IEnumerable<string> args)
{
try
{
Options.Parse(args);
CrashReporter.SetShowCrashReport(ExceptionString, int.Parse(Attempts));
}
catch (Exception ex)
{
Task.FromException(ex);
}
return Task.FromResult(0);
}
}
}
| using Mono.Options;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using WalletWasabi.Helpers;
using WalletWasabi.Gui.CrashReport;
namespace WalletWasabi.Gui.CommandLine
{
internal class CrashReportCommand : Command
{
public CrashReportCommand(CrashReporter crashReporter) : base("crashreport", "Activates the internal crash reporting mechanism.")
{
CrashReporter = Guard.NotNull(nameof(crashReporter), crashReporter);
Options = new OptionSet()
{
{ "attempt=", "Number of attempts at starting the crash reporter.", x => Attempts = x },
{ "exception=", "The serialized exception from the previous crash.", x => ExceptionString = x },
};
}
public CrashReporter CrashReporter { get; }
public string Attempts { get; private set; }
public string ExceptionString { get; private set; }
public override Task<int> InvokeAsync(IEnumerable<string> args)
{
try
{
Options.Parse(args);
CrashReporter.SetShowCrashReport(ExceptionString, int.Parse(Attempts));
}
catch (Exception ex)
{
return Task.FromException<int>(ex);
}
return Task.FromResult(0);
}
}
}
|
Fix a typo in a code comment, thanks StyleCop! | using System;
using OpenQA.Selenium;
namespace ExampleApp.Test.Functional.Models.ExampleAppPages
{
/// <summary>
/// Modles the Slinqy Example App Homepage.
/// </summary>
public class HomePage : SlinqyExampleWebPage
{
public const string RelativePath = "/";
/// <summary>
/// Initializes the HomePage with the IWebDriver to use for controlling the page.
/// </summary>
/// <param name="webBrowserDriver">
/// Specifies the IWebDriver to use to interact with the Homepage.
/// </param>
public
HomePage(
IWebDriver webBrowserDriver)
: base(webBrowserDriver, new Uri(RelativePath, UriKind.Relative))
{
}
}
} | using System;
using OpenQA.Selenium;
namespace ExampleApp.Test.Functional.Models.ExampleAppPages
{
/// <summary>
/// Models the Slinqy Example App Homepage.
/// </summary>
public class HomePage : SlinqyExampleWebPage
{
public const string RelativePath = "/";
/// <summary>
/// Initializes the HomePage with the IWebDriver to use for controlling the page.
/// </summary>
/// <param name="webBrowserDriver">
/// Specifies the IWebDriver to use to interact with the Homepage.
/// </param>
public
HomePage(
IWebDriver webBrowserDriver)
: base(webBrowserDriver, new Uri(RelativePath, UriKind.Relative))
{
}
}
} |
Remove role=navigation on nav tag |
<div class="l-header-container">
<nav class="skip-to-main-content healthy-skip" role="navigation" aria-label="skip to main content">
<a href="#content" tabindex="1" class="skip-main"> Skip to main content </a>
</nav>
<header id="header" class="grid-container grid-100">
<div class="grid-75 mobile-grid-60 tablet-grid-50 logo-main">
<a href="/"><img src="/assets/images/ui-images/logo-main@2x.png" alt="Healthy Stockport Logo Homepage Link " title="Welcome to Healthy Stockport" class="logo-main-image"></a>
</div>
<div class="grid-25 mobile-grid-25 tablet-grid-50 grid-parent pull-right">
<div class="header-container grid-100 grid-parent">
<div class="grid-parent pull-right header-search-bar">
<partial name="HeaderSearchBar" />
</div>
</div>
</div>
</header>
</div>
<partial name="MobileSearchBar" />
|
<div class="l-header-container">
<nav class="skip-to-main-content healthy-skip" aria-label="skip to main content">
<a href="#content" tabindex="1" class="skip-main"> Skip to main content </a>
</nav>
<header id="header" class="grid-container grid-100">
<div class="grid-75 mobile-grid-60 tablet-grid-50 logo-main">
<a href="/"><img src="/assets/images/ui-images/logo-main@2x.png" alt="Healthy Stockport Logo Homepage Link " title="Welcome to Healthy Stockport" class="logo-main-image"></a>
</div>
<div class="grid-25 mobile-grid-25 tablet-grid-50 grid-parent pull-right">
<div class="header-container grid-100 grid-parent">
<div class="grid-parent pull-right header-search-bar">
<partial name="HeaderSearchBar" />
</div>
</div>
</div>
</header>
</div>
<partial name="MobileSearchBar" />
|
Update server side API for single multiple answer question | using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRepository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var questions = _dbContext.SingleMultipleAnswerQuestion.ToList();
return questions;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SaveChanges();
}
/// <summary>
/// Add option of single multiple answer question into SingleMultipleAnswerQuestionOption model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
| using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRepository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var questions = _dbContext.SingleMultipleAnswerQuestion.ToList();
return questions;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SaveChanges();
}
/// <summary>
/// Add option of single multiple answer question into SingleMultipleAnswerQuestionOption model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
|
Revert "Fill out the assembly metadata because Squirrel will use it" | // -----------------------------------------------------------------------
// Copyright (c) David Kean.
// -----------------------------------------------------------------------
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("AudioSwitcher")]
[assembly: AssemblyDescription("App that lets you easily switch Windows audio devices")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("David Kean")]
[assembly: AssemblyProduct("AudioSwitcher")]
[assembly: AssemblyCopyright("Copyright (c) David Kean")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: NeutralResourcesLanguage("en")] | // -----------------------------------------------------------------------
// Copyright (c) David Kean.
// -----------------------------------------------------------------------
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("AudioSwitcher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AudioSwitcher")]
[assembly: AssemblyCopyright("Copyright (c) David Kean")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: NeutralResourcesLanguage("en")]
|
Add multiple named instances on same type test | using Core;
using StructureMap;
using System;
using Xunit;
namespace Tests
{
public class BasicConfigationTests
{
[Fact]
public void NamedInstance()
{
ObjectFactory.Initialize(x =>
{
x.For<IService>().Use<Service>().Named("A");
x.For<IService>().Use<ServiceB>().Named("B");
});
var service = ObjectFactory.GetNamedInstance<IService>("A");
Assert.IsType<Service>(service);
}
/// <remarks>
/// This isn't the best practice.
/// Demoing that specifying constructor parameters as part of wireup is possible.
/// Ideally, other rules would make this unnecessary.
/// </remarks>
[Fact]
public void ProvideConstructorDependencyManually()
{
var value = Guid.NewGuid().ToString();
ObjectFactory.Initialize(x =>
{
// appSetting myAppSetting does not exist, will use defaultValue
x.For<IService>().Use<ServiceWithCtorArg>()
.Ctor<string>("id").EqualToAppSetting("myAppSetting", defaultValue: value);
});
var service = ObjectFactory.GetInstance<IService>();
Assert.Equal(value, service.Id);
}
}
}
| using Core;
using StructureMap;
using System;
using Xunit;
namespace Tests
{
public class BasicConfigationTests
{
[Fact]
public void NamedInstance()
{
ObjectFactory.Initialize(x =>
{
x.For<IService>().Use<Service>().Named("A");
x.For<IService>().Use<ServiceB>().Named("B");
});
var service = ObjectFactory.GetNamedInstance<IService>("A");
Assert.IsType<Service>(service);
}
[Fact]
public void GetInstanceT_MultipleNamedInstances_LastInWins()
{
ObjectFactory.Initialize(x =>
{
x.For<IService>().Use<Service>().Named("A");
x.For<IService>().Use<ServiceB>().Named("B");
});
var service = ObjectFactory.GetInstance<IService>();
Assert.IsType<ServiceB>(service);
}
/// <remarks>
/// This isn't the best practice.
/// Demoing that specifying constructor parameters as part of wireup is possible.
/// Ideally, other rules would make this unnecessary.
/// </remarks>
[Fact]
public void ProvideConstructorDependencyManually()
{
var value = Guid.NewGuid().ToString();
ObjectFactory.Initialize(x =>
{
// appSetting myAppSetting does not exist, will use defaultValue
x.For<IService>().Use<ServiceWithCtorArg>()
.Ctor<string>("id").EqualToAppSetting("myAppSetting", defaultValue: value);
});
var service = ObjectFactory.GetInstance<IService>();
Assert.Equal(value, service.Id);
}
}
}
|
Add Sleep(int) and Sleep(TimeSpan) to threading proxy. | using System;
namespace ItzWarty.Threading {
public interface IThreadingProxy {
IThread CreateThread(ThreadEntryPoint entryPoint, ThreadCreationOptions options);
ISemaphore CreateSemaphore(int initialCount, int maximumCount);
ICountdownEvent CreateCountdownEvent(int initialCount);
ICancellationTokenSource CreateCancellationTokenSource();
ICancellationTokenSource CreateCancellationTokenSource(int cancellationDelayMilliseconds);
ICancellationTokenSource CreateCancellationTokenSource(TimeSpan cancellationDelay);
}
}
| using System;
namespace ItzWarty.Threading {
public interface IThreadingProxy {
void Sleep(int durationMilliseconds);
void Sleep(TimeSpan duration);
IThread CreateThread(ThreadEntryPoint entryPoint, ThreadCreationOptions options);
ISemaphore CreateSemaphore(int initialCount, int maximumCount);
ICountdownEvent CreateCountdownEvent(int initialCount);
ICancellationTokenSource CreateCancellationTokenSource();
ICancellationTokenSource CreateCancellationTokenSource(int cancellationDelayMilliseconds);
ICancellationTokenSource CreateCancellationTokenSource(TimeSpan cancellationDelay);
}
}
|
Fix not using correct path to runtime library | using dnlib.DotNet;
namespace Confuser.Core.Services {
internal class RuntimeService : IRuntimeService {
private ModuleDef rtModule;
/// <inheritdoc />
public TypeDef GetRuntimeType(string fullName) {
if (rtModule == null) {
rtModule = ModuleDefMD.Load("Confuser.Runtime.dll");
rtModule.EnableTypeDefFindCache = true;
}
return rtModule.Find(fullName, true);
}
}
/// <summary>
/// Provides methods to obtain runtime library injection type.
/// </summary>
public interface IRuntimeService {
/// <summary>
/// Gets the specified runtime type for injection.
/// </summary>
/// <param name="fullName">The full name of the runtime type.</param>
/// <returns>The requested runtime type.</returns>
TypeDef GetRuntimeType(string fullName);
}
} | using System;
using System.IO;
using System.Reflection;
using dnlib.DotNet;
namespace Confuser.Core.Services {
internal class RuntimeService : IRuntimeService {
private ModuleDef rtModule;
/// <inheritdoc />
public TypeDef GetRuntimeType(string fullName) {
if (rtModule == null) {
Module module = typeof (RuntimeService).Assembly.ManifestModule;
string rtPath = "Confuser.Runtime.dll";
if (module.FullyQualifiedName[0] != '<')
rtPath = Path.Combine(Path.GetDirectoryName(module.FullyQualifiedName), rtPath);
rtModule = ModuleDefMD.Load(rtPath);
rtModule.EnableTypeDefFindCache = true;
}
return rtModule.Find(fullName, true);
}
}
/// <summary>
/// Provides methods to obtain runtime library injection type.
/// </summary>
public interface IRuntimeService {
/// <summary>
/// Gets the specified runtime type for injection.
/// </summary>
/// <param name="fullName">The full name of the runtime type.</param>
/// <returns>The requested runtime type.</returns>
TypeDef GetRuntimeType(string fullName);
}
} |
Change _creationOptions modifier to 'private' |
using System;
namespace Advasoft.CmdArgsTool
{
public abstract class OptionsFactoryBase
{
protected IOptionsPolicy _creationPolicy;
private ILogger _logger;
protected OptionsFactoryBase(IOptionsPolicy creationPolicy, ILogger logger)
{
_creationPolicy = creationPolicy;
_logger = logger;
}
protected abstract OptionsBase CreateOptionsByPolicy(string[] cmdArgsArray,
IOptionsPolicy creationPolicy);
public OptionsBase CreateOptions(string[] cmdArgsArray)
{
try
{
return CreateOptionsByPolicy(cmdArgsArray, _creationPolicy);
}
catch (Exception exception)
{
_logger.LogError(exception);
}
throw new ApplicationException("Invalid parse cmd arguments");
}
}
}
|
using System;
namespace Advasoft.CmdArgsTool
{
public abstract class OptionsFactoryBase
{
private IOptionsPolicy _creationPolicy;
private ILogger _logger;
protected OptionsFactoryBase(IOptionsPolicy creationPolicy, ILogger logger)
{
_creationPolicy = creationPolicy;
_logger = logger;
}
protected abstract OptionsBase CreateOptionsByPolicy(string[] cmdArgsArray,
IOptionsPolicy creationPolicy);
public OptionsBase CreateOptions(string[] cmdArgsArray)
{
try
{
return CreateOptionsByPolicy(cmdArgsArray, _creationPolicy);
}
catch (Exception exception)
{
_logger.LogError(exception);
}
throw new ApplicationException("Invalid parse cmd arguments");
}
}
}
|
Set assembly version to 1.2.0.0 | using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über folgende
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("SeafClient")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("René Bergelt")]
[assembly: AssemblyProduct("SeafClient")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("de")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// durch Einsatz von '*', wie in nachfolgendem Beispiel:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über folgende
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("SeafClient")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("René Bergelt")]
[assembly: AssemblyProduct("SeafClient")]
[assembly: AssemblyCopyright("Copyright © 2016-2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("de")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// durch Einsatz von '*', wie in nachfolgendem Beispiel:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
|
Fix broken create pool test. | using Hyperledger.Indy.PoolApi;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using System.Threading.Tasks;
namespace Hyperledger.Indy.Test.PoolTests
{
[TestClass]
public class CreatePoolTest : IndyIntegrationTestBase
{
[TestMethod]
public async Task TestCreatePoolWorksForNullConfig()
{
var txnFile = "testCreatePoolWorks.txn";
try
{
File.Create(txnFile).Dispose();
await Pool.CreatePoolLedgerConfigAsync("testCreatePoolWorks", null);
}
finally
{
File.Delete(txnFile);
}
}
[TestMethod]
public async Task TestCreatePoolWorksForConfigJSON()
{
var genesisTxnFile = PoolUtils.CreateGenesisTxnFile("genesis.txn");
var path = Path.GetFullPath(genesisTxnFile).Replace('\\', '/');
var configJson = string.Format("{{\"genesis_txn\":\"{0}\"}}", path);
await Pool.CreatePoolLedgerConfigAsync("testCreatePoolWorks", configJson);
}
[TestMethod]
public async Task TestCreatePoolWorksForTwice()
{
var genesisTxnFile = PoolUtils.CreateGenesisTxnFile("genesis.txn");
var path = Path.GetFullPath(genesisTxnFile).Replace('\\', '/');
var configJson = string.Format("{{\"genesis_txn\":\"{0}\"}}", path);
await Pool.CreatePoolLedgerConfigAsync("pool1", configJson);
var ex = await Assert.ThrowsExceptionAsync<PoolLedgerConfigExistsException>(() =>
Pool.CreatePoolLedgerConfigAsync("pool1", configJson)
);;
}
}
}
| using Hyperledger.Indy.PoolApi;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using System.Threading.Tasks;
namespace Hyperledger.Indy.Test.PoolTests
{
[TestClass]
public class CreatePoolTest : IndyIntegrationTestBase
{
[TestMethod]
public async Task TestCreatePoolWorksForNullConfig()
{
var file = File.Create("testCreatePoolWorks.txn");
PoolUtils.WriteTransactions(file, 1);
await Pool.CreatePoolLedgerConfigAsync("testCreatePoolWorks", null);
}
[TestMethod]
public async Task TestCreatePoolWorksForConfigJSON()
{
var genesisTxnFile = PoolUtils.CreateGenesisTxnFile("genesis.txn");
var path = Path.GetFullPath(genesisTxnFile.Name).Replace('\\', '/');
var configJson = string.Format("{{\"genesis_txn\":\"{0}\"}}", path);
await Pool.CreatePoolLedgerConfigAsync("testCreatePoolWorks", configJson);
}
[TestMethod]
public async Task TestCreatePoolWorksForTwice()
{
var genesisTxnFile = PoolUtils.CreateGenesisTxnFile("genesis.txn");
var path = Path.GetFullPath(genesisTxnFile.Name).Replace('\\', '/');
var configJson = string.Format("{{\"genesis_txn\":\"{0}\"}}", path);
await Pool.CreatePoolLedgerConfigAsync("pool1", configJson);
var ex = await Assert.ThrowsExceptionAsync<PoolLedgerConfigExistsException>(() =>
Pool.CreatePoolLedgerConfigAsync("pool1", configJson)
);;
}
}
}
|
Use local static to determine score per spinner tick | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Rulesets.Judgements;
namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces
{
/// <summary>
/// Shows incremental bonus score achieved for a spinner.
/// </summary>
public class SpinnerBonusDisplay : CompositeDrawable
{
private readonly OsuSpriteText bonusCounter;
public SpinnerBonusDisplay()
{
AutoSizeAxes = Axes.Both;
InternalChild = bonusCounter = new OsuSpriteText
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Font = OsuFont.Numeric.With(size: 24),
Alpha = 0,
};
}
private int displayedCount;
public void SetBonusCount(int count)
{
if (displayedCount == count)
return;
displayedCount = count;
bonusCounter.Text = $"{Judgement.LARGE_BONUS_SCORE * count}";
bonusCounter.FadeOutFromOne(1500);
bonusCounter.ScaleTo(1.5f).Then().ScaleTo(1f, 1000, Easing.OutQuint);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces
{
/// <summary>
/// Shows incremental bonus score achieved for a spinner.
/// </summary>
public class SpinnerBonusDisplay : CompositeDrawable
{
private static readonly int score_per_tick = new SpinnerBonusTick().CreateJudgement().MaxNumericResult;
private readonly OsuSpriteText bonusCounter;
public SpinnerBonusDisplay()
{
AutoSizeAxes = Axes.Both;
InternalChild = bonusCounter = new OsuSpriteText
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Font = OsuFont.Numeric.With(size: 24),
Alpha = 0,
};
}
private int displayedCount;
public void SetBonusCount(int count)
{
if (displayedCount == count)
return;
displayedCount = count;
bonusCounter.Text = $"{score_per_tick * count}";
bonusCounter.FadeOutFromOne(1500);
bonusCounter.ScaleTo(1.5f).Then().ScaleTo(1f, 1000, Easing.OutQuint);
}
}
}
|
Fix FEZ not exiting when FEZMod PreInitialize crashes | using System;
using FezGame.Mod;
namespace FezGame {
public class Program {
public static void orig_Main(string[] args) {
}
public static void Main(string[] args) {
try {
FEZMod.PreInitialize(args);
} catch (Exception e) {
ModLogger.Log("FEZMod", "Handling FEZMod PreInitialize crash...");
for (Exception e_ = e; e_ != null; e_ = e_.InnerException) {
ModLogger.Log("FEZMod", e_.ToString());
}
FEZMod.HandleCrash(e);
}
ModLogger.Log("FEZMod", "Passing to FEZ...");
orig_Main(args);
}
private static void orig_MainInternal() {
}
private static void MainInternal() {
try {
orig_MainInternal();
} catch (Exception e) {
ModLogger.Log("FEZMod", "Handling FEZ crash...");
for (Exception e_ = e; e_ != null; e_ = e_.InnerException) {
ModLogger.Log("FEZMod", e_.ToString());
}
FEZMod.HandleCrash(e);
}
}
}
}
| using System;
using FezGame.Mod;
namespace FezGame {
public class Program {
public static void orig_Main(string[] args) {
}
public static void Main(string[] args) {
try {
FEZMod.PreInitialize(args);
} catch (Exception e) {
ModLogger.Log("FEZMod", "Handling FEZMod PreInitialize crash...");
for (Exception e_ = e; e_ != null; e_ = e_.InnerException) {
ModLogger.Log("FEZMod", e_.ToString());
}
FEZMod.HandleCrash(e);
return;
}
ModLogger.Log("FEZMod", "Passing to FEZ...");
orig_Main(args);
}
private static void orig_MainInternal() {
}
private static void MainInternal() {
try {
orig_MainInternal();
} catch (Exception e) {
ModLogger.Log("FEZMod", "Handling FEZ crash...");
for (Exception e_ = e; e_ != null; e_ = e_.InnerException) {
ModLogger.Log("FEZMod", e_.ToString());
}
FEZMod.HandleCrash(e);
}
}
}
}
|
Change the method to expression body definition | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SCPI
{
public class RAW : ICommand
{
public string Description => "Send a raw SCPI command to instrument";
public string Command(params string[] parameters)
{
if (parameters.Length != 0)
{
if (parameters.Length > 1)
{
return $"{parameters[0]} {string.Join(", ", parameters, 1, parameters.Length - 1)}";
}
return parameters[0];
}
return string.Empty;
}
public string HelpMessage()
{
var message = nameof(RAW) + " SCPI_COMMAND <arg1> <arg2> ... <argn>\n";
message += " <arg1>, extra argument to command\n";
message += " <arg2>, extra argument to command\n\n";
message += "Example: " + nameof(RAW) + " :DISPlay:DATA? ON 0 TIFF\n";
message += "Example: " + nameof(RAW) + " *IDN?";
return message;
}
public bool Parse(byte[] data)
{
return true;
}
}
}
| namespace SCPI
{
public class RAW : ICommand
{
public string Description => "Send a raw SCPI command to instrument";
public string Command(params string[] parameters)
{
if (parameters.Length != 0)
{
if (parameters.Length > 1)
{
return $"{parameters[0]} {string.Join(", ", parameters, 1, parameters.Length - 1)}";
}
return parameters[0];
}
return string.Empty;
}
public string HelpMessage()
{
var message = nameof(RAW) + " SCPI_COMMAND <arg1> <arg2> ... <argn>\n";
message += " <arg1>, extra argument to command\n";
message += " <arg2>, extra argument to command\n\n";
message += "Example: " + nameof(RAW) + " :DISPlay:DATA? ON 0 TIFF\n";
message += "Example: " + nameof(RAW) + " *IDN?";
return message;
}
public bool Parse(byte[] data) => true;
}
}
|
Replace UrlHelperBase with IUrlHelper so it can be used in Views | #if NETCOREAPP
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Routing;
namespace SFA.DAS.ProviderUrlHelper.Core
{
public static class ProviderUrlHelperExtensions
{
public static string ProviderCommitmentsLink(this UrlHelperBase helper, string path)
{
var linkGenerator = GetLinkGenerator(helper.ActionContext.HttpContext);
return linkGenerator.ProviderCommitmentsLink(path);
}
public static string ProviderApprenticeshipServiceLink(this UrlHelperBase helper, string path)
{
var linkGenerator = GetLinkGenerator(helper.ActionContext.HttpContext);
return linkGenerator.ProviderApprenticeshipServiceLink(path);
}
public static string ReservationsLink(this UrlHelperBase helper, string path)
{
var linkGenerator = GetLinkGenerator(helper.ActionContext.HttpContext);
return linkGenerator.ReservationsLink(path);
}
public static string RecruitLink(this UrlHelperBase helper, string path)
{
var linkGenerator = GetLinkGenerator(helper.ActionContext.HttpContext);
return linkGenerator.RecruitLink(path);
}
private static ILinkGenerator GetLinkGenerator(HttpContext httpContext)
{
return ServiceLocator.Get<ILinkGenerator>(httpContext);
}
}
}
#endif | #if NETCOREAPP
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
namespace SFA.DAS.ProviderUrlHelper.Core
{
public static class ProviderUrlHelperExtensions
{
public static string ProviderCommitmentsLink(this IUrlHelper helper, string path)
{
var linkGenerator = GetLinkGenerator(helper.ActionContext.HttpContext);
return linkGenerator.ProviderCommitmentsLink(path);
}
public static string ProviderApprenticeshipServiceLink(this IUrlHelper helper, string path)
{
var linkGenerator = GetLinkGenerator(helper.ActionContext.HttpContext);
return linkGenerator.ProviderApprenticeshipServiceLink(path);
}
public static string ReservationsLink(this IUrlHelper helper, string path)
{
var linkGenerator = GetLinkGenerator(helper.ActionContext.HttpContext);
return linkGenerator.ReservationsLink(path);
}
public static string RecruitLink(this IUrlHelper helper, string path)
{
var linkGenerator = GetLinkGenerator(helper.ActionContext.HttpContext);
return linkGenerator.RecruitLink(path);
}
private static ILinkGenerator GetLinkGenerator(HttpContext httpContext)
{
return ServiceLocator.Get<ILinkGenerator>(httpContext);
}
}
}
#endif |
Add datasource support for streaming model | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityCNTK;
using CNTK;
using System;
namespace UnityCNTK{
public class StreamingModel<T, V> : Model
where T:IConvertible
where V:IConvertible
{
public new T input;
public new V output;
// Evaluation carry out in every 'evaluationPeriod' second
public double evaluationPeriod = 10;
public override void Evaluate()
{
if (isEvaluating)
{
throw new TimeoutException("Evalauation not finished before the another call, ");
}
isEvaluating = true;
}
public override void LoadModel()
{
throw new NotImplementedException();
}
protected override void OnEvaluated(Dictionary<Variable, Value> outputDataMap)
{
isEvaluating = false;
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityCNTK;
using CNTK;
using System;
namespace UnityCNTK{
/// <summary>
/// Streaming model streams a datasource to a model every set period
/// </summary>
public class StreamingModel: Model
{
public new DataSource input;
[Tooltip("Evaluation carry out in every specificed second")]
public double evaluationPeriod = 10;
public override void Evaluate()
{
if (isEvaluating)
{
throw new TimeoutException("Evalauation not finished before the another call, ");
}
isEvaluating = true;
}
public override void LoadModel()
{
throw new NotImplementedException();
}
protected override void OnEvaluated(Dictionary<Variable, Value> outputDataMap)
{
isEvaluating = false;
}
}
}
|
Fix bug when a user tries to join an already created multiplayer match | public class ClientNetworkWaitingGui : AbstractNetworkWaitingGui
{
private ClientNetworkEntityWaiting network;
private GuiButtonRendererControl[] buttons = new GuiButtonRendererControl[0];
public ClientNetworkWaitingGui(NetworkEntityWaiting networkEntity)
{
network = (ClientNetworkEntityWaiting) networkEntity;
}
protected override void Update()
{
if (network.Updated()) {
Init();
addServersHeader();
addServers();
}
network.RefreshServers();
}
private void addServersHeader()
{
Add("Servers:", size: HEADING_SIZE, bold: true);
}
private void addServers()
{
string[] servers = network.GetServers();
buttons = new GuiButtonRendererControl[servers.Length];
for (int i = 0; i < servers.Length; i++) {
buttons[i] = new GuiButtonRendererControl(() => network.Connect(i));
addServer(servers[i], buttons[i]);
}
}
private void addServer(string server, GuiRendererControl control)
{
Add(server, control: control);
}
protected override void HandleInput()
{
for (int i = 0; i < buttons.Length; i++) {
buttons[i].Check();
}
}
}
| public class ClientNetworkWaitingGui : AbstractNetworkWaitingGui
{
private ClientNetworkEntityWaiting network;
private GuiButtonRendererControl[] buttons = new GuiButtonRendererControl[0];
public ClientNetworkWaitingGui(NetworkEntityWaiting networkEntity)
{
network = (ClientNetworkEntityWaiting) networkEntity;
}
protected override void Update()
{
if (network.Updated()) {
Init();
addServersHeader();
addServers();
}
network.RefreshServers();
}
private void addServersHeader()
{
Add("Servers:", size: HEADING_SIZE, bold: true);
}
private void addServers()
{
string[] servers = network.GetServers();
buttons = new GuiButtonRendererControl[servers.Length];
for (int i = 0; i < servers.Length; i++) {
int index = i; // store the current value of "i", so that it is not affected by subsequent increments
buttons[i] = new GuiButtonRendererControl(() => network.Connect(index));
addServer(servers[i], buttons[i]);
}
}
private void addServer(string server, GuiRendererControl control)
{
Add(server, control: control);
}
protected override void HandleInput()
{
for (int i = 0; i < buttons.Length; i++) {
buttons[i].Check();
}
}
}
|
Change AppointmentOptimizatinCode from short to int | namespace SnapMD.VirtualCare.ApiModels.Scheduling
{
/// <summary>
/// Appointment optimization code.
/// </summary>
public enum AppointmentOptimizationCode : short
{
/// <summary>
/// Single booking.
/// </summary>
SingleBooking,
/// <summary>
/// Double booking.
/// </summary>
DoubleBooking
}
}
| namespace SnapMD.VirtualCare.ApiModels.Scheduling
{
/// <summary>
/// Appointment optimization code.
/// </summary>
public enum AppointmentOptimizationCode : int
{
/// <summary>
/// Single booking.
/// </summary>
SingleBooking,
/// <summary>
/// Double booking.
/// </summary>
DoubleBooking
}
}
|
Fix for first unreliable sequenced message automatically being dropped | using System;
namespace Lidgren.Network
{
internal sealed class NetUnreliableSequencedReceiver : NetReceiverChannelBase
{
private int m_lastReceivedSequenceNumber;
public NetUnreliableSequencedReceiver(NetConnection connection)
: base(connection)
{
}
internal override void ReceiveMessage(NetIncomingMessage msg)
{
int nr = msg.m_sequenceNumber;
// ack no matter what
m_connection.QueueAck(msg.m_receivedMessageType, nr);
int relate = NetUtility.RelativeSequenceNumber(nr, m_lastReceivedSequenceNumber + 1);
if (relate < 0)
return; // drop if late
m_lastReceivedSequenceNumber = nr;
m_peer.ReleaseMessage(msg);
}
}
}
| using System;
namespace Lidgren.Network
{
internal sealed class NetUnreliableSequencedReceiver : NetReceiverChannelBase
{
private int m_lastReceivedSequenceNumber = -1;
public NetUnreliableSequencedReceiver(NetConnection connection)
: base(connection)
{
}
internal override void ReceiveMessage(NetIncomingMessage msg)
{
int nr = msg.m_sequenceNumber;
// ack no matter what
m_connection.QueueAck(msg.m_receivedMessageType, nr);
int relate = NetUtility.RelativeSequenceNumber(nr, m_lastReceivedSequenceNumber + 1);
if (relate < 0)
return; // drop if late
m_lastReceivedSequenceNumber = nr;
m_peer.ReleaseMessage(msg);
}
}
}
|
Use exception assertion instead of deprecated attribute | using NUnit.Framework;
namespace HandlebarsDotNet.Test
{
[TestFixture]
public class ExceptionTests
{
[Test]
[ExpectedException("HandlebarsDotNet.HandlebarsCompilerException", ExpectedMessage = "Reached end of template before block expression 'if' was closed")]
public void TestNonClosingBlockExpressionException()
{
Handlebars.Compile( "{{#if 0}}test" )( new { } );
}
}
}
| using NUnit.Framework;
namespace HandlebarsDotNet.Test
{
[TestFixture]
public class ExceptionTests
{
[Test]
public void TestNonClosingBlockExpressionException()
{
Assert.Throws<HandlebarsCompilerException>(() =>
{
Handlebars.Compile("{{#if 0}}test")(new { });
},
"Reached end of template before block expression 'if' was closed");
}
}
}
|
Return correct error code for missing reserve numbers | using Kentor.PU_Adapter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace PU_Stub.Controllers
{
public class SnodController : ApiController
{
private static readonly IDictionary<string, string> TestPersons;
static SnodController()
{
TestPersons = Kentor.PU_Adapter.TestData.TestPersonsPuData.PuDataList
.ToDictionary(p => p.Substring(8, 12)); // index by person number
}
[HttpGet]
public HttpResponseMessage PKNODPLUS(string arg)
{
System.Threading.Thread.Sleep(30); // Introduce production like latency
string result;
if (!TestPersons.TryGetValue(arg, out result))
{
// Returkod: 0001 = Sökt person saknas i registren
result = "13270001 _";
}
result = "0\n0\n1327\n" + result; // add magic initial lines, like production PU does
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(result, System.Text.Encoding.GetEncoding("ISO-8859-1"), "text/plain");
return resp;
}
}
}
| using Kentor.PU_Adapter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace PU_Stub.Controllers
{
public class SnodController : ApiController
{
private static readonly IDictionary<string, string> TestPersons;
static SnodController()
{
TestPersons = Kentor.PU_Adapter.TestData.TestPersonsPuData.PuDataList
.ToDictionary(p => p.Substring(8, 12)); // index by person number
}
[HttpGet]
public HttpResponseMessage PKNODPLUS(string arg)
{
System.Threading.Thread.Sleep(30); // Introduce production like latency
string result;
if (!TestPersons.TryGetValue(arg, out result))
{
if (arg.StartsWith("99"))
{
// Returkod: 0102 = Sökt reservnummer saknas i registren
result = "13270102 _";
}
else
{
// Returkod: 0001 = Sökt person saknas i registren
result = "13270001 _";
}
}
result = "0\n0\n1327\n" + result; // add magic initial lines, like production PU does
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(result, System.Text.Encoding.GetEncoding("ISO-8859-1"), "text/plain");
return resp;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.