commit
stringlengths
40
40
old_file
stringlengths
4
237
new_file
stringlengths
4
237
old_contents
stringlengths
1
4.24k
new_contents
stringlengths
1
4.87k
subject
stringlengths
15
778
message
stringlengths
15
8.75k
lang
stringclasses
266 values
license
stringclasses
13 values
repos
stringlengths
5
127k
79d4fb4d25f2bc6186ee72aa58ecf25d30d5d333
TestMoya.Runner/Runners/TimerDecoratorTests.cs
TestMoya.Runner/Runners/TimerDecoratorTests.cs
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); } } } }
Make sure timerdecoratortest always succeeds
Make sure timerdecoratortest always succeeds
C#
mit
Hammerstad/Moya
4b8bbfc78d6169092cdde5002cc9fe808c621cb4
src/CGO.Web/Views/Shared/_Sidebar.cshtml
src/CGO.Web/Views/Shared/_Sidebar.cshtml
@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> } }
Tidy up the display of the side bar.
Tidy up the display of the side bar. Upgrade the classes to Bootstrap 3.
C#
mit
alastairs/cgowebsite,alastairs/cgowebsite
de968c1842027d55da5d639782cad31b90fae2c7
src/Leeroy/Program.cs
src/Leeroy/Program.cs
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); } }
Allow Leeroy to run until canceled in test mode.
Allow Leeroy to run until canceled in test mode.
C#
mit
LogosBible/Leeroy
4cde3fd9872ed0fa801c45acb9c2850e31c1738c
src/Couchbase.Lite.Support.NetDesktop/Support/DefaultDirectoryResolver.cs
src/Couchbase.Lite.Support.NetDesktop/Support/DefaultDirectoryResolver.cs
// // 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 } }
Revert change to .NET desktop default directory logic
Revert change to .NET desktop default directory logic It was causing DB creation in the nuget package folder Fixes #1108
C#
apache-2.0
couchbase/couchbase-lite-net,couchbase/couchbase-lite-net,couchbase/couchbase-lite-net
1310e2d6c1eb586b445c3fdf2133e622b45a33a5
data/layouts/default/StaticContentModule.cs
data/layouts/default/StaticContentModule.cs
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 (); } } }
Make sure to End StaticContent.
Make sure to End StaticContent.
C#
mit
jacksonh/manos,mdavid/manos-spdy,jmptrader/manos,mdavid/manos-spdy,jacksonh/manos,jmptrader/manos,jacksonh/manos,jmptrader/manos,jmptrader/manos,jacksonh/manos,mdavid/manos-spdy,jmptrader/manos,jacksonh/manos,mdavid/manos-spdy,jmptrader/manos,mdavid/manos-spdy,jmptrader/manos,mdavid/manos-spdy,jacksonh/manos,jacksonh/manos,mdavid/manos-spdy,jacksonh/manos,jmptrader/manos
793acfe174786431d7ffb20cddeb4be28b95199c
src/MagicOnion.Server/ReturnStatusException.cs
src/MagicOnion.Server/ReturnStatusException.cs
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 ?? ""); } } }
Set an exception message for ReturnStatusMessage
Set an exception message for ReturnStatusMessage
C#
mit
neuecc/MagicOnion
c775562d917749a72052298a9df49284a360009b
Tests/Serilog.Exceptions.Test/GlobalSuppressions.cs
Tests/Serilog.Exceptions.Test/GlobalSuppressions.cs
// 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")]
Enlarge the scope of SA1600 supression to whole test project
Enlarge the scope of SA1600 supression to whole test project
C#
mit
RehanSaeed/Serilog.Exceptions,RehanSaeed/Serilog.Exceptions
e5c0b8168763adc0d98fdc7883a4711a32a6e372
Bumblebee/Interfaces/ITextField.cs
Bumblebee/Interfaces/ITextField.cs
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); } }
Allow noop on text fields
Allow noop on text fields
C#
mit
kool79/Bumblebee,chrisblock/Bumblebee,chrisblock/Bumblebee,Bumblebee/Bumblebee,qchicoq/Bumblebee,kool79/Bumblebee,qchicoq/Bumblebee,toddmeinershagen/Bumblebee,toddmeinershagen/Bumblebee,Bumblebee/Bumblebee
a71e52da4caf53c88b772263d4b7fb89090a34ec
osu.Game/Screens/Select/Filter/SortMode.cs
osu.Game/Screens/Select/Filter/SortMode.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.ComponentModel; namespace osu.Game.Screens.Select.Filter { public enum SortMode { [Description("Artist")] Artist, [Description("Author")] Author, [Description("BPM")] BPM, [Description("Date Added")] DateAdded, [Description("Difficulty")] Difficulty, [Description("Length")] Length, [Description("Rank Achieved")] RankAchieved, [Description("Title")] Title, [Description("Source")] Source, } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.ComponentModel; namespace osu.Game.Screens.Select.Filter { public enum SortMode { [Description("Artist")] Artist, [Description("Author")] Author, [Description("BPM")] BPM, [Description("Date Added")] DateAdded, [Description("Difficulty")] Difficulty, [Description("Length")] Length, [Description("Rank Achieved")] RankAchieved, [Description("Source")] Source, [Description("Title")] Title, } }
Fix enum ordering after adding source
Fix enum ordering after adding source
C#
mit
peppy/osu,peppy/osu-new,peppy/osu,smoogipoo/osu,ppy/osu,ppy/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,UselessToucan/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu
c6fb842a7210c4e8f690518ea86d244cb4643f3b
AssemblyInfo.Shared.cs
AssemblyInfo.Shared.cs
//----------------------------------------------------------------------- // <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)]
Change version number to 2.2.1
Change version number to 2.2.1
C#
mit
SonarSource-VisualStudio/sonar-scanner-msbuild,SonarSource/sonar-msbuild-runner,SonarSource-VisualStudio/sonar-msbuild-runner,SonarSource-DotNet/sonar-msbuild-runner,duncanpMS/sonar-msbuild-runner,SonarSource-VisualStudio/sonar-scanner-msbuild,duncanpMS/sonar-msbuild-runner,SonarSource-VisualStudio/sonar-scanner-msbuild,SonarSource-VisualStudio/sonar-msbuild-runner,duncanpMS/sonar-msbuild-runner
6b493047b3268da50b1599172c1c099a4ede48cd
GUI/Controls/TreeViewFileSorter.cs
GUI/Controls/TreeViewFileSorter.cs
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); } } }
Check folders by its tag
Check folders by its tag
C#
mit
SteamDatabase/ValveResourceFormat
40c4fe26f048d7dcc87a6c92baffbcfb34a32a65
HALClient/HalClient.cs
HALClient/HalClient.cs
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; } } }
Add support for basic auth
Add support for basic auth
C#
apache-2.0
Xerosigma/halclient
de05c3628c006991f5f0129bb7031b70e638432f
src/SharpGraphEditor/Models/ZoomManager.cs
src/SharpGraphEditor/Models/ZoomManager.cs
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 bug with zoom when it didnt limit
Fix bug with zoom when it didnt limit
C#
apache-2.0
AceSkiffer/SharpGraphEditor
5da9f67c170cf3f601b7efca5a595091c1988760
Battery-Commander.Web/Jobs/SqliteBackupJob.cs
Battery-Commander.Web/Jobs/SqliteBackupJob.cs
using BatteryCommander.Web.Services; using FluentScheduler; using SendGrid.Helpers.Mail; using System; using System.Collections.Generic; namespace BatteryCommander.Web.Jobs { public class SqliteBackupJob : IJob { private const String Recipient = "mattgwagner+backup@gmail.com"; // TODO Make this configurable private readonly IEmailService emailSvc; public SqliteBackupJob(IEmailService emailSvc) { this.emailSvc = emailSvc; } public virtual void Execute() { var data = System.IO.File.ReadAllBytes("Data.db"); var encoded = System.Convert.ToBase64String(data); var message = new SendGridMessage { From = new EmailAddress("Battery-Commander@redlegdev.com"), Subject = "Nightly Db Backup", Contents = new List<Content>() { new Content { Type = "text/plain", Value = "Please find the nightly database backup attached." } }, Attachments = new List<Attachment>() { new Attachment { Filename = "Data.db", Type = "application/octet-stream", Content = encoded } } }; message.AddTo(Recipient); emailSvc.Send(message).Wait(); } } }
using BatteryCommander.Web.Services; using FluentScheduler; using SendGrid.Helpers.Mail; using System; using System.Collections.Generic; namespace BatteryCommander.Web.Jobs { public class SqliteBackupJob : IJob { private const String Recipient = "mattgwagner+backup@gmail.com"; // TODO Make this configurable private readonly IEmailService emailSvc; public SqliteBackupJob(IEmailService emailSvc) { this.emailSvc = emailSvc; } public virtual void Execute() { var data = System.IO.File.ReadAllBytes("Data.db"); var encoded = System.Convert.ToBase64String(data); var message = new SendGridMessage { From = EmailService.FROM_ADDRESS, Subject = "Nightly Db Backup", Contents = new List<Content>() { new Content { Type = "text/plain", Value = "Please find the nightly database backup attached." } }, Attachments = new List<Attachment>() { new Attachment { Filename = "Data.db", Type = "application/octet-stream", Content = encoded } } }; message.AddTo(Recipient); emailSvc.Send(message).Wait(); } } }
Use common from address for backup
Use common from address for backup
C#
mit
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
f6029b829d2c865aa54473b222d5408bb27c545a
PivotalTrackerDotNet/AAuthenticatedService.cs
PivotalTrackerDotNet/AAuthenticatedService.cs
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; } } }
Fix RestClient BaseUrl change to Uri
Fix RestClient BaseUrl change to Uri
C#
mit
Charcoals/PivotalTracker.NET,Charcoals/PivotalTracker.NET
215aa81735ca7644073d368f8093a9b3e11c5395
setup.cake
setup.cake
#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();
Exclude Shouldly from code coverage
Exclude Shouldly from code coverage
C#
mit
bbtsoftware/TfsUrlParser
90b04283f259e108ebce82b4f1180c73ded1d3a6
MimeBank/MimeChecker.cs
MimeBank/MimeChecker.cs
/* * 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)); } } }
Define a const for read buffer size
Define a const for read buffer size
C#
apache-2.0
detaybey/MimeBank
b3c482ad1f60f3226cc7ae693369a828bb166266
Framework.Core/System/Threading/MonitorEx.cs
Framework.Core/System/Threading/MonitorEx.cs
#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 } } }
Use static class for static methods.
Use static class for static methods.
C#
mit
theraot/Theraot
fb3576bda16ee05f0240f0bdac359dab788b4bc4
src/Nancy/ISerializer.cs
src/Nancy/ISerializer.cs
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); } }
Revert "Swapping Silly UK English ;)"
Revert "Swapping Silly UK English ;)" This reverts commit 3b10acc9f764cf31b2718abf906b28ce7d200cff.
C#
mit
jongleur1983/Nancy,MetSystem/Nancy,vladlopes/Nancy,thecodejunkie/Nancy,dbolkensteyn/Nancy,anton-gogolev/Nancy,malikdiarra/Nancy,hitesh97/Nancy,EliotJones/NancyTest,Novakov/Nancy,AcklenAvenue/Nancy,AIexandr/Nancy,jongleur1983/Nancy,JoeStead/Nancy,VQComms/Nancy,fly19890211/Nancy,asbjornu/Nancy,lijunle/Nancy,thecodejunkie/Nancy,AIexandr/Nancy,davidallyoung/Nancy,SaveTrees/Nancy,dbolkensteyn/Nancy,AlexPuiu/Nancy,cgourlay/Nancy,jongleur1983/Nancy,wtilton/Nancy,tparnell8/Nancy,jonathanfoster/Nancy,EliotJones/NancyTest,wtilton/Nancy,damianh/Nancy,thecodejunkie/Nancy,jmptrader/Nancy,tparnell8/Nancy,guodf/Nancy,joebuschmann/Nancy,sroylance/Nancy,adamhathcock/Nancy,NancyFx/Nancy,wtilton/Nancy,thecodejunkie/Nancy,phillip-haydon/Nancy,danbarua/Nancy,fly19890211/Nancy,grumpydev/Nancy,Worthaboutapig/Nancy,murador/Nancy,NancyFx/Nancy,grumpydev/Nancy,jchannon/Nancy,felipeleusin/Nancy,jmptrader/Nancy,fly19890211/Nancy,adamhathcock/Nancy,SaveTrees/Nancy,damianh/Nancy,tareq-s/Nancy,khellang/Nancy,charleypeng/Nancy,phillip-haydon/Nancy,anton-gogolev/Nancy,cgourlay/Nancy,phillip-haydon/Nancy,rudygt/Nancy,ccellar/Nancy,nicklv/Nancy,danbarua/Nancy,felipeleusin/Nancy,felipeleusin/Nancy,sadiqhirani/Nancy,grumpydev/Nancy,asbjornu/Nancy,nicklv/Nancy,jonathanfoster/Nancy,murador/Nancy,sloncho/Nancy,guodf/Nancy,jeff-pang/Nancy,JoeStead/Nancy,ayoung/Nancy,albertjan/Nancy,sroylance/Nancy,xt0rted/Nancy,VQComms/Nancy,jeff-pang/Nancy,jchannon/Nancy,dbabox/Nancy,jeff-pang/Nancy,jchannon/Nancy,ccellar/Nancy,vladlopes/Nancy,dbabox/Nancy,nicklv/Nancy,dbolkensteyn/Nancy,jmptrader/Nancy,tsdl2013/Nancy,nicklv/Nancy,duszekmestre/Nancy,Worthaboutapig/Nancy,jongleur1983/Nancy,horsdal/Nancy,JoeStead/Nancy,davidallyoung/Nancy,EIrwin/Nancy,guodf/Nancy,ayoung/Nancy,cgourlay/Nancy,albertjan/Nancy,tparnell8/Nancy,grumpydev/Nancy,cgourlay/Nancy,Novakov/Nancy,jchannon/Nancy,AlexPuiu/Nancy,AlexPuiu/Nancy,duszekmestre/Nancy,sloncho/Nancy,ayoung/Nancy,khellang/Nancy,sadiqhirani/Nancy,horsdal/Nancy,Novakov/Nancy,EliotJones/NancyTest,vladlopes/Nancy,rudygt/Nancy,SaveTrees/Nancy,jonathanfoster/Nancy,xt0rted/Nancy,fly19890211/Nancy,sadiqhirani/Nancy,sroylance/Nancy,charleypeng/Nancy,asbjornu/Nancy,daniellor/Nancy,AIexandr/Nancy,JoeStead/Nancy,tareq-s/Nancy,blairconrad/Nancy,joebuschmann/Nancy,guodf/Nancy,horsdal/Nancy,xt0rted/Nancy,sloncho/Nancy,SaveTrees/Nancy,davidallyoung/Nancy,malikdiarra/Nancy,charleypeng/Nancy,khellang/Nancy,anton-gogolev/Nancy,asbjornu/Nancy,ccellar/Nancy,rudygt/Nancy,jonathanfoster/Nancy,jmptrader/Nancy,blairconrad/Nancy,felipeleusin/Nancy,tsdl2013/Nancy,tareq-s/Nancy,NancyFx/Nancy,albertjan/Nancy,EIrwin/Nancy,joebuschmann/Nancy,rudygt/Nancy,vladlopes/Nancy,charleypeng/Nancy,danbarua/Nancy,Worthaboutapig/Nancy,tsdl2013/Nancy,tparnell8/Nancy,ccellar/Nancy,albertjan/Nancy,damianh/Nancy,tsdl2013/Nancy,dbabox/Nancy,davidallyoung/Nancy,AlexPuiu/Nancy,EIrwin/Nancy,khellang/Nancy,murador/Nancy,MetSystem/Nancy,dbolkensteyn/Nancy,sroylance/Nancy,adamhathcock/Nancy,wtilton/Nancy,sadiqhirani/Nancy,AcklenAvenue/Nancy,MetSystem/Nancy,AIexandr/Nancy,asbjornu/Nancy,blairconrad/Nancy,AcklenAvenue/Nancy,AcklenAvenue/Nancy,VQComms/Nancy,hitesh97/Nancy,VQComms/Nancy,daniellor/Nancy,danbarua/Nancy,lijunle/Nancy,NancyFx/Nancy,xt0rted/Nancy,blairconrad/Nancy,duszekmestre/Nancy,malikdiarra/Nancy,daniellor/Nancy,adamhathcock/Nancy,ayoung/Nancy,tareq-s/Nancy,dbabox/Nancy,malikdiarra/Nancy,jchannon/Nancy,lijunle/Nancy,hitesh97/Nancy,joebuschmann/Nancy,EIrwin/Nancy,horsdal/Nancy,charleypeng/Nancy,lijunle/Nancy,phillip-haydon/Nancy,Novakov/Nancy,hitesh97/Nancy,jeff-pang/Nancy,MetSystem/Nancy,EliotJones/NancyTest,sloncho/Nancy,AIexandr/Nancy,duszekmestre/Nancy,davidallyoung/Nancy,anton-gogolev/Nancy,daniellor/Nancy,VQComms/Nancy,murador/Nancy,Worthaboutapig/Nancy
ea1c50db7b9f8f57439d01ddac9ec462c9fd5ad0
src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs
src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs
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; } } }
Add OrderingDomainException when the order doesn't exist with id orderId
Add OrderingDomainException when the order doesn't exist with id orderId
C#
mit
skynode/eShopOnContainers,andrelmp/eShopOnContainers,skynode/eShopOnContainers,productinfo/eShopOnContainers,productinfo/eShopOnContainers,productinfo/eShopOnContainers,albertodall/eShopOnContainers,TypeW/eShopOnContainers,skynode/eShopOnContainers,albertodall/eShopOnContainers,dotnet-architecture/eShopOnContainers,dotnet-architecture/eShopOnContainers,andrelmp/eShopOnContainers,dotnet-architecture/eShopOnContainers,andrelmp/eShopOnContainers,productinfo/eShopOnContainers,productinfo/eShopOnContainers,TypeW/eShopOnContainers,productinfo/eShopOnContainers,albertodall/eShopOnContainers,TypeW/eShopOnContainers,andrelmp/eShopOnContainers,dotnet-architecture/eShopOnContainers,TypeW/eShopOnContainers,skynode/eShopOnContainers,albertodall/eShopOnContainers,albertodall/eShopOnContainers,skynode/eShopOnContainers,andrelmp/eShopOnContainers,TypeW/eShopOnContainers,dotnet-architecture/eShopOnContainers,andrelmp/eShopOnContainers
2485f6692f988393c354d5f4e9af0b962622e976
Control/WatchDogManager.cs
Control/WatchDogManager.cs
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()); } } } } }
Handle oddity in watchdog naming convention
Handle oddity in watchdog naming convention
C#
agpl-3.0
dasgarner/xibo-dotnetclient,xibosignage/xibo-dotnetclient
862f0e0d2ecb61a86faa9100469422705f8bf622
src/BloomExe/web/controllers/KeybordingConfigAPI.cs
src/BloomExe/web/controllers/KeybordingConfigAPI.cs
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); } } }
Fix BL-3614 Crash while checking for keyman
Fix BL-3614 Crash while checking for keyman I wasn't able to reproduce the crash, but I made it not require UI thread and catch any errors and report them passively.
C#
mit
StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop
b1dc7bbda59c05193ef1e5dcfad44f69dcfb0cb0
src/Noobot.Core/Configuration/ConfigReader.cs
src/Noobot.Core/Configuration/ConfigReader.cs
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; } } }
Allow config.json path to work on non-Windows OS
Allow config.json path to work on non-Windows OS Changed the config.json path so it works on non-Windows OS where forward slashes are used instead of backslashes.
C#
mit
Workshop2/noobot,noobot/noobot
63d44d313f9c838326785ea3ca3d5b4654e9c262
src/wp8/FileOpener2.cs
src/wp8/FileOpener2.cs
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); } } } }
Add support for local folder
[WP8] Add support for local folder If file wasnt found then path is assumed to be relative path to local directory
C#
mit
tectronik/cordova-plugin-file-opener2-tectronik,tectronik/cordova-plugin-file-opener2-tectronik,tectronik/cordova-plugin-file-opener2-tectronik
3a6a3a067b4816b81bf1851b75640a8e73349221
osu.Game.Tests/Visual/Online/TestSceneAccountCreationOverlay.cs
osu.Game.Tests/Visual/Online/TestSceneAccountCreationOverlay.cs
// 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); } } }
Rewrite test to cover failure case
Rewrite test to cover failure case
C#
mit
smoogipooo/osu,peppy/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu-new,smoogipoo/osu,NeoAdonis/osu,peppy/osu,ppy/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,ppy/osu
88642323010d16b48740d178e53cd6342c58f113
zipkin4net-aspnetcore/Criteo.Profiling.Tracing.Middleware/TracingMiddleware.cs
zipkin4net-aspnetcore/Criteo.Profiling.Tracing.Middleware/TracingMiddleware.cs
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()); } }); } } }
Add http.host and http.path annotations
Add http.host and http.path annotations
C#
apache-2.0
criteo/zipkin4net,criteo/zipkin4net
e3274ed908492ff478076da270c6ba1071b27034
Source/TranslationTest/MainWindowTranslation.cs
Source/TranslationTest/MainWindowTranslation.cs
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 translation work with inheritance
Make translation work with inheritance
C#
mit
pdfforge/translatable
05ae25fb6943689897b2b6578353f7da6581ee98
osu.Framework.Tests/Input/KeyCombinationTest.cs
osu.Framework.Tests/Input/KeyCombinationTest.cs
// 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)); } }
Make tests actually test the string output
Make tests actually test the string output
C#
mit
smoogipooo/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework
2524ebb93f0ae26d3f8a6ec495e6af82034375fe
DapperTesting/Core/Data/DapperPostRepository.cs
DapperTesting/Core/Data/DapperPostRepository.cs
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(); } } }
Add basic Get for a post
Add basic Get for a post
C#
mit
tvanfosson/dapper-integration-testing
4344d78a4d960a71490a186f822a5b9c94a3bbb8
src/SevenDigital.Api.Wrapper.Integration.Tests/Exceptions/ErrorConditionTests.cs
src/SevenDigital.Api.Wrapper.Integration.Tests/Exceptions/ErrorConditionTests.cs
using System; using NUnit.Framework; using SevenDigital.Api.Schema; using SevenDigital.Api.Wrapper.Exceptions; using SevenDigital.Api.Schema.ArtistEndpoint; using SevenDigital.Api.Schema.LockerEndpoint; namespace SevenDigital.Api.Wrapper.Integration.Tests.Exceptions { [TestFixture] public class ErrorConditionTests { [Test] public void Should_fail_with_input_parameter_exception_if_xml_error_returned() { // -- Deliberate error response Console.WriteLine("Trying artist/details without artistId parameter..."); var apiXmlException = Assert.Throws<InputParameterException>(() => Api<Artist>.Create.Please()); Assert.That(apiXmlException.ErrorCode, Is.EqualTo(ErrorCode.RequiredParameterMissing)); Assert.That(apiXmlException.Message, Is.EqualTo("Missing parameter artistId")); } [Test] public void Should_fail_with_non_xml_exception_if_plaintext_error_returned_eg_unauthorised() { // -- Deliberate unauthorized response Console.WriteLine("Trying user/locker without any credentials..."); var apiXmlException = Assert.Throws<OAuthException>(() => Api<Locker>.Create.Please()); Assert.That(apiXmlException.ResponseBody, Is.EqualTo("OAuth authentication error: Resource requires access token")); } } }
using System; using NUnit.Framework; using SevenDigital.Api.Schema; using SevenDigital.Api.Wrapper.Exceptions; using SevenDigital.Api.Schema.ArtistEndpoint; using SevenDigital.Api.Schema.LockerEndpoint; namespace SevenDigital.Api.Wrapper.Integration.Tests.Exceptions { [TestFixture] public class ErrorConditionTests { [Test] public void Should_fail_with_input_parameter_exception_if_xml_error_returned() { // -- Deliberate error response Console.WriteLine("Trying artist/details without artistId parameter..."); var apiXmlException = Assert.Throws<InputParameterException>(() => Api<Artist>.Create.Please()); Assert.That(apiXmlException.ErrorCode, Is.EqualTo(ErrorCode.RequiredParameterMissing)); Assert.That(apiXmlException.Message, Is.StringStarting("Missing parameter artistId")); } [Test] public void Should_fail_with_non_xml_exception_if_plaintext_error_returned_eg_unauthorised() { // -- Deliberate unauthorized response Console.WriteLine("Trying user/locker without any credentials..."); var apiXmlException = Assert.Throws<OAuthException>(() => Api<Locker>.Create.Please()); Assert.That(apiXmlException.ResponseBody, Is.EqualTo("OAuth authentication error: Resource requires access token")); } } }
Make inputexception message tests more robust
Make inputexception message tests more robust
C#
mit
gregsochanik/SevenDigital.Api.Wrapper,danbadge/SevenDigital.Api.Wrapper,emashliles/SevenDigital.Api.Wrapper,bnathyuw/SevenDigital.Api.Wrapper,bettiolo/SevenDigital.Api.Wrapper,AnthonySteele/SevenDigital.Api.Wrapper,mattgray/SevenDigital.Api.Wrapper,danhaller/SevenDigital.Api.Wrapper,luiseduardohdbackup/SevenDigital.Api.Wrapper,raoulmillais/SevenDigital.Api.Wrapper,minkaotic/SevenDigital.Api.Wrapper
5a02e477bfc0f52a9fb273faaa3b574517999aee
NuGet.Extensions.Tests/TestData/Isolation.cs
NuGet.Extensions.Tests/TestData/Isolation.cs
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)); } } }
Create temp directories in temp folder
Create temp directories in temp folder
C#
mit
BenPhegan/NuGet.Extensions
37ef42a633586abc13e43bdad74731b25ad55742
examples/dotnetcore2.0/Function.cs
examples/dotnetcore2.0/Function.cs
// 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 RemainingTime and env vars to dotnetcore2.0 example
Add RemainingTime and env vars to dotnetcore2.0 example
C#
mit
lambci/docker-lambda,lambci/docker-lambda,lambci/docker-lambda,lambci/docker-lambda,lambci/docker-lambda,lambci/docker-lambda,lambci/docker-lambda
3b25539b725493d8d8de9d858c1e7636061aca44
src/GitVersionTask.Tests/GetVersionTaskTests.cs
src/GitVersionTask.Tests/GetVersionTaskTests.cs
using System.Linq; using GitVersion; using GitVersionTask; using Microsoft.Build.Framework; using NUnit.Framework; using Shouldly; [TestFixture] public class GetVersionTaskTests { [Test] public void OutputsShouldMatchVariableProvider() { var taskProperties = typeof(GetVersion) .GetProperties() .Where(p => p.GetCustomAttributes(typeof(OutputAttribute), false).Any()) .Select(p => p.Name); var variablesProperties = typeof(VersionVariables) .GetProperties() .Select(p => p.Name) .Except(new[] { "AvailableVariables", "Item" }); taskProperties.ShouldBe(variablesProperties, ignoreOrder: true); } }
using System.Linq; using GitVersion; using GitVersionTask; using Microsoft.Build.Framework; using NUnit.Framework; using Shouldly; [TestFixture] public class GetVersionTaskTests { [Test] public void OutputsShouldMatchVariableProvider() { var taskProperties = typeof(GetVersion) .GetProperties() .Where(p => p.GetCustomAttributes(typeof(OutputAttribute), false).Any()) .Select(p => p.Name); var variablesProperties = VersionVariables.AvailableVariables; taskProperties.ShouldBe(variablesProperties, ignoreOrder: true); } }
Use the AvailableVariables property instead of doing GetProperties() everywhere.
Use the AvailableVariables property instead of doing GetProperties() everywhere.
C#
mit
ermshiperete/GitVersion,dpurge/GitVersion,ermshiperete/GitVersion,dpurge/GitVersion,gep13/GitVersion,Philo/GitVersion,pascalberger/GitVersion,onovotny/GitVersion,asbjornu/GitVersion,onovotny/GitVersion,onovotny/GitVersion,dpurge/GitVersion,gep13/GitVersion,DanielRose/GitVersion,dpurge/GitVersion,pascalberger/GitVersion,ermshiperete/GitVersion,JakeGinnivan/GitVersion,ParticularLabs/GitVersion,FireHost/GitVersion,dazinator/GitVersion,dazinator/GitVersion,asbjornu/GitVersion,DanielRose/GitVersion,ParticularLabs/GitVersion,JakeGinnivan/GitVersion,GitTools/GitVersion,DanielRose/GitVersion,ermshiperete/GitVersion,GitTools/GitVersion,Philo/GitVersion,FireHost/GitVersion,JakeGinnivan/GitVersion,pascalberger/GitVersion,JakeGinnivan/GitVersion
8442489aa773a11609da66cf732f7099a3e7b2f4
WundergroundClient/Autocomplete/AutocompleteRequest.cs
WundergroundClient/Autocomplete/AutocompleteRequest.cs
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() //{ //} } }
Add comments to constructors, use constructor chaining.
Add comments to constructors, use constructor chaining.
C#
mit
jcheng31/WundergroundAutocomplete.NET
7c00a9944936a22aab6e59c51a6fbe2b4cacfbf4
OpenStardriveServer/HostedServices/ServerInitializationService.cs
OpenStardriveServer/HostedServices/ServerInitializationService.cs
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"); } }
Initialize the server with a report-state command
Initialize the server with a report-state command
C#
apache-2.0
openstardrive/server,openstardrive/server,openstardrive/server
4e6b240e77c80ee4e0ebef669d4f62b68c54ad47
apis/Google.Cloud.Translation.V2/Google.Cloud.Translation.V2.Tests/CodeHealthTest.cs
apis/Google.Cloud.Translation.V2/Google.Cloud.Translation.V2.Tests/CodeHealthTest.cs
// 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)); } } }
Clean up Translation code health test
Clean up Translation code health test (This is somewhat unrelated to the AdvancedTranslationClient work, hence the separate commit.)
C#
apache-2.0
evildour/google-cloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,iantalarico/google-cloud-dotnet,benwulfe/google-cloud-dotnet,jskeet/google-cloud-dotnet,evildour/google-cloud-dotnet,chrisdunelm/google-cloud-dotnet,googleapis/google-cloud-dotnet,googleapis/google-cloud-dotnet,chrisdunelm/gcloud-dotnet,benwulfe/google-cloud-dotnet,iantalarico/google-cloud-dotnet,jskeet/google-cloud-dotnet,chrisdunelm/google-cloud-dotnet,evildour/google-cloud-dotnet,chrisdunelm/google-cloud-dotnet,benwulfe/google-cloud-dotnet,iantalarico/google-cloud-dotnet,jskeet/gcloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet
3e828a6521917bb2d0eac85b7f3668ff73415bae
Casper.Mvc/Casper.Mvc/Views/Home/Index.cshtml
Casper.Mvc/Casper.Mvc/Views/Home/Index.cshtml
@{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 second build step from TC, thanks to Sean
Remove second build step from TC, thanks to Sean
C#
mit
rippo/testing.casperjs.presentation.vscode.50mins,rippo/testing.casperjs.presentation.vscode.50mins,rippo/testing.casperjs.presentation.vscode.50mins,rippo/testing.casperjs.presentation.vscode.50mins
47e00887a29a2a468cd920c1e548e00cbc6cf468
src/NodaTime.Test/Annotations/MutabilityTest.cs
src/NodaTime.Test/Annotations/MutabilityTest.cs
// 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))); } } }
Remove some spurious Console.WriteLine() calls from a test.
Remove some spurious Console.WriteLine() calls from a test.
C#
apache-2.0
BenJenkinson/nodatime,malcolmr/nodatime,malcolmr/nodatime,jskeet/nodatime,nodatime/nodatime,zaccharles/nodatime,zaccharles/nodatime,zaccharles/nodatime,malcolmr/nodatime,zaccharles/nodatime,zaccharles/nodatime,jskeet/nodatime,nodatime/nodatime,zaccharles/nodatime,BenJenkinson/nodatime,malcolmr/nodatime
0b4a36b6a62eaa5435ddb949e864025e32d9cce8
src/Services/HourlyAndMinutelyDarkSkyService.cs
src/Services/HourlyAndMinutelyDarkSkyService.cs
using DarkSky.Models; using DarkSky.Services; using Microsoft.Extensions.Options; using System.Collections.Generic; using System.Threading.Tasks; using WeatherLink.Models; namespace WeatherLink.Services { /// <summary> /// A service to get a Dark Sky forecast for a latitude and longitude. /// </summary> public class HourlyAndMinutelyDarkSkyService : IDarkSkyService { private readonly DarkSkyService.OptionalParameters _darkSkyParameters = new DarkSkyService.OptionalParameters() { DataBlocksToExclude = new List<string> { "daily", "alerts", "flags" } }; private readonly DarkSkyService _darkSkyService; /// <summary> /// An implementation of IDarkSkyService that exlcudes daily data, alert data, and flags data. /// </summary> /// <param name="optionsAccessor"></param> public HourlyAndMinutelyDarkSkyService(IOptions<WeatherLinkSettings> optionsAccessor) { _darkSkyService = new DarkSkyService(optionsAccessor.Value.DarkSkyApiKey); } /// <summary> /// Make a request to get forecast data. /// </summary> /// <param name="latitude">Latitude to request data for in decimal degrees.</param> /// <param name="longitude">Longitude to request data for in decimal degrees.</param> /// <returns>A DarkSkyResponse with the API headers and data.</returns> public async Task<DarkSkyResponse> GetForecast(double latitude, double longitude) { return await _darkSkyService.GetForecast(latitude, longitude, _darkSkyParameters); } } }
using DarkSky.Models; using DarkSky.Services; using Microsoft.Extensions.Options; using System.Collections.Generic; using System.Threading.Tasks; using WeatherLink.Models; namespace WeatherLink.Services { /// <summary> /// A service to get a Dark Sky forecast for a latitude and longitude. /// </summary> public class HourlyAndMinutelyDarkSkyService : IDarkSkyService { private readonly DarkSkyService.OptionalParameters _darkSkyParameters = new DarkSkyService.OptionalParameters { DataBlocksToExclude = new List<string> { "daily", "alerts", "flags" } }; private readonly DarkSkyService _darkSkyService; /// <summary> /// An implementation of IDarkSkyService that exlcudes daily data, alert data, and flags data. /// </summary> /// <param name="optionsAccessor"></param> public HourlyAndMinutelyDarkSkyService(IOptions<WeatherLinkSettings> optionsAccessor) { _darkSkyService = new DarkSkyService(optionsAccessor.Value.DarkSkyApiKey); } /// <summary> /// Make a request to get forecast data. /// </summary> /// <param name="latitude">Latitude to request data for in decimal degrees.</param> /// <param name="longitude">Longitude to request data for in decimal degrees.</param> /// <returns>A DarkSkyResponse with the API headers and data.</returns> public async Task<DarkSkyResponse> GetForecast(double latitude, double longitude) { return await _darkSkyService.GetForecast(latitude, longitude, _darkSkyParameters); } } }
Fix warning about empty constructor
Fix warning about empty constructor
C#
mit
amweiss/WeatherLink
3e9f23df8e72c8c547e37798db9fb5a3ac68bb1d
LiveSplit/LiveSplit.Core/Model/TimeSpanParser.cs
LiveSplit/LiveSplit.Core/Model/TimeSpanParser.cs
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); } } }
Rewrite of the Time Parsing code
Rewrite of the Time Parsing code
C#
mit
stoye/LiveSplit,Dalet/LiveSplit,zoton2/LiveSplit,CryZe/LiveSplit,Jiiks/LiveSplit,kugelrund/LiveSplit,drtchops/LiveSplit,Dalet/LiveSplit,PackSciences/LiveSplit,glasnonck/LiveSplit,Fluzzarn/LiveSplit,Seldszar/LiveSplit,glasnonck/LiveSplit,chloe747/LiveSplit,drtchops/LiveSplit,stoye/LiveSplit,kugelrund/LiveSplit,CryZe/LiveSplit,chloe747/LiveSplit,Jiiks/LiveSplit,kugelrund/LiveSplit,PackSciences/LiveSplit,PackSciences/LiveSplit,glasnonck/LiveSplit,madzinah/LiveSplit,ROMaster2/LiveSplit,ROMaster2/LiveSplit,Fluzzarn/LiveSplit,ROMaster2/LiveSplit,chloe747/LiveSplit,madzinah/LiveSplit,stoye/LiveSplit,madzinah/LiveSplit,Seldszar/LiveSplit,zoton2/LiveSplit,CryZe/LiveSplit,Fluzzarn/LiveSplit,zoton2/LiveSplit,Glurmo/LiveSplit,drtchops/LiveSplit,Glurmo/LiveSplit,Seldszar/LiveSplit,Glurmo/LiveSplit,Jiiks/LiveSplit,Dalet/LiveSplit,LiveSplit/LiveSplit
d12e4928e62023e26aa90ce32bbf84f087886e7d
osu.Game/Screens/Edit/Verify/VerifyScreen.cs
osu.Game/Screens/Edit/Verify/VerifyScreen.cs
// 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(), }, } } }; } } }
Increase editor verify settings width to give more breathing space
Increase editor verify settings width to give more breathing space
C#
mit
ppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu
3b10811e61ed71ec331dd606b0234c7cb934f2bb
samples/HelloWorld/Startup.cs
samples/HelloWorld/Startup.cs
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(); } } }
Set compatibility version to 2.2 in hello world sample project
Set compatibility version to 2.2 in hello world sample project
C#
mit
ExplicitlyImplicit/AspNetCore.Mvc.FluentActions,ExplicitlyImplicit/AspNetCore.Mvc.FluentActions
f28dcd8d0c37eb63b1eefb9ca1cf17d3dd92f63b
src/StreamDeckSharp/StreamDeckExtensions.cs
src/StreamDeckSharp/StreamDeckExtensions.cs
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StreamDeckSharp { /// <summary> /// </summary> /// <remarks> /// The <see cref="IStreamDeck"/> interface is pretty basic to simplify implementation. /// This extension class adds some commonly used functions to make things simpler. /// </remarks> public static class StreamDeckExtensions { public static void SetKeyBitmap(this IStreamDeck deck, int keyId, StreamDeckKeyBitmap bitmap) { deck.SetKeyBitmap(keyId, bitmap.rawBitmapData); } public static void ClearKey(this IStreamDeck deck, int keyId) { deck.SetKeyBitmap(keyId, StreamDeckKeyBitmap.Black); } public static void ClearKeys(this IStreamDeck deck) { for (int i = 0; i < StreamDeckHID.numOfKeys; i++) deck.SetKeyBitmap(i, StreamDeckKeyBitmap.Black); } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StreamDeckSharp { /// <summary> /// </summary> /// <remarks> /// The <see cref="IStreamDeck"/> interface is pretty basic to simplify implementation. /// This extension class adds some commonly used functions to make things simpler. /// </remarks> public static class StreamDeckExtensions { /// <summary> /// Sets a background image for a given key /// </summary> /// <param name="deck"></param> /// <param name="keyId"></param> /// <param name="bitmap"></param> public static void SetKeyBitmap(this IStreamDeck deck, int keyId, StreamDeckKeyBitmap bitmap) { deck.SetKeyBitmap(keyId, bitmap.rawBitmapData); } /// <summary> /// Sets a background image for all keys /// </summary> /// <param name="deck"></param> /// <param name="bitmap"></param> public static void SetKeyBitmap(this IStreamDeck deck, StreamDeckKeyBitmap bitmap) { for (int i = 0; i < StreamDeckHID.numOfKeys; i++) deck.SetKeyBitmap(i, bitmap.rawBitmapData); } /// <summary> /// Sets background to black for a given key /// </summary> /// <param name="deck"></param> /// <param name="keyId"></param> public static void ClearKey(this IStreamDeck deck, int keyId) { deck.SetKeyBitmap(keyId, StreamDeckKeyBitmap.Black); } /// <summary> /// Sets background to black for all given keys /// </summary> /// <param name="deck"></param> public static void ClearKeys(this IStreamDeck deck) { deck.SetKeyBitmap(StreamDeckKeyBitmap.Black); } } }
Add extension method to set bitmap for all keys (+Xml documentation)
Add extension method to set bitmap for all keys (+Xml documentation)
C#
mit
OpenStreamDeck/StreamDeckSharp
81e5d852c6e277535f1268e5225bbdf7afedb288
src/ByteSizeLib.Tests/Binary/ToBinaryStringMethod.cs
src/ByteSizeLib.Tests/Binary/ToBinaryStringMethod.cs
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); } } }
Fix ReturnsDefaultRepresenationCurrentCulture test for all cultures
Fix ReturnsDefaultRepresenationCurrentCulture test for all cultures Use NumberDecimalSeparator instead of CurrencyDecimalSeparator. In some cultures it may be different. For example, in the fr-CH culture, the currency separator is a dot and the number separator is a comma.
C#
mit
omar/ByteSize
16973e7db1fb7610e39a68976237b72fca28b1c5
AngleSharp.Performance.Css/AngleSharpParser.cs
AngleSharp.Performance.Css/AngleSharpParser.cs
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); } } }
Use CssParser front-end as intended
Use CssParser front-end as intended
C#
mit
Livven/AngleSharp,FlorianRappl/AngleSharp,AngleSharp/AngleSharp,FlorianRappl/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,zedr0n/AngleSharp.Local,Livven/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,Livven/AngleSharp,FlorianRappl/AngleSharp,FlorianRappl/AngleSharp,zedr0n/AngleSharp.Local,zedr0n/AngleSharp.Local
1674f6afc68a89a2570c35fd40a0f1d277f08ac5
DanTup.DartAnalysis/Commands/AnalysisGetHover.cs
DanTup.DartAnalysis/Commands/AnalysisGetHover.cs
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; } } }
Add some more properties to hover info.
Add some more properties to hover info.
C#
mit
DartVS/DartVS,DartVS/DartVS,modulexcite/DartVS,modulexcite/DartVS,DartVS/DartVS,modulexcite/DartVS
6382df06d25699c285f0fc313dd6bcccfe2c260e
CodePlayground/Program.cs
CodePlayground/Program.cs
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); } } }
Implement the second overload of Select
Implement the second overload of Select Because sometimes we need the index of an item.
C#
apache-2.0
BillWagner/MVA-LINQ,sushantgoel/MVA-LINQ
714720b9aa80b63403551d88f5a7e1fbf35b00ea
src/CustomerListEquip.aspx.cs
src/CustomerListEquip.aspx.cs
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); } }
Update sql commands and use the new method
Update sql commands and use the new method
C#
mit
Mimalef/repop
01961a2cfdfe3635bca0419d315f63672ebfc14e
EngineTest/ActorShould.cs
EngineTest/ActorShould.cs
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)); } } }
Fix tests - all green
Fix tests - all green
C#
mit
sheix/GameEngine,sheix/GameEngine,sheix/GameEngine
56d2afabe55562282e79a3d9f7fbe986ddebcedd
TeleBot/API/Extensions/ParseModeEnumConverter.cs
TeleBot/API/Extensions/ParseModeEnumConverter.cs
using System; using Newtonsoft.Json; using TeleBot.API.Enums; namespace TeleBot.API.Extensions { public class ParseModeEnumConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(string); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var enumString = (string)reader.Value; return Enum.Parse(typeof(ParseMode), enumString, true); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (!value.Equals(ParseMode.Default)) { var type = (ParseMode)value; writer.WriteValue(type.ToString()); } else return; } } }
using System; using Newtonsoft.Json; using TeleBot.API.Enums; namespace TeleBot.API.Extensions { public class ParseModeEnumConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(string); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var enumString = (string)reader.Value; return Enum.Parse(typeof(ParseMode), enumString, true); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (!value.Equals(ParseMode.Default)) { var type = (ParseMode)value; writer.WriteValue(type.ToString()); } } } }
Remove unnecessary else statement. Remove unnecessary return statement.
Remove unnecessary else statement. Remove unnecessary return statement.
C#
mit
kreynes/TeleBot
0f2e4c47c695686ef42d36c144887de28113caa3
BikeMates/BikeMates.Contracts/IUserRepository.cs
BikeMates/BikeMates.Contracts/IUserRepository.cs
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. } }
Revert "Added edit method into UserRepository"
Revert "Added edit method into UserRepository" This reverts commit b1727daccbcaeba70c7fa2e60c787528dd250037.
C#
mit
BikeMates/bike-mates,BikeMates/bike-mates,BikeMates/bike-mates
7072d089ef9671e5e42a05b687968c46cc566d4e
src/Hangfire.EntityFramework/HangfireServer.cs
src/Hangfire.EntityFramework/HangfireServer.cs
// 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; } } }
Remove heartbeat server property index name
Remove heartbeat server property index name
C#
mit
sergezhigunov/Hangfire.EntityFramework
f6e38562ca963299ec18f590b33a3d01ac767168
CarFuel/Controllers/CarsController.cs
CarFuel/Controllers/CarsController.cs
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); } } }
Handle null id for Cars/Details action
Handle null id for Cars/Details action If users don't supply id value in the URL, instead of displaying YSOD, we are now return BadRequest.
C#
mit
tipjung/tdd-carfuel,tipjung/tdd-carfuel,tipjung/tdd-carfuel
92ad156d83af9051d2214878c468116bdf7f616e
tests/Avalonia.Controls.UnitTests/TextBlockTests.cs
tests/Avalonia.Controls.UnitTests/TextBlockTests.cs
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using Avalonia.Data; using Xunit; namespace Avalonia.Controls.UnitTests { public class TextBlockTests { [Fact] public void DefaultBindingMode_Should_Be_OneWay() { Assert.Equal( BindingMode.OneWay, TextBlock.TextProperty.GetMetadata(typeof(TextBlock)).DefaultBindingMode); } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using Avalonia.Data; using Xunit; namespace Avalonia.Controls.UnitTests { public class TextBlockTests { [Fact] public void DefaultBindingMode_Should_Be_OneWay() { Assert.Equal( BindingMode.OneWay, TextBlock.TextProperty.GetMetadata(typeof(TextBlock)).DefaultBindingMode); } [Fact] public void Default_Text_Value_Should_Be_EmptyString() { var textBlock = new TextBlock(); Assert.Equal( "", textBlock.Text); } } }
Add test that default value of TextBlock.Text property is empty string.
Add test that default value of TextBlock.Text property is empty string.
C#
mit
SuperJMN/Avalonia,wieslawsoltes/Perspex,grokys/Perspex,jkoritzinsky/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,Perspex/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,akrisiun/Perspex,grokys/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,Perspex/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia
259a13587787dd799018e47e0c336aad714cf699
Infusion.Desktop/InterProcessCommunication.cs
Infusion.Desktop/InterProcessCommunication.cs
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(); } } }
Use background thread, otherwise process is not terminated after closing application window.
Use background thread, otherwise process is not terminated after closing application window.
C#
mit
uoinfusion/Infusion
074bf195ebc0c59b1335983904ab0176996ceef5
dotnet/Mammoth.Tests/DocumentConverterTests.cs
dotnet/Mammoth.Tests/DocumentConverterTests.cs
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); } } }
Add test for reading files with UTF-8 BOM
Add test for reading files with UTF-8 BOM
C#
bsd-2-clause
mwilliamson/java-mammoth
633810f139f43b39999f99fb0669e02029df1612
Testing-001/MyApplication/PersonService.cs
Testing-001/MyApplication/PersonService.cs
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)]; } } }
Make initial task easier given the number of refactorings needed.
Make initial task easier given the number of refactorings needed.
C#
mit
Tom-Kuhn/scratch-UnitTest,Tom-Kuhn/scratch-UnitTest
3a656a7bc575c482de6f169945629d771c3d6b3a
Visma.net/lib/DAta/JournalTransactionData.cs
Visma.net/lib/DAta/JournalTransactionData.cs
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 release action to journal transaction
Add release action to journal transaction
C#
mit
ON-IT/Visma.Net
89dc280c468a7369417b055719a40e98569c4b84
Assets/Alensia/Tests/Camera/ThirdPersonCameraTest.cs
Assets/Alensia/Tests/Camera/ThirdPersonCameraTest.cs
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."); } } }
Add test cases for wall avoidance settings
Add test cases for wall avoidance settings
C#
apache-2.0
mysticfall/Alensia
e4f6c6d255b4ec4d68eb182883edc3cf00b4828a
src/NodaTime.Web/Views/Documentation/Docs.cshtml
src/NodaTime.Web/Views/Documentation/Docs.cshtml
@model MarkdownPage <section class="body"> <div class="row"> <div class="large-9 columns"> <h1>@Model.Title</h1> @Model.Content </div> <div class="large-3 columns"> <div class="section-container accordian"> @foreach (var category in Model.Bundle.Categories) { <section> <p class="title" data-section-title>@category.Title</p> <div class="content" data-section-content> <ul class="side-nav"> @foreach (var page in category.Pages) { <li><a href="@page.Id">@page.Title</a></li> } </ul> </div> </section> } @if (Model.Bundle.Name != "developer") { <footer>Version @Model.Bundle.Name</footer> } </div> </div> </div> </section>
@model MarkdownPage @{ ViewBag.Title = Model.Title; } <section class="body"> <div class="row"> <div class="large-9 columns"> <h1>@Model.Title</h1> @Model.Content </div> <div class="large-3 columns"> <div class="section-container accordian"> @foreach (var category in Model.Bundle.Categories) { <section> <p class="title" data-section-title>@category.Title</p> <div class="content" data-section-content> <ul class="side-nav"> @foreach (var page in category.Pages) { <li><a href="@page.Id">@page.Title</a></li> } </ul> </div> </section> } @if (Model.Bundle.Name != "developer") { <footer>Version @Model.Bundle.Name</footer> } </div> </div> </div> </section>
Fix the viewbag title, used for the page title
Fix the viewbag title, used for the page title
C#
apache-2.0
malcolmr/nodatime,malcolmr/nodatime,malcolmr/nodatime,nodatime/nodatime,BenJenkinson/nodatime,BenJenkinson/nodatime,malcolmr/nodatime,nodatime/nodatime,jskeet/nodatime,jskeet/nodatime
ae380d6e5e0d487009fde7bfea85f0835412c202
TicketTimer.Core/Services/WorkItemServiceImpl.cs
TicketTimer.Core/Services/WorkItemServiceImpl.cs
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(); } } }
Save work items after starting.
[master] Save work items after starting.
C#
mit
n-develop/tickettimer
d10c0f15ed66c82c4669a9d51cde27cccec9cbb8
UndisposedExe/Program.cs
UndisposedExe/Program.cs
// 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); } } }
Allow standalone program to process multiple files at once
Allow standalone program to process multiple files at once
C#
mit
ermshiperete/undisposed-fody,ermshiperete/undisposed-fody
e45ccd7d61cfa68c19a5f13e0b6ec95d30109b95
src/System.Web.Http/ModelBinding/IModelBinder.cs
src/System.Web.Http/ModelBinding/IModelBinder.cs
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); } }
Change comment to doc comment
Change comment to doc comment
C#
mit
LianwMS/WebApi,chimpinano/WebApi,scz2011/WebApi,chimpinano/WebApi,congysu/WebApi,LianwMS/WebApi,abkmr/WebApi,congysu/WebApi,lewischeng-ms/WebApi,abkmr/WebApi,scz2011/WebApi,yonglehou/WebApi,lungisam/WebApi,lewischeng-ms/WebApi,yonglehou/WebApi,lungisam/WebApi
aff1bb8ba0d0f28c3d5e086952e91e76bbcfb905
RestImageResize/Config.cs
RestImageResize/Config.cs
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; } } } }
Fix private keys config parsing
Fix private keys config parsing
C#
mit
Romanets/RestImageResize,Romanets/RestImageResize,Romanets/RestImageResize,Romanets/RestImageResize,Romanets/RestImageResize
10a10007567c1e523e6c874b4f07b9ff5cf09b70
Tamarind/Cache/ICache.cs
Tamarind/Cache/ICache.cs
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(); } }
Add link to Guava implementation of Cache.
Add link to Guava implementation of Cache.
C#
mit
NextMethod/Tamarind
7e0b214510fa6e3f4b1cd3f0b6d6474145ce5893
TwilioAPI.cs
TwilioAPI.cs
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); } } }
Remove account and api key
Remove account and api key
C#
mit
jnnfrlocke/VendingMachineNew,jnnfrlocke/VendingMachineNew,jnnfrlocke/VendingMachineNew
3df96746c6dc8951428d0a674b11faf07fd1d513
src/Abp.TestBase/TestBase/AbpTestBaseModule.cs
src/Abp.TestBase/TestBase/AbpTestBaseModule.cs
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()); } } }
Set Configuration.DefaultNameOrConnectionString for unit tests by default.
Set Configuration.DefaultNameOrConnectionString for unit tests by default.
C#
mit
verdentk/aspnetboilerplate,ilyhacker/aspnetboilerplate,luchaoshuai/aspnetboilerplate,ZhaoRd/aspnetboilerplate,zquans/aspnetboilerplate,ryancyq/aspnetboilerplate,virtualcca/aspnetboilerplate,jaq316/aspnetboilerplate,ShiningRush/aspnetboilerplate,carldai0106/aspnetboilerplate,zquans/aspnetboilerplate,luchaoshuai/aspnetboilerplate,Nongzhsh/aspnetboilerplate,zclmoon/aspnetboilerplate,beratcarsi/aspnetboilerplate,AlexGeller/aspnetboilerplate,virtualcca/aspnetboilerplate,yuzukwok/aspnetboilerplate,verdentk/aspnetboilerplate,ryancyq/aspnetboilerplate,zclmoon/aspnetboilerplate,s-takatsu/aspnetboilerplate,fengyeju/aspnetboilerplate,berdankoca/aspnetboilerplate,Nongzhsh/aspnetboilerplate,verdentk/aspnetboilerplate,jaq316/aspnetboilerplate,jaq316/aspnetboilerplate,beratcarsi/aspnetboilerplate,ryancyq/aspnetboilerplate,virtualcca/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ilyhacker/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,carldai0106/aspnetboilerplate,oceanho/aspnetboilerplate,yuzukwok/aspnetboilerplate,fengyeju/aspnetboilerplate,andmattia/aspnetboilerplate,zquans/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ShiningRush/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ilyhacker/aspnetboilerplate,andmattia/aspnetboilerplate,andmattia/aspnetboilerplate,ShiningRush/aspnetboilerplate,ZhaoRd/aspnetboilerplate,carldai0106/aspnetboilerplate,s-takatsu/aspnetboilerplate,oceanho/aspnetboilerplate,fengyeju/aspnetboilerplate,zclmoon/aspnetboilerplate,ZhaoRd/aspnetboilerplate,ryancyq/aspnetboilerplate,carldai0106/aspnetboilerplate,AlexGeller/aspnetboilerplate,yuzukwok/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,s-takatsu/aspnetboilerplate,berdankoca/aspnetboilerplate,oceanho/aspnetboilerplate,Nongzhsh/aspnetboilerplate,AlexGeller/aspnetboilerplate,beratcarsi/aspnetboilerplate,berdankoca/aspnetboilerplate
a7fa3b11a2ef001745ab5169b55039abf036df5c
PathfinderAPI/Action/DelayablePathfinderAction.cs
PathfinderAPI/Action/DelayablePathfinderAction.cs
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 DelayableAction delays persisting DAH serialization
Fix DelayableAction delays persisting DAH serialization
C#
mit
Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder
b2cbb48cc3952d53acea7a677e8407f7e5e30ecb
Tools/ControlsLibrary/BasicControls/TextWindow.cs
Tools/ControlsLibrary/BasicControls/TextWindow.cs
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; } } } }
Fix for shader preview window in material tool appearing and then just disappearing
Fix for shader preview window in material tool appearing and then just disappearing
C#
mit
xlgames-inc/XLE,xlgames-inc/XLE,xlgames-inc/XLE,xlgames-inc/XLE,xlgames-inc/XLE,xlgames-inc/XLE,xlgames-inc/XLE,xlgames-inc/XLE
674100ec36eafc6b19ce268f8e55d8ca06fe206c
dotnet/Tests/Clients/JsonTests/OptionTests.cs
dotnet/Tests/Clients/JsonTests/OptionTests.cs
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); } } }
Remove test intead of fixing it 👍
Remove test intead of fixing it 👍
C#
mit
TheTree/branch,TheTree/branch,TheTree/branch
f56cc5371ca05303615feebfbe5392c8120b1783
KmlToGpxConverter/KmlReader.cs
KmlToGpxConverter/KmlReader.cs
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; } } }
Handle elements without elevation data
Handle elements without elevation data * Handle elements without elevation data * Fix issue where the converter would bail out at the first error encountered in the input file.
C#
mit
pacurrie/KmlToGpxConverter
56eebd86d7fd261c92100857d550a3d974e136a9
Core.Shogi.Tests/BitVersion/BitboardShogiGameShould.cs
Core.Shogi.Tests/BitVersion/BitboardShogiGameShould.cs
using NSubstitute; using Xunit; namespace Core.Shogi.Tests.BitVersion { public class BitboardShogiGameShould { [Fact] public void IdentifyACheckMateState() { var blackPlayer = new Player(PlayerType.Black); var whitePlayer = new Player(PlayerType.White); var board = new NewBitboard(blackPlayer, whitePlayer); var render = Substitute.For<IBoardRender>(); var shogi = new BitboardShogiGame(board, render); blackPlayer.Move("7g7f"); whitePlayer.Move("6a7b"); blackPlayer.Move("8h3c"); whitePlayer.Move("4a4b"); blackPlayer.Move("3c4b"); whitePlayer.Move("5a6a"); var result = blackPlayer.Move("G*5b"); Assert.Equal(BoardResult.CheckMate, result); } } public class NewBitboard : Board { public NewBitboard(Player blackPlayer, Player whitePlayer) { } } public class BitboardShogiGame { public BitboardShogiGame(Board board, IBoardRender render) { } } }
using NSubstitute; using Xunit; namespace Core.Shogi.Tests.BitVersion { public class BitboardShogiGameShould { [Fact] public void IdentifyACheckMateState() { var blackPlayer = new Player(PlayerType.Black); var whitePlayer = new Player(PlayerType.White); var board = new NewBitboard(blackPlayer, whitePlayer); var render = Substitute.For<IBoardRender>(); var shogi = new BitboardShogiGame(board, render); shogi.Start(); blackPlayer.Move("7g7f"); whitePlayer.Move("6a7b"); blackPlayer.Move("8h3c"); whitePlayer.Move("4a4b"); blackPlayer.Move("3c4b"); whitePlayer.Move("5a6a"); var result = blackPlayer.Move("G*5b"); Assert.Equal(BoardResult.CheckMate, result); } [Fact] public void EnsureBoardIsResetAtStartOfGame() { var board = Substitute.For<IBoard>(); var render = Substitute.For<IBoardRender>(); var shogi = new BitboardShogiGame(board, render); shogi.Start(); board.ReceivedWithAnyArgs(1).Reset(); } } public interface IBoard { void Reset(); } public class NewBitboard : IBoard { public NewBitboard(Player blackPlayer, Player whitePlayer) { } public void Reset() { } } public class BitboardShogiGame { private readonly IBoard _board; public BitboardShogiGame(IBoard board, IBoardRender render) { _board = board; } public void Start() { _board.Reset(); } } }
Reset board at start of the game.
Reset board at start of the game.
C#
mit
pjbgf/shogi,pjbgf/shogi
93a8092da6504019b871ba4f219e8b9634715b28
osu.Game/Screens/Edit/Verify/VerifyScreen.cs
osu.Game/Screens/Edit/Verify/VerifyScreen.cs
// 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(), }, } } }; } } }
Increase usable width slightly further
Increase usable width slightly further
C#
mit
peppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,ppy/osu
e256d4a58138fd52c1c583dc07ab11412f5ea24b
Pennyworth/DropHelper.cs
Pennyworth/DropHelper.cs
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(); } } } } }
Use the shortest path if assemblies have the same file name
Use the shortest path if assemblies have the same file name
C#
mit
hruan/Pennyworth
d83337e7c1094a1626c9325024387a6a35f56e9f
AndHUD/XHUD.cs
AndHUD/XHUD.cs
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 XHud MaskType cast-able to AndHud MaskType
Make XHud MaskType cast-able to AndHud MaskType
C#
apache-2.0
Redth/AndHUD,Redth/AndHUD
76d2dc40d94b1a79f100fe3a4f6521bb095cf9b0
src/WordList/Program.cs
src/WordList/Program.cs
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(); } } }
Make the code in the entrypoint even shorter.
Make the code in the entrypoint even shorter.
C#
mit
DavidLievrouw/WordList
030865cf921b6fb731d26bce98cc2f873d9eaff1
src/Evolve/Exception/EvolveConfigurationException.cs
src/Evolve/Exception/EvolveConfigurationException.cs
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 FirstLetterToLower() to each exception message
Add FirstLetterToLower() to each exception message
C#
mit
lecaillon/Evolve
ec241ae48a8082d7516bfd84fd4e790d20730fea
src/Symbooglix/Executor/ExecutionTreeNode.cs
src/Symbooglix/Executor/ExecutionTreeNode.cs
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); } } }
Add assertion to check for cycles in ExecutionTree
Add assertion to check for cycles in ExecutionTree
C#
bsd-2-clause
symbooglix/symbooglix,symbooglix/symbooglix,symbooglix/symbooglix
49a3685e27c985d0a2cbbff8b80b84bdf2165055
ReverseWords/BracesValidator/BracesValidator.cs
ReverseWords/BracesValidator/BracesValidator.cs
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; } } }
Use dictionary instead of lists
Use dictionary instead of lists
C#
apache-2.0
ozim/CakeStuff
51f447a5f2594a56c20988f1a57dc1f6dd51d380
service/DotNetApis.Common/AsyncLocalAblyLogger.cs
service/DotNetApis.Common/AsyncLocalAblyLogger.cs
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(); } }
Remove warnings from Ably log to reduce noise.
Remove warnings from Ably log to reduce noise.
C#
mit
StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis
9bc96d2bbf17e574c9563ee8a71d928cf6a2951e
glib/GLib.cs
glib/GLib.cs
// 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 } }
Make sure we only ever initialize once
Make sure we only ever initialize once
C#
mit
mono/dbus-sharp-glib,mono/dbus-sharp-glib
d3a1e82d76719bd8c9d439946f6d365a964174ed
src/SignaturePad.Android/ClearingImageView.cs
src/SignaturePad.Android/ClearingImageView.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Util; using Android.Graphics; namespace SignaturePad { public class ClearingImageView : ImageView { private Bitmap imageBitmap = null; public ClearingImageView (Context context) : base (context) { } public ClearingImageView (Context context, IAttributeSet attrs) : base (context, attrs) { } public ClearingImageView (Context context, IAttributeSet attrs, int defStyle) : base (context, attrs, defStyle) { } public override void SetImageBitmap(Bitmap bm) { base.SetImageBitmap (bm); if (imageBitmap != null) { imageBitmap.Recycle (); } imageBitmap = bm; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Util; using Android.Graphics; namespace SignaturePad { public class ClearingImageView : ImageView { private Bitmap imageBitmap = null; public ClearingImageView (Context context) : base (context) { } public ClearingImageView (Context context, IAttributeSet attrs) : base (context, attrs) { } public ClearingImageView (Context context, IAttributeSet attrs, int defStyle) : base (context, attrs, defStyle) { } public override void SetImageBitmap(Bitmap bm) { base.SetImageBitmap (bm); if (imageBitmap != null) { imageBitmap.Recycle (); imageBitmap.Dispose (); } imageBitmap = bm; System.GC.Collect (); } } }
Call Dispose and the GC to avoid leaking memory.
[SignaturePad] Call Dispose and the GC to avoid leaking memory. If the end user does too many successive strokes, the app will crash with an OutOfMemory exception.
C#
mit
xamarin/SignaturePad,xamarin/SignaturePad
1f7909117f1fd7d565b8a6bc2c51003191034802
src/Atata.Tests/Properties/AssemblyInfo.cs
src/Atata.Tests/Properties/AssemblyInfo.cs
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")]
Add parallelism to Tests project
Add parallelism to Tests project
C#
apache-2.0
atata-framework/atata,YevgeniyShunevych/Atata,YevgeniyShunevych/Atata,atata-framework/atata
b76fbbf8e51014995bb2e6aed0735430abbe3af6
HeadRaceTiming-Site/Controllers/CrewController.cs
HeadRaceTiming-Site/Controllers/CrewController.cs
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); } } }
Fix crew to reference by BroeCrewId
Fix crew to reference by BroeCrewId
C#
mit
MelHarbour/HeadRaceTiming-Site,MelHarbour/HeadRaceTiming-Site,MelHarbour/HeadRaceTiming-Site
886bee57c85901d09f815da232a4fb5969e01a4c
MonoMod.UnitTest/RuntimeDetour/DetourEmptyTest.cs
MonoMod.UnitTest/RuntimeDetour/DetourEmptyTest.cs
#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() { } } }
Mark the empty method detour test as NoInlining
Mark the empty method detour test as NoInlining
C#
mit
AngelDE98/MonoMod,0x0ade/MonoMod
6f92b46999af97d5d43285679a23aa79b00d79f7
JabbR/ContentProviders/UserVoiceContentProvider.cs
JabbR/ContentProviders/UserVoiceContentProvider.cs
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 user voice content provider work with https.
Make user voice content provider work with https.
C#
mit
e10/JabbR,ClarkL/test09jabbr,test0925/test0925,mogultest2/Project92104,aapttester/jack12051317,LookLikeAPro/JabbR,M-Zuber/JabbR,mogulTest1/Project13171109,test0925/test0925,mogulTest1/Project13231109,LookLikeAPro/JabbR,meebey/JabbR,AAPT/jean0226case1322,ClarkL/1317on17jabbr,MogulTestOrg914/Project91407,mogulTest1/Project13231113,mogulTest1/Project13231109,clarktestkudu1029/test08jabbr,mogulTest1/Project13171106,v-mohua/TestProject91001,mogulTest1/ProjectfoIssue6,MogulTestOrg2/JabbrApp,mogulTest1/Project13171205,KuduApps/TestDeploy123,Org1106/Project13221106,meebey/JabbR,mogultest2/Project13171008,KuduApps/TestDeploy123,mogulTest1/Project91404,MogulTestOrg2/JabbrApp,Org1106/Project13221106,mogulTest1/Project13171024,mogulTest1/Project13171024,lukehoban/JabbR,mogulTest1/Project91009,mogulTest1/ProjectfoIssue6,mogulTest1/MogulVerifyIssue5,mogulTest1/Project91101,mogultest2/Project13171008,mogultest2/Project92105,ClarkL/test09jabbr,mogultest2/Project13231008,M-Zuber/JabbR,mogultest2/Project92109,mogulTest1/Project91105,ajayanandgit/JabbR,CrankyTRex/JabbRMirror,JabbR/JabbR,MogulTestOrg9221/Project92108,AAPT/jean0226case1322,mogulTest1/Project90301,mogulTest1/ProjectJabbr01,fuzeman/vox,kudutest/FaizJabbr,mogulTest1/ProjectVerify912,mogulTest1/Project13171109,Org1106/Project13221113,mogulTest1/Project91409,mogulTest1/Project90301,meebey/JabbR,18098924759/JabbR,mogultest2/Project13171210,lukehoban/JabbR,e10/JabbR,18098924759/JabbR,mogulTest1/Project13231106,borisyankov/JabbR,mogultest2/Project13171010,LookLikeAPro/JabbR,mogulTest1/Project91009,yadyn/JabbR,mogultest2/Project13171010,mogulTest1/Project91101,mogultest2/Project13231008,mogulTest1/ProjectVerify912,timgranstrom/JabbR,mogulTest1/Project91409,JabbR/JabbR,borisyankov/JabbR,mogulTest1/Project91404,mogulTest1/Project13171205,mogulTest1/MogulVerifyIssue5,fuzeman/vox,mogultest2/Project92109,v-mohua/TestProject91001,Createfor1322/jessica0122-1322,mogultest2/Project13171210,yadyn/JabbR,SonOfSam/JabbR,mogulTest1/Project91105,mzdv/JabbR,MogulTestOrg911/Project91104,ClarkL/1323on17jabbr-,borisyankov/JabbR,mogulTest1/Project13171113,mogulTest1/Project13161127,ajayanandgit/JabbR,aapttester/jack12051317,lukehoban/JabbR,MogulTestOrg914/Project91407,CrankyTRex/JabbRMirror,Createfor1322/jessica0122-1322,CrankyTRex/JabbRMirror,MogulTestOrg1008/Project13221008,MogulTestOrg9221/Project92108,timgranstrom/JabbR,yadyn/JabbR,mogulTest1/Project13171009,mogulTest1/Project13231106,fuzeman/vox,mogulTest1/Project13161127,huanglitest/JabbRTest2,huanglitest/JabbRTest2,mogulTest1/Project13231113,MogulTestOrg/JabbrApp,ClarkL/1317on17jabbr,ClarkL/new09,Org1106/Project13221113,mogulTest1/Project13231205,mogulTest1/Project13171106,mogulTest1/Project13171009,mzdv/JabbR,mogulTest1/Project13231212,SonOfSam/JabbR,clarktestkudu1029/test08jabbr,MogulTestOrg/JabbrApp,ClarkL/new09,mogulTest1/Project13231212,ClarkL/new1317,mogulTest1/Project13231213,mogulTest1/Project13231213,MogulTestOrg1008/Project13221008,mogulTest1/ProjectJabbr01,mogulTest1/Project13231205,ClarkL/new1317,mogulTest1/Project13171113,ClarkL/1323on17jabbr-,kudutest/FaizJabbr,MogulTestOrg911/Project91104,mogultest2/Project92104,huanglitest/JabbRTest2,mogultest2/Project92105
b66566e96d4f22d7e4351443ea8d999fd7f9bce7
osu.Game/Overlays/Settings/Sections/SizeSlider.cs
osu.Game/Overlays/Settings/Sections/SizeSlider.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Localisation; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays.Settings.Sections { /// <summary> /// A slider intended to show a "size" multiplier number, where 1x is 1.0. /// </summary> internal class SizeSlider<T> : OsuSliderBar<T> where T : struct, IEquatable<T>, IComparable<T>, IConvertible, IFormattable { public override LocalisableString TooltipText => Current.Value.ToString(@"0.##x", null); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Globalization; using osu.Framework.Localisation; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays.Settings.Sections { /// <summary> /// A slider intended to show a "size" multiplier number, where 1x is 1.0. /// </summary> internal class SizeSlider<T> : OsuSliderBar<T> where T : struct, IEquatable<T>, IComparable<T>, IConvertible, IFormattable { public override LocalisableString TooltipText => Current.Value.ToString(@"0.##x", NumberFormatInfo.CurrentInfo); } }
Use explicit culture info rather than `null`
Use explicit culture info rather than `null`
C#
mit
NeoAdonis/osu,ppy/osu,ppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu
8b24b861a3cbdf9e2411716e391e60965072ca0d
Docker.DotNet.X509/CertificateCredentials.cs
Docker.DotNet.X509/CertificateCredentials.cs
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() { } } }
Make X509 work with ManagedHandler
Make X509 work with ManagedHandler This eliminates the full-framework dependency. A follow-up change should start building this fore CoreCLR.
C#
apache-2.0
jterry75/Docker.DotNet,jterry75/Docker.DotNet,ahmetalpbalkan/Docker.DotNet
51f69f171192e0534e3221be9f2b41023fac8cf5
Azimuth.Migrations/Migrations/Migration_201409101200_RemoveListenedTableAndAddCounterToPlaylistTable.cs
Azimuth.Migrations/Migrations/Migration_201409101200_RemoveListenedTableAndAddCounterToPlaylistTable.cs
 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"); } } }
Rename listened table in migration
Rename listened table in migration
C#
mit
B1naryStudio/Azimuth,B1naryStudio/Azimuth
9ba8441a3bebe5133c5f5639cb2d6178dc4a7083
test/MathParser.Tests/InfixLexicalAnalyzerTest.cs
test/MathParser.Tests/InfixLexicalAnalyzerTest.cs
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"); } } }
Include Fact attribute on test method
Include Fact attribute on test method
C#
mit
henriqueprj/infixtopostfix
a5e642016966fb44270c21143ca6e7b31b7838ec
Synapse.RestClient/SynapseRestClientFactory.cs
Synapse.RestClient/SynapseRestClientFactory.cs
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); } } }
Update servicepointmanager to use newer TLS
Update servicepointmanager to use newer TLS
C#
mit
neuralaxis/synapsecsharpclient
c89ec0dda19893397055f75ebf1ff01d859c3dfd
src/BloomTests/ProblemReporterDialogTests.cs
src/BloomTests/ProblemReporterDialogTests.cs
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 missing "using geckofx" for mono build
Add missing "using geckofx" for mono build
C#
mit
StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop
5f9d2ebf02326f505a2a3c4c476659aed225c172
csharp/Hello/HelloClient/Program.cs
csharp/Hello/HelloClient/Program.cs
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(); } } }
Add client for simple call
Add client for simple call
C#
mit
avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors
5aac6dd314fad2c821543e29fcd4c6b391c661b1
WebNoodle/NodeHelper.cs
WebNoodle/NodeHelper.cs
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; } } } }
Throw 404 when you can't find the node
Throw 404 when you can't find the node
C#
mit
mcintyre321/Noodles,mcintyre321/Noodles
b62b3a1d2d64aa9194cf6a42e556b6f421e0e1fd
Source/MonoGame.Extended/FramesPerSecondCounter.cs
Source/MonoGame.Extended/FramesPerSecondCounter.cs
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); } } }
Make FPS counter to a GameComponent
Make FPS counter to a GameComponent
C#
mit
rafaelalmeidatk/MonoGame.Extended,Aurioch/MonoGame.Extended,HyperionMT/MonoGame.Extended,LithiumToast/MonoGame.Extended,cra0zy/MonoGame.Extended,rafaelalmeidatk/MonoGame.Extended
aad3111d03eca22bb366daa3cfdbf283e341c463
osu.Framework.Tests/Localisation/CultureInfoHelperTest.cs
osu.Framework.Tests/Localisation/CultureInfoHelperTest.cs
// 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)); } } }
Fix tests failing due to not being updated with new behaviour
Fix tests failing due to not being updated with new behaviour
C#
mit
ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework
1ce92e0330ea1abc9d2860e127490eaf9f10e664
src/LfMerge/LanguageForge/Model/LfAuthorInfo.cs
src/LfMerge/LanguageForge/Model/LfAuthorInfo.cs
// 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; } } }
Handle Mongo ObjectId references better
Handle Mongo ObjectId references better ObjectId is a struct in the Mongo C# driver, so it's a non-nullable object by default. However, our PHP code stores null for these UserRef fields if no user reference is available. I had been making these fields strings, but nullable ObjectId values are better: they will round-trip correctly this way whether there is data there or not.
C#
mit
ermshiperete/LfMerge,ermshiperete/LfMerge,ermshiperete/LfMerge,sillsdev/LfMerge,sillsdev/LfMerge,sillsdev/LfMerge
9180ab4442a25925192da08a7ea5d42ebe7e7af7
src/Umbraco.Core/Models/TagCacheStorageType.cs
src/Umbraco.Core/Models/TagCacheStorageType.cs
namespace Umbraco.Core.Models { public enum TagCacheStorageType { Json, Csv } }
namespace Umbraco.Core.Models { public enum TagCacheStorageType { Csv, Json } }
Reset commit to not break backwards compatibility mode
Reset commit to not break backwards compatibility mode
C#
mit
aaronpowell/Umbraco-CMS,abryukhov/Umbraco-CMS,WebCentrum/Umbraco-CMS,NikRimington/Umbraco-CMS,leekelleher/Umbraco-CMS,hfloyd/Umbraco-CMS,tompipe/Umbraco-CMS,dawoe/Umbraco-CMS,aaronpowell/Umbraco-CMS,rasmuseeg/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,tcmorris/Umbraco-CMS,abryukhov/Umbraco-CMS,bjarnef/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,tcmorris/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,hfloyd/Umbraco-CMS,hfloyd/Umbraco-CMS,KevinJump/Umbraco-CMS,mattbrailsford/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,lars-erik/Umbraco-CMS,leekelleher/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,leekelleher/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,rasmuseeg/Umbraco-CMS,abjerner/Umbraco-CMS,tompipe/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,NikRimington/Umbraco-CMS,aaronpowell/Umbraco-CMS,lars-erik/Umbraco-CMS,robertjf/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,bjarnef/Umbraco-CMS,mattbrailsford/Umbraco-CMS,leekelleher/Umbraco-CMS,madsoulswe/Umbraco-CMS,umbraco/Umbraco-CMS,tompipe/Umbraco-CMS,bjarnef/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,rasmuseeg/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,leekelleher/Umbraco-CMS,WebCentrum/Umbraco-CMS,NikRimington/Umbraco-CMS,madsoulswe/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,hfloyd/Umbraco-CMS,lars-erik/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,tcmorris/Umbraco-CMS,lars-erik/Umbraco-CMS,lars-erik/Umbraco-CMS,marcemarc/Umbraco-CMS,madsoulswe/Umbraco-CMS,WebCentrum/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,arknu/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,mattbrailsford/Umbraco-CMS,hfloyd/Umbraco-CMS,bjarnef/Umbraco-CMS
60e69f5b8dccb55eb1e34a778a99a042f0165c18
EOLib/Domain/Interact/MapNPCActions.cs
EOLib/Domain/Interact/MapNPCActions.cs
using AutomaticTypeMapper; using EOLib.Domain.NPC; using EOLib.IO.Repositories; using EOLib.Net; using EOLib.Net.Communication; namespace EOLib.Domain.Interact { [AutoMappedType] public class MapNPCActions : IMapNPCActions { private readonly IPacketSendService _packetSendService; private readonly IENFFileProvider _enfFileProvider; public MapNPCActions(IPacketSendService packetSendService, IENFFileProvider enfFileProvider) { _packetSendService = packetSendService; _enfFileProvider = enfFileProvider; } public void RequestShop(INPC npc) { var packet = new PacketBuilder(PacketFamily.Shop, PacketAction.Open) .AddShort(npc.Index) .Build(); _packetSendService.SendPacket(packet); } public void RequestQuest(INPC npc) { var data = _enfFileProvider.ENFFile[npc.ID]; var packet = new PacketBuilder(PacketFamily.Quest, PacketAction.Use) .AddShort(npc.Index) .AddShort(data.VendorID) .Build(); _packetSendService.SendPacket(packet); } } public interface IMapNPCActions { void RequestShop(INPC npc); void RequestQuest(INPC npc); } }
using AutomaticTypeMapper; using EOLib.Domain.Interact.Quest; using EOLib.Domain.NPC; using EOLib.IO.Repositories; using EOLib.Net; using EOLib.Net.Communication; namespace EOLib.Domain.Interact { [AutoMappedType] public class MapNPCActions : IMapNPCActions { private readonly IPacketSendService _packetSendService; private readonly IENFFileProvider _enfFileProvider; private readonly IQuestDataRepository _questDataRepository; public MapNPCActions(IPacketSendService packetSendService, IENFFileProvider enfFileProvider, IQuestDataRepository questDataRepository) { _packetSendService = packetSendService; _enfFileProvider = enfFileProvider; _questDataRepository = questDataRepository; } public void RequestShop(INPC npc) { var packet = new PacketBuilder(PacketFamily.Shop, PacketAction.Open) .AddShort(npc.Index) .Build(); _packetSendService.SendPacket(packet); } public void RequestQuest(INPC npc) { _questDataRepository.RequestedNPC = npc; var data = _enfFileProvider.ENFFile[npc.ID]; var packet = new PacketBuilder(PacketFamily.Quest, PacketAction.Use) .AddShort(npc.Index) .AddShort(data.VendorID) .Build(); _packetSendService.SendPacket(packet); } } public interface IMapNPCActions { void RequestShop(INPC npc); void RequestQuest(INPC npc); } }
Fix bug where quest NPC dialog caused a crash because the requested NPC was never set
Fix bug where quest NPC dialog caused a crash because the requested NPC was never set
C#
mit
ethanmoffat/EndlessClient
f9ca48054b89faa433f0577820964be2b45d4242
source/Glimpse.Core2/Extensibility/ScriptOrder.cs
source/Glimpse.Core2/Extensibility/ScriptOrder.cs
namespace Glimpse.Core2.Extensibility { public enum ScriptOrder { IncludeBeforeClientInterfaceScript, ClientInterfaceScript, IncludeAfterClientInterfaceScript, IncludeBeforeRequestDataScript, RequestDataScript, RequestMetadataScript, IncludeAfterRequestDataScript, } }
namespace Glimpse.Core2.Extensibility { public enum ScriptOrder { IncludeBeforeClientInterfaceScript, ClientInterfaceScript, IncludeAfterClientInterfaceScript, IncludeBeforeRequestDataScript, RequestMetadataScript, RequestDataScript, IncludeAfterRequestDataScript, } }
Switch the load order so that metadata comes first in the dom
Switch the load order so that metadata comes first in the dom
C#
apache-2.0
paynecrl97/Glimpse,sorenhl/Glimpse,dudzon/Glimpse,sorenhl/Glimpse,SusanaL/Glimpse,flcdrg/Glimpse,codevlabs/Glimpse,codevlabs/Glimpse,rho24/Glimpse,rho24/Glimpse,paynecrl97/Glimpse,elkingtonmcb/Glimpse,codevlabs/Glimpse,SusanaL/Glimpse,Glimpse/Glimpse,Glimpse/Glimpse,paynecrl97/Glimpse,SusanaL/Glimpse,flcdrg/Glimpse,paynecrl97/Glimpse,flcdrg/Glimpse,gabrielweyer/Glimpse,gabrielweyer/Glimpse,elkingtonmcb/Glimpse,rho24/Glimpse,dudzon/Glimpse,elkingtonmcb/Glimpse,sorenhl/Glimpse,Glimpse/Glimpse,rho24/Glimpse,gabrielweyer/Glimpse,dudzon/Glimpse