Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Change static content to dynamic | @{
ViewData["Title"] = "List of Articles I've Written";
}
<h1 id="page_title">Articles I've written</h1>
<div class="centered_wrapper">
<input type="text" class="search" placeholder="Filter by title/tag">
<article>
<p class="date">Monday Aug 28</p>
<h2><a href="#">Change Kestrel default url on Asp Net Core</a></h2>
<div class="tags">
<a href="#">asp net core</a>
<a href="#">asp net core</a>
<a href="#">asp net core</a>
</div>
<hr>
</article>
<article>
<p class="date">Monday Aug 28</p>
<h2><a href="#">Change Kestrel default url on Asp Net Core</a></h2>
<div class="tags">
<a href="#">asp net core</a>
<a href="#">asp net core</a>
<a href="#">asp net core</a>
</div>
<hr>
</article>
<article>
<p class="date">Monday Aug 28</p>
<h2><a href="#">Change Kestrel default url on Asp Net Core</a></h2>
<div class="tags">
<a href="#">asp net core</a>
<a href="#">asp net core</a>
<a href="#">asp net core</a>
</div>
<hr>
</article>
<article>
<p class="date">Monday Aug 28</p>
<h2><a href="#">Change Kestrel default url on Asp Net Core</a></h2>
<div class="tags">
<a href="#">asp net core</a>
<a href="#">asp net core</a>
<a href="#">asp net core</a>
</div>
<hr>
</article>
</div>
<div class="pagination">
<span class="previous_page disabled">Previous</span>
<span class="current">1</span>
<a href="#" rel="next">2</a>
<a href="#" class="next_page">Next</a>
</div> | @model IEnumerable<ArticleModel>
@{
ViewData["Title"] = "List of Articles I've Written";
}
<h1 id="page_title">Articles I've written</h1>
<div class="centered_wrapper">
<input type="text" class="search" placeholder="Filter by title/tag">
@foreach (var article in Model)
{
<article>
<p class="date">@article.FormattedPublishedAt()</p>
<h2><a href="@article.Link" target="_blank">@article.Title</a></h2>
<div class="tags">
@foreach (var tag in article.Tags)
{
<a href="#">@tag</a>
}
</div>
<hr>
</article>
}
</div>
<!--<div class="pagination">
<span class="previous_page disabled">Previous</span>
<span class="current">1</span>
<a href="#" rel="next">2</a>
<a href="#" class="next_page">Next</a>
</div>--> |
Add simple interpolated motion driver | using System;
using System.Numerics;
namespace DynamixelServo.Quadruped
{
public class BasicQuadrupedGaitEngine : QuadrupedGaitEngine
{
private const int Speed = 10;
private const int MaxForward = 5;
private const int MinForward = -5;
private const int LegDistance = 15;
private const int LegHeight = -13;
private bool _movingForward;
private Vector3 _lastWrittenPosition = Vector3.Zero;
public BasicQuadrupedGaitEngine(QuadrupedIkDriver driver) : base(driver)
{
Driver.Setup();
Driver.StandUpfromGround();
StartEngine();
}
protected override void EngineSpin()
{
var translate = Vector3.Zero;
if (_movingForward)
{
translate.Y += Speed * 0.001f * TimeSincelastTick;
}
else
{
translate.Y -= Speed * 0.001f * TimeSincelastTick;
}
_lastWrittenPosition += translate;
if (_movingForward && _lastWrittenPosition.Y > MaxForward)
{
_movingForward = false;
}
else if (!_movingForward && _lastWrittenPosition.Y < MinForward)
{
_movingForward = true;
}
Driver.MoveAbsoluteCenterMass(_lastWrittenPosition, LegDistance, LegHeight);
}
}
}
| using System;
using System.Numerics;
namespace DynamixelServo.Quadruped
{
public class BasicQuadrupedGaitEngine : QuadrupedGaitEngine
{
private const int Speed = 12;
private int _currentIndex;
private readonly Vector3[] _positions =
{
new Vector3(-5, 5, 3),
new Vector3(5, 5, -3),
new Vector3(5, -5, 3),
new Vector3(-5, -5, -3)
};
private const float LegHeight = -11f;
private const int LegDistance = 15;
private Vector3 _lastWrittenPosition = Vector3.Zero;
public BasicQuadrupedGaitEngine(QuadrupedIkDriver driver) : base(driver)
{
Driver.Setup();
Driver.StandUpfromGround();
StartEngine();
}
protected override void EngineSpin()
{
if (_lastWrittenPosition.Similar(_positions[_currentIndex], 0.25f))
{
_currentIndex++;
if (_currentIndex >= _positions.Length)
{
_currentIndex = 0;
}
}
_lastWrittenPosition =
_lastWrittenPosition.MoveTowards(_positions[_currentIndex], Speed * 0.001f * TimeSincelastTick);
Driver.MoveAbsoluteCenterMass(_lastWrittenPosition, LegDistance, LegHeight);
}
}
}
|
Handle correctly the special HTML characters and tags | namespace AnimalHope.Web
{
using System.Web;
using System.Web.Mvc;
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
| namespace AnimalHope.Web
{
using System.Web;
using System.Web.Mvc;
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new ValidateInputAttribute(false));
}
}
}
|
Make Hot the default reddit post category | using System.Diagnostics;
using CommonBotLibrary.Interfaces.Models;
using RedditSharp.Things;
namespace CommonBotLibrary.Services.Models
{
[DebuggerDisplay("{Url, nq}")]
public class RedditResult : IWebpage
{
public RedditResult(Post post)
{
Title = post.Title;
Url = post.Url.OriginalString;
Post = post;
}
/// <summary>
/// The wrapped model returned by RedditSharp with more submission props.
/// </summary>
public Post Post { get; }
public string Url { get; set; }
public string Title { get; set; }
public static implicit operator Post(RedditResult redditResult)
=> redditResult.Post;
public enum PostCategory
{
New,
Controversial,
Rising,
Hot,
Top
}
}
}
| using System.Diagnostics;
using CommonBotLibrary.Interfaces.Models;
using RedditSharp.Things;
namespace CommonBotLibrary.Services.Models
{
[DebuggerDisplay("{Url, nq}")]
public class RedditResult : IWebpage
{
public RedditResult(Post post)
{
Title = post.Title;
Url = post.Url.OriginalString;
Post = post;
}
/// <summary>
/// The wrapped model returned by RedditSharp with more submission props.
/// </summary>
public Post Post { get; }
public string Url { get; set; }
public string Title { get; set; }
public static implicit operator Post(RedditResult redditResult)
=> redditResult.Post;
public enum PostCategory
{
Hot,
New,
Controversial,
Rising,
Top
}
}
}
|
Revert change to pump in the wrong spot. | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
namespace Roslyn.Test.Utilities
{
public static class WaitHelper
{
public static void WaitForDispatchedOperationsToComplete(DispatcherPriority priority)
{
new FrameworkElement().Dispatcher.DoEvents();
}
public static void PumpingWait(this Task task)
{
PumpingWaitAll(new[] { task });
}
public static T PumpingWaitResult<T>(this Task<T> task)
{
PumpingWait(task);
return task.Result;
}
public static void PumpingWaitAll(this IEnumerable<Task> tasks)
{
var smallTimeout = TimeSpan.FromMilliseconds(10);
var taskArray = tasks.ToArray();
var done = false;
while (!done)
{
done = Task.WaitAll(taskArray, smallTimeout);
if (!done)
{
WaitForDispatchedOperationsToComplete(DispatcherPriority.ApplicationIdle);
}
}
foreach (var task in tasks)
{
if (task.Exception != null)
{
throw task.Exception;
}
}
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
namespace Roslyn.Test.Utilities
{
public static class WaitHelper
{
public static void WaitForDispatchedOperationsToComplete(DispatcherPriority priority)
{
Action action = delegate { };
new FrameworkElement().Dispatcher.Invoke(action, priority);
}
public static void PumpingWait(this Task task)
{
PumpingWaitAll(new[] { task });
}
public static T PumpingWaitResult<T>(this Task<T> task)
{
PumpingWait(task);
return task.Result;
}
public static void PumpingWaitAll(this IEnumerable<Task> tasks)
{
var smallTimeout = TimeSpan.FromMilliseconds(10);
var taskArray = tasks.ToArray();
var done = false;
while (!done)
{
done = Task.WaitAll(taskArray, smallTimeout);
if (!done)
{
WaitForDispatchedOperationsToComplete(DispatcherPriority.ApplicationIdle);
}
}
foreach (var task in tasks)
{
if (task.Exception != null)
{
throw task.Exception;
}
}
}
}
}
|
Use red color when outputting error message | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Windsor;
namespace AppHarbor
{
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer()
.Install(new AppHarborInstaller());
var commandDispatcher = container.Resolve<CommandDispatcher>();
try
{
commandDispatcher.Dispatch(args);
}
catch (DispatchException exception)
{
Console.WriteLine();
Console.WriteLine("Error: {0}", exception.Message);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Windsor;
namespace AppHarbor
{
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer()
.Install(new AppHarborInstaller());
var commandDispatcher = container.Resolve<CommandDispatcher>();
try
{
commandDispatcher.Dispatch(args);
}
catch (DispatchException exception)
{
Console.WriteLine();
using (new ForegroundColor(ConsoleColor.Red))
{
Console.WriteLine("Error: {0}", exception.Message);
}
}
}
}
}
|
Fix issue that the changes to the connection strings were not registered before you're changing the focus to another connection string. | using System;
using System.Linq;
using System.Windows.Forms;
using NBi.UI.Genbi.Presenter;
namespace NBi.UI.Genbi.View.TestSuiteGenerator
{
public partial class SettingsControl : UserControl
{
public SettingsControl()
{
InitializeComponent();
}
internal void DataBind(SettingsPresenter presenter)
{
if (presenter != null)
{
settingsName.DataSource = presenter.SettingsNames;
settingsName.DataBindings.Add("SelectedItem", presenter, "SettingsNameSelected", true, DataSourceUpdateMode.OnValidation);
settingsName.SelectedIndexChanged += (s, args) => settingsName.DataBindings["SelectedItem"].WriteValue();
settingsValue.DataBindings.Add("Text", presenter, "SettingsValue", true, DataSourceUpdateMode.OnPropertyChanged);
}
}
public Button AddCommand
{
get {return addReference;}
}
public Button RemoveCommand
{
get { return removeReference; }
}
}
}
| using System;
using System.Linq;
using System.Windows.Forms;
using NBi.UI.Genbi.Presenter;
namespace NBi.UI.Genbi.View.TestSuiteGenerator
{
public partial class SettingsControl : UserControl
{
public SettingsControl()
{
InitializeComponent();
}
internal void DataBind(SettingsPresenter presenter)
{
if (presenter != null)
{
settingsName.DataSource = presenter.SettingsNames;
settingsName.DataBindings.Add("SelectedItem", presenter, "SettingsNameSelected", true, DataSourceUpdateMode.OnValidation);
settingsName.SelectedIndexChanged += (s, args) => settingsName.DataBindings["SelectedItem"].WriteValue();
settingsValue.TextChanged += (s, args) => presenter.UpdateValue((string)settingsName.SelectedValue, settingsValue.Text);
settingsValue.DataBindings.Add("Text", presenter, "SettingsValue", true, DataSourceUpdateMode.OnPropertyChanged);
}
}
private void toto(object s, EventArgs args)
{
MessageBox.Show("Hello");
}
public Button AddCommand
{
get {return addReference;}
}
public Button RemoveCommand
{
get { return removeReference; }
}
}
}
|
Fix the broken NuGet build. | using System;
using Microsoft.MixedReality.Toolkit;
using Microsoft.MixedReality.Toolkit.Input;
using UnityEngine;
// Simple example script that subscribes to primary pointer changes and applies a cursor highlight to the current one.
public class PrimaryPointerHandlerExample : MonoBehaviour
{
public GameObject CursorHighlight;
private void OnEnable()
{
MixedRealityToolkit.InputSystem?.FocusProvider?.SubscribeToPrimaryPointerChanged(OnPrimaryPointerChanged, true);
}
private void OnPrimaryPointerChanged(IMixedRealityPointer oldPointer, IMixedRealityPointer newPointer)
{
if (CursorHighlight != null)
{
if (newPointer != null)
{
Transform parentTransform = newPointer.BaseCursor?.GameObjectReference?.transform;
// If there's no cursor try using the controller pointer transform instead
if (parentTransform == null)
{
var controllerPointer = newPointer as BaseControllerPointer;
parentTransform = controllerPointer?.transform;
}
if (parentTransform != null)
{
CursorHighlight.transform.SetParent(parentTransform, false);
CursorHighlight.SetActive(true);
return;
}
}
CursorHighlight.SetActive(false);
CursorHighlight.transform.SetParent(null, false);
}
}
private void OnDisable()
{
MixedRealityToolkit.InputSystem?.FocusProvider?.UnsubscribeFromPrimaryPointerChanged(OnPrimaryPointerChanged);
OnPrimaryPointerChanged(null, null);
}
}
| using Microsoft.MixedReality.Toolkit;
using Microsoft.MixedReality.Toolkit.Input;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Examples.Demos
{
// Simple example script that subscribes to primary pointer changes and applies a cursor highlight to the current one.
public class PrimaryPointerHandlerExample : MonoBehaviour
{
public GameObject CursorHighlight;
private void OnEnable()
{
MixedRealityToolkit.InputSystem?.FocusProvider?.SubscribeToPrimaryPointerChanged(OnPrimaryPointerChanged, true);
}
private void OnPrimaryPointerChanged(IMixedRealityPointer oldPointer, IMixedRealityPointer newPointer)
{
if (CursorHighlight != null)
{
if (newPointer != null)
{
Transform parentTransform = newPointer.BaseCursor?.GameObjectReference?.transform;
// If there's no cursor try using the controller pointer transform instead
if (parentTransform == null)
{
var controllerPointer = newPointer as BaseControllerPointer;
parentTransform = controllerPointer?.transform;
}
if (parentTransform != null)
{
CursorHighlight.transform.SetParent(parentTransform, false);
CursorHighlight.SetActive(true);
return;
}
}
CursorHighlight.SetActive(false);
CursorHighlight.transform.SetParent(null, false);
}
}
private void OnDisable()
{
MixedRealityToolkit.InputSystem?.FocusProvider?.UnsubscribeFromPrimaryPointerChanged(OnPrimaryPointerChanged);
OnPrimaryPointerChanged(null, null);
}
}
} |
Add Refund as paymentmethod so we can use it in SettlementPeriodRevenue. | using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Mollie.Api.Models.Payment {
[JsonConverter(typeof(StringEnumConverter))]
public enum PaymentMethod {
[EnumMember(Value = "ideal")] Ideal,
[EnumMember(Value = "creditcard")] CreditCard,
[EnumMember(Value = "mistercash")] MisterCash,
[EnumMember(Value = "sofort")] Sofort,
[EnumMember(Value = "banktransfer")] BankTransfer,
[EnumMember(Value = "directdebit")] DirectDebit,
[EnumMember(Value = "belfius")] Belfius,
[EnumMember(Value = "bitcoin")] Bitcoin,
[EnumMember(Value = "podiumcadeaukaart")] PodiumCadeaukaart,
[EnumMember(Value = "paypal")] PayPal,
[EnumMember(Value = "paysafecard")] PaySafeCard,
[EnumMember(Value = "kbc")] Kbc,
[EnumMember(Value = "giftcard")] GiftCard,
[EnumMember(Value = "inghomepay")] IngHomePay,
}
} | using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Mollie.Api.Models.Payment {
[JsonConverter(typeof(StringEnumConverter))]
public enum PaymentMethod {
[EnumMember(Value = "ideal")] Ideal,
[EnumMember(Value = "creditcard")] CreditCard,
[EnumMember(Value = "mistercash")] MisterCash,
[EnumMember(Value = "sofort")] Sofort,
[EnumMember(Value = "banktransfer")] BankTransfer,
[EnumMember(Value = "directdebit")] DirectDebit,
[EnumMember(Value = "belfius")] Belfius,
[EnumMember(Value = "bitcoin")] Bitcoin,
[EnumMember(Value = "podiumcadeaukaart")] PodiumCadeaukaart,
[EnumMember(Value = "paypal")] PayPal,
[EnumMember(Value = "paysafecard")] PaySafeCard,
[EnumMember(Value = "kbc")] Kbc,
[EnumMember(Value = "giftcard")] GiftCard,
[EnumMember(Value = "inghomepay")] IngHomePay,
[EnumMember(Value = "refund")] Refund,
}
} |
Add basics to load compiled client app | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace KenticoInspector.WebApplication
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace KenticoInspector.WebApplication
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSpaStaticFiles(configuration => {
configuration.RootPath = "ClientApp/dist";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc();
app.UseSpa(spa => {
spa.Options.SourcePath = "ClientApp";
//if (env.IsDevelopment()) {
// spa.UseProxyToSpaDevelopmentServer("http://localhost:1234");
//}
});
}
}
}
|
Fix detectors link to the slot | @{
var ownerName = Environment.GetEnvironmentVariable("WEBSITE_OWNER_NAME") ?? "";
var subscriptionId = ownerName;
var resourceGroup = Environment.GetEnvironmentVariable("WEBSITE_RESOURCE_GROUP") ?? "";
var siteName = Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME") ?? "";
var index = ownerName.IndexOf('+');
if (index >= 0)
{
subscriptionId = ownerName.Substring(0, index);
}
string detectorPath;
if (Kudu.Core.Helpers.OSDetector.IsOnWindows())
{
detectorPath = "diagnostics%2Favailability%2Fanalysis";
}
else
{
detectorPath = "detectors%2FLinuxAppDown";
}
var detectorDeepLink = "https://portal.azure.com/?websitesextension_ext=asd.featurePath%3D"
+ detectorPath
+ "#resource/subscriptions/" + subscriptionId
+ "/resourceGroups/" + resourceGroup
+ "/providers/Microsoft.Web/sites/"
+ siteName
+ "/troubleshoot";
Response.Redirect(detectorDeepLink);
}
| @{
var ownerName = Environment.GetEnvironmentVariable("WEBSITE_OWNER_NAME") ?? "";
var subscriptionId = ownerName;
var resourceGroup = Environment.GetEnvironmentVariable("WEBSITE_RESOURCE_GROUP") ?? "";
var siteName = Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME") ?? "";
var hostName = Environment.GetEnvironmentVariable("HTTP_HOST") ?? "";
var index = ownerName.IndexOf('+');
if (index >= 0)
{
subscriptionId = ownerName.Substring(0, index);
}
string detectorPath;
if (Kudu.Core.Helpers.OSDetector.IsOnWindows())
{
detectorPath = "diagnostics%2Favailability%2Fanalysis";
}
else
{
detectorPath = "detectors%2FLinuxAppDown";
}
var hostNameIndex = hostName.IndexOf('.');
if (hostNameIndex >= 0)
{
hostName = hostName.Substring(0, hostNameIndex);
}
var runtimeSuffxIndex = siteName.IndexOf("__");
if (runtimeSuffxIndex >= 0)
{
siteName = siteName.Substring(0, runtimeSuffxIndex);
}
// Get the slot name
if (!hostName.Equals(siteName, StringComparison.CurrentCultureIgnoreCase))
{
var slotNameIndex = siteName.Length;
if (hostName.Length > slotNameIndex && hostName[slotNameIndex] == '-')
{
// Fix up hostName by replacing "-SLOTNAME" with "/slots/SLOTNAME"
var slotName = hostName.Substring(slotNameIndex + 1);
hostName = hostName.Substring(0, slotNameIndex) + "/slots/" + slotName;
}
}
var detectorDeepLink = "https://portal.azure.com/?websitesextension_ext=asd.featurePath%3D"
+ detectorPath
+ "#resource/subscriptions/" + subscriptionId
+ "/resourceGroups/" + resourceGroup
+ "/providers/Microsoft.Web/sites/"
+ hostName
+ "/troubleshoot";
Response.Redirect(detectorDeepLink);
}
|
Add move towards method for vectors | using System.Numerics;
namespace DynamixelServo.Quadruped
{
public static class Vector3Extensions
{
public static Vector3 Normal(this Vector3 vector)
{
return Vector3.Normalize(vector);
}
public static bool Similar(this Vector3 a, Vector3 b, float marginOfError = float.Epsilon)
{
return Vector3.Distance(a, b) <= marginOfError;
}
}
}
| using System.Numerics;
namespace DynamixelServo.Quadruped
{
public static class Vector3Extensions
{
public static Vector3 Normal(this Vector3 vector)
{
return Vector3.Normalize(vector);
}
public static bool Similar(this Vector3 a, Vector3 b, float marginOfError = float.Epsilon)
{
return Vector3.Distance(a, b) <= marginOfError;
}
public static Vector3 MoveTowards(this Vector3 current, Vector3 target, float distance)
{
var transport = target - current;
var len = transport.Length();
if (len < distance)
{
return target;
}
return current + transport.Normal() * distance;
}
}
}
|
Update default logging behaviors to use functions that correspond to log level | using System;
using System.Diagnostics;
namespace Spiffy.Monitoring
{
public static class Behavior
{
static Action<Level, string> _loggingAction;
/// <summary>
/// Whether or not to remove newline characters from logged values.
/// </summary>
/// <returns>
/// <code>true</code> if newline characters will be removed from logged
/// values, <code>false</code> otherwise.
/// </returns>
public static bool RemoveNewlines { get; set; }
public static void UseBuiltInLogging(BuiltInLogging behavior)
{
switch (behavior)
{
case Monitoring.BuiltInLogging.Console:
_loggingAction = (level, message) => Console.WriteLine(message);
break;
case Monitoring.BuiltInLogging.Trace:
_loggingAction = (level, message) => Trace.WriteLine(message);
break;
default:
throw new NotSupportedException($"{behavior} is not supported");
}
}
public static void UseCustomLogging(Action<Level, string> loggingAction)
{
_loggingAction = loggingAction;
}
internal static Action<Level, string> GetLoggingAction()
{
return _loggingAction;
}
}
public enum BuiltInLogging
{
Trace,
Console
}
} | using System;
using System.Diagnostics;
namespace Spiffy.Monitoring
{
public static class Behavior
{
static Action<Level, string> _loggingAction;
/// <summary>
/// Whether or not to remove newline characters from logged values.
/// </summary>
/// <returns>
/// <code>true</code> if newline characters will be removed from logged
/// values, <code>false</code> otherwise.
/// </returns>
public static bool RemoveNewlines { get; set; }
public static void UseBuiltInLogging(BuiltInLogging behavior)
{
switch (behavior)
{
case Monitoring.BuiltInLogging.Console:
_loggingAction = (level, message) =>
{
if (level == Level.Error)
{
Console.Error.WriteLine(message);
}
else
{
Console.WriteLine(message);
}
};
break;
case Monitoring.BuiltInLogging.Trace:
_loggingAction = (level, message) =>
{
switch (level)
{
case Level.Info:
Trace.TraceInformation(message);
break;
case Level.Warning:
Trace.TraceWarning(message);
break;
case Level.Error:
Trace.TraceError(message);
break;
default:
Trace.WriteLine(message);
break;
}
};
break;
default:
throw new NotSupportedException($"{behavior} is not supported");
}
}
public static void UseCustomLogging(Action<Level, string> loggingAction)
{
_loggingAction = loggingAction;
}
internal static Action<Level, string> GetLoggingAction()
{
return _loggingAction;
}
}
public enum BuiltInLogging
{
Trace,
Console
}
}
|
Fix build issues with 4.12 | //Copyright (c) 2016 Artem A. Mavrin and other contributors
using UnrealBuildTool;
public class DialogueSystem : ModuleRules
{
public DialogueSystem(TargetInfo Target)
{
PrivateIncludePaths.AddRange(
new string[] {"DialogueSystem/Private"});
PublicDependencyModuleNames.AddRange(
new string[]
{
"Core",
"CoreUObject",
"Engine",
"UMG",
"SlateCore",
"Slate",
"AIModule"
}
);
}
}
| //Copyright (c) 2016 Artem A. Mavrin and other contributors
using UnrealBuildTool;
public class DialogueSystem : ModuleRules
{
public DialogueSystem(TargetInfo Target)
{
PrivateIncludePaths.AddRange(
new string[] {"DialogueSystem/Private"});
PublicDependencyModuleNames.AddRange(
new string[]
{
"Core",
"CoreUObject",
"Engine",
"UMG",
"SlateCore",
"Slate",
"AIModule",
"GameplayTasks"
}
);
}
}
|
Update expression to match dots following dots | using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms
{
public class DefaultSafeNamespaceValueFormModel : IValueForm
{
public DefaultSafeNamespaceValueFormModel()
{
}
public static readonly string FormName = "safe_namespace";
public virtual string Identifier => FormName;
public string Name => Identifier;
public IValueForm FromJObject(string name, JObject configuration)
{
throw new NotImplementedException();
}
public virtual string Process(IReadOnlyDictionary<string, IValueForm> forms, string value)
{
string workingValue = Regex.Replace(value, @"(^\s+|\s+$)", "");
workingValue = Regex.Replace(workingValue, @"(((?<=\.)|^)(?=\d)|[^\w\.])", "_");
return workingValue;
}
}
}
| using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms
{
public class DefaultSafeNamespaceValueFormModel : IValueForm
{
public DefaultSafeNamespaceValueFormModel()
{
}
public static readonly string FormName = "safe_namespace";
public virtual string Identifier => FormName;
public string Name => Identifier;
public IValueForm FromJObject(string name, JObject configuration)
{
throw new NotImplementedException();
}
public virtual string Process(IReadOnlyDictionary<string, IValueForm> forms, string value)
{
string workingValue = Regex.Replace(value, @"(^\s+|\s+$)", "");
workingValue = Regex.Replace(workingValue, @"(((?<=\.)|^)((?=\d)|\.)|[^\w\.])", "_");
return workingValue;
}
}
}
|
Make sure timerdecoratortest always succeeds | namespace TestMoya.Runner.Runners
{
using System;
using System.Reflection;
using Moq;
using Moya.Attributes;
using Moya.Models;
using Moya.Runner.Runners;
using Xunit;
public class TimerDecoratorTests
{
private readonly Mock<ITestRunner> testRunnerMock;
private TimerDecorator timerDecorator;
public TimerDecoratorTests()
{
testRunnerMock = new Mock<ITestRunner>();
}
[Fact]
public void TimerDecoratorExecuteRunsMethod()
{
timerDecorator = new TimerDecorator(testRunnerMock.Object);
bool methodRun = false;
MethodInfo method = ((Action)(() => methodRun = true)).Method;
testRunnerMock
.Setup(x => x.Execute(method))
.Callback(() => methodRun = true)
.Returns(new TestResult());
timerDecorator.Execute(method);
Assert.True(methodRun);
}
[Fact]
public void TimerDecoratorExecuteAddsDurationToResult()
{
MethodInfo method = ((Action)TestClass.MethodWithMoyaAttribute).Method;
timerDecorator = new TimerDecorator(new StressTestRunner());
var result = timerDecorator.Execute(method);
Assert.True(result.Duration > 0);
}
public class TestClass
{
[Stress]
public static void MethodWithMoyaAttribute()
{
}
}
}
} | using System.Threading;
namespace TestMoya.Runner.Runners
{
using System;
using System.Reflection;
using Moq;
using Moya.Attributes;
using Moya.Models;
using Moya.Runner.Runners;
using Xunit;
public class TimerDecoratorTests
{
private readonly Mock<ITestRunner> testRunnerMock;
private TimerDecorator timerDecorator;
public TimerDecoratorTests()
{
testRunnerMock = new Mock<ITestRunner>();
}
[Fact]
public void TimerDecoratorExecuteRunsMethod()
{
timerDecorator = new TimerDecorator(testRunnerMock.Object);
bool methodRun = false;
MethodInfo method = ((Action)(() => methodRun = true)).Method;
testRunnerMock
.Setup(x => x.Execute(method))
.Callback(() => methodRun = true)
.Returns(new TestResult());
timerDecorator.Execute(method);
Assert.True(methodRun);
}
[Fact]
public void TimerDecoratorExecuteAddsDurationToResult()
{
MethodInfo method = ((Action)TestClass.MethodWithMoyaAttribute).Method;
timerDecorator = new TimerDecorator(new StressTestRunner());
var result = timerDecorator.Execute(method);
Assert.True(result.Duration > 0);
}
public class TestClass
{
[Stress]
public static void MethodWithMoyaAttribute()
{
Thread.Sleep(1);
}
}
}
} |
Tidy up the display of the side bar. | @using CGO.Web.Models
@model IEnumerable<SideBarSection>
<div class="span3">
<div class="well sidebar-nav">
<ul class="nav nav-list">
@foreach (var sideBarSection in Model)
{
<li class="nav-header">@sideBarSection.Title</li>
foreach (var link in sideBarSection.Links)
{
@SideBarLink(link)
}
}
</ul>
</div>
</div>
@helper SideBarLink(SideBarLink link)
{
if (link.IsActive)
{
<li class="active"><a href="@link.Uri" title="@link.Title">@link.Title</a></li>
}
else
{
<li><a href="@link.Uri" title="@link.Title">@link.Title</a></li>
}
}
| @using CGO.Web.Models
@model IEnumerable<SideBarSection>
<div class="col-lg-3">
<div class="well">
<ul class="nav nav-stacked">
@foreach (var sideBarSection in Model)
{
<li class="navbar-header">@sideBarSection.Title</li>
foreach (var link in sideBarSection.Links)
{
@SideBarLink(link)
}
}
</ul>
</div>
</div>
@helper SideBarLink(SideBarLink link)
{
if (link.IsActive)
{
<li class="active"><a href="@link.Uri" title="@link.Title">@link.Title</a></li>
}
else
{
<li><a href="@link.Uri" title="@link.Title">@link.Title</a></li>
}
}
|
Allow Leeroy to run until canceled in test mode. | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
namespace Leeroy
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
if (args.FirstOrDefault() == "/test")
{
Overseer overseer = new Overseer(new CancellationTokenSource().Token, "BradleyGrainger", "Configuration", "master");
overseer.Run(null);
}
else
{
ServiceBase.Run(new ServiceBase[] { new Service() });
}
}
}
}
| using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Threading;
using System.Threading.Tasks;
namespace Leeroy
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
if (args.FirstOrDefault() == "/test")
{
var tokenSource = new CancellationTokenSource();
Overseer overseer = new Overseer(tokenSource.Token, "BradleyGrainger", "Configuration", "master");
var task = Task.Factory.StartNew(overseer.Run, tokenSource, TaskCreationOptions.LongRunning);
MessageBox(IntPtr.Zero, "Leeroy is running. Click OK to stop.", "Leeroy", 0);
tokenSource.Cancel();
try
{
task.Wait();
}
catch (AggregateException)
{
// TODO: verify this contains a single OperationCanceledException
}
// shut down
task.Dispose();
tokenSource.Dispose();
}
else
{
ServiceBase.Run(new ServiceBase[] { new Service() });
}
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, int options);
}
}
|
Revert change to .NET desktop default directory logic | //
// DefaultDirectoryResolver.cs
//
// Copyright (c) 2017 Couchbase, 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 System;
using System.IO;
using Couchbase.Lite.DI;
namespace Couchbase.Lite.Support
{
// NOTE: AppContext.BaseDirectory is not entirely reliable, but there is no other choice
// It seems to usually be in the right place?
[CouchbaseDependency]
internal sealed class DefaultDirectoryResolver : IDefaultDirectoryResolver
{
#region IDefaultDirectoryResolver
public string DefaultDirectory()
{
var dllDirectory = Path.GetDirectoryName(typeof(DefaultDirectoryResolver).Assembly.Location);
return Path.Combine(dllDirectory, "CouchbaseLite");
}
#endregion
}
}
| //
// DefaultDirectoryResolver.cs
//
// Copyright (c) 2017 Couchbase, 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 System;
using System.IO;
using Couchbase.Lite.DI;
namespace Couchbase.Lite.Support
{
// NOTE: AppContext.BaseDirectory is not entirely reliable, but there is no other choice
// It seems to usually be in the right place?
[CouchbaseDependency]
internal sealed class DefaultDirectoryResolver : IDefaultDirectoryResolver
{
#region IDefaultDirectoryResolver
public string DefaultDirectory()
{
var baseDirectory = AppContext.BaseDirectory ??
throw new RuntimeException("BaseDirectory was null, cannot continue...");
return Path.Combine(baseDirectory, "CouchbaseLite");
}
#endregion
}
}
|
Make sure to End StaticContent. |
using System;
using System.IO;
using Manos;
//
// This the default StaticContentModule that comes with all Manos apps
// if you do not wish to serve any static content with Manos you can
// remove its route handler from <YourApp>.cs's constructor and delete
// this file.
//
// All Content placed on the Content/ folder should be handled by this
// module.
//
namespace $APPNAME {
public class StaticContentModule : ManosModule {
public StaticContentModule ()
{
Get (".*", Content);
}
public static void Content (IManosContext ctx)
{
string path = ctx.Request.LocalPath;
if (path.StartsWith ("/"))
path = path.Substring (1);
if (File.Exists (path)) {
ctx.Response.SendFile (path);
} else
ctx.Response.StatusCode = 404;
}
}
}
|
using System;
using System.IO;
using Manos;
//
// This the default StaticContentModule that comes with all Manos apps
// if you do not wish to serve any static content with Manos you can
// remove its route handler from <YourApp>.cs's constructor and delete
// this file.
//
// All Content placed on the Content/ folder should be handled by this
// module.
//
namespace $APPNAME {
public class StaticContentModule : ManosModule {
public StaticContentModule ()
{
Get (".*", Content);
}
public static void Content (IManosContext ctx)
{
string path = ctx.Request.LocalPath;
if (path.StartsWith ("/"))
path = path.Substring (1);
if (File.Exists (path)) {
ctx.Response.SendFile (path);
} else
ctx.Response.StatusCode = 404;
ctx.Response.End ();
}
}
}
|
Set an exception message for ReturnStatusMessage | using Grpc.Core;
using System;
namespace MagicOnion
{
public class ReturnStatusException : Exception
{
public StatusCode StatusCode { get; private set; }
public string Detail { get; private set; }
public ReturnStatusException(StatusCode statusCode, string detail)
{
this.StatusCode = statusCode;
this.Detail = detail;
}
public Status ToStatus()
{
return new Status(StatusCode, Detail ?? "");
}
}
}
| using Grpc.Core;
using System;
namespace MagicOnion
{
public class ReturnStatusException : Exception
{
public StatusCode StatusCode { get; private set; }
public string Detail { get; private set; }
public ReturnStatusException(StatusCode statusCode, string detail)
: base($"The method has returned the status code '{statusCode}'." + (string.IsNullOrWhiteSpace(detail) ? "" : $" (Detail={detail})"))
{
this.StatusCode = statusCode;
this.Detail = detail;
}
public Status ToStatus()
{
return new Status(StatusCode, Detail ?? "");
}
}
}
|
Enlarge the scope of SA1600 supression to whole test project | // This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:Elements should be documented", Justification = "Test project classes do not need to be documented", Scope = "type", Target = "~T:Serilog.Exceptions.Test.Destructurers.ReflectionBasedDestructurerTest")] | // This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:Elements should be documented", Justification = "Test project classes do not need to be documented")] |
Allow noop on text fields | namespace Bumblebee.Interfaces
{
public interface ITextField : IElement, IHasText
{
TCustomResult EnterText<TCustomResult>(string text) where TCustomResult : IBlock;
TCustomResult AppendText<TCustomResult>(string text) where TCustomResult : IBlock;
}
public interface ITextField<out TResult> : ITextField, IGenericElement<TResult> where TResult : IBlock
{
TResult EnterText(string text);
TResult AppendText(string text);
}
} | namespace Bumblebee.Interfaces
{
public interface ITextField : IElement, IHasText
{
TCustomResult EnterText<TCustomResult>(string text) where TCustomResult : IBlock;
TCustomResult AppendText<TCustomResult>(string text) where TCustomResult : IBlock;
}
public interface ITextField<out TResult> : ITextField, IAllowsNoOp<TResult> where TResult : IBlock
{
TResult EnterText(string text);
TResult AppendText(string text);
}
} |
Change version number to 2.2.1 | //-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.Shared.cs" company="SonarSource SA and Microsoft Corporation">
// Copyright (c) SonarSource SA and Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// </copyright>
//-----------------------------------------------------------------------
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("2.2.0")]
[assembly: AssemblyFileVersion("2.2.0.0")]
[assembly: AssemblyInformationalVersion("Version:2.2.0.0 Branch:not-set Sha1:not-set")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SonarSource and Microsoft")]
[assembly: AssemblyCopyright("Copyright © SonarSource and Microsoft 2015/2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
| //-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.Shared.cs" company="SonarSource SA and Microsoft Corporation">
// Copyright (c) SonarSource SA and Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// </copyright>
//-----------------------------------------------------------------------
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("2.2.1")]
[assembly: AssemblyFileVersion("2.2.1.0")]
[assembly: AssemblyInformationalVersion("Version:2.2.1.0 Branch:not-set Sha1:not-set")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SonarSource and Microsoft")]
[assembly: AssemblyCopyright("Copyright © SonarSource and Microsoft 2015/2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
|
Check folders by its tag | using System.Collections;
using System.Windows.Forms;
namespace GUI.Controls
{
internal class TreeViewFileSorter : IComparer
{
public int Compare(object x, object y)
{
var tx = x as TreeNode;
var ty = y as TreeNode;
var folderx = tx.ImageKey == @"_folder";
var foldery = ty.ImageKey == @"_folder";
if (folderx && !foldery)
{
return -1;
}
if (!folderx && foldery)
{
return 1;
}
return string.CompareOrdinal(tx.Text, ty.Text);
}
}
}
| using System.Collections;
using System.Windows.Forms;
namespace GUI.Controls
{
internal class TreeViewFileSorter : IComparer
{
public int Compare(object x, object y)
{
var tx = x as TreeNode;
var ty = y as TreeNode;
var folderx = tx.Tag is TreeViewFolder;
var foldery = ty.Tag is TreeViewFolder;
if (folderx && !foldery)
{
return -1;
}
if (!folderx && foldery)
{
return 1;
}
return string.CompareOrdinal(tx.Text, ty.Text);
}
}
}
|
Add support for basic auth | using System;
using System.Net.Http;
using System.Threading.Tasks;
using Ecom.Hal.JSON;
using Newtonsoft.Json;
namespace Ecom.Hal
{
public class HalClient
{
public HalClient(Uri endpoint)
{
Client = new HttpClient {BaseAddress = endpoint};
}
public T Parse<T>(string content)
{
return JsonConvert.DeserializeObject<T>(content, new JsonConverter[] {new HalResourceConverter()});
}
public Task<T> Get<T>(string path)
{
return Task<T>
.Factory
.StartNew(() =>
{
var body = Client.GetStringAsync(new Uri(path, UriKind.Relative)).Result;
return Parse<T>(body);
});
}
protected HttpClient Client { get; set; }
}
}
| using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Ecom.Hal.JSON;
using Newtonsoft.Json;
namespace Ecom.Hal
{
public class HalClient
{
public HalClient(Uri endpoint)
{
Client = new HttpClient {BaseAddress = endpoint};
}
public T Parse<T>(string content)
{
return JsonConvert.DeserializeObject<T>(content, new JsonConverter[] {new HalResourceConverter()});
}
public Task<T> Get<T>(string path)
{
return Task<T>
.Factory
.StartNew(() =>
{
var body = Client.GetStringAsync(new Uri(path, UriKind.Relative)).Result;
return Parse<T>(body);
});
}
public void SetCredentials(string username, string password)
{
Client
.DefaultRequestHeaders
.Authorization = new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password))));
}
protected HttpClient Client { get; set; }
}
}
|
Fix bug with zoom when it didnt limit | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Caliburn.Micro;
namespace SharpGraphEditor.Models
{
public class ZoomManager : PropertyChangedBase
{
public int MaxZoom { get; } = 2;
public double CurrentZoom { get; private set; }
public int CurrentZoomInPercents => (int)(CurrentZoom * 100);
public ZoomManager()
{
CurrentZoom = 1;
}
public void ChangeCurrentZoom(double value)
{
if (value >= (1 / MaxZoom) && value <= MaxZoom)
{
CurrentZoom = Math.Round(value, 2);
}
}
public void ChangeZoomByPercents(double percents)
{
CurrentZoom += percents / 100;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Caliburn.Micro;
namespace SharpGraphEditor.Models
{
public class ZoomManager : PropertyChangedBase
{
public double MaxZoom { get; } = 2;
public double CurrentZoom { get; private set; }
public int CurrentZoomInPercents => (int)(CurrentZoom * 100);
public ZoomManager()
{
CurrentZoom = 1.0;
}
public void ChangeCurrentZoom(double value)
{
var newZoom = CurrentZoom + value;
if (newZoom >= (1.0 / MaxZoom) && newZoom <= MaxZoom)
{
CurrentZoom = Math.Round(newZoom, 2);
}
}
public void ChangeZoomByPercents(double percents)
{
ChangeCurrentZoom(percents / 100);
}
}
}
|
Fix RestClient BaseUrl change to Uri | using RestSharp;
namespace PivotalTrackerDotNet
{
public abstract class AAuthenticatedService
{
protected readonly string m_token;
protected RestClient RestClient;
protected AAuthenticatedService(string token)
{
m_token = token;
RestClient = new RestClient {BaseUrl = PivotalTrackerRestEndpoint.SSLENDPOINT};
}
protected RestRequest BuildGetRequest()
{
var request = new RestRequest(Method.GET);
request.AddHeader("X-TrackerToken", m_token);
request.RequestFormat = DataFormat.Json;
return request;
}
protected RestRequest BuildPutRequest()
{
var request = new RestRequest(Method.PUT);
request.AddHeader("X-TrackerToken", m_token);
request.RequestFormat = DataFormat.Json;
return request;
}
protected RestRequest BuildDeleteRequest()
{
var request = new RestRequest(Method.DELETE);
request.AddHeader("X-TrackerToken", m_token);
request.RequestFormat = DataFormat.Json;
return request;
}
protected RestRequest BuildPostRequest()
{
var request = new RestRequest(Method.POST);
request.AddHeader("X-TrackerToken", m_token);
request.RequestFormat = DataFormat.Json;
return request;
}
}
} | using RestSharp;
namespace PivotalTrackerDotNet
{
using System;
public abstract class AAuthenticatedService
{
protected readonly string m_token;
protected RestClient RestClient;
protected AAuthenticatedService(string token)
{
m_token = token;
RestClient = new RestClient { BaseUrl = new Uri(PivotalTrackerRestEndpoint.SSLENDPOINT) };
}
protected RestRequest BuildGetRequest()
{
var request = new RestRequest(Method.GET);
request.AddHeader("X-TrackerToken", m_token);
request.RequestFormat = DataFormat.Json;
return request;
}
protected RestRequest BuildPutRequest()
{
var request = new RestRequest(Method.PUT);
request.AddHeader("X-TrackerToken", m_token);
request.RequestFormat = DataFormat.Json;
return request;
}
protected RestRequest BuildDeleteRequest()
{
var request = new RestRequest(Method.DELETE);
request.AddHeader("X-TrackerToken", m_token);
request.RequestFormat = DataFormat.Json;
return request;
}
protected RestRequest BuildPostRequest()
{
var request = new RestRequest(Method.POST);
request.AddHeader("X-TrackerToken", m_token);
request.RequestFormat = DataFormat.Json;
return request;
}
}
} |
Exclude Shouldly from code coverage | #load nuget:?package=Cake.Recipe&version=1.0.0
Environment.SetVariableNames();
BuildParameters.SetParameters(
context: Context,
buildSystem: BuildSystem,
sourceDirectoryPath: "./src",
title: "TfsUrlParser",
repositoryOwner: "bbtsoftware",
repositoryName: "TfsUrlParser",
appVeyorAccountName: "BBTSoftwareAG",
shouldPublishMyGet: false,
shouldRunCodecov: false,
shouldDeployGraphDocumentation: false);
BuildParameters.PrintParameters(Context);
ToolSettings.SetToolSettings(
context: Context,
dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/src/TfsUrlParser.Tests/*.cs" },
testCoverageFilter: "+[*]* -[xunit.*]* -[*.Tests]* ",
testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*",
testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs");
Build.RunDotNetCore();
| #load nuget:?package=Cake.Recipe&version=1.0.0
Environment.SetVariableNames();
BuildParameters.SetParameters(
context: Context,
buildSystem: BuildSystem,
sourceDirectoryPath: "./src",
title: "TfsUrlParser",
repositoryOwner: "bbtsoftware",
repositoryName: "TfsUrlParser",
appVeyorAccountName: "BBTSoftwareAG",
shouldPublishMyGet: false,
shouldRunCodecov: false,
shouldDeployGraphDocumentation: false);
BuildParameters.PrintParameters(Context);
ToolSettings.SetToolSettings(
context: Context,
dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/src/TfsUrlParser.Tests/*.cs" },
testCoverageFilter: "+[*]* -[xunit.*]* -[*.Tests]* -[Shouldly]*",
testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*",
testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs");
Build.RunDotNetCore();
|
Define a const for read buffer size | /*
* Programmed by Umut Celenli umut@celenli.com
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MimeBank
{
/// <summary>
/// This is the main class to check the file mime type
/// Header list is loaded once
/// </summary>
public class MimeChecker
{
private static List<FileHeader> list { get; set; }
private List<FileHeader> List
{
get
{
if (list == null)
{
list = HeaderData.GetList();
}
return list;
}
}
private byte[] Buffer;
public MimeChecker()
{
Buffer = new byte[256];
}
public FileHeader GetFileHeader(string file)
{
using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
fs.Read(Buffer, 0, 256);
}
return this.List.FirstOrDefault(mime => mime.Check(Buffer) == true);
}
}
} | /*
* Programmed by Umut Celenli umut@celenli.com
*/
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MimeBank
{
/// <summary>
/// This is the main class to check the file mime type
/// Header list is loaded once
/// </summary>
public class MimeChecker
{
private const int maxBufferSize = 256;
private static List<FileHeader> list { get; set; }
private List<FileHeader> List
{
get
{
if (list == null)
{
list = HeaderData.GetList();
}
return list;
}
}
private byte[] Buffer;
public MimeChecker()
{
Buffer = new byte[maxBufferSize];
}
public FileHeader GetFileHeader(string file)
{
using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
fs.Read(Buffer, 0, maxBufferSize);
}
return this.List.FirstOrDefault(mime => mime.Check(Buffer));
}
}
} |
Use static class for static methods. | #if !(LESSTHAN_NET40 || NETSTANDARD1_0)
using System.Runtime.CompilerServices;
#endif
namespace System.Threading
{
public class MonitorEx
{
#if !(LESSTHAN_NET40 || NETSTANDARD1_0)
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
#endif
public static void Enter(object obj, ref bool lockTaken)
{
#if LESSTHAN_NET40 || NETSTANDARD1_0
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
if (lockTaken)
{
throw new ArgumentException("Lock taken", nameof(lockTaken));
}
Monitor.Enter(obj);
Volatile.Write(ref lockTaken, true);
#else
Monitor.Enter(obj, ref lockTaken);
#endif
}
}
}
| #if !(LESSTHAN_NET40 || NETSTANDARD1_0)
using System.Runtime.CompilerServices;
#endif
namespace System.Threading
{
public static class MonitorEx
{
#if !(LESSTHAN_NET40 || NETSTANDARD1_0)
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
#endif
public static void Enter(object obj, ref bool lockTaken)
{
#if LESSTHAN_NET40 || NETSTANDARD1_0
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
if (lockTaken)
{
throw new ArgumentException("Lock taken", nameof(lockTaken));
}
Monitor.Enter(obj);
Volatile.Write(ref lockTaken, true);
#else
Monitor.Enter(obj, ref lockTaken);
#endif
}
}
}
|
Revert "Swapping Silly UK English ;)" | namespace Nancy
{
using System.Collections.Generic;
using System.IO;
public interface ISerializer
{
/// <summary>
/// Whether the serializer can serialize the content type
/// </summary>
/// <param name="contentType">Content type to serialize</param>
/// <returns>True if supported, false otherwise</returns>
bool CanSerialize(string contentType);
/// <summary>
/// Gets the list of extensions that the serializer can handle.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> of extensions if any are available, otherwise an empty enumerable.</value>
IEnumerable<string> Extensions { get; }
/// <summary>
/// Serialize the given model with the given contentType
/// </summary>
/// <param name="contentType">Content type to serialize into</param>
/// <param name="model">Model to serialize</param>
/// <param name="outputStream">Output stream to serialize to</param>
/// <returns>Serialized object</returns>
void Serialize<TModel>(string contentType, TModel model, Stream outputStream);
}
} | namespace Nancy
{
using System.Collections.Generic;
using System.IO;
public interface ISerializer
{
/// <summary>
/// Whether the serializer can serialize the content type
/// </summary>
/// <param name="contentType">Content type to serialise</param>
/// <returns>True if supported, false otherwise</returns>
bool CanSerialize(string contentType);
/// <summary>
/// Gets the list of extensions that the serializer can handle.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> of extensions if any are available, otherwise an empty enumerable.</value>
IEnumerable<string> Extensions { get; }
/// <summary>
/// Serialize the given model with the given contentType
/// </summary>
/// <param name="contentType">Content type to serialize into</param>
/// <param name="model">Model to serialize</param>
/// <param name="outputStream">Output stream to serialize to</param>
/// <returns>Serialised object</returns>
void Serialize<TModel>(string contentType, TModel model, Stream outputStream);
}
} |
Add OrderingDomainException when the order doesn't exist with id orderId | using Microsoft.EntityFrameworkCore;
using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate;
using Microsoft.eShopOnContainers.Services.Ordering.Domain.Seedwork;
using System;
using System.Threading.Tasks;
namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Repositories
{
public class OrderRepository
: IOrderRepository
{
private readonly OrderingContext _context;
public IUnitOfWork UnitOfWork
{
get
{
return _context;
}
}
public OrderRepository(OrderingContext context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
public Order Add(Order order)
{
return _context.Orders.Add(order).Entity;
}
public async Task<Order> GetAsync(int orderId)
{
return await _context.Orders.FindAsync(orderId);
}
public void Update(Order order)
{
_context.Entry(order).State = EntityState.Modified;
}
}
}
| using Microsoft.EntityFrameworkCore;
using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate;
using Microsoft.eShopOnContainers.Services.Ordering.Domain.Seedwork;
using Ordering.Domain.Exceptions;
using System;
using System.Threading.Tasks;
namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Repositories
{
public class OrderRepository
: IOrderRepository
{
private readonly OrderingContext _context;
public IUnitOfWork UnitOfWork
{
get
{
return _context;
}
}
public OrderRepository(OrderingContext context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
public Order Add(Order order)
{
return _context.Orders.Add(order).Entity;
}
public async Task<Order> GetAsync(int orderId)
{
return await _context.Orders.FindAsync(orderId)
?? throw new OrderingDomainException($"Not able to get the order. Reason: no valid orderId: {orderId}");
}
public void Update(Order order)
{
_context.Entry(order).State = EntityState.Modified;
}
}
}
|
Handle oddity in watchdog naming convention | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace XiboClient.Control
{
class WatchDogManager
{
public static void Start()
{
// Check to see if the WatchDog EXE exists where we expect it to be
// Uncomment to test local watchdog install.
//string path = @"C:\Program Files (x86)\Xibo Player\watchdog\x86\XiboClientWatchdog.exe";
string path = Path.GetDirectoryName(Application.ExecutablePath) + @"\watchdog\x86\" + Application.ProductName + "ClientWatchdog.exe";
string args = "-p \"" + Application.ExecutablePath + "\" -l \"" + ApplicationSettings.Default.LibraryPath + "\"";
// Start it
if (File.Exists(path))
{
try
{
Process process = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
info.FileName = "cmd.exe";
info.Arguments = "/c start \"watchdog\" \"" + path + "\" " + args;
process.StartInfo = info;
process.Start();
}
catch (Exception e)
{
Trace.WriteLine(new LogMessage("WatchDogManager - Start", "Unable to start: " + e.Message), LogType.Error.ToString());
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace XiboClient.Control
{
class WatchDogManager
{
public static void Start()
{
// Check to see if the WatchDog EXE exists where we expect it to be
// Uncomment to test local watchdog install.
//string path = @"C:\Program Files (x86)\Xibo Player\watchdog\x86\XiboClientWatchdog.exe";
string path = Path.GetDirectoryName(Application.ExecutablePath) + @"\watchdog\x86\" + ((Application.ProductName != "Xibo") ? Application.ProductName + "Watchdog.exe" : "XiboClientWatchdog.exe");
string args = "-p \"" + Application.ExecutablePath + "\" -l \"" + ApplicationSettings.Default.LibraryPath + "\"";
// Start it
if (File.Exists(path))
{
try
{
Process process = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
info.FileName = "cmd.exe";
info.Arguments = "/c start \"watchdog\" \"" + path + "\" " + args;
process.StartInfo = info;
process.Start();
}
catch (Exception e)
{
Trace.WriteLine(new LogMessage("WatchDogManager - Start", "Unable to start: " + e.Message), LogType.Error.ToString());
}
}
}
}
}
|
Fix BL-3614 Crash while checking for keyman | using System.Linq;
using System.Windows.Forms;
using Bloom.Api;
namespace Bloom.web.controllers
{
class KeybordingConfigApi
{
public void RegisterWithServer(EnhancedImageServer server)
{
server.RegisterEndpointHandler("keyboarding/useLongPress", (ApiRequest request) =>
{
//detect if some keyboarding system is active, e.g. KeyMan. If it is, don't enable LongPress
var form = Application.OpenForms.Cast<Form>().Last();
request.ReplyWithText(SIL.Windows.Forms.Keyboarding.KeyboardController.IsFormUsingInputProcessor(form)?"false":"true");
});
}
}
}
| using System;
using System.Linq;
using System.Windows.Forms;
using Bloom.Api;
namespace Bloom.web.controllers
{
class KeybordingConfigApi
{
public void RegisterWithServer(EnhancedImageServer server)
{
server.RegisterEndpointHandler("keyboarding/useLongPress", (ApiRequest request) =>
{
try
{
//detect if some keyboarding system is active, e.g. KeyMan. If it is, don't enable LongPress
var form = Application.OpenForms.Cast<Form>().Last();
request.ReplyWithText(SIL.Windows.Forms.Keyboarding.KeyboardController.IsFormUsingInputProcessor(form)
? "false"
: "true");
}
catch(Exception error)
{
request.ReplyWithText("true"); // This is arbitrary. I don't know if it's better to assume keyman, or not.
NonFatalProblem.Report(ModalIf.None, PassiveIf.All, "Error checking for keyman","", error);
}
}, handleOnUiThread:false);
}
}
}
|
Allow config.json path to work on non-Windows OS | using System;
using System.IO;
using System.Reflection;
using Newtonsoft.Json.Linq;
namespace Noobot.Core.Configuration
{
public class ConfigReader : IConfigReader
{
private JObject _currentJObject;
private readonly string _configLocation;
private readonly object _lock = new object();
private const string DEFAULT_LOCATION = @"configuration\config.json";
private const string SLACKAPI_CONFIGVALUE = "slack:apiToken";
public ConfigReader() : this(DEFAULT_LOCATION) { }
public ConfigReader(string configurationFile)
{
_configLocation = configurationFile;
}
public bool HelpEnabled { get; set; } = true;
public bool StatsEnabled { get; set; } = true;
public bool AboutEnabled { get; set; } = true;
public string SlackApiKey => GetConfigEntry<string>(SLACKAPI_CONFIGVALUE);
public T GetConfigEntry<T>(string entryName)
{
return GetJObject().Value<T>(entryName);
}
private JObject GetJObject()
{
lock (_lock)
{
if (_currentJObject == null)
{
string assemblyLocation = AssemblyLocation();
string fileName = Path.Combine(assemblyLocation, _configLocation);
string json = File.ReadAllText(fileName);
_currentJObject = JObject.Parse(json);
}
}
return _currentJObject;
}
private string AssemblyLocation()
{
var assembly = Assembly.GetExecutingAssembly();
var codebase = new Uri(assembly.CodeBase);
var path = Path.GetDirectoryName(codebase.LocalPath);
return path;
}
}
} | using System;
using System.IO;
using System.Reflection;
using Newtonsoft.Json.Linq;
namespace Noobot.Core.Configuration
{
public class ConfigReader : IConfigReader
{
private JObject _currentJObject;
private readonly string _configLocation;
private readonly object _lock = new object();
private static readonly string DEFAULT_LOCATION = Path.Combine("configuration", "config.json");
private const string SLACKAPI_CONFIGVALUE = "slack:apiToken";
public ConfigReader() : this(DEFAULT_LOCATION) { }
public ConfigReader(string configurationFile)
{
_configLocation = configurationFile;
}
public bool HelpEnabled { get; set; } = true;
public bool StatsEnabled { get; set; } = true;
public bool AboutEnabled { get; set; } = true;
public string SlackApiKey => GetConfigEntry<string>(SLACKAPI_CONFIGVALUE);
public T GetConfigEntry<T>(string entryName)
{
return GetJObject().Value<T>(entryName);
}
private JObject GetJObject()
{
lock (_lock)
{
if (_currentJObject == null)
{
string assemblyLocation = AssemblyLocation();
string fileName = Path.Combine(assemblyLocation, _configLocation);
string json = File.ReadAllText(fileName);
_currentJObject = JObject.Parse(json);
}
}
return _currentJObject;
}
private string AssemblyLocation()
{
var assembly = Assembly.GetExecutingAssembly();
var codebase = new Uri(assembly.CodeBase);
var path = Path.GetDirectoryName(codebase.LocalPath);
return path;
}
}
} |
Add support for local folder | using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using Windows.Storage;
using System.Diagnostics;
using System.IO;
namespace WPCordovaClassLib.Cordova.Commands
{
public class FileOpener2 : BaseCommand
{
public async void open(string options)
{
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
string aliasCurrentCommandCallbackId = args[2];
try
{
// Get the file.
StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(args[0]);
// Launch the bug query file.
await Windows.System.Launcher.LaunchFileAsync(file);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK), aliasCurrentCommandCallbackId);
}
catch (FileNotFoundException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION), aliasCurrentCommandCallbackId);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), aliasCurrentCommandCallbackId);
}
}
}
} | using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using Windows.Storage;
using System.Diagnostics;
using System.IO;
namespace WPCordovaClassLib.Cordova.Commands
{
public class FileOpener2 : BaseCommand
{
public async void open(string options)
{
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
this.openPath(args[0].Replace("/", "\\"), args[2]);
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
}
private async void openPath(string path, string cbid)
{
try
{
StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(path);
await Windows.System.Launcher.LaunchFileAsync(file);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK), cbid);
}
catch (FileNotFoundException)
{
this.openInLocalFolder(path, cbid);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), cbid);
}
}
private async void openInLocalFolder(string path, string cbid)
{
try
{
StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(
Path.Combine(
Windows.Storage.ApplicationData.Current.LocalFolder.Path,
path.TrimStart('\\')
)
);
await Windows.System.Launcher.LaunchFileAsync(file);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK), cbid);
}
catch (FileNotFoundException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION), cbid);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), cbid);
}
}
}
}
|
Rewrite test to cover failure case | // 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.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Overlays;
using osu.Game.Users;
namespace osu.Game.Tests.Visual.Online
{
public class TestSceneAccountCreationOverlay : OsuTestScene
{
private readonly Container userPanelArea;
private IBindable<User> localUser;
public TestSceneAccountCreationOverlay()
{
AccountCreationOverlay accountCreation;
Children = new Drawable[]
{
accountCreation = new AccountCreationOverlay(),
userPanelArea = new Container
{
Padding = new MarginPadding(10),
AutoSizeAxes = Axes.Both,
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
},
};
AddStep("show", () => accountCreation.Show());
}
[BackgroundDependencyLoader]
private void load()
{
API.Logout();
localUser = API.LocalUser.GetBoundCopy();
localUser.BindValueChanged(user => { userPanelArea.Child = new UserGridPanel(user.NewValue) { Width = 200 }; }, true);
AddStep("logout", API.Logout);
}
}
}
| // 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.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Overlays;
using osu.Game.Users;
namespace osu.Game.Tests.Visual.Online
{
public class TestSceneAccountCreationOverlay : OsuTestScene
{
private readonly Container userPanelArea;
private readonly AccountCreationOverlay accountCreation;
private IBindable<User> localUser;
public TestSceneAccountCreationOverlay()
{
Children = new Drawable[]
{
accountCreation = new AccountCreationOverlay(),
userPanelArea = new Container
{
Padding = new MarginPadding(10),
AutoSizeAxes = Axes.Both,
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
},
};
}
[BackgroundDependencyLoader]
private void load()
{
API.Logout();
localUser = API.LocalUser.GetBoundCopy();
localUser.BindValueChanged(user => { userPanelArea.Child = new UserGridPanel(user.NewValue) { Width = 200 }; }, true);
}
[Test]
public void TestOverlayVisibility()
{
AddStep("start hidden", () => accountCreation.Hide());
AddStep("log out", API.Logout);
AddStep("show manually", () => accountCreation.Show());
AddUntilStep("overlay is visible", () => accountCreation.State.Value == Visibility.Visible);
AddStep("log back in", () => API.Login("dummy", "password"));
AddUntilStep("overlay is hidden", () => accountCreation.State.Value == Visibility.Hidden);
}
}
}
|
Add http.host and http.path annotations | using System;
using Microsoft.AspNetCore.Builder;
using Criteo.Profiling.Tracing;
using Criteo.Profiling.Tracing.Utils;
namespace Criteo.Profiling.Tracing.Middleware
{
public static class TracingMiddleware
{
public static void UseTracing(this IApplicationBuilder app, string serviceName)
{
var extractor = new Middleware.ZipkinHttpTraceExtractor();
app.Use(async (context, next) =>
{
Trace trace;
var request = context.Request;
if (!extractor.TryExtract(request.Headers, out trace))
{
trace = Trace.Create();
}
Trace.Current = trace;
using (new ServerTrace(serviceName, request.Method))
{
trace.Record(Annotations.Tag("http.uri", request.Path));
await TraceHelper.TracedActionAsync(next());
}
});
}
}
} | using System;
using Microsoft.AspNetCore.Builder;
using Criteo.Profiling.Tracing;
using Criteo.Profiling.Tracing.Utils;
using Microsoft.AspNetCore.Http.Extensions;
namespace Criteo.Profiling.Tracing.Middleware
{
public static class TracingMiddleware
{
public static void UseTracing(this IApplicationBuilder app, string serviceName)
{
var extractor = new Middleware.ZipkinHttpTraceExtractor();
app.Use(async (context, next) =>
{
Trace trace;
var request = context.Request;
if (!extractor.TryExtract(request.Headers, out trace))
{
trace = Trace.Create();
}
Trace.Current = trace;
using (new ServerTrace(serviceName, request.Method))
{
trace.Record(Annotations.Tag("http.host", request.Host.ToString()));
trace.Record(Annotations.Tag("http.uri", UriHelper.GetDisplayUrl(request)));
trace.Record(Annotations.Tag("http.path", request.Path));
await TraceHelper.TracedActionAsync(next());
}
});
}
}
} |
Make translation work with inheritance | namespace Translatable.TranslationTest
{
public class MainWindowTranslation : ITranslatable
{
private IPluralBuilder PluralBuilder { get; set; } = new DefaultPluralBuilder();
public string Title { get; private set; } = "Main window title";
public string SampleText { get; private set; } = "This is my content\r\nwith multiple lines";
public string Messages { get; private set; } = "Messages";
[Context("Some context")]
public string Messages2 { get; private set; } = "Messages";
private string[] NewMessagesText { get; set; } = {"You have {0} new message", "You have {0} new messages"};
[TranslatorComment("This page is intentionally left blank")]
public string MissingTranslation { get; set; } = "This translation might be \"missing\"";
public EnumTranslation<TestEnum>[] TestEnumTranslation { get; private set; } = EnumTranslation<TestEnum>.CreateDefaultEnumTranslation();
public string FormatMessageText(int messages)
{
var translation = PluralBuilder.GetPlural(messages, NewMessagesText);
return string.Format(translation, messages);
}
}
}
| namespace Translatable.TranslationTest
{
public class MainWindowTranslation : ITranslatable
{
protected IPluralBuilder PluralBuilder { get; set; } = new DefaultPluralBuilder();
public string Title { get; protected set; } = "Main window title";
public string SampleText { get; protected set; } = "This is my content\r\nwith multiple lines";
public string Messages { get; protected set; } = "Messages";
[Context("Some context")]
public string Messages2 { get; protected set; } = "Messages";
protected string[] NewMessagesText { get; set; } = { "You have {0} new message", "You have {0} new messages" };
[TranslatorComment("This page is intentionally left blank")]
public string MissingTranslation { get; set; } = "This translation might be \"missing\"";
public EnumTranslation<TestEnum>[] TestEnumTranslation { get; protected set; } = EnumTranslation<TestEnum>.CreateDefaultEnumTranslation();
public string FormatMessageText(int messages)
{
var translation = PluralBuilder.GetPlural(messages, NewMessagesText);
return string.Format(translation, messages);
}
}
public class TestTranslation : MainWindowTranslation
{
public string Text { get; private set; } = "Test";
}
}
|
Make tests actually test the string output | // 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.Input.Bindings;
using osu.Framework.Input.States;
using osuTK.Input;
using KeyboardState = osu.Framework.Input.States.KeyboardState;
namespace osu.Framework.Tests.Input
{
[TestFixture]
public class KeyCombinationTest
{
[Test]
public void TestKeyCombinationDisplayTrueOrder()
{
var keyCombination1 = new KeyCombination(InputKey.Control, InputKey.Shift, InputKey.R);
var keyCombination2 = new KeyCombination(InputKey.R, InputKey.Shift, InputKey.Control);
Assert.AreEqual(keyCombination1.ReadableString(), keyCombination2.ReadableString());
}
[Test]
public void TestKeyCombinationFromKeyboardStateDisplayTrueOrder()
{
var keyboardState = new KeyboardState();
keyboardState.Keys.Add(Key.R);
keyboardState.Keys.Add(Key.LShift);
keyboardState.Keys.Add(Key.LControl);
var keyCombination1 = KeyCombination.FromInputState(new InputState(keyboard: keyboardState));
var keyCombination2 = new KeyCombination(InputKey.Control, InputKey.Shift, InputKey.R);
Assert.AreEqual(keyCombination1.ReadableString(), keyCombination2.ReadableString());
}
}
}
| // 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.Input.Bindings;
namespace osu.Framework.Tests.Input
{
[TestFixture]
public class KeyCombinationTest
{
private static readonly object[][] key_combination_display_test_cases =
{
new object[] { new KeyCombination(InputKey.Alt, InputKey.F4), "Alt-F4" },
new object[] { new KeyCombination(InputKey.D, InputKey.Control), "Ctrl-D" },
new object[] { new KeyCombination(InputKey.Shift, InputKey.F, InputKey.Control), "Ctrl-Shift-F" },
new object[] { new KeyCombination(InputKey.Alt, InputKey.Control, InputKey.Super, InputKey.Shift), "Ctrl-Alt-Shift-Win" }
};
[TestCaseSource(nameof(key_combination_display_test_cases))]
public void TestKeyCombinationDisplayOrder(KeyCombination keyCombination, string expectedRepresentation)
=> Assert.That(keyCombination.ReadableString(), Is.EqualTo(expectedRepresentation));
}
}
|
Add basic Get for a post | using System;
using System.Collections.Generic;
using DapperTesting.Core.Model;
namespace DapperTesting.Core.Data
{
public class DapperPostRepository : DapperRepositoryBase, IPostRepository
{
public DapperPostRepository(IConnectionFactory connectionFactory, string connectionStringName) : base(connectionFactory, connectionStringName)
{
}
public void Create(Post post)
{
throw new NotImplementedException();
}
public void AddDetails(int postId, PostDetails details)
{
throw new NotImplementedException();
}
public bool Delete(int postId)
{
throw new NotImplementedException();
}
public bool DeleteDetails(int detailsId)
{
throw new NotImplementedException();
}
public List<Post> GetPostsForUser(int userId)
{
throw new NotImplementedException();
}
public Post Get(int id)
{
throw new NotImplementedException();
}
public PostDetails GetDetails(int postId, int sequence)
{
throw new NotImplementedException();
}
public bool Update(Post post)
{
throw new NotImplementedException();
}
public bool UpdateDetails(PostDetails details)
{
throw new NotImplementedException();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Dapper;
using DapperTesting.Core.Model;
namespace DapperTesting.Core.Data
{
public class DapperPostRepository : DapperRepositoryBase, IPostRepository
{
public DapperPostRepository(IConnectionFactory connectionFactory, string connectionStringName) : base(connectionFactory, connectionStringName)
{
}
public void Create(Post post)
{
throw new NotImplementedException();
}
public void AddDetails(int postId, PostDetails details)
{
throw new NotImplementedException();
}
public bool Delete(int postId)
{
throw new NotImplementedException();
}
public bool DeleteDetails(int detailsId)
{
throw new NotImplementedException();
}
public List<Post> GetPostsForUser(int userId)
{
throw new NotImplementedException();
}
public Post Get(int id)
{
const string sql = "SELECT * FROM [Posts] WHERE [Id] = @postId";
var post = Fetch(c => c.Query<Post>(sql, new { postId = id })).SingleOrDefault();
return post;
}
public PostDetails GetDetails(int postId, int sequence)
{
throw new NotImplementedException();
}
public bool Update(Post post)
{
throw new NotImplementedException();
}
public bool UpdateDetails(PostDetails details)
{
throw new NotImplementedException();
}
}
}
|
Create temp directories in temp folder | using System.IO;
namespace NuGet.Extensions.Tests.TestData
{
public class Isolation
{
public static DirectoryInfo GetIsolatedTestSolutionDir()
{
var solutionDir = new DirectoryInfo(Path.GetRandomFileName());
CopyFilesRecursively(new DirectoryInfo(Paths.TestSolutionForAdapterFolder), solutionDir);
return solutionDir;
}
public static DirectoryInfo GetIsolatedPackageSourceFromThisSolution()
{
var packageSource = new DirectoryInfo(Path.GetRandomFileName());
CopyFilesRecursively(new DirectoryInfo("../packages"), packageSource);
return packageSource;
}
public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)
{
if (!target.Exists) target.Create();
foreach (DirectoryInfo dir in source.GetDirectories())
CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
foreach (FileInfo file in source.GetFiles())
file.CopyTo(Path.Combine(target.FullName, file.Name));
}
}
} | using System.IO;
namespace NuGet.Extensions.Tests.TestData
{
public class Isolation
{
public static DirectoryInfo GetIsolatedTestSolutionDir()
{
var solutionDir = new DirectoryInfo(GetRandomTempDirectoryPath());
CopyFilesRecursively(new DirectoryInfo(Paths.TestSolutionForAdapterFolder), solutionDir);
return solutionDir;
}
private static string GetRandomTempDirectoryPath()
{
return Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
}
public static DirectoryInfo GetIsolatedPackageSourceFromThisSolution()
{
var packageSource = new DirectoryInfo(GetRandomTempDirectoryPath());
CopyFilesRecursively(new DirectoryInfo("../packages"), packageSource);
return packageSource;
}
public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)
{
if (!target.Exists) target.Create();
foreach (DirectoryInfo dir in source.GetDirectories())
CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
foreach (FileInfo file in source.GetFiles())
file.CopyTo(Path.Combine(target.FullName, file.Name));
}
}
} |
Add RemainingTime and env vars to dotnetcore2.0 example | // Compile with:
// docker run --rm -v "$PWD":/var/task lambci/lambda:build-dotnetcore2.0 dotnet publish -c Release -o pub
// Run with:
// docker run --rm -v "$PWD"/pub:/var/task lambci/lambda:dotnetcore2.0 test::test.Function::FunctionHandler "some"
using Amazon.Lambda.Core;
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace test
{
public class Function
{
public string FunctionHandler(object inputEvent, ILambdaContext context)
{
context.Logger.Log($"inputEvent: {inputEvent}");
return "Hello World!";
}
}
}
| // Compile with:
// docker run --rm -v "$PWD":/var/task lambci/lambda:build-dotnetcore2.0 dotnet publish -c Release -o pub
// Run with:
// docker run --rm -v "$PWD"/pub:/var/task lambci/lambda:dotnetcore2.0 test::test.Function::FunctionHandler "some"
using System;
using System.Collections;
using Amazon.Lambda.Core;
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace test
{
public class Function
{
public string FunctionHandler(object inputEvent, ILambdaContext context)
{
context.Logger.Log($"inputEvent: {inputEvent}");
LambdaLogger.Log($"RemainingTime: {context.RemainingTime}");
foreach (DictionaryEntry kv in Environment.GetEnvironmentVariables())
{
context.Logger.Log($"{kv.Key}={kv.Value}");
}
return "Hello World!";
}
}
}
|
Add comments to constructors, use constructor chaining. | using System;
namespace WundergroundClient.Autocomplete
{
enum ResultFilter
{
CitiesOnly,
HurricanesOnly,
CitiesAndHurricanes
}
class AutocompleteRequest
{
private String _searchString;
private ResultFilter _filter = ResultFilter.CitiesOnly;
private String _countryCode = null;
public AutocompleteRequest(String searchString)
{
_searchString = searchString;
}
public AutocompleteRequest(String query, ResultFilter filter)
{
_searchString = query;
_filter = filter;
}
public AutocompleteRequest(String searchString, ResultFilter filter, string countryCode)
{
_searchString = searchString;
_filter = filter;
_countryCode = countryCode;
}
//public async Task<String> ExecuteAsync()
//{
//}
}
}
| using System;
namespace WundergroundClient.Autocomplete
{
enum ResultFilter
{
CitiesOnly,
HurricanesOnly,
CitiesAndHurricanes
}
class AutocompleteRequest
{
private const String BaseUrl = "http://autocomplete.wunderground.com/";
private readonly String _searchString;
private readonly ResultFilter _filter;
private readonly String _countryCode;
/// <summary>
/// Creates a request to search for cities.
/// </summary>
/// <param name="city">The full or partial name of a city to look for.</param>
public AutocompleteRequest(String city) : this(city, ResultFilter.CitiesOnly, null)
{
}
/// <summary>
/// Creates a general query for cities, hurricanes, or both.
/// </summary>
/// <param name="query">The full or partial name to be looked up.</param>
/// <param name="filter">The types of results that are expected.</param>
public AutocompleteRequest(String query, ResultFilter filter) : this(query, filter, null)
{
}
/// <summary>
/// Creates a query for cities, hurricanes, or both,
/// restricted to a particular country.
///
/// Note: Wunderground does not use the standard ISO country codes.
/// See http://www.wunderground.com/weather/api/d/docs?d=resources/country-to-iso-matching
/// </summary>
/// <param name="query">The full or partial name to be looked up.</param>
/// <param name="filter">The types of results that are expected.</param>
/// <param name="countryCode">The Wunderground country code to restrict results to.</param>
public AutocompleteRequest(String query, ResultFilter filter, String countryCode)
{
_searchString = query;
_filter = filter;
_countryCode = countryCode;
}
//public async Task<String> ExecuteAsync()
//{
//}
}
}
|
Initialize the server with a report-state command | using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenStardriveServer.Domain.Database;
using OpenStardriveServer.Domain.Systems;
namespace OpenStardriveServer.HostedServices;
public class ServerInitializationService : BackgroundService
{
private readonly IRegisterSystemsCommand registerSystemsCommand;
private readonly ISqliteDatabaseInitializer sqliteDatabaseInitializer;
private readonly ILogger<ServerInitializationService> logger;
public ServerInitializationService(IRegisterSystemsCommand registerSystemsCommand,
ISqliteDatabaseInitializer sqliteDatabaseInitializer,
ILogger<ServerInitializationService> logger)
{
this.sqliteDatabaseInitializer = sqliteDatabaseInitializer;
this.logger = logger;
this.registerSystemsCommand = registerSystemsCommand;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
logger.LogInformation("Registering systems...");
registerSystemsCommand.Register();
logger.LogInformation("Initializing database...");
await sqliteDatabaseInitializer.Initialize();
logger.LogInformation("Server ready");
}
} | using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenStardriveServer.Domain;
using OpenStardriveServer.Domain.Database;
using OpenStardriveServer.Domain.Systems;
namespace OpenStardriveServer.HostedServices;
public class ServerInitializationService : BackgroundService
{
private readonly IRegisterSystemsCommand registerSystemsCommand;
private readonly ISqliteDatabaseInitializer sqliteDatabaseInitializer;
private readonly ILogger<ServerInitializationService> logger;
private readonly ICommandRepository commandRepository;
public ServerInitializationService(IRegisterSystemsCommand registerSystemsCommand,
ISqliteDatabaseInitializer sqliteDatabaseInitializer,
ILogger<ServerInitializationService> logger,
ICommandRepository commandRepository)
{
this.sqliteDatabaseInitializer = sqliteDatabaseInitializer;
this.logger = logger;
this.commandRepository = commandRepository;
this.registerSystemsCommand = registerSystemsCommand;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
logger.LogInformation("Registering systems...");
registerSystemsCommand.Register();
logger.LogInformation("Initializing database...");
await sqliteDatabaseInitializer.Initialize();
await commandRepository.Save(new Command { Type = "report-state" });
logger.LogInformation("Server ready");
}
} |
Clean up Translation code health test | // 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 Google.Cloud.ClientTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Xunit;
namespace Google.Cloud.Translation.V2.Tests
{
public class CodeHealthTest
{
// TODO: Remove the autogenerated type exemptions when we depend on the package instead.
[Fact]
public void PrivateFields()
{
CodeHealthTester.AssertAllFieldsPrivate(typeof(TranslationClient), GetExemptedTypes());
}
[Fact]
public void SealedClasses()
{
CodeHealthTester.AssertClassesAreSealedOrAbstract(typeof(TranslationClient), GetExemptedTypes());
}
private static IEnumerable<Type> GetExemptedTypes() =>
typeof(TranslationClient).GetTypeInfo().Assembly.DefinedTypes
.Where(t => t.Namespace.StartsWith("Google.Apis."))
.Select(t => t.AsType())
.ToList();
}
}
| // 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 Google.Cloud.ClientTesting;
using Xunit;
namespace Google.Cloud.Translation.V2.Tests
{
public class CodeHealthTest
{
[Fact]
public void PrivateFields()
{
CodeHealthTester.AssertAllFieldsPrivate(typeof(TranslationClient));
}
[Fact]
public void SealedClasses()
{
CodeHealthTester.AssertClassesAreSealedOrAbstract(typeof(TranslationClient));
}
}
}
|
Remove second build step from TC, thanks to Sean | @{ViewBag.Title = "Home";}
<div class="jumbotron">
<h1>CasperJS Testing!</h1>
<p>CasperJS is a navigation scripting & testing utility for PhantomJS written in Javascript</p>
<p><a target="_blank" href="http://casperjs.org/" class="btn btn-primary btn-lg" role="button">Learn more</a></p>
</div>
<div class="row">
<div class="col-xs-1 imgbg">
<img src="~/Content/casperjs-logo.png" style="width: 100%;" />
</div>
<div class="col-xs-5">
In case you haven’t seen CasperJS yet, go and take a look, it’s an extremely useful companion to PhantomJS.
<a href="http://ariya.ofilabs.com/2012/03/phantomjs-and-travis-ci.html" target="_blank">Ariya Hidayat</a>, creator of Phantomjs
</div>
<div class="col-xs-1 imgbg">
<img src="~/Content/phantomjs-logo.png" style="width: 100%;" />
</div>
<div class="col-xs-5">
<a href="http://phantomjs.org/" target="_blank">PhantomJS</a> is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.
</div>
</div>
| @{ViewBag.Title = "Home";}
<div class="jumbotron">
<h1>CasperJS Testing!!!</h1>
<p>CasperJS is a navigation scripting & testing utility for PhantomJS written in Javascript</p>
<p><a target="_blank" href="http://casperjs.org/" class="btn btn-primary btn-lg" role="button">Learn more</a></p>
</div>
<div class="row">
<div class="col-xs-1 imgbg">
<img src="~/Content/casperjs-logo.png" style="width: 100%;" />
</div>
<div class="col-xs-5">
In case you haven’t seen CasperJS yet, go and take a look, it’s an extremely useful companion to PhantomJS.
<a href="http://ariya.ofilabs.com/2012/03/phantomjs-and-travis-ci.html" target="_blank">Ariya Hidayat</a>, creator of Phantomjs
</div>
<div class="col-xs-1 imgbg">
<img src="~/Content/phantomjs-logo.png" style="width: 100%;" />
</div>
<div class="col-xs-5">
<a href="http://phantomjs.org/" target="_blank">PhantomJS</a> is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.
</div>
</div>
|
Remove some spurious Console.WriteLine() calls from a test. | // 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;
using System.Linq;
using NodaTime.Annotations;
using NUnit.Framework;
namespace NodaTime.Test.Annotations
{
[TestFixture]
public class MutabilityTest
{
[Test]
public void AllPublicClassesAreMutableOrImmutable()
{
var unannotatedClasses = typeof(Instant).Assembly
.GetTypes()
.Concat(new[] { typeof(ZonedDateTime.Comparer) })
.Where(t => t.IsClass && t.IsPublic && t.BaseType != typeof(MulticastDelegate))
.Where(t => !(t.IsAbstract && t.IsSealed)) // Ignore static classes
.OrderBy(t => t.Name)
.Where(t => !t.IsDefined(typeof(ImmutableAttribute), false) &&
!t.IsDefined(typeof(MutableAttribute), false))
.ToList();
var type = typeof (ZonedDateTime.Comparer);
Console.WriteLine(type.IsClass && type.IsPublic && type.BaseType != typeof (MulticastDelegate));
Console.WriteLine(!(type.IsAbstract && type.IsSealed));
Assert.IsEmpty(unannotatedClasses, "Unannotated classes: " + string.Join(", ", unannotatedClasses.Select(c => c.Name)));
}
}
}
| // 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;
using System.Linq;
using NodaTime.Annotations;
using NUnit.Framework;
namespace NodaTime.Test.Annotations
{
[TestFixture]
public class MutabilityTest
{
[Test]
public void AllPublicClassesAreMutableOrImmutable()
{
var unannotatedClasses = typeof(Instant).Assembly
.GetTypes()
.Concat(new[] { typeof(ZonedDateTime.Comparer) })
.Where(t => t.IsClass && t.IsPublic && t.BaseType != typeof(MulticastDelegate))
.Where(t => !(t.IsAbstract && t.IsSealed)) // Ignore static classes
.OrderBy(t => t.Name)
.Where(t => !t.IsDefined(typeof(ImmutableAttribute), false) &&
!t.IsDefined(typeof(MutableAttribute), false))
.ToList();
var type = typeof (ZonedDateTime.Comparer);
Assert.IsEmpty(unannotatedClasses, "Unannotated classes: " + string.Join(", ", unannotatedClasses.Select(c => c.Name)));
}
}
}
|
Rewrite of the Time Parsing code | using System;
using System.Globalization;
namespace LiveSplit.Model
{
public static class TimeSpanParser
{
public static TimeSpan? ParseNullable(String timeString)
{
if (String.IsNullOrEmpty(timeString))
return null;
return Parse(timeString);
}
public static TimeSpan Parse(String timeString)
{
double num = 0.0;
var factor = 1;
if (timeString.StartsWith("-"))
{
factor = -1;
timeString = timeString.Substring(1);
}
string[] array = timeString.Split(':');
foreach (string s in array)
{
double num2;
if (double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out num2))
{
num = num * 60.0 + num2;
}
else
{
throw new Exception();
}
}
if (factor * num > 864000)
throw new Exception();
return new TimeSpan((long)(factor * num * 10000000));
}
}
}
| using System;
using System.Linq;
using System.Globalization;
namespace LiveSplit.Model
{
public static class TimeSpanParser
{
public static TimeSpan? ParseNullable(String timeString)
{
if (String.IsNullOrEmpty(timeString))
return null;
return Parse(timeString);
}
public static TimeSpan Parse(String timeString)
{
var factor = 1;
if (timeString.StartsWith("-"))
{
factor = -1;
timeString = timeString.Substring(1);
}
var seconds = timeString
.Split(':')
.Select(x => Double.Parse(x, NumberStyles.Float, CultureInfo.InvariantCulture))
.Aggregate(0.0, (a, b) => 60 * a + b);
return TimeSpan.FromSeconds(factor * seconds);
}
}
}
|
Increase editor verify settings width to give more breathing space | // 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.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Edit.Checks.Components;
namespace osu.Game.Screens.Edit.Verify
{
[Cached]
public class VerifyScreen : EditorScreen
{
public readonly Bindable<Issue> SelectedIssue = new Bindable<Issue>();
public readonly Bindable<DifficultyRating> InterpretedDifficulty = new Bindable<DifficultyRating>();
public readonly BindableList<IssueType> HiddenIssueTypes = new BindableList<IssueType> { IssueType.Negligible };
public IssueList IssueList { get; private set; }
public VerifyScreen()
: base(EditorScreenMode.Verify)
{
}
[BackgroundDependencyLoader]
private void load()
{
InterpretedDifficulty.Default = BeatmapDifficultyCache.GetDifficultyRating(EditorBeatmap.BeatmapInfo.StarRating);
InterpretedDifficulty.SetDefault();
Child = new Container
{
RelativeSizeAxes = Axes.Both,
Child = new GridContainer
{
RelativeSizeAxes = Axes.Both,
ColumnDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.Absolute, 200),
},
Content = new[]
{
new Drawable[]
{
IssueList = new IssueList(),
new IssueSettings(),
},
}
}
};
}
}
}
| // 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.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Edit.Checks.Components;
namespace osu.Game.Screens.Edit.Verify
{
[Cached]
public class VerifyScreen : EditorScreen
{
public readonly Bindable<Issue> SelectedIssue = new Bindable<Issue>();
public readonly Bindable<DifficultyRating> InterpretedDifficulty = new Bindable<DifficultyRating>();
public readonly BindableList<IssueType> HiddenIssueTypes = new BindableList<IssueType> { IssueType.Negligible };
public IssueList IssueList { get; private set; }
public VerifyScreen()
: base(EditorScreenMode.Verify)
{
}
[BackgroundDependencyLoader]
private void load()
{
InterpretedDifficulty.Default = BeatmapDifficultyCache.GetDifficultyRating(EditorBeatmap.BeatmapInfo.StarRating);
InterpretedDifficulty.SetDefault();
Child = new Container
{
RelativeSizeAxes = Axes.Both,
Child = new GridContainer
{
RelativeSizeAxes = Axes.Both,
ColumnDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.Absolute, 225),
},
Content = new[]
{
new Drawable[]
{
IssueList = new IssueList(),
new IssueSettings(),
},
}
}
};
}
}
}
|
Set compatibility version to 2.2 in hello world sample project | using ExplicitlyImpl.AspNetCore.Mvc.FluentActions;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace HelloWorld
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddFluentActions();
}
public void Configure(IApplicationBuilder app)
{
app.UseFluentActions(actions =>
{
actions.RouteGet("/").To(() => "Hello World!");
});
app.UseMvc();
}
}
}
| using ExplicitlyImpl.AspNetCore.Mvc.FluentActions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
namespace HelloWorld
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc()
.AddFluentActions()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app)
{
app.UseFluentActions(actions =>
{
actions.RouteGet("/").To(() => "Hello World!");
});
app.UseMvc();
}
}
}
|
Fix ReturnsDefaultRepresenationCurrentCulture test for all cultures | using System.Globalization;
using Xunit;
namespace ByteSizeLib.Tests.BinaryByteSizeTests
{
public class ToBinaryStringMethod
{
[Fact]
public void ReturnsDefaultRepresenation()
{
// Arrange
var b = ByteSize.FromKiloBytes(10);
// Act
var result = b.ToBinaryString(CultureInfo.InvariantCulture);
// Assert
Assert.Equal("9.77 KiB", result);
}
[Fact]
public void ReturnsDefaultRepresenationCurrentCulture()
{
// Arrange
var b = ByteSize.FromKiloBytes(10);
var s = CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;
// Act
var result = b.ToBinaryString(CultureInfo.CurrentCulture);
// Assert
Assert.Equal($"9{s}77 KiB", result);
}
}
}
| using System.Globalization;
using Xunit;
namespace ByteSizeLib.Tests.BinaryByteSizeTests
{
public class ToBinaryStringMethod
{
[Fact]
public void ReturnsDefaultRepresenation()
{
// Arrange
var b = ByteSize.FromKiloBytes(10);
// Act
var result = b.ToBinaryString(CultureInfo.InvariantCulture);
// Assert
Assert.Equal("9.77 KiB", result);
}
[Fact]
public void ReturnsDefaultRepresenationCurrentCulture()
{
// Arrange
var b = ByteSize.FromKiloBytes(10);
var s = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
// Act
var result = b.ToBinaryString(CultureInfo.CurrentCulture);
// Assert
Assert.Equal($"9{s}77 KiB", result);
}
}
}
|
Use CssParser front-end as intended | namespace AngleSharp.Performance.Css
{
using AngleSharp;
using AngleSharp.Parser.Css;
using System;
class AngleSharpParser : ITestee
{
static readonly IConfiguration configuration = new Configuration().WithCss();
public String Name
{
get { return "AngleSharp"; }
}
public Type Library
{
get { return typeof(CssParser); }
}
public void Run(String source)
{
var parser = new CssParser(source, configuration);
parser.Parse(new CssParserOptions
{
IsIncludingUnknownDeclarations = true,
IsIncludingUnknownRules = true,
IsToleratingInvalidConstraints = true,
IsToleratingInvalidValues = true
});
}
}
}
| namespace AngleSharp.Performance.Css
{
using AngleSharp;
using AngleSharp.Parser.Css;
using System;
class AngleSharpParser : ITestee
{
static readonly IConfiguration configuration = new Configuration().WithCss();
static readonly CssParserOptions options = new CssParserOptions
{
IsIncludingUnknownDeclarations = true,
IsIncludingUnknownRules = true,
IsToleratingInvalidConstraints = true,
IsToleratingInvalidValues = true
};
static readonly CssParser parser = new CssParser(options, configuration);
public String Name
{
get { return "AngleSharp"; }
}
public Type Library
{
get { return typeof(CssParser); }
}
public void Run(String source)
{
parser.ParseStylesheet(source);
}
}
}
|
Add some more properties to hover info. | using System.Threading.Tasks;
namespace DanTup.DartAnalysis
{
class AnalysisGetHoverRequest : Request<AnalysisGetHoverParams, Response<AnalysisGetHoverResponse>>
{
public string method = "analysis.getHover";
public AnalysisGetHoverRequest(string file, int offset)
{
this.@params = new AnalysisGetHoverParams(file, offset);
}
}
class AnalysisGetHoverParams
{
public string file;
public int offset;
public AnalysisGetHoverParams(string file, int offset)
{
this.file = file;
this.offset = offset;
}
}
class AnalysisGetHoverResponse
{
public AnalysisHoverItem[] hovers = null;
}
public class AnalysisHoverItem
{
public string containingLibraryPath;
public string containingLibraryName;
public string dartdoc;
public string elementDescription;
}
public static class AnalysisGetHoverImplementation
{
public static async Task<AnalysisHoverItem[]> GetHover(this DartAnalysisService service, string file, int offset)
{
var response = await service.Service.Send(new AnalysisGetHoverRequest(file, offset));
return response.result.hovers;
}
}
}
| using System.Threading.Tasks;
namespace DanTup.DartAnalysis
{
class AnalysisGetHoverRequest : Request<AnalysisGetHoverParams, Response<AnalysisGetHoverResponse>>
{
public string method = "analysis.getHover";
public AnalysisGetHoverRequest(string file, int offset)
{
this.@params = new AnalysisGetHoverParams(file, offset);
}
}
class AnalysisGetHoverParams
{
public string file;
public int offset;
public AnalysisGetHoverParams(string file, int offset)
{
this.file = file;
this.offset = offset;
}
}
class AnalysisGetHoverResponse
{
public AnalysisHoverItem[] hovers = null;
}
public class AnalysisHoverItem
{
public string containingLibraryPath;
public string containingLibraryName;
public string dartdoc;
public string elementDescription;
public string parameter;
public string propagatedType;
public string staticType;
}
public static class AnalysisGetHoverImplementation
{
public static async Task<AnalysisHoverItem[]> GetHover(this DartAnalysisService service, string file, int offset)
{
var response = await service.Service.Send(new AnalysisGetHoverRequest(file, offset));
return response.result.hovers;
}
}
}
|
Implement the second overload of Select | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodePlayground
{
public static class MyLinqMethods
{
public static IEnumerable<T> Where<T>(
this IEnumerable<T> inputSequence,
Func<T, bool> predicate)
{
foreach (T item in inputSequence)
if (predicate(item))
yield return item;
}
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> inputSequence,
Func<TSource, TResult> transform)
{
foreach (TSource item in inputSequence)
yield return transform(item);
}
}
class Program
{
static void Main(string[] args)
{
// Generate items using a factory:
var items = GenerateSequence(i => i.ToString());
foreach (var item in items.Where(item => item.Length < 2))
Console.WriteLine(item);
foreach (var item in items.Select(item =>
new string(item.PadRight(9).Reverse().ToArray())))
Console.WriteLine(item);
return;
var moreItems = GenerateSequence(i => i);
foreach (var item in moreItems)
Console.WriteLine(item);
}
// Core syntax for an enumerable:
private static IEnumerable<T> GenerateSequence<T>(Func<int, T> factory)
{
var i = 0;
while (i++ < 100)
yield return factory(i);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodePlayground
{
public static class MyLinqMethods
{
public static IEnumerable<T> Where<T>(
this IEnumerable<T> inputSequence,
Func<T, bool> predicate)
{
foreach (T item in inputSequence)
if (predicate(item))
yield return item;
}
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> inputSequence,
Func<TSource, TResult> transform)
{
foreach (TSource item in inputSequence)
yield return transform(item);
}
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> inputSequence,
Func<TSource, int, TResult> transform)
{
int index = 0;
foreach (TSource item in inputSequence)
yield return transform(item, index++);
}
}
class Program
{
static void Main(string[] args)
{
// Generate items using a factory:
var items = GenerateSequence(i => i.ToString());
foreach (var item in items.Where(item => item.Length < 2))
Console.WriteLine(item);
foreach (var item in items.Select((item, index) =>
new { index, item }))
Console.WriteLine(item);
return;
var moreItems = GenerateSequence(i => i);
foreach (var item in moreItems)
Console.WriteLine(item);
}
// Core syntax for an enumerable:
private static IEnumerable<T> GenerateSequence<T>(Func<int, T> factory)
{
var i = 0;
while (i++ < 100)
yield return factory(i);
}
}
}
|
Update sql commands and use the new method | using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class CustomerListEquip : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
string sql = @"
SELECT *
FROM equipments
WHERE customer = '{0}'";
sql = string.Format(
sql,
Session["customer"]);
DataTable table = doQuery(sql);
foreach(DataRow row in table.Rows)
{
TableRow trow = new TableRow();
for (int i = 0; i < table.Columns.Count; i++)
{
if (table.Columns[i].ColumnName == "customer") continue;
if (table.Columns[i].ColumnName == "id") continue;
TableCell cell = new TableCell();
cell.Text = row[i].ToString();
trow.Cells.Add(cell);
}
TableEquipments.Rows.Add(trow);
}
}
}
| using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class CustomerListEquip : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
string sql = @"
SELECT *
FROM equipments
WHERE customer = '{0}'";
sql = string.Format(
sql,
Session["customer"]);
fillTable(sql, ref TableEquipments);
}
}
|
Fix tests - all green | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Moq;
using Engine;
namespace EngineTest
{
[TestFixture()]
public class ActorShould
{
Mock<IScene> scene;
Actor actor;
Mock<IStrategy> strategy;
[SetUp()]
public void SetUp()
{
strategy = new Mock<IStrategy>();
actor = new Actor(strategy.Object);
scene = new Mock<IScene>();
strategy.Setup(mn => mn.SelectAction(It.IsAny<List<IAct>>(),It.IsAny<IScene>())).Returns(new Act("Act 1",actor,null ));
scene.Setup(mn => mn.GetPossibleActions(It.IsAny<IActor>())).Returns(new List<IAct>{new Act("Act 1",actor,null ),new Act("Act 2", actor,null)});
}
[Test()]
public void GetPossibleActionsFromScene()
{
//arrange
//act
actor.Act(scene.Object);
var actions = actor.AllActions;
//assert
Assert.AreNotEqual(0, actions.Count);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Moq;
using Engine;
namespace EngineTest
{
[TestFixture()]
public class ActorShould
{
Mock<IScene> scene;
Actor actor;
Mock<IStrategy> strategy;
private Mock<IAct> act;
[SetUp()]
public void SetUp()
{
act = new Mock<IAct>();
strategy = new Mock<IStrategy>();
actor = new Actor(strategy.Object);
scene = new Mock<IScene>();
strategy.Setup(mn => mn.SelectAction(It.IsAny<List<IAct>>(),It.IsAny<IScene>())).Returns(act.Object);
scene.Setup(mn => mn.GetPossibleActions(It.IsAny<IActor>())).Returns(new List<IAct>{act.Object});
}
[Test()]
public void ActOnScene()
{
//arrange
//act
actor.Act(scene.Object);
//assert
act.Verify(m => m.Do(scene.Object));
}
}
}
|
Revert "Added edit method into UserRepository" | using BikeMates.DataAccess.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BikeMates.Contracts
{
//TODO: Create folder Repositories and move this interface into it
//TODO: Create a base IRepository interface
public interface IUserRepository
{
void Add(ApplicationUser entity);
void Delete(ApplicationUser entity);
IEnumerable<ApplicationUser> GetAll();
ApplicationUser Get(string id);
void Edit(ApplicationUser entity);
void SaveChanges(); //TODO: Remove this method. Use it inside each methods like Add, Delete, etc.
}
}
| using BikeMates.DataAccess.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BikeMates.Contracts
{
//TODO: Create folder Repositories and move this interface into it
//TODO: Create a base IRepository interface
public interface IUserRepository
{
void Add(ApplicationUser entity);
void Delete(ApplicationUser entity);
IEnumerable<ApplicationUser> GetAll();
ApplicationUser Get(string id);
void SaveChanges(); //TODO: Remove this method. Use it inside each methods like Add, Delete, etc.
}
}
|
Remove heartbeat server property index name | // Copyright (c) 2017 Sergey Zhigunov.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Hangfire.EntityFramework
{
internal class HangfireServer
{
[Key]
[MaxLength(100)]
public string Id { get; set; }
[ForeignKey(nameof(ServerHost))]
public Guid ServerHostId { get; set; }
public string Data { get; set; }
[Index("IX_HangfireServer_Heartbeat")]
[DateTimePrecision(7)]
public DateTime Heartbeat { get; set; }
public virtual HangfireServerHost ServerHost { get; set; }
}
} | // Copyright (c) 2017 Sergey Zhigunov.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Hangfire.EntityFramework
{
internal class HangfireServer
{
[Key]
[MaxLength(100)]
public string Id { get; set; }
[ForeignKey(nameof(ServerHost))]
public Guid ServerHostId { get; set; }
public string Data { get; set; }
[Index]
[DateTimePrecision(7)]
public DateTime Heartbeat { get; set; }
public virtual HangfireServerHost ServerHost { get; set; }
}
} |
Handle null id for Cars/Details action | using CarFuel.DataAccess;
using CarFuel.Models;
using CarFuel.Services;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CarFuel.Controllers
{
public class CarsController : Controller
{
private ICarDb db;
private CarService carService;
public CarsController()
{
db = new CarDb();
carService = new CarService(db);
}
[Authorize]
public ActionResult Index()
{
var userId = new Guid(User.Identity.GetUserId());
IEnumerable<Car> cars = carService.GetCarsByMember(userId);
return View(cars);
}
[Authorize]
public ActionResult Create()
{
return View();
}
[HttpPost]
[Authorize]
public ActionResult Create(Car item)
{
var userId = new Guid(User.Identity.GetUserId());
try
{
carService.AddCar(item, userId);
}
catch (OverQuotaException ex)
{
TempData["error"] = ex.Message;
}
return RedirectToAction("Index");
}
public ActionResult Details(Guid id)
{
var userId = new Guid(User.Identity.GetUserId());
var c = carService.GetCarsByMember(userId).SingleOrDefault(x => x.Id == id);
return View(c);
}
}
} | using CarFuel.DataAccess;
using CarFuel.Models;
using CarFuel.Services;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
namespace CarFuel.Controllers
{
public class CarsController : Controller
{
private ICarDb db;
private CarService carService;
public CarsController()
{
db = new CarDb();
carService = new CarService(db);
}
[Authorize]
public ActionResult Index()
{
var userId = new Guid(User.Identity.GetUserId());
IEnumerable<Car> cars = carService.GetCarsByMember(userId);
return View(cars);
}
[Authorize]
public ActionResult Create()
{
return View();
}
[HttpPost]
[Authorize]
public ActionResult Create(Car item)
{
var userId = new Guid(User.Identity.GetUserId());
try
{
carService.AddCar(item, userId);
}
catch (OverQuotaException ex)
{
TempData["error"] = ex.Message;
}
return RedirectToAction("Index");
}
public ActionResult Details(Guid? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var userId = new Guid(User.Identity.GetUserId());
var c = carService.GetCarsByMember(userId).SingleOrDefault(x => x.Id == id);
return View(c);
}
}
} |
Use background thread, otherwise process is not terminated after closing application window. | using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Threading;
using UltimaRX.Proxy.InjectionApi;
namespace Infusion.Desktop
{
internal static class InterProcessCommunication
{
private static readonly EventWaitHandle MessageSentEvent = new EventWaitHandle(false, EventResetMode.ManualReset,
"Infusion.Desktop.CommandMessageSent");
public static void StartReceiving()
{
var receivingThread = new Thread(ReceivingLoop);
receivingThread.Start();
}
private static void ReceivingLoop(object data)
{
MemoryMappedFile messageFile =
MemoryMappedFile.CreateOrOpen("Infusion.Desktop.CommandMessages", 2048);
while (true)
{
MessageSentEvent.WaitOne();
string command;
using (var stream = messageFile.CreateViewStream())
{
using (var reader = new StreamReader(stream))
{
command = reader.ReadLine();
}
}
if (!string.IsNullOrEmpty(command))
{
if (command.StartsWith(","))
Injection.CommandHandler.Invoke(command);
else
Injection.CommandHandler.Invoke("," + command);
}
}
}
public static void SendCommand(string command)
{
MemoryMappedFile messageFile =
MemoryMappedFile.CreateOrOpen("Infusion.Desktop.CommandMessages", 2048);
using (var stream = messageFile.CreateViewStream())
{
using (var writer = new StreamWriter(stream))
{
writer.WriteLine(command);
writer.Flush();
}
}
MessageSentEvent.Set();
MessageSentEvent.Reset();
}
}
} | using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Threading;
using UltimaRX.Proxy.InjectionApi;
namespace Infusion.Desktop
{
internal static class InterProcessCommunication
{
private static readonly EventWaitHandle MessageSentEvent = new EventWaitHandle(false, EventResetMode.ManualReset,
"Infusion.Desktop.CommandMessageSent");
public static void StartReceiving()
{
var receivingThread = new Thread(ReceivingLoop);
receivingThread.IsBackground = true;
receivingThread.Start();
}
private static void ReceivingLoop(object data)
{
MemoryMappedFile messageFile =
MemoryMappedFile.CreateOrOpen("Infusion.Desktop.CommandMessages", 2048);
while (true)
{
MessageSentEvent.WaitOne();
string command;
using (var stream = messageFile.CreateViewStream())
{
using (var reader = new StreamReader(stream))
{
command = reader.ReadLine();
}
}
if (!string.IsNullOrEmpty(command))
{
if (command.StartsWith(","))
Injection.CommandHandler.Invoke(command);
else
Injection.CommandHandler.Invoke("," + command);
}
}
}
public static void SendCommand(string command)
{
MemoryMappedFile messageFile =
MemoryMappedFile.CreateOrOpen("Infusion.Desktop.CommandMessages", 2048);
using (var stream = messageFile.CreateViewStream())
{
using (var writer = new StreamWriter(stream))
{
writer.WriteLine(command);
writer.Flush();
}
}
MessageSentEvent.Set();
MessageSentEvent.Reset();
}
}
} |
Add test for reading files with UTF-8 BOM | using Xunit;
using System.IO;
namespace Mammoth.Tests {
public class DocumentConverterTests {
[Fact]
public void DocxContainingOneParagraphIsConvertedToSingleParagraphElement() {
assertSuccessfulConversion(
convertToHtml("single-paragraph.docx"),
"<p>Walking on imported air</p>");
}
private void assertSuccessfulConversion(IResult<string> result, string expectedValue) {
Assert.Empty(result.Warnings);
Assert.Equal(expectedValue, result.Value);
}
private IResult<string> convertToHtml(string name) {
return new DocumentConverter().ConvertToHtml(TestFilePath(name));
}
private string TestFilePath(string name) {
return Path.Combine("../../TestData", name);
}
}
}
| using Xunit;
using System.IO;
namespace Mammoth.Tests {
public class DocumentConverterTests {
[Fact]
public void DocxContainingOneParagraphIsConvertedToSingleParagraphElement() {
assertSuccessfulConversion(
ConvertToHtml("single-paragraph.docx"),
"<p>Walking on imported air</p>");
}
[Fact]
public void CanReadFilesWithUtf8Bom() {
assertSuccessfulConversion(
ConvertToHtml("utf8-bom.docx"),
"<p>This XML has a byte order mark.</p>");
}
private void assertSuccessfulConversion(IResult<string> result, string expectedValue) {
Assert.Empty(result.Warnings);
Assert.Equal(expectedValue, result.Value);
}
private IResult<string> ConvertToHtml(string name) {
return new DocumentConverter().ConvertToHtml(TestFilePath(name));
}
private string TestFilePath(string name) {
return Path.Combine("../../TestData", name);
}
}
}
|
Make initial task easier given the number of refactorings needed. | using System;
using System.Linq;
using MyApplication.dependencies;
using System.Collections.Generic;
namespace MyApplication
{
public class PersonService
{
/// <summary>
/// Initializes a new instance of the <see cref="PersonService"/> class.
/// </summary>
public PersonService()
{
AgeGroupMap = new Dictionary<int,AgeGroup>();
AgeGroupMap[14] = AgeGroup.Child;
AgeGroupMap[18] = AgeGroup.Teen;
AgeGroupMap[25] = AgeGroup.YoungAdult;
AgeGroupMap[75] = AgeGroup.Adult;
AgeGroupMap[999] = AgeGroup.Retired;
}
public Dictionary<int, AgeGroup> AgeGroupMap { get; set; }
/// <summary>
/// Gets the age group for a particular customer.
/// </summary>
/// <param name="customer">The customer to calculate the AgeGroup of.</param>
/// <returns>The correct age group for the customer</returns>
/// <exception cref="System.ApplicationException">If the customer is invalid</exception>
public AgeGroup GetAgeGroup(Person customer)
{
if (!customer.IsValid())
{
throw new ApplicationException("customer is invalid");
}
// Calculate age
DateTime zeroTime = new DateTime(1, 1, 1);
int age = (zeroTime + (DateTime.Today - customer.DOB)).Year;
// Return the correct age group
return AgeGroupMap.OrderBy(x => x.Key).First(x => x.Key < age).Value;
}
}
} | using System;
using System.Linq;
using MyApplication.dependencies;
using System.Collections.Generic;
namespace MyApplication
{
public class PersonService
{
/// <summary>
/// Initializes a new instance of the <see cref="PersonService"/> class.
/// </summary>
public PersonService()
{
AgeGroupMap = new Dictionary<int,AgeGroup>();
AgeGroupMap[14] = AgeGroup.Child;
AgeGroupMap[18] = AgeGroup.Teen;
AgeGroupMap[25] = AgeGroup.YoungAdult;
AgeGroupMap[75] = AgeGroup.Adult;
AgeGroupMap[999] = AgeGroup.Retired;
}
public Dictionary<int, AgeGroup> AgeGroupMap { get; set; }
/// <summary>
/// Gets the age group for a particular customer.
/// </summary>
/// <param name="customer">The customer to calculate the AgeGroup of.</param>
/// <returns>The correct age group for the customer</returns>
/// <exception cref="System.ApplicationException">If the customer is invalid</exception>
public AgeGroup GetAgeGroup(Person customer)
{
if (!customer.IsValid())
{
throw new ApplicationException("customer is invalid");
}
// Calculate age
DateTime zeroTime = new DateTime(1, 1, 1);
int age = (zeroTime + (DateTime.Today - customer.DOB)).Year;
// Return the correct age group
var viableBuckets = AgeGroupMap.Where(x => x.Key >= age);
return AgeGroupMap[viableBuckets.Min(x => x.Key)];
}
}
} |
Add release action to journal transaction | using ONIT.VismaNetApi.Models;
using System.Threading.Tasks;
namespace ONIT.VismaNetApi.Lib.Data
{
public class JournalTransactionData : BaseCrudDataClass<JournalTransaction>
{
public JournalTransactionData(VismaNetAuthorization auth) : base(auth)
{
ApiControllerUri = VismaNetControllers.JournalTransaction;
}
public async Task AddAttachment(JournalTransaction journalTransaction, byte[] data, string filename)
{
await VismaNetApiHelper.AddAttachment(Authorization, ApiControllerUri, journalTransaction.GetIdentificator(), data, filename);
}
public async Task AddAttachment(JournalTransaction journalTransaction, int lineNumber, byte[] data, string filename)
{
await VismaNetApiHelper.AddAttachment(Authorization, ApiControllerUri, $"{journalTransaction.GetIdentificator()}/{lineNumber}", data, filename);
}
}
} | using ONIT.VismaNetApi.Models;
using System.Threading.Tasks;
namespace ONIT.VismaNetApi.Lib.Data
{
public class JournalTransactionData : BaseCrudDataClass<JournalTransaction>
{
public JournalTransactionData(VismaNetAuthorization auth) : base(auth)
{
ApiControllerUri = VismaNetControllers.JournalTransaction;
}
public async Task AddAttachment(JournalTransaction journalTransaction, byte[] data, string filename)
{
await VismaNetApiHelper.AddAttachment(Authorization, ApiControllerUri, journalTransaction.GetIdentificator(), data, filename);
}
public async Task AddAttachment(JournalTransaction journalTransaction, int lineNumber, byte[] data, string filename)
{
await VismaNetApiHelper.AddAttachment(Authorization, ApiControllerUri, $"{journalTransaction.GetIdentificator()}/{lineNumber}", data, filename);
}
public async Task<VismaActionResult> Release(JournalTransaction transaction)
{
return await VismaNetApiHelper.Action(Authorization, ApiControllerUri, transaction.GetIdentificator(), "release");
}
}
} |
Add test cases for wall avoidance settings | using Alensia.Core.Actor;
using Alensia.Core.Camera;
using Alensia.Tests.Actor;
using NUnit.Framework;
namespace Alensia.Tests.Camera
{
[TestFixture, Description("Test suite for ThirdPersonCamera class.")]
public class ThirdPersonCameraTest : BaseOrbitingCameraTest<ThirdPersonCamera, IHumanoid>
{
protected override ThirdPersonCamera CreateCamera(UnityEngine.Camera camera)
{
var cam = new ThirdPersonCamera(camera);
cam.RotationalConstraints.Up = 90;
cam.RotationalConstraints.Down = 90;
cam.RotationalConstraints.Side = 180;
cam.WallAvoidanceSettings.AvoidWalls = false;
cam.Initialize(Actor);
return cam;
}
protected override IHumanoid CreateActor()
{
return new DummyHumanoid();
}
}
} | using Alensia.Core.Actor;
using Alensia.Core.Camera;
using Alensia.Tests.Actor;
using NUnit.Framework;
using UnityEngine;
namespace Alensia.Tests.Camera
{
[TestFixture, Description("Test suite for ThirdPersonCamera class.")]
public class ThirdPersonCameraTest : BaseOrbitingCameraTest<ThirdPersonCamera, IHumanoid>
{
private GameObject _obstacle;
[TearDown]
public override void TearDown()
{
base.TearDown();
if (_obstacle == null) return;
Object.Destroy(_obstacle);
_obstacle = null;
}
protected override ThirdPersonCamera CreateCamera(UnityEngine.Camera camera)
{
var cam = new ThirdPersonCamera(camera);
cam.RotationalConstraints.Up = 90;
cam.RotationalConstraints.Down = 90;
cam.RotationalConstraints.Side = 180;
cam.WallAvoidanceSettings.AvoidWalls = false;
cam.Initialize(Actor);
return cam;
}
protected override IHumanoid CreateActor()
{
return new DummyHumanoid();
}
[Test, Description("It should adjust camera position according to obstacles when AvoidWalls is true.")]
[TestCase(0, 0, 10, 1, 4)]
[TestCase(0, 0, 2, 1, 2)]
[TestCase(0, 0, 10, 2, 3)]
[TestCase(45, 0, 10, 1, 10)]
[TestCase(0, 45, 10, 1, 10)]
public void ShouldAdjustCameraPositionAccordingToObstacles(
float heading,
float elevation,
float distance,
float proximity,
float actual)
{
var transform = Actor.Transform;
_obstacle = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
_obstacle.transform.position = transform.position + new Vector3(0, 1, -5);
Camera.WallAvoidanceSettings.AvoidWalls = true;
Camera.WallAvoidanceSettings.MinimumDistance = proximity;
Camera.Heading = heading;
Camera.Elevation = elevation;
Camera.Distance = distance;
Expect(
ActualDistance,
Is.EqualTo(actual).Within(Tolerance),
"Unexpected camera distance.");
}
}
} |
Save work items after starting. | using TicketTimer.Core.Infrastructure;
namespace TicketTimer.Core.Services
{
// TODO this should have a better name
public class WorkItemServiceImpl : WorkItemService
{
private readonly WorkItemStore _workItemStore;
private readonly DateProvider _dateProvider;
public WorkItemServiceImpl(WorkItemStore workItemStore, DateProvider dateProvider)
{
_workItemStore = workItemStore;
_dateProvider = dateProvider;
}
public void StartWorkItem(string ticketNumber)
{
StartWorkItem(ticketNumber, string.Empty);
}
public void StartWorkItem(string ticketNumber, string comment)
{
var workItem = new WorkItem(ticketNumber)
{
Comment = comment,
Started = _dateProvider.Now
};
_workItemStore.Add(workItem);
}
public void StopWorkItem()
{
throw new System.NotImplementedException();
}
}
} | using TicketTimer.Core.Infrastructure;
namespace TicketTimer.Core.Services
{
// TODO this should have a better name
public class WorkItemServiceImpl : WorkItemService
{
private readonly WorkItemStore _workItemStore;
private readonly DateProvider _dateProvider;
public WorkItemServiceImpl(WorkItemStore workItemStore, DateProvider dateProvider)
{
_workItemStore = workItemStore;
_dateProvider = dateProvider;
}
public void StartWorkItem(string ticketNumber)
{
StartWorkItem(ticketNumber, string.Empty);
}
public void StartWorkItem(string ticketNumber, string comment)
{
var workItem = new WorkItem(ticketNumber)
{
Comment = comment,
Started = _dateProvider.Now
};
_workItemStore.Add(workItem);
_workItemStore.Save();
}
public void StopWorkItem()
{
throw new System.NotImplementedException();
}
}
} |
Allow standalone program to process multiple files at once | // Copyright (c) 2014 Eberhard Beilharz
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using Undisposed;
namespace UndisposedExe
{
class MainClass
{
private static void Usage()
{
Console.WriteLine("Usage");
Console.WriteLine("Undisposed.exe [-o outputfile] assemblyname");
}
public static void Main(string[] args)
{
if (args.Length < 1)
{
Usage();
return;
}
string inputFile = args[args.Length - 1];
string outputFile;
if (args.Length >= 3)
{
if (args[0] == "-o" || args[0] == "--output")
{
outputFile = args[1];
}
else
{
Usage();
return;
}
}
else
outputFile = inputFile;
var def = Mono.Cecil.ModuleDefinition.ReadModule(inputFile);
var moduleWeaver = new ModuleWeaver();
moduleWeaver.ModuleDefinition = def;
moduleWeaver.Execute();
def.Write(outputFile);
}
}
}
| // Copyright (c) 2014 Eberhard Beilharz
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using Undisposed;
namespace UndisposedExe
{
class MainClass
{
private static void Usage()
{
Console.WriteLine("Usage");
Console.WriteLine("Undisposed.exe [-o outputfile] assemblyname");
}
private static void ProcessFile(string inputFile, string outputFile)
{
Console.WriteLine("Processing {0} -> {1}", inputFile, outputFile);
var def = Mono.Cecil.ModuleDefinition.ReadModule(inputFile);
var moduleWeaver = new ModuleWeaver();
moduleWeaver.ModuleDefinition = def;
moduleWeaver.Execute();
def.Write(outputFile);
}
public static void Main(string[] args)
{
if (args.Length < 1)
{
Usage();
return;
}
string inputFile = args[args.Length - 1];
string outputFile = string.Empty;
bool isOutputFileSet = false;
if (args.Length >= 3)
{
if (args[0] == "-o" || args[0] == "--output")
{
outputFile = args[1];
isOutputFileSet = true;
}
else
{
Usage();
return;
}
}
if (!isOutputFileSet)
{
for (int i = 0; i < args.Length; i++)
{
inputFile = args[i];
ProcessFile(inputFile, inputFile);
}
}
else
ProcessFile(inputFile, outputFile);
}
}
}
|
Change comment to doc comment | using System.Web.Http.Controllers;
namespace System.Web.Http.ModelBinding
{
// Interface for model binding
public interface IModelBinder
{
bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext);
}
}
| using System.Web.Http.Controllers;
namespace System.Web.Http.ModelBinding
{
/// <summary>
/// Interface for model binding.
/// </summary>
public interface IModelBinder
{
bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext);
}
}
|
Fix private keys config parsing | using System.Collections.Generic;
using System.Linq;
using RestImageResize.Security;
using RestImageResize.Utils;
namespace RestImageResize
{
/// <summary>
/// Provides configuration options.
/// </summary>
internal static class Config
{
private static class AppSettingKeys
{
private const string Prefix = "RestImageResize.";
// ReSharper disable MemberHidesStaticFromOuterClass
public const string DefaultTransform = Prefix + "DefautTransform";
public const string PrivateKeys = Prefix + "PrivateKeys";
// ReSharper restore MemberHidesStaticFromOuterClass
}
/// <summary>
/// Gets the default image transformation type.
/// </summary>
public static ImageTransform DefaultTransform
{
get { return ConfigUtils.ReadAppSetting(AppSettingKeys.DefaultTransform, ImageTransform.DownFit); }
}
public static IList<PrivateKey> PrivateKeys
{
get
{
var privateKeysString = ConfigUtils.ReadAppSetting<string>(AppSettingKeys.PrivateKeys);
var privateKeys = privateKeysString.Split('|')
.Select(val => new PrivateKey
{
Name = val.Split(':').First(),
Key = val.Split(':').Last()
})
.ToList();
return privateKeys;
}
}
}
}
| using System.Collections.Generic;
using System.Linq;
using RestImageResize.Security;
using RestImageResize.Utils;
namespace RestImageResize
{
/// <summary>
/// Provides configuration options.
/// </summary>
internal static class Config
{
private static class AppSettingKeys
{
private const string Prefix = "RestImageResize.";
// ReSharper disable MemberHidesStaticFromOuterClass
public const string DefaultTransform = Prefix + "DefautTransform";
public const string PrivateKeys = Prefix + "PrivateKeys";
// ReSharper restore MemberHidesStaticFromOuterClass
}
/// <summary>
/// Gets the default image transformation type.
/// </summary>
public static ImageTransform DefaultTransform
{
get { return ConfigUtils.ReadAppSetting(AppSettingKeys.DefaultTransform, ImageTransform.DownFit); }
}
public static IList<PrivateKey> PrivateKeys
{
get
{
var privateKeysString = ConfigUtils.ReadAppSetting<string>(AppSettingKeys.PrivateKeys);
if (string.IsNullOrEmpty(privateKeysString))
{
return new List<PrivateKey>();
}
var privateKeys = privateKeysString.Split('|')
.Select(val => new PrivateKey
{
Name = val.Split(':').First(),
Key = val.Split(':').Last()
})
.ToList();
return privateKeys;
}
}
}
}
|
Add link to Guava implementation of Cache. | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace Tamarind.Cache
{
// TODO: NEEDS DOCUMENTATION.
public interface ICache<K, V>
{
V GetIfPresent(K key);
V Get(K key, Func<V> valueLoader);
ImmutableDictionary<K, V> GetAllPresent(IEnumerator<K> keys);
void Put(K key, V value);
void PutAll(Dictionary<K, V> xs);
void Invalidate(K key);
void InvlidateAll(IEnumerator<K> keys);
long Count { get; }
//CacheStats Stats { get; }
ConcurrentDictionary<K, V> ToDictionary();
void CleanUp();
}
}
| using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace Tamarind.Cache
{
// Guava Reference: https://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/cache/Cache.java
// TODO: NEEDS DOCUMENTATION.
public interface ICache<K, V>
{
V GetIfPresent(K key);
V Get(K key, Func<V> valueLoader);
ImmutableDictionary<K, V> GetAllPresent(IEnumerator<K> keys);
void Put(K key, V value);
void PutAll(Dictionary<K, V> xs);
void Invalidate(K key);
void InvlidateAll(IEnumerator<K> keys);
long Count { get; }
//CacheStats Stats { get; }
ConcurrentDictionary<K, V> ToDictionary();
void CleanUp();
}
}
|
Remove account and api key | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
namespace VendingMachineNew
{
public class TwilioAPI
{
static void Main(string[] args)
{
SendSms().Wait();
Console.Write("Press any key to continue.");
Console.ReadKey();
}
static async Task SendSms()
{
// Your Account SID from twilio.com/console
var accountSid = "AC745137d20b51ab66c4fd18de86d3831c";
// Your Auth Token from twilio.com/console
var authToken = "789153e001d240e55a499bf070e75dfe";
TwilioClient.Init(accountSid, authToken);
var message = await MessageResource.CreateAsync(
to: new PhoneNumber("+14148070975"),
from: new PhoneNumber("+14142693915"),
body: "The confirmation number will be here");
Console.WriteLine(message.Sid);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
namespace VendingMachineNew
{
public class TwilioAPI
{
static void Main(string[] args)
{
SendSms().Wait();
Console.Write("Press any key to continue.");
Console.ReadKey();
}
static async Task SendSms()
{
// Your Account SID from twilio.com/console
var accountSid = "x";
// Your Auth Token from twilio.com/console
var authToken = "x";
TwilioClient.Init(accountSid, authToken);
var message = await MessageResource.CreateAsync(
to: new PhoneNumber("+14148070975"),
from: new PhoneNumber("+14142693915"),
body: "The confirmation number will be here");
Console.WriteLine(message.Sid);
}
}
}
|
Set Configuration.DefaultNameOrConnectionString for unit tests by default. | using System.Reflection;
using Abp.Modules;
namespace Abp.TestBase
{
[DependsOn(typeof(AbpKernelModule))]
public class AbpTestBaseModule : AbpModule
{
public override void PreInitialize()
{
Configuration.EventBus.UseDefaultEventBus = false;
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
}
}
} | using System.Reflection;
using Abp.Modules;
namespace Abp.TestBase
{
[DependsOn(typeof(AbpKernelModule))]
public class AbpTestBaseModule : AbpModule
{
public override void PreInitialize()
{
Configuration.EventBus.UseDefaultEventBus = false;
Configuration.DefaultNameOrConnectionString = "Default";
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
}
}
} |
Fix DelayableAction delays persisting DAH serialization | using System;
using System.Xml;
using Hacknet;
using Pathfinder.Util;
using Pathfinder.Util.XML;
namespace Pathfinder.Action
{
public abstract class DelayablePathfinderAction : PathfinderAction
{
[XMLStorage]
public string DelayHost;
[XMLStorage]
public string Delay;
private DelayableActionSystem delayHost;
private float delay = 0f;
public sealed override void Trigger(object os_obj)
{
if (delayHost == null && DelayHost != null)
{
var delayComp = Programs.getComputer(OS.currentInstance, DelayHost);
if (delayComp == null)
throw new FormatException($"{this.GetType().Name}: DelayHost could not be found");
delayHost = DelayableActionSystem.FindDelayableActionSystemOnComputer(delayComp);
}
if (delay <= 0f || delayHost == null)
{
Trigger((OS)os_obj);
return;
}
delayHost.AddAction(this, delay);
delay = 0f;
}
public abstract void Trigger(OS os);
public override void LoadFromXml(ElementInfo info)
{
base.LoadFromXml(info);
if (Delay != null && !float.TryParse(Delay, out delay))
throw new FormatException($"{this.GetType().Name}: Couldn't parse delay time!");
}
}
}
| using System;
using System.Xml;
using Hacknet;
using Pathfinder.Util;
using Pathfinder.Util.XML;
namespace Pathfinder.Action
{
public abstract class DelayablePathfinderAction : PathfinderAction
{
[XMLStorage]
public string DelayHost;
[XMLStorage]
public string Delay;
private DelayableActionSystem delayHost;
private float delay = 0f;
public sealed override void Trigger(object os_obj)
{
if (delayHost == null && DelayHost != null)
{
var delayComp = Programs.getComputer(OS.currentInstance, DelayHost);
if (delayComp == null)
throw new FormatException($"{this.GetType().Name}: DelayHost could not be found");
delayHost = DelayableActionSystem.FindDelayableActionSystemOnComputer(delayComp);
}
if (delay <= 0f || delayHost == null)
{
Trigger((OS)os_obj);
return;
}
DelayHost = null;
Delay = null;
delayHost.AddAction(this, delay);
delay = 0f;
}
public abstract void Trigger(OS os);
public override void LoadFromXml(ElementInfo info)
{
base.LoadFromXml(info);
if (Delay != null && !float.TryParse(Delay, out delay))
throw new FormatException($"{this.GetType().Name}: Couldn't parse delay time!");
}
}
}
|
Fix for shader preview window in material tool appearing and then just disappearing | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ControlsLibrary.BasicControls
{
public partial class TextWindow : Form
{
public TextWindow()
{
InitializeComponent();
}
static public void ShowModal(String text)
{
using (var dlg = new TextWindow())
{
dlg.Text = text;
dlg.ShowDialog();
}
}
static public void Show(String text)
{
using (var dlg = new TextWindow())
{
dlg.Text = text;
dlg.Show();
}
}
public new string Text { set { _textBox.Text = value; } }
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ControlsLibrary.BasicControls
{
public partial class TextWindow : Form
{
public TextWindow()
{
InitializeComponent();
}
static public void ShowModal(String text)
{
using (var dlg = new TextWindow())
{
dlg.Text = text;
dlg.ShowDialog();
}
}
static public void Show(String text)
{
new TextWindow() { Text = text }.Show();
}
public new string Text { set { _textBox.Text = value; } }
}
}
|
Remove test intead of fixing it 👍 | using System;
using Xunit;
using Branch.Clients.Json;
using System.Threading.Tasks;
using Branch.Clients.Http.Models;
using System.Collections.Generic;
namespace Branch.Tests.Clients.JsonTests
{
public class OptionTests
{
[Fact]
public void RespectOptions()
{
var options = new Options
{
Headers = new Dictionary<string, string>
{
{"X-Test-Header", "testing"},
{"Content-Type", "application/json"},
},
Timeout = TimeSpan.FromMilliseconds(2500),
};
var client = new JsonClient("https://example.com", options);
Assert.Equal(client.Client.Options.Timeout, options.Timeout);
Assert.Equal(client.Client.Options.Headers, options.Headers);
}
}
}
| using System;
using Xunit;
using Branch.Clients.Json;
using System.Threading.Tasks;
using Branch.Clients.Http.Models;
using System.Collections.Generic;
namespace Branch.Tests.Clients.JsonTests
{
public class OptionTests
{
[Fact]
public void RespectOptions()
{
var options = new Options
{
Timeout = TimeSpan.FromMilliseconds(2500),
};
var client = new JsonClient("https://example.com", options);
Assert.Equal(client.Client.Options.Timeout, options.Timeout);
}
}
}
|
Handle elements without elevation data | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace KmlToGpxConverter
{
internal static class KmlReader
{
public const string FileExtension = "kml";
public static IList<GpsTimePoint> ReadFile(string filename)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filename);
var nsManager = new XmlNamespaceManager(xmlDoc.NameTable);
nsManager.AddNamespace("gx", @"http://www.google.com/kml/ext/2.2");
var list = xmlDoc.SelectNodes("//gx:MultiTrack/gx:Track", nsManager);
var nodes = new List<GpsTimePoint>();
foreach (XmlNode element in list)
{
nodes.AddRange(GetGpsPoints(element.ChildNodes));
}
return nodes;
}
private static IList<GpsTimePoint> GetGpsPoints(XmlNodeList nodes)
{
var retVal = new List<GpsTimePoint>();
var e = nodes.GetEnumerator();
while (e.MoveNext())
{
var utcTimepoint = ((XmlNode)e.Current).InnerText;
if (!e.MoveNext()) break;
var t = ((XmlNode)e.Current).InnerText.Split(new[] { ' ' });
if (t.Length != 3) break;
retVal.Add(new GpsTimePoint(t[0], t[1], t[2], utcTimepoint));
}
return retVal;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace KmlToGpxConverter
{
internal static class KmlReader
{
public const string FileExtension = "kml";
public static IList<GpsTimePoint> ReadFile(string filename)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filename);
var nsManager = new XmlNamespaceManager(xmlDoc.NameTable);
nsManager.AddNamespace("gx", @"http://www.google.com/kml/ext/2.2");
var list = xmlDoc.SelectNodes("//gx:MultiTrack/gx:Track", nsManager);
var nodes = new List<GpsTimePoint>();
foreach (XmlNode element in list)
{
nodes.AddRange(GetGpsPoints(element.ChildNodes));
}
return nodes;
}
private static IList<GpsTimePoint> GetGpsPoints(XmlNodeList nodes)
{
var retVal = new List<GpsTimePoint>();
var e = nodes.GetEnumerator();
while (e.MoveNext())
{
var utcTimepoint = ((XmlNode)e.Current).InnerText;
if (!e.MoveNext()) break;
var t = ((XmlNode)e.Current).InnerText.Split(new[] { ' ' });
if (t.Length < 2) continue;
retVal.Add(new GpsTimePoint(t[0], t[1], t.ElementAtOrDefault(2), utcTimepoint));
}
return retVal;
}
}
}
|
Increase usable width slightly further | // 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.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Edit.Checks.Components;
namespace osu.Game.Screens.Edit.Verify
{
[Cached]
public class VerifyScreen : EditorScreen
{
public readonly Bindable<Issue> SelectedIssue = new Bindable<Issue>();
public readonly Bindable<DifficultyRating> InterpretedDifficulty = new Bindable<DifficultyRating>();
public readonly BindableList<IssueType> HiddenIssueTypes = new BindableList<IssueType> { IssueType.Negligible };
public IssueList IssueList { get; private set; }
public VerifyScreen()
: base(EditorScreenMode.Verify)
{
}
[BackgroundDependencyLoader]
private void load()
{
InterpretedDifficulty.Default = BeatmapDifficultyCache.GetDifficultyRating(EditorBeatmap.BeatmapInfo.StarRating);
InterpretedDifficulty.SetDefault();
Child = new Container
{
RelativeSizeAxes = Axes.Both,
Child = new GridContainer
{
RelativeSizeAxes = Axes.Both,
ColumnDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.Absolute, 225),
},
Content = new[]
{
new Drawable[]
{
IssueList = new IssueList(),
new IssueSettings(),
},
}
}
};
}
}
}
| // 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.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Edit.Checks.Components;
namespace osu.Game.Screens.Edit.Verify
{
[Cached]
public class VerifyScreen : EditorScreen
{
public readonly Bindable<Issue> SelectedIssue = new Bindable<Issue>();
public readonly Bindable<DifficultyRating> InterpretedDifficulty = new Bindable<DifficultyRating>();
public readonly BindableList<IssueType> HiddenIssueTypes = new BindableList<IssueType> { IssueType.Negligible };
public IssueList IssueList { get; private set; }
public VerifyScreen()
: base(EditorScreenMode.Verify)
{
}
[BackgroundDependencyLoader]
private void load()
{
InterpretedDifficulty.Default = BeatmapDifficultyCache.GetDifficultyRating(EditorBeatmap.BeatmapInfo.StarRating);
InterpretedDifficulty.SetDefault();
Child = new Container
{
RelativeSizeAxes = Axes.Both,
Child = new GridContainer
{
RelativeSizeAxes = Axes.Both,
ColumnDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.Absolute, 250),
},
Content = new[]
{
new Drawable[]
{
IssueList = new IssueList(),
new IssueSettings(),
},
}
}
};
}
}
}
|
Use the shortest path if assemblies have the same file name | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Pennyworth {
public static class DropHelper {
public static IEnumerable<String> GetAssembliesFromDropData(IEnumerable<FileInfo> data) {
Func<FileInfo, Boolean> isDir = fi => ((fi.Attributes & FileAttributes.Directory) == FileAttributes.Directory);
Func<FileInfo, Boolean> isFile = fi => ((fi.Attributes & FileAttributes.Directory) != FileAttributes.Directory);
var files = data.Where(isFile);
var dirs = data
.Where(isDir)
.Select(fi => {
if (fi.FullName.EndsWith("bin", StringComparison.OrdinalIgnoreCase))
return new FileInfo(fi.Directory.FullName);
return fi;
})
.SelectMany(fi => Directory.EnumerateDirectories(fi.FullName, "bin", SearchOption.AllDirectories));
var firstAssemblies = dirs.Select(dir => Directory.EnumerateFiles(dir, "*.exe", SearchOption.AllDirectories)
.FirstOrDefault(path => !path.Contains("vshost")))
.Where(dir => !String.IsNullOrEmpty(dir));
return files.Select(fi => fi.FullName)
.Concat(firstAssemblies)
.Where(path => Path.HasExtension(path)
&& (path.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)
|| path.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)));
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Pennyworth {
public static class DropHelper {
public static IEnumerable<String> GetAssembliesFromDropData(IEnumerable<FileInfo> data) {
Func<FileInfo, Boolean> isDir = fi => ((fi.Attributes & FileAttributes.Directory) == FileAttributes.Directory);
Func<FileInfo, Boolean> isFile = fi => ((fi.Attributes & FileAttributes.Directory) != FileAttributes.Directory);
var files = data.Where(isFile);
var dirs = data.Where(isDir);
var assembliesInDirs =
dirs.SelectMany(dir => Directory.EnumerateFiles(dir.FullName, "*.exe", SearchOption.AllDirectories)
.Where(path => !path.Contains("vshost")));
return files.Select(fi => fi.FullName).Concat(DiscardSimilarFiles(assembliesInDirs.ToList()));
}
private static IEnumerable<String> DiscardSimilarFiles(List<String> assemblies) {
var fileNames = assemblies.Select(Path.GetFileName).Distinct();
var namePathLookup = assemblies.ToLookup(Path.GetFileName);
foreach (var file in fileNames) {
var paths = namePathLookup[file].ToList();
if (paths.Any()) {
if (paths.Count > 1) {
paths.Sort(String.CompareOrdinal);
}
yield return paths.First();
}
}
}
}
}
|
Make XHud MaskType cast-able to AndHud MaskType | using System;
using Android.App;
using AndroidHUD;
namespace XHUD
{
public enum MaskType
{
// None = 1,
Clear,
Black,
// Gradient
}
public static class HUD
{
public static Activity MyActivity;
public static void Show(string message, int progress = -1, MaskType maskType = MaskType.Black)
{
AndHUD.Shared.Show(HUD.MyActivity, message, progress,(AndroidHUD.MaskType)maskType);
}
public static void Dismiss()
{
AndHUD.Shared.Dismiss(HUD.MyActivity);
}
public static void ShowToast(string message, bool showToastCentered = true, double timeoutMs = 1000)
{
AndHUD.Shared.ShowToast(HUD.MyActivity, message, (AndroidHUD.MaskType)MaskType.Black, TimeSpan.FromSeconds(timeoutMs/1000), showToastCentered);
}
public static void ShowToast(string message, MaskType maskType, bool showToastCentered = true, double timeoutMs = 1000)
{
AndHUD.Shared.ShowToast(HUD.MyActivity, message, (AndroidHUD.MaskType)maskType, TimeSpan.FromSeconds(timeoutMs/1000), showToastCentered);
}
}
}
| using System;
using Android.App;
using AndroidHUD;
namespace XHUD
{
public enum MaskType
{
// None = 1,
Clear = 2,
Black = 3,
// Gradient
}
public static class HUD
{
public static Activity MyActivity;
public static void Show(string message, int progress = -1, MaskType maskType = MaskType.Black)
{
AndHUD.Shared.Show(HUD.MyActivity, message, progress,(AndroidHUD.MaskType)maskType);
}
public static void Dismiss()
{
AndHUD.Shared.Dismiss(HUD.MyActivity);
}
public static void ShowToast(string message, bool showToastCentered = true, double timeoutMs = 1000)
{
AndHUD.Shared.ShowToast(HUD.MyActivity, message, (AndroidHUD.MaskType)MaskType.Black, TimeSpan.FromSeconds(timeoutMs/1000), showToastCentered);
}
public static void ShowToast(string message, MaskType maskType, bool showToastCentered = true, double timeoutMs = 1000)
{
AndHUD.Shared.ShowToast(HUD.MyActivity, message, (AndroidHUD.MaskType)maskType, TimeSpan.FromSeconds(timeoutMs/1000), showToastCentered);
}
}
}
|
Make the code in the entrypoint even shorter. | using System;
using Autofac;
using WordList.Composition;
namespace WordList {
public class Program {
public static void Main(string[] args) {
var compositionRoot = CompositionRoot.Compose();
var wordListProgram = compositionRoot.Resolve<IWordListProgram>();
wordListProgram.Run();
Console.WriteLine("Press any key to quit...");
Console.ReadKey();
}
}
} | using System;
using Autofac;
using WordList.Composition;
namespace WordList {
public class Program {
public static void Main(string[] args) {
CompositionRoot.Compose().Resolve<IWordListProgram>().Run();
Console.WriteLine("Press any key to quit...");
Console.ReadKey();
}
}
} |
Add FirstLetterToLower() to each exception message | using System;
namespace Evolve
{
public class EvolveConfigurationException : EvolveException
{
private const string EvolveConfigurationError = "Evolve configuration error: ";
public EvolveConfigurationException(string message) : base(EvolveConfigurationError + message) { }
public EvolveConfigurationException(string message, Exception innerException) : base(EvolveConfigurationError + message, innerException) { }
}
}
| using System;
namespace Evolve
{
public class EvolveConfigurationException : EvolveException
{
private const string EvolveConfigurationError = "Evolve configuration error: ";
public EvolveConfigurationException(string message) : base(EvolveConfigurationError + FirstLetterToLower(message)) { }
public EvolveConfigurationException(string message, Exception innerException) : base(EvolveConfigurationError + FirstLetterToLower(message), innerException) { }
private static string FirstLetterToLower(string str)
{
if (str == null)
{
return "";
}
if (str.Length > 1)
{
return Char.ToLowerInvariant(str[0]) + str.Substring(1);
}
return str.ToLowerInvariant();
}
}
}
|
Add assertion to check for cycles in ExecutionTree | using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Symbooglix
{
public class ExecutionTreeNode
{
public readonly ExecutionTreeNode Parent;
public readonly ProgramLocation CreatedAt;
public readonly ExecutionState State; // Should this be a weak reference to allow GC?
public readonly int Depth;
private List<ExecutionTreeNode> Children;
public ExecutionTreeNode(ExecutionState self, ExecutionTreeNode parent, ProgramLocation createdAt)
{
Debug.Assert(self != null, "self cannot be null!");
this.State = self;
if (parent == null)
this.Parent = null;
else
{
this.Parent = parent;
// Add this as a child of the parent
this.Parent.AddChild(this);
}
this.Depth = self.ExplicitBranchDepth;
this.CreatedAt = createdAt;
Children = new List<ExecutionTreeNode>(); // Should we lazily create this?
}
public ExecutionTreeNode GetChild(int index)
{
return Children[index];
}
public int ChildrenCount
{
get { return Children.Count; }
}
public void AddChild(ExecutionTreeNode node)
{
Debug.Assert(node != null, "Child cannot be null");
Children.Add(node);
}
public override string ToString()
{
return string.Format ("[{0}.{1}]", State.Id, State.ExplicitBranchDepth);
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Symbooglix
{
public class ExecutionTreeNode
{
public readonly ExecutionTreeNode Parent;
public readonly ProgramLocation CreatedAt;
public readonly ExecutionState State; // Should this be a weak reference to allow GC?
public readonly int Depth;
private List<ExecutionTreeNode> Children;
public ExecutionTreeNode(ExecutionState self, ExecutionTreeNode parent, ProgramLocation createdAt)
{
Debug.Assert(self != null, "self cannot be null!");
this.State = self;
if (parent == null)
this.Parent = null;
else
{
this.Parent = parent;
// Add this as a child of the parent
this.Parent.AddChild(this);
}
this.Depth = self.ExplicitBranchDepth;
this.CreatedAt = createdAt;
Children = new List<ExecutionTreeNode>(); // Should we lazily create this?
}
public ExecutionTreeNode GetChild(int index)
{
return Children[index];
}
public int ChildrenCount
{
get { return Children.Count; }
}
public void AddChild(ExecutionTreeNode node)
{
Debug.Assert(node != null, "Child cannot be null");
Debug.Assert(node != this, "Cannot have cycles");
Children.Add(node);
}
public override string ToString()
{
return string.Format ("[{0}.{1}]", State.Id, State.ExplicitBranchDepth);
}
}
}
|
Use dictionary instead of lists | namespace BracesValidator
{
using System.Collections.Generic;
public class BracesValidator
{
public bool Validate(string code)
{
char[] codeArray = code.ToCharArray();
List<char> openers = new List<char> { '{', '[', '(' };
List<char> closers = new List<char> { '}', ']', ')' };
Stack<char> parensStack = new Stack<char>();
int braceCounter = 0;
for (int i = 0; i < codeArray.Length; i++)
{
if(openers.Contains(codeArray[i])) {
parensStack.Push(codeArray[i]);
}
if(closers.Contains(codeArray[i])) {
var current = parensStack.Pop();
if(openers.IndexOf(current) != closers.IndexOf(codeArray[i])) {
return false;
}
}
}
return parensStack.Count == 0;
}
}
}
| namespace BracesValidator
{
using System.Collections.Generic;
public class BracesValidator
{
public bool Validate(string code)
{
char[] codeArray = code.ToCharArray();
Dictionary<char, char> openersClosersMap = new Dictionary<char, char>();
openersClosersMap.Add('{', '}');
openersClosersMap.Add('[', ']');
openersClosersMap.Add('(', ')');
Stack<char> parensStack = new Stack<char>();
int braceCounter = 0;
for (int i = 0; i < codeArray.Length; i++)
{
if(openersClosersMap.ContainsKey(codeArray[i])) {
parensStack.Push(codeArray[i]);
}
if(openersClosersMap.ContainsValue(codeArray[i])) {
var current = parensStack.Pop();
if(openersClosersMap[current] != codeArray[i]) {
return false;
}
}
}
return parensStack.Count == 0;
}
}
}
|
Remove warnings from Ably log to reduce noise. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using DotNetApis.Common.Internals;
using Microsoft.Extensions.Logging;
namespace DotNetApis.Common
{
/// <summary>
/// A logger that attempts to write to an implicit Ably channel. This type can be safely created before its channel is created.
/// </summary>
public sealed class AsyncLocalAblyLogger : ILogger
{
private static readonly AsyncLocal<AblyChannel> ImplicitChannel = new AsyncLocal<AblyChannel>();
public static void TryCreate(string channelName, ILogger logger)
{
try
{
ImplicitChannel.Value = AblyService.CreateLogChannel(channelName);
}
catch (Exception ex)
{
logger.LogWarning(0, ex, "Could not initialize Ably: {exceptionMessage}", ex.Message);
}
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (IsEnabled(logLevel))
ImplicitChannel.Value?.LogMessage(logLevel.ToString(), formatter(state, exception));
}
public bool IsEnabled(LogLevel logLevel) => ImplicitChannel.Value != null && logLevel >= LogLevel.Information;
public IDisposable BeginScope<TState>(TState state) => throw new NotImplementedException();
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using DotNetApis.Common.Internals;
using Microsoft.Extensions.Logging;
namespace DotNetApis.Common
{
/// <summary>
/// A logger that attempts to write to an implicit Ably channel. This type can be safely created before its channel is created.
/// </summary>
public sealed class AsyncLocalAblyLogger : ILogger
{
private static readonly AsyncLocal<AblyChannel> ImplicitChannel = new AsyncLocal<AblyChannel>();
public static void TryCreate(string channelName, ILogger logger)
{
try
{
ImplicitChannel.Value = AblyService.CreateLogChannel(channelName);
}
catch (Exception ex)
{
logger.LogWarning(0, ex, "Could not initialize Ably: {exceptionMessage}", ex.Message);
}
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (IsEnabled(logLevel))
ImplicitChannel.Value?.LogMessage(logLevel.ToString(), formatter(state, exception));
}
public bool IsEnabled(LogLevel logLevel) => ImplicitChannel.Value != null && logLevel >= LogLevel.Information && logLevel != LogLevel.Warning;
public IDisposable BeginScope<TState>(TState state) => throw new NotImplementedException();
}
}
|
Make sure we only ever initialize once | // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
//using GLib;
//using Gtk;
using NDesk.DBus;
using NDesk.GLib;
using org.freedesktop.DBus;
namespace NDesk.DBus
{
//FIXME: this API needs review and de-unixification. It is horrid, but gets the job done.
public static class BusG
{
static bool SystemDispatch (IOChannel source, IOCondition condition, IntPtr data)
{
Bus.System.Iterate ();
return true;
}
static bool SessionDispatch (IOChannel source, IOCondition condition, IntPtr data)
{
Bus.Session.Iterate ();
return true;
}
public static void Init ()
{
Init (Bus.System, SystemDispatch);
Init (Bus.Session, SessionDispatch);
}
public static void Init (Connection conn, IOFunc dispatchHandler)
{
IOChannel channel = new IOChannel ((int)conn.SocketHandle);
IO.AddWatch (channel, IOCondition.In, dispatchHandler);
}
//TODO: add public API to watch an arbitrary connection
}
}
| // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
//using GLib;
//using Gtk;
using NDesk.DBus;
using NDesk.GLib;
using org.freedesktop.DBus;
namespace NDesk.DBus
{
//FIXME: this API needs review and de-unixification. It is horrid, but gets the job done.
public static class BusG
{
static bool SystemDispatch (IOChannel source, IOCondition condition, IntPtr data)
{
Bus.System.Iterate ();
return true;
}
static bool SessionDispatch (IOChannel source, IOCondition condition, IntPtr data)
{
Bus.Session.Iterate ();
return true;
}
static bool initialized = false;
public static void Init ()
{
if (initialized)
return;
Init (Bus.System, SystemDispatch);
Init (Bus.Session, SessionDispatch);
initialized = true;
}
public static void Init (Connection conn, IOFunc dispatchHandler)
{
IOChannel channel = new IOChannel ((int)conn.SocketHandle);
IO.AddWatch (channel, IOCondition.In, dispatchHandler);
}
//TODO: add public API to watch an arbitrary connection
}
}
|
Add parallelism to Tests project | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Atata.Tests")]
[assembly: Guid("9d0aa4f2-4987-4395-be95-76abc329b7a0")] | using NUnit.Framework;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Atata.Tests")]
[assembly: Guid("9d0aa4f2-4987-4395-be95-76abc329b7a0")]
[assembly: LevelOfParallelism(4)]
[assembly: Parallelizable(ParallelScope.Fixtures)]
[assembly: Atata.Culture("en-us")] |
Fix crew to reference by BroeCrewId | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using HeadRaceTimingSite.Models;
using Microsoft.EntityFrameworkCore;
namespace HeadRaceTimingSite.Controllers
{
public class CrewController : BaseController
{
public CrewController(TimingSiteContext context) : base(context) { }
public async Task<IActionResult> Details(int? id)
{
Crew crew = await _context.Crews.Include(c => c.Competition)
.Include(c => c.Athletes)
.Include("Athletes.Athlete")
.Include("Awards.Award")
.SingleOrDefaultAsync(c => c.CrewId == id);
return View(crew);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using HeadRaceTimingSite.Models;
using Microsoft.EntityFrameworkCore;
namespace HeadRaceTimingSite.Controllers
{
public class CrewController : BaseController
{
public CrewController(TimingSiteContext context) : base(context) { }
public async Task<IActionResult> Details(int? id)
{
Crew crew = await _context.Crews.Include(c => c.Competition)
.Include(c => c.Athletes)
.Include("Athletes.Athlete")
.Include("Awards.Award")
.SingleOrDefaultAsync(c => c.BroeCrewId == id);
return View(crew);
}
}
} |
Mark the empty method detour test as NoInlining | #pragma warning disable CS1720 // Expression will always cause a System.NullReferenceException because the type's default value is null
#pragma warning disable xUnit1013 // Public method should be marked as test
using Xunit;
using MonoMod.RuntimeDetour;
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using MonoMod.Utils;
using System.Reflection.Emit;
using System.Text;
namespace MonoMod.UnitTest {
[Collection("RuntimeDetour")]
public class DetourEmptyTest {
private bool DidNothing = true;
[Fact]
public void TestDetoursEmpty() {
// The following use cases are not meant to be usage examples.
// Please take a look at DetourTest and HookTest instead.
Assert.True(DidNothing);
using (Hook h = new Hook(
// .GetNativeStart() to enforce a native detour.
typeof(DetourEmptyTest).GetMethod("DoNothing"),
new Action<DetourEmptyTest>(self => {
DidNothing = false;
})
)) {
DoNothing();
Assert.False(DidNothing);
}
}
public void DoNothing() {
}
}
}
| #pragma warning disable CS1720 // Expression will always cause a System.NullReferenceException because the type's default value is null
#pragma warning disable xUnit1013 // Public method should be marked as test
using Xunit;
using MonoMod.RuntimeDetour;
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using MonoMod.Utils;
using System.Reflection.Emit;
using System.Text;
namespace MonoMod.UnitTest {
[Collection("RuntimeDetour")]
public class DetourEmptyTest {
private bool DidNothing = true;
[Fact]
public void TestDetoursEmpty() {
// The following use cases are not meant to be usage examples.
// Please take a look at DetourTest and HookTest instead.
Assert.True(DidNothing);
using (Hook h = new Hook(
// .GetNativeStart() to enforce a native detour.
typeof(DetourEmptyTest).GetMethod("DoNothing"),
new Action<DetourEmptyTest>(self => {
DidNothing = false;
})
)) {
DoNothing();
Assert.False(DidNothing);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public void DoNothing() {
}
}
}
|
Make user voice content provider work with https. | using System;
using System.Threading.Tasks;
using JabbR.ContentProviders.Core;
using JabbR.Infrastructure;
namespace JabbR.ContentProviders
{
public class UserVoiceContentProvider : CollapsibleContentProvider
{
private static readonly string _uservoiceAPIURL = "http://{0}/api/v1/oembed.json?url={1}";
protected override Task<ContentProviderResult> GetCollapsibleContent(ContentProviderHttpRequest request)
{
return FetchArticle(request.RequestUri).Then(article =>
{
return new ContentProviderResult()
{
Title = article.title,
Content = article.html
};
});
}
private static Task<dynamic> FetchArticle(Uri url)
{
return Http.GetJsonAsync(String.Format(_uservoiceAPIURL, url.Host, url.AbsoluteUri));
}
public override bool IsValidContent(Uri uri)
{
return uri.Host.IndexOf("uservoice.com", StringComparison.OrdinalIgnoreCase) >= 0;
}
}
} | using System;
using System.Threading.Tasks;
using JabbR.ContentProviders.Core;
using JabbR.Infrastructure;
namespace JabbR.ContentProviders
{
public class UserVoiceContentProvider : CollapsibleContentProvider
{
private static readonly string _uservoiceAPIURL = "https://{0}/api/v1/oembed.json?url={1}";
protected override Task<ContentProviderResult> GetCollapsibleContent(ContentProviderHttpRequest request)
{
return FetchArticle(request.RequestUri).Then(article =>
{
return new ContentProviderResult()
{
Title = article.title,
Content = article.html
};
});
}
private static Task<dynamic> FetchArticle(Uri url)
{
return Http.GetJsonAsync(String.Format(_uservoiceAPIURL, url.Host, url.AbsoluteUri));
}
public override bool IsValidContent(Uri uri)
{
return uri.Host.IndexOf("uservoice.com", StringComparison.OrdinalIgnoreCase) >= 0;
}
}
} |
Make X509 work with ManagedHandler | using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
namespace Docker.DotNet.X509
{
public class CertificateCredentials : Credentials
{
private readonly WebRequestHandler _handler;
public CertificateCredentials(X509Certificate2 clientCertificate)
{
_handler = new WebRequestHandler()
{
ClientCertificateOptions = ClientCertificateOption.Manual,
UseDefaultCredentials = false
};
_handler.ClientCertificates.Add(clientCertificate);
}
public override HttpMessageHandler Handler
{
get
{
return _handler;
}
}
public override bool IsTlsCredentials()
{
return true;
}
public override void Dispose()
{
_handler.Dispose();
}
}
} | using System.Net;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Net.Http.Client;
namespace Docker.DotNet.X509
{
public class CertificateCredentials : Credentials
{
private X509Certificate2 _certificate;
public CertificateCredentials(X509Certificate2 clientCertificate)
{
_certificate = clientCertificate;
}
public override HttpMessageHandler GetHandler(HttpMessageHandler innerHandler)
{
var handler = (ManagedHandler)innerHandler;
handler.ClientCertificates = new X509CertificateCollection
{
_certificate
};
handler.ServerCertificateValidationCallback = ServicePointManager.ServerCertificateValidationCallback;
return handler;
}
public override bool IsTlsCredentials()
{
return true;
}
public override void Dispose()
{
}
}
} |
Rename listened table in migration |
using FluentMigrator;
namespace Azimuth.Migrations
{
[Migration(201409101200)]
public class Migration_201409101200_RemoveListenedTableAndAddCounterToPlaylistTable: Migration
{
public override void Up()
{
Delete.Table("Listened");
Alter.Table("Playlists").AddColumn("Listened").AsInt64().WithDefaultValue(0);
}
public override void Down()
{
Create.Table("UnauthorizedListeners")
.WithColumn("Id").AsInt64().NotNullable().Identity().PrimaryKey()
.WithColumn("PlaylistId").AsInt64().NotNullable().ForeignKey("Playlists", "PlaylistsId")
.WithColumn("Amount").AsInt64().NotNullable();
Delete.Column("Listened").FromTable("Playlists");
}
}
}
|
using FluentMigrator;
namespace Azimuth.Migrations
{
[Migration(201409101200)]
public class Migration_201409101200_RemoveListenedTableAndAddCounterToPlaylistTable: Migration
{
public override void Up()
{
Delete.Table("Listened");
Alter.Table("Playlists").AddColumn("Listened").AsInt64().WithDefaultValue(0);
}
public override void Down()
{
Create.Table("Listened")
.WithColumn("Id").AsInt64().NotNullable().Identity().PrimaryKey()
.WithColumn("PlaylistId").AsInt64().NotNullable().ForeignKey("Playlists", "PlaylistsId")
.WithColumn("Amount").AsInt64().NotNullable();
Delete.Column("Listened").FromTable("Playlists");
}
}
}
|
Include Fact attribute on test method | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MathParser.Tests
{
public class InfixLexicalAnalyzerTest
{
public void Expressao_binaria_simples_com_espacos()
{
//var analyzer = new InfixLexicalAnalyzer();
//analyzer.Analyze("2 + 2");
}
}
}
| using Xunit;
namespace MathParser.Tests
{
public class InfixLexicalAnalyzerTest
{
[Fact]
public void Expressao_binaria_simples_com_espacos()
{
//var analyzer = new InfixLexicalAnalyzer();
//analyzer.Analyze("2 + 2");
}
}
}
|
Update servicepointmanager to use newer TLS | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Synapse.RestClient.Transaction;
namespace Synapse.RestClient
{
using User;
using Node;
public class SynapseRestClientFactory
{
private SynapseApiCredentials _creds;
private string _baseUrl;
public SynapseRestClientFactory(SynapseApiCredentials credentials, string baseUrl)
{
this._creds = credentials;
this._baseUrl = baseUrl;
}
public ISynapseUserApiClient CreateUserClient()
{
return new SynapseUserApiClient(this._creds, this._baseUrl);
}
public ISynapseNodeApiClient CreateNodeClient()
{
return new SynapseNodeApiClient(this._creds, this._baseUrl);
}
public ISynapseTransactionApiClient CreateTransactionClient()
{
return new SynapseTransactionApiClient(this._creds, this._baseUrl);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Synapse.RestClient.Transaction;
namespace Synapse.RestClient
{
using User;
using Node;
using System.Net;
public class SynapseRestClientFactory
{
private SynapseApiCredentials _creds;
private string _baseUrl;
public SynapseRestClientFactory(SynapseApiCredentials credentials, string baseUrl)
{
this._creds = credentials;
this._baseUrl = baseUrl;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
}
public ISynapseUserApiClient CreateUserClient()
{
return new SynapseUserApiClient(this._creds, this._baseUrl);
}
public ISynapseNodeApiClient CreateNodeClient()
{
return new SynapseNodeApiClient(this._creds, this._baseUrl);
}
public ISynapseTransactionApiClient CreateTransactionClient()
{
return new SynapseTransactionApiClient(this._creds, this._baseUrl);
}
}
}
|
Add missing "using geckofx" for mono build | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Bloom;
using Bloom.MiscUI;
using NUnit.Framework;
namespace BloomTests
{
[TestFixture]
#if __MonoCS__
[RequiresSTA]
#endif
public class ProblemReporterDialogTests
{
[TestFixtureSetUp]
public void FixtureSetup()
{
Browser.SetUpXulRunner();
}
[TestFixtureTearDown]
public void FixtureTearDown()
{
#if __MonoCS__
// Doing this in Windows works on dev machines but somehow freezes the TC test runner
Xpcom.Shutdown();
#endif
}
/// <summary>
/// This is just a smoke-test that will notify us if the SIL JIRA stops working with the API we're relying on.
/// It sends reports to https://jira.sil.org/browse/AUT
/// </summary>
[Test]
public void CanSubmitToSILJiraAutomatedTestProject()
{
using (var dlg = new ProblemReporterDialog(null, null))
{
dlg.SetupForUnitTest("AUT");
dlg.ShowDialog();
}
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Bloom;
using Bloom.MiscUI;
using NUnit.Framework;
#if __MonoCS__
using Gecko;
#endif
namespace BloomTests
{
[TestFixture]
#if __MonoCS__
[RequiresSTA]
#endif
public class ProblemReporterDialogTests
{
[TestFixtureSetUp]
public void FixtureSetup()
{
Browser.SetUpXulRunner();
}
[TestFixtureTearDown]
public void FixtureTearDown()
{
#if __MonoCS__
// Doing this in Windows works on dev machines but somehow freezes the TC test runner
Xpcom.Shutdown();
#endif
}
/// <summary>
/// This is just a smoke-test that will notify us if the SIL JIRA stops working with the API we're relying on.
/// It sends reports to https://jira.sil.org/browse/AUT
/// </summary>
[Test]
public void CanSubmitToSILJiraAutomatedTestProject()
{
using (var dlg = new ProblemReporterDialog(null, null))
{
dlg.SetupForUnitTest("AUT");
dlg.ShowDialog();
}
}
}
} |
Add client for simple call | using System;
namespace HelloClient
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
| using System;
using Grpc.Core;
using Hello;
namespace HelloClient
{
class Program
{
public static void Main(string[] args)
{
Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure);
var client = new HelloService.HelloServiceClient(channel);
String user = "Euler";
var reply = client.SayHello(new HelloReq { Name = user });
Console.WriteLine(reply.Result);
channel.ShutdownAsync().Wait();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
|
Throw 404 when you can't find the node | using System;
using System.Collections.Generic;
namespace WebNoodle
{
public static class NodeHelper
{
public static IEnumerable<object> YieldChildren(this object node, string path, bool breakOnNull = false)
{
path = string.IsNullOrWhiteSpace(path) ? "/" : path;
yield return node;
var parts = (path).Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (var part in parts)
{
node = node.GetChild(part);
if (node == null)
{
if (breakOnNull) yield break;
throw new Exception("Node '" + part + "' not found in path '" + path + "'");
}
yield return node;
}
}
}
} | using System;
using System.Collections.Generic;
using System.Web;
namespace WebNoodle
{
public static class NodeHelper
{
public static IEnumerable<object> YieldChildren(this object node, string path, bool breakOnNull = false)
{
path = string.IsNullOrWhiteSpace(path) ? "/" : path;
yield return node;
var parts = (path).Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (var part in parts)
{
node = node.GetChild(part);
if (node == null)
{
if (breakOnNull) yield break;
throw new HttpException(404, "Node '" + part + "' not found in path '" + path + "'");
}
yield return node;
}
}
}
} |
Make FPS counter to a GameComponent | using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
namespace MonoGame.Extended
{
public class FramesPerSecondCounter : IUpdate
{
public FramesPerSecondCounter(int maximumSamples = 100)
{
MaximumSamples = maximumSamples;
}
private readonly Queue<float> _sampleBuffer = new Queue<float>();
public long TotalFrames { get; private set; }
public float AverageFramesPerSecond { get; private set; }
public float CurrentFramesPerSecond { get; private set; }
public int MaximumSamples { get; }
public void Reset()
{
TotalFrames = 0;
_sampleBuffer.Clear();
}
public void Update(float deltaTime)
{
CurrentFramesPerSecond = 1.0f / deltaTime;
_sampleBuffer.Enqueue(CurrentFramesPerSecond);
if (_sampleBuffer.Count > MaximumSamples)
{
_sampleBuffer.Dequeue();
AverageFramesPerSecond = _sampleBuffer.Average(i => i);
}
else
{
AverageFramesPerSecond = CurrentFramesPerSecond;
}
TotalFrames++;
}
public void Update(GameTime gameTime)
{
Update((float)gameTime.ElapsedGameTime.TotalSeconds);
}
}
}
| using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
namespace MonoGame.Extended
{
public class FramesPerSecondCounter : DrawableGameComponent
{
public FramesPerSecondCounter(Game game, int maximumSamples = 100)
:base(game)
{
MaximumSamples = maximumSamples;
}
private readonly Queue<float> _sampleBuffer = new Queue<float>();
public long TotalFrames { get; private set; }
public float AverageFramesPerSecond { get; private set; }
public float CurrentFramesPerSecond { get; private set; }
public int MaximumSamples { get; }
public void Reset()
{
TotalFrames = 0;
_sampleBuffer.Clear();
}
public void UpdateFPS(float deltaTime)
{
CurrentFramesPerSecond = 1.0f / deltaTime;
_sampleBuffer.Enqueue(CurrentFramesPerSecond);
if (_sampleBuffer.Count > MaximumSamples)
{
_sampleBuffer.Dequeue();
AverageFramesPerSecond = _sampleBuffer.Average(i => i);
}
else
{
AverageFramesPerSecond = CurrentFramesPerSecond;
}
TotalFrames++;
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
}
public override void Draw(GameTime gameTime)
{
UpdateFPS((float)gameTime.ElapsedGameTime.TotalSeconds);
base.Draw(gameTime);
}
}
}
|
Fix tests failing due to not being updated with new behaviour | // 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.Globalization;
using NUnit.Framework;
using osu.Framework.Localisation;
namespace osu.Framework.Tests.Localisation
{
[TestFixture]
public class CultureInfoHelperTest
{
private const string invariant_culture = "";
[TestCase("en-US", true, "en-US")]
[TestCase("invalid name", false, invariant_culture)]
[TestCase(invariant_culture, true, invariant_culture)]
[TestCase("ko_KR", false, invariant_culture)]
public void TestTryGetCultureInfo(string name, bool expectedReturnValue, string expectedCultureName)
{
CultureInfo expectedCulture;
switch (expectedCultureName)
{
case invariant_culture:
expectedCulture = CultureInfo.InvariantCulture;
break;
default:
expectedCulture = CultureInfo.GetCultureInfo(expectedCultureName);
break;
}
bool retVal = CultureInfoHelper.TryGetCultureInfo(name, out var culture);
Assert.That(retVal, Is.EqualTo(expectedReturnValue));
Assert.That(culture, Is.EqualTo(expectedCulture));
}
}
}
| // 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.Globalization;
using NUnit.Framework;
using osu.Framework.Localisation;
namespace osu.Framework.Tests.Localisation
{
[TestFixture]
public class CultureInfoHelperTest
{
private const string system_culture = "";
[TestCase("en-US", true, "en-US")]
[TestCase("invalid name", false, system_culture)]
[TestCase(system_culture, true, system_culture)]
[TestCase("ko_KR", false, system_culture)]
public void TestTryGetCultureInfo(string name, bool expectedReturnValue, string expectedCultureName)
{
CultureInfo expectedCulture;
switch (expectedCultureName)
{
case system_culture:
expectedCulture = CultureInfo.CurrentCulture;
break;
default:
expectedCulture = CultureInfo.GetCultureInfo(expectedCultureName);
break;
}
bool retVal = CultureInfoHelper.TryGetCultureInfo(name, out var culture);
Assert.That(retVal, Is.EqualTo(expectedReturnValue));
Assert.That(culture, Is.EqualTo(expectedCulture));
}
}
}
|
Handle Mongo ObjectId references better | // Copyright (c) 2015 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
namespace LfMerge.LanguageForge.Model
{
public class LfAuthorInfo : LfFieldBase
{
public string CreatedByUserRef { get; set; }
public DateTime CreatedDate { get; set; }
public string ModifiedByUserRef { get; set; }
public DateTime ModifiedDate { get; set; }
}
}
| // Copyright (c) 2015 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using MongoDB.Bson;
namespace LfMerge.LanguageForge.Model
{
public class LfAuthorInfo : LfFieldBase
{
public ObjectId? CreatedByUserRef { get; set; }
public DateTime CreatedDate { get; set; }
public ObjectId? ModifiedByUserRef { get; set; }
public DateTime ModifiedDate { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.