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
838cd975c6c31c55e303594139e32454eba6996d
src/Compilers/Shared/DesktopShim.cs
src/Compilers/Shared/DesktopShim.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Reflection; namespace Roslyn.Utilities { /// <summary> /// This is a bridge for APIs that are only available on Desktop /// and NOT on CoreCLR. The compiler currently targets .NET 4.5 and CoreCLR /// so this shim is necessary for switching on the dependent behavior. /// </summary> internal static class DesktopShim { internal static class FileNotFoundException { internal static readonly Type Type = ReflectionUtilities.TryGetType( "System.IO.FileNotFoundException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); private static PropertyInfo s_fusionLog = Type?.GetTypeInfo().GetDeclaredProperty("FusionLog"); internal static string TryGetFusionLog(object obj) => s_fusionLog.GetValue(obj) as string; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Reflection; namespace Roslyn.Utilities { /// <summary> /// This is a bridge for APIs that are only available on Desktop /// and NOT on CoreCLR. The compiler currently targets .NET 4.5 and CoreCLR /// so this shim is necessary for switching on the dependent behavior. /// </summary> internal static class DesktopShim { internal static class FileNotFoundException { internal static readonly Type Type = typeof(FileNotFoundException); private static PropertyInfo s_fusionLog = Type?.GetTypeInfo().GetDeclaredProperty("FusionLog"); internal static string TryGetFusionLog(object obj) => s_fusionLog?.GetValue(obj) as string; } } }
Make the FNF exception light up more robust
Make the FNF exception light up more robust
C#
mit
AlekseyTs/roslyn,davkean/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,CyrusNajmabadi/roslyn,swaroop-sridhar/roslyn,dotnet/roslyn,panopticoncentral/roslyn,VSadov/roslyn,mavasani/roslyn,diryboy/roslyn,dotnet/roslyn,VSadov/roslyn,bartdesmet/roslyn,aelij/roslyn,DustinCampbell/roslyn,agocke/roslyn,mgoertz-msft/roslyn,DustinCampbell/roslyn,nguerrera/roslyn,nguerrera/roslyn,physhi/roslyn,abock/roslyn,jasonmalinowski/roslyn,stephentoub/roslyn,tannergooding/roslyn,gafter/roslyn,sharwell/roslyn,gafter/roslyn,reaction1989/roslyn,mgoertz-msft/roslyn,eriawan/roslyn,abock/roslyn,agocke/roslyn,jcouv/roslyn,diryboy/roslyn,KevinRansom/roslyn,KevinRansom/roslyn,tmat/roslyn,jcouv/roslyn,mavasani/roslyn,DustinCampbell/roslyn,KirillOsenkov/roslyn,swaroop-sridhar/roslyn,diryboy/roslyn,MichalStrehovsky/roslyn,brettfo/roslyn,AlekseyTs/roslyn,heejaechang/roslyn,eriawan/roslyn,brettfo/roslyn,genlu/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,weltkante/roslyn,mgoertz-msft/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,abock/roslyn,MichalStrehovsky/roslyn,sharwell/roslyn,tmat/roslyn,jmarolf/roslyn,CyrusNajmabadi/roslyn,AlekseyTs/roslyn,gafter/roslyn,KirillOsenkov/roslyn,heejaechang/roslyn,weltkante/roslyn,stephentoub/roslyn,aelij/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,jcouv/roslyn,jmarolf/roslyn,agocke/roslyn,dotnet/roslyn,wvdd007/roslyn,jmarolf/roslyn,tannergooding/roslyn,stephentoub/roslyn,panopticoncentral/roslyn,KirillOsenkov/roslyn,aelij/roslyn,VSadov/roslyn,ErikSchierboom/roslyn,KevinRansom/roslyn,tmat/roslyn,sharwell/roslyn,panopticoncentral/roslyn,bartdesmet/roslyn,ErikSchierboom/roslyn,nguerrera/roslyn,genlu/roslyn,weltkante/roslyn,davkean/roslyn,shyamnamboodiripad/roslyn,ErikSchierboom/roslyn,AmadeusW/roslyn,reaction1989/roslyn,reaction1989/roslyn,physhi/roslyn,tannergooding/roslyn,mavasani/roslyn,MichalStrehovsky/roslyn,swaroop-sridhar/roslyn,AmadeusW/roslyn,jasonmalinowski/roslyn,brettfo/roslyn,genlu/roslyn,AmadeusW/roslyn,davkean/roslyn,bartdesmet/roslyn,eriawan/roslyn
8f4213994da35a84551f4aa546ed99cd63518ed0
src/Options/GeneralOptionControl.cs
src/Options/GeneralOptionControl.cs
using System; using System.Diagnostics; using System.IO; using System.Windows.Forms; using NuGet.VisualStudio; namespace NuGet.Options { public partial class GeneralOptionControl : UserControl { private IRecentPackageRepository _recentPackageRepository; private IProductUpdateSettings _productUpdateSettings; public GeneralOptionControl() { InitializeComponent(); _productUpdateSettings = ServiceLocator.GetInstance<IProductUpdateSettings>(); Debug.Assert(_productUpdateSettings != null); _recentPackageRepository = ServiceLocator.GetInstance<IRecentPackageRepository>(); Debug.Assert(_recentPackageRepository != null); } private void OnClearRecentPackagesClick(object sender, EventArgs e) { _recentPackageRepository.Clear(); MessageHelper.ShowInfoMessage(Resources.ShowInfo_ClearRecentPackages, Resources.ShowWarning_Title); } internal void OnActivated() { checkForUpdate.Checked = _productUpdateSettings.ShouldCheckForUpdate; browsePackageCacheButton.Enabled = clearPackageCacheButton.Enabled = Directory.Exists(MachineCache.Default.Source); } internal void OnApply() { _productUpdateSettings.ShouldCheckForUpdate = checkForUpdate.Checked; } private void OnClearPackageCacheClick(object sender, EventArgs e) { MachineCache.Default.Clear(); MessageHelper.ShowInfoMessage(Resources.ShowInfo_ClearRecentPackages, Resources.ShowWarning_Title); } private void OnBrowsePackageCacheClick(object sender, EventArgs e) { if (Directory.Exists(MachineCache.Default.Source)) { Process.Start(MachineCache.Default.Source); } } } }
using System; using System.Diagnostics; using System.IO; using System.Windows.Forms; using NuGet.VisualStudio; namespace NuGet.Options { public partial class GeneralOptionControl : UserControl { private IRecentPackageRepository _recentPackageRepository; private IProductUpdateSettings _productUpdateSettings; public GeneralOptionControl() { InitializeComponent(); _productUpdateSettings = ServiceLocator.GetInstance<IProductUpdateSettings>(); Debug.Assert(_productUpdateSettings != null); _recentPackageRepository = ServiceLocator.GetInstance<IRecentPackageRepository>(); Debug.Assert(_recentPackageRepository != null); } private void OnClearRecentPackagesClick(object sender, EventArgs e) { _recentPackageRepository.Clear(); MessageHelper.ShowInfoMessage(Resources.ShowInfo_ClearRecentPackages, Resources.ShowWarning_Title); } internal void OnActivated() { checkForUpdate.Checked = _productUpdateSettings.ShouldCheckForUpdate; browsePackageCacheButton.Enabled = clearPackageCacheButton.Enabled = Directory.Exists(MachineCache.Default.Source); } internal void OnApply() { _productUpdateSettings.ShouldCheckForUpdate = checkForUpdate.Checked; } private void OnClearPackageCacheClick(object sender, EventArgs e) { MachineCache.Default.Clear(); MessageHelper.ShowInfoMessage(Resources.ShowInfo_ClearPackageCache, Resources.ShowWarning_Title); } private void OnBrowsePackageCacheClick(object sender, EventArgs e) { if (Directory.Exists(MachineCache.Default.Source)) { Process.Start(MachineCache.Default.Source); } } } }
Fix bug: Clearing the cache says "All items have been cleared from the recent packages list." Work items: 986
Fix bug: Clearing the cache says "All items have been cleared from the recent packages list." Work items: 986
C#
apache-2.0
xoofx/NuGet,indsoft/NuGet2,dolkensp/node.net,mono/nuget,xero-github/Nuget,anurse/NuGet,antiufo/NuGet2,indsoft/NuGet2,themotleyfool/NuGet,jholovacs/NuGet,themotleyfool/NuGet,alluran/node.net,RichiCoder1/nuget-chocolatey,kumavis/NuGet,zskullz/nuget,mrward/nuget,jholovacs/NuGet,jmezach/NuGet2,GearedToWar/NuGet2,ctaggart/nuget,mono/nuget,ctaggart/nuget,xoofx/NuGet,GearedToWar/NuGet2,pratikkagda/nuget,jmezach/NuGet2,antiufo/NuGet2,dolkensp/node.net,zskullz/nuget,chocolatey/nuget-chocolatey,RichiCoder1/nuget-chocolatey,antiufo/NuGet2,oliver-feng/nuget,ctaggart/nuget,akrisiun/NuGet,alluran/node.net,oliver-feng/nuget,xoofx/NuGet,atheken/nuget,mono/nuget,antiufo/NuGet2,jmezach/NuGet2,pratikkagda/nuget,oliver-feng/nuget,indsoft/NuGet2,RichiCoder1/nuget-chocolatey,oliver-feng/nuget,chocolatey/nuget-chocolatey,indsoft/NuGet2,chester89/nugetApi,OneGet/nuget,jmezach/NuGet2,jholovacs/NuGet,jholovacs/NuGet,pratikkagda/nuget,mrward/nuget,atheken/nuget,RichiCoder1/nuget-chocolatey,rikoe/nuget,jmezach/NuGet2,RichiCoder1/nuget-chocolatey,mrward/nuget,mono/nuget,oliver-feng/nuget,mrward/NuGet.V2,chocolatey/nuget-chocolatey,xoofx/NuGet,pratikkagda/nuget,xoofx/NuGet,mrward/nuget,kumavis/NuGet,xoofx/NuGet,dolkensp/node.net,OneGet/nuget,mrward/NuGet.V2,dolkensp/node.net,ctaggart/nuget,jholovacs/NuGet,jmezach/NuGet2,zskullz/nuget,RichiCoder1/nuget-chocolatey,zskullz/nuget,chester89/nugetApi,mrward/nuget,rikoe/nuget,GearedToWar/NuGet2,chocolatey/nuget-chocolatey,OneGet/nuget,antiufo/NuGet2,themotleyfool/NuGet,chocolatey/nuget-chocolatey,mrward/nuget,mrward/NuGet.V2,alluran/node.net,akrisiun/NuGet,indsoft/NuGet2,GearedToWar/NuGet2,mrward/NuGet.V2,OneGet/nuget,GearedToWar/NuGet2,oliver-feng/nuget,mrward/NuGet.V2,rikoe/nuget,mrward/NuGet.V2,anurse/NuGet,alluran/node.net,pratikkagda/nuget,indsoft/NuGet2,chocolatey/nuget-chocolatey,rikoe/nuget,pratikkagda/nuget,antiufo/NuGet2,jholovacs/NuGet,GearedToWar/NuGet2
f0e56a1455be4ede45bc9a4683227f6b84cf0fa0
src/dotless.Core/Parser/Tree/Url.cs
src/dotless.Core/Parser/Tree/Url.cs
namespace dotless.Core.Parser.Tree { using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Infrastructure; using Infrastructure.Nodes; using Utils; using Exceptions; public class Url : Node { public Node Value { get; set; } public Url(Node value, IEnumerable<string> paths) { if (value is TextNode) { var textValue = value as TextNode; if (!Regex.IsMatch(textValue.Value, @"^(([A-z]+:)|(\/))") && paths.Any()) { textValue.Value = paths.Concat(new[] { textValue.Value }).AggregatePaths(); } } Value = value; } public Url(Node value) { Value = value; } public string GetUrl() { if (Value is TextNode) return (Value as TextNode).Value; throw new ParserException("Imports do not allow expressions"); } public override Node Evaluate(Env env) { return new Url(Value.Evaluate(env)); } public override void AppendCSS(Env env) { env.Output .Append("url(") .Append(Value) .Append(")"); } } }
namespace dotless.Core.Parser.Tree { using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Infrastructure; using Infrastructure.Nodes; using Utils; using Exceptions; public class Url : Node { public Node Value { get; set; } public Url(Node value, IEnumerable<string> paths) { if (value is TextNode) { var textValue = value as TextNode; if (!Regex.IsMatch(textValue.Value, @"^(([a-zA-Z]+:)|(\/))") && paths.Any()) { textValue.Value = paths.Concat(new[] { textValue.Value }).AggregatePaths(); } } Value = value; } public Url(Node value) { Value = value; } public string GetUrl() { if (Value is TextNode) return (Value as TextNode).Value; throw new ParserException("Imports do not allow expressions"); } public override Node Evaluate(Env env) { return new Url(Value.Evaluate(env)); } public override void AppendCSS(Env env) { env.Output .Append("url(") .Append(Value) .Append(")"); } } }
Change a-Z to a-zA-Z as reccomended
Change a-Z to a-zA-Z as reccomended
C#
apache-2.0
r2i-sitecore/dotless,rytmis/dotless,dotless/dotless,dotless/dotless,modulexcite/dotless,rytmis/dotless,modulexcite/dotless,rytmis/dotless,modulexcite/dotless,r2i-sitecore/dotless,rytmis/dotless,rytmis/dotless,r2i-sitecore/dotless,modulexcite/dotless,rytmis/dotless,r2i-sitecore/dotless,modulexcite/dotless,r2i-sitecore/dotless,modulexcite/dotless,r2i-sitecore/dotless,rytmis/dotless,r2i-sitecore/dotless,modulexcite/dotless
c5471cc62ebe67750c990c40fbe9bf0e40537259
src/Glimpse.Agent.AspNet/Internal/Inspectors/AspNet/EnvironmentInspector.cs
src/Glimpse.Agent.AspNet/Internal/Inspectors/AspNet/EnvironmentInspector.cs
using System; using Glimpse.Agent.AspNet.Messages; using Glimpse.Agent.Inspectors; using Microsoft.AspNet.Http; namespace Glimpse.Agent.AspNet.Internal.Inspectors.AspNet { public class EnvironmentInspector : Inspector { private readonly IAgentBroker _broker; private EnvironmentMessage _message; public EnvironmentInspector(IAgentBroker broker) { _broker = broker; } public override void Before(HttpContext context) { if (_message == null) { _message = new EnvironmentMessage { Server = Environment.MachineName, OperatingSystem = Environment.OSVersion.VersionString, ProcessorCount = Environment.ProcessorCount, Is64Bit = Environment.Is64BitOperatingSystem, CommandLineArgs = Environment.GetCommandLineArgs(), EnvironmentVariables = Environment.GetEnvironmentVariables() }; } _broker.SendMessage(_message); } } }
using System; using Glimpse.Agent.AspNet.Messages; using Glimpse.Agent.Inspectors; using Microsoft.AspNet.Http; namespace Glimpse.Agent.AspNet.Internal.Inspectors.AspNet { public class EnvironmentInspector : Inspector { private readonly IAgentBroker _broker; private EnvironmentMessage _message; public EnvironmentInspector(IAgentBroker broker) { _broker = broker; } public override void Before(HttpContext context) { //if (_message == null) //{ // _message = new EnvironmentMessage // { // Server = Environment.MachineName, // OperatingSystem = Environment.OSVersion.VersionString, // ProcessorCount = Environment.ProcessorCount, // Is64Bit = Environment.Is64BitOperatingSystem, // CommandLineArgs = Environment.GetCommandLineArgs(), // EnvironmentVariables = Environment.GetEnvironmentVariables() // }; //} //_broker.SendMessage(_message); } } }
Comment out the environment message for the time being
Comment out the environment message for the time being
C#
mit
Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype
36be6f9a16363774af9584f14a938f6397374b74
NavigationSample/Controllers/PersonController.cs
NavigationSample/Controllers/PersonController.cs
using Navigation.Sample.Models; using System; using System.Web.Mvc; namespace Navigation.Sample.Controllers { public class PersonController : Controller { public ActionResult Index(PersonSearchModel model, string sortExpression, int startRowIndex, int maximumRows) { DateTime outDate; if (model.MinDateOfBirth == null || DateTime.TryParse(model.MinDateOfBirth, out outDate)) { StateContext.Bag.name = model.Name; StateContext.Bag.minDateOfBirth = model.MinDateOfBirth; } else { ModelState.AddModelError("MinDateOfBirth", "date error"); } model.People = new PersonSearch().Search(StateContext.Bag.name, StateContext.Bag.minDateOfBirth, sortExpression, startRowIndex, maximumRows); return View("Listing", model); } public ActionResult GetDetails(int id) { return View("Details", new PersonSearch().GetDetails(id)); } } }
using Navigation.Sample.Models; using System; using System.Web.Mvc; namespace Navigation.Sample.Controllers { public class PersonController : Controller { public ActionResult Index(PersonSearchModel model) { DateTime outDate; if (model.MinDateOfBirth == null || DateTime.TryParse(model.MinDateOfBirth, out outDate)) { if (StateContext.Bag.name != model.Name || StateContext.Bag.minDateOfBirth != model.MinDateOfBirth) { StateContext.Bag.startRowIndex = null; StateContext.Bag.sortExpression = null; } StateContext.Bag.name = model.Name; StateContext.Bag.minDateOfBirth = model.MinDateOfBirth; } else { ModelState.AddModelError("MinDateOfBirth", "date error"); } model.People = new PersonSearch().Search(StateContext.Bag.name, StateContext.Bag.minDateOfBirth, StateContext.Bag.sortExpression, StateContext.Bag.startRowIndex, StateContext.Bag.maximumRows); return View("Listing", model); } public ActionResult GetDetails(int id) { return View("Details", new PersonSearch().GetDetails(id)); } } }
Clear sort and start when search changes (same as Web Forms). Cleaner to take data from StateContext instead of parameters because most can change within the method
Clear sort and start when search changes (same as Web Forms). Cleaner to take data from StateContext instead of parameters because most can change within the method
C#
apache-2.0
grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation
647d8adb568935f38246403416673d2a67f36537
RestSharp.Portable.Test/HttpBin/HttpBinResponse.cs
RestSharp.Portable.Test/HttpBin/HttpBinResponse.cs
using System.Collections.Generic; namespace RestSharp.Portable.Test.HttpBin { public class HttpBinResponse { public Dictionary<string, string> Args { get; set; } public Dictionary<string, string> Form { get; set; } public Dictionary<string, string> Headers { get; set; } public string Data { get; } public object Json { get; set; } } }
using System.Collections.Generic; namespace RestSharp.Portable.Test.HttpBin { public class HttpBinResponse { public Dictionary<string, string> Args { get; set; } public Dictionary<string, string> Form { get; set; } public Dictionary<string, string> Headers { get; set; } public string Data { get; set; } public object Json { get; set; } } }
Fix unit test by making the Data property writable
Fix unit test by making the Data property writable
C#
bsd-2-clause
gabornemeth/restsharp.portable
6fdced25dc7a38f312ea28c50b6f19484a958bb9
src/SparkPost/RequestSenders/AsyncRequestSender.cs
src/SparkPost/RequestSenders/AsyncRequestSender.cs
using System; using System.Globalization; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace SparkPost.RequestSenders { public class AsyncRequestSender : IRequestSender { private readonly IClient client; public AsyncRequestSender(IClient client) { this.client = client; } public async virtual Task<Response> Send(Request request) { using (var httpClient = client.CustomSettings.CreateANewHttpClient()) { httpClient.BaseAddress = new Uri(client.ApiHost); httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Add("Authorization", client.ApiKey); if (client.SubaccountId != 0) { httpClient.DefaultRequestHeaders.Add("X-MSYS-SUBACCOUNT", client.SubaccountId.ToString(CultureInfo.InvariantCulture)); } var result = await GetTheResponse(request, httpClient); return new Response { StatusCode = result.StatusCode, ReasonPhrase = result.ReasonPhrase, Content = await result.Content.ReadAsStringAsync() }; } } protected virtual async Task<HttpResponseMessage> GetTheResponse(Request request, HttpClient httpClient) { return await new RequestMethodFinder(httpClient) .FindFor(request) .Execute(request); } } }
using System; using System.Globalization; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace SparkPost.RequestSenders { public class AsyncRequestSender : IRequestSender { private readonly IClient client; public AsyncRequestSender(IClient client) { this.client = client; } public async virtual Task<Response> Send(Request request) { using (var httpClient = client.CustomSettings.CreateANewHttpClient()) { httpClient.BaseAddress = new Uri(client.ApiHost); // I don't think this is the right spot for this //httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Add("Authorization", client.ApiKey); if (client.SubaccountId != 0) { httpClient.DefaultRequestHeaders.Add("X-MSYS-SUBACCOUNT", client.SubaccountId.ToString(CultureInfo.InvariantCulture)); } var result = await GetTheResponse(request, httpClient); return new Response { StatusCode = result.StatusCode, ReasonPhrase = result.ReasonPhrase, Content = await result.Content.ReadAsStringAsync() }; } } protected virtual async Task<HttpResponseMessage> GetTheResponse(Request request, HttpClient httpClient) { return await new RequestMethodFinder(httpClient) .FindFor(request) .Execute(request); } } }
Drop in a note for later.
Drop in a note for later.
C#
apache-2.0
darrencauthon/csharp-sparkpost,kirilsi/csharp-sparkpost,SparkPost/csharp-sparkpost,kirilsi/csharp-sparkpost,darrencauthon/csharp-sparkpost,ZA1/csharp-sparkpost
b364aa61b137e4e37744ebb0cbeac3908524f4ce
src/Infrastructure/Repository/RoomRepository.cs
src/Infrastructure/Repository/RoomRepository.cs
using System; using System.Collections.Generic; using System.Linq; using ISTS.Domain.Rooms; using ISTS.Domain.Schedules; namespace ISTS.Infrastructure.Repository { public class RoomRepository : IRoomRepository { public Room Get(Guid id) { return null; } public RoomSession GetSession(Guid id) { return null; } public RoomSession CreateSession(Guid roomId, RoomSession entity) { return null; } public RoomSession RescheduleSession(Guid id, DateRange schedule) { return null; } public RoomSession StartSession(Guid id, DateTime time) { return null; } public RoomSession EndSession(Guid id, DateTime time) { return null; } public IEnumerable<RoomSessionSchedule> GetSchedule(Guid id, DateRange range) { return Enumerable.Empty<RoomSessionSchedule>(); } } }
using System; using System.Collections.Generic; using System.Linq; using ISTS.Domain.Rooms; using ISTS.Domain.Schedules; using ISTS.Infrastructure.Model; namespace ISTS.Infrastructure.Repository { public class RoomRepository : IRoomRepository { private readonly IstsContext _context; public RoomRepository( IstsContext context) { _context = context; } public Room Get(Guid id) { return null; } public RoomSession GetSession(Guid id) { return null; } public RoomSession CreateSession(Guid roomId, RoomSession entity) { return null; } public RoomSession RescheduleSession(Guid id, DateRange schedule) { return null; } public RoomSession StartSession(Guid id, DateTime time) { return null; } public RoomSession EndSession(Guid id, DateTime time) { return null; } public IEnumerable<RoomSessionSchedule> GetSchedule(Guid id, DateRange range) { var sessions = _context.Sessions .Where(s => s.RoomId == id) .ToList(); var schedule = sessions .Select(s => RoomSessionSchedule.Create(s.Id, s.Schedule)); return schedule; } } }
Implement GetSchedule functionality for Rooms
Implement GetSchedule functionality for Rooms
C#
mit
meutley/ISTS
749a0dd8779b4d075ecd7a84769718c0d28e1f7e
src/SFA.DAS.EmployerUsers.Web/Views/Account/Login.cshtml
src/SFA.DAS.EmployerUsers.Web/Views/Account/Login.cshtml
<div class="grid-row"> <div class="column-half"> <h1 class="heading-large">Sign in</h1> <form method="post"> @Html.AntiForgeryToken() <div class="form-group"> <label class="form-label" for="email-address">Email address</label> <input class="form-control form-control-3-4" id="email-address" name="EmailAddress" type="text"> </div> <div class="form-group"> <label class="form-label" for="password">Password</label> <input class="form-control form-control-3-4" id="password" name="Password" type="password"> <p> <a href="#">I can't access my account</a> </p> </div> <div class="form-group"> <button type="submit" class="button">Sign in</button> </div> </form> </div> <div class="column-half"> <h1 class="heading-large">New to this service?</h1> <p>If you haven’t used this service before you must <a href="@Url.Action("Register", "Account")">create an account</a></p> </div> </div>
@model bool @{ var invalidAttributes = Model ? "aria-invalid=\"true\" aria-labeledby=\"invalidMessage\"" : ""; } <div class="grid-row"> <div class="column-half"> <h1 class="heading-large">Sign in</h1> @if (Model) { <div class="error" style="margin-bottom: 10px;" id="invalidMessage"> <p class="error-message">Invalid Email address / Password</p> </div> } <form method="post"> @Html.AntiForgeryToken() <div class="form-group"> <label class="form-label" for="email-address">Email address</label> <input class="form-control form-control-3-4" id="email-address" name="EmailAddress" type="text" autofocus="autofocus" aria-required="true" @invalidAttributes> </div> <div class="form-group"> <label class="form-label" for="password">Password</label> <input class="form-control form-control-3-4" id="password" name="Password" type="password" aria-required="true" @invalidAttributes> <p> <a href="#">I can't access my account</a> </p> </div> <div class="form-group"> <button type="submit" class="button">Sign in</button> </div> </form> </div> <div class="column-half"> <h1 class="heading-large">New to this service?</h1> <p>If you haven’t used this service before you must <a href="@Url.Action("Register", "Account")">create an account</a></p> </div> </div>
Add invalid message + aria tags to login
Add invalid message + aria tags to login
C#
mit
SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers
dcfe9e39a17d3739942e4f619404d6ba9c618942
src/AST/Preprocessor.cs
src/AST/Preprocessor.cs
namespace CppSharp.AST { public enum MacroLocation { Unknown, ClassHead, ClassBody, FunctionHead, FunctionParameters, FunctionBody, }; /// <summary> /// Base class that describes a preprocessed entity, which may /// be a preprocessor directive or macro expansion. /// </summary> public abstract class PreprocessedEntity : Declaration { public MacroLocation MacroLocation = MacroLocation.Unknown; } /// <summary> /// Represents a C preprocessor macro expansion. /// </summary> public class MacroExpansion : PreprocessedEntity { // Contains the macro expansion text. public string Text; public MacroDefinition Definition; public override T Visit<T>(IDeclVisitor<T> visitor) { //return visitor.VisitMacroExpansion(this); return default(T); } public override string ToString() { return Text; } } /// <summary> /// Represents a C preprocessor macro definition. /// </summary> public class MacroDefinition : PreprocessedEntity { // Contains the macro definition text. public string Expression; // Backing enumeration if one was generated. public Enumeration Enumeration; public override T Visit<T>(IDeclVisitor<T> visitor) { return visitor.VisitMacroDefinition(this); } public override string ToString() { return Expression; } } }
namespace CppSharp.AST { public enum MacroLocation { Unknown, ClassHead, ClassBody, FunctionHead, FunctionParameters, FunctionBody, }; /// <summary> /// Base class that describes a preprocessed entity, which may /// be a preprocessor directive or macro expansion. /// </summary> public abstract class PreprocessedEntity : Declaration { public MacroLocation MacroLocation = MacroLocation.Unknown; } /// <summary> /// Represents a C preprocessor macro expansion. /// </summary> public class MacroExpansion : PreprocessedEntity { // Contains the macro expansion text. public string Text; public MacroDefinition Definition; public override T Visit<T>(IDeclVisitor<T> visitor) { //return visitor.VisitMacroExpansion(this); return default(T); } public override string ToString() { return Text; } } /// <summary> /// Represents a C preprocessor macro definition. /// </summary> public class MacroDefinition : PreprocessedEntity { // Contains the macro definition text. public string Expression; // Backing enumeration if one was generated. public Enumeration Enumeration; public override T Visit<T>(IDeclVisitor<T> visitor) { return visitor.VisitMacroDefinition(this); } public override string ToString() { return string.Format("{0} = {1}", Name, Expression); } } }
Improve debug string representation of MacroDefinition.
Improve debug string representation of MacroDefinition.
C#
mit
inordertotest/CppSharp,SonyaSa/CppSharp,genuinelucifer/CppSharp,SonyaSa/CppSharp,mono/CppSharp,zillemarco/CppSharp,u255436/CppSharp,mono/CppSharp,genuinelucifer/CppSharp,inordertotest/CppSharp,mydogisbox/CppSharp,ktopouzi/CppSharp,zillemarco/CppSharp,mono/CppSharp,inordertotest/CppSharp,mono/CppSharp,mohtamohit/CppSharp,ddobrev/CppSharp,ddobrev/CppSharp,ktopouzi/CppSharp,u255436/CppSharp,ddobrev/CppSharp,genuinelucifer/CppSharp,mohtamohit/CppSharp,ddobrev/CppSharp,zillemarco/CppSharp,inordertotest/CppSharp,u255436/CppSharp,Samana/CppSharp,mydogisbox/CppSharp,Samana/CppSharp,ktopouzi/CppSharp,mono/CppSharp,Samana/CppSharp,SonyaSa/CppSharp,ddobrev/CppSharp,inordertotest/CppSharp,zillemarco/CppSharp,genuinelucifer/CppSharp,SonyaSa/CppSharp,Samana/CppSharp,ktopouzi/CppSharp,mohtamohit/CppSharp,zillemarco/CppSharp,mono/CppSharp,u255436/CppSharp,mydogisbox/CppSharp,u255436/CppSharp,ktopouzi/CppSharp,mohtamohit/CppSharp,SonyaSa/CppSharp,genuinelucifer/CppSharp,mydogisbox/CppSharp,mohtamohit/CppSharp,mydogisbox/CppSharp,Samana/CppSharp
ae4cf0abfc1312e7c3c9513e3ddd8d4b43ce6b4d
LiteDB.Tests/Crud/FileStorageTest.cs
LiteDB.Tests/Crud/FileStorageTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; namespace LiteDB.Tests { [TestClass] public class FileStorage_Test { [TestMethod] public void FileStorage_InsertDelete() { // create a dump file File.WriteAllText("Core.dll", "FileCoreContent"); using (var db = new LiteDatabase(new MemoryStream())) { db.FileStorage.Upload("Core.dll", "Core.dll"); var exists = db.FileStorage.Exists("Core.dll"); Assert.AreEqual(true, exists); var deleted = db.FileStorage.Delete("Core.dll"); Assert.AreEqual(true, deleted); var deleted2 = db.FileStorage.Delete("Core.dll"); Assert.AreEqual(false, deleted2); } File.Delete("Core.dll"); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; using System.Linq; using System.Text; namespace LiteDB.Tests { [TestClass] public class FileStorage_Test { [TestMethod] public void FileStorage_InsertDelete() { // create a dump file File.WriteAllText("Core.dll", "FileCoreContent"); using (var db = new LiteDatabase(new MemoryStream())) { // upload db.FileStorage.Upload("Core.dll", "Core.dll"); // exits var exists = db.FileStorage.Exists("Core.dll"); Assert.AreEqual(true, exists); // find var files = db.FileStorage.Find("Core"); Assert.AreEqual(1, files.Count()); Assert.AreEqual("Core.dll", files.First().Id); // find by id var core = db.FileStorage.FindById("Core.dll"); Assert.IsNotNull(core); Assert.AreEqual("Core.dll", core.Id); // download var mem = new MemoryStream(); db.FileStorage.Download("Core.dll", mem); var content = Encoding.UTF8.GetString(mem.ToArray()); Assert.AreEqual("FileCoreContent", content); // delete var deleted = db.FileStorage.Delete("Core.dll"); Assert.AreEqual(true, deleted); // not found deleted var deleted2 = db.FileStorage.Delete("Core.dll"); Assert.AreEqual(false, deleted2); } File.Delete("Core.dll"); } } }
Add more unit test filestorage
Add more unit test filestorage
C#
mit
masterdidoo/LiteDB,falahati/LiteDB,89sos98/LiteDB,RytisLT/LiteDB,prepare/LiteDB,RytisLT/LiteDB,89sos98/LiteDB,prepare/LiteDB,prepare/LiteDB,falahati/LiteDB,Skysper/LiteDB,prepare/LiteDB,Xicy/LiteDB,masterdidoo/LiteDB,mbdavid/LiteDB,icelty/LiteDB
6832af7196b6f87925f4aea65e7a8a6aef72242e
Core/OfficeDevPnP.Core/Pages/ClientSideSectionEmphasis.cs
Core/OfficeDevPnP.Core/Pages/ClientSideSectionEmphasis.cs
using Newtonsoft.Json; namespace OfficeDevPnP.Core.Pages { public class ClientSideSectionEmphasis { [JsonIgnore] public int ZoneEmphasis { get { if (!string.IsNullOrWhiteSpace(ZoneEmphasisString) && int.TryParse(ZoneEmphasisString, out int result)) { return result; } return 0; } set { ZoneEmphasisString = value.ToString(); } } [JsonProperty(PropertyName = "zoneEmphasis", NullValueHandling = NullValueHandling.Ignore)] public string ZoneEmphasisString { get; set; } } }
using Newtonsoft.Json; namespace OfficeDevPnP.Core.Pages { public class ClientSideSectionEmphasis { [JsonProperty(PropertyName = "zoneEmphasis", NullValueHandling = NullValueHandling.Ignore)] public int ZoneEmphasis { get { if (!string.IsNullOrWhiteSpace(ZoneEmphasisString) && int.TryParse(ZoneEmphasisString, out int result)) { return result; } return 0; } set { ZoneEmphasisString = value.ToString(); } } [JsonIgnore] public string ZoneEmphasisString { get; set; } } }
Fix serialization of the zoneemphasis
Fix serialization of the zoneemphasis
C#
mit
OfficeDev/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,OfficeDev/PnP-Sites-Core
2da8f73a056e13f249f47de1dd0640f5374f5cca
UnityProject/Assets/Scripts/Messages/GameMessageBase.cs
UnityProject/Assets/Scripts/Messages/GameMessageBase.cs
using System.Collections; using UnityEngine; using UnityEngine.Networking; public abstract class GameMessageBase : MessageBase { public GameObject NetworkObject; public GameObject[] NetworkObjects; protected IEnumerator WaitFor(NetworkInstanceId id) { int tries = 0; while ((NetworkObject = ClientScene.FindLocalObject(id)) == null) { if (tries++ > 10) { Debug.LogWarning("GameMessageBase could not find object with id " + id); yield break; } yield return YieldHelper.EndOfFrame; } } protected IEnumerator WaitFor(params NetworkInstanceId[] ids) { NetworkObjects = new GameObject[ids.Length]; while (!AllLoaded(ids)) { yield return YieldHelper.EndOfFrame; } } private bool AllLoaded(NetworkInstanceId[] ids) { for (int i = 0; i < ids.Length; i++) { GameObject obj = ClientScene.FindLocalObject(ids[i]); if (obj == null) { return false; } NetworkObjects[i] = obj; } return true; } }
using System.Collections; using UnityEngine; using UnityEngine.Networking; public abstract class GameMessageBase : MessageBase { public GameObject NetworkObject; public GameObject[] NetworkObjects; protected IEnumerator WaitFor(NetworkInstanceId id) { int tries = 0; while ((NetworkObject = ClientScene.FindLocalObject(id)) == null) { if (tries++ > 10) { Debug.LogWarning($"{this} could not find object with id {id}"); yield break; } yield return YieldHelper.EndOfFrame; } } protected IEnumerator WaitFor(params NetworkInstanceId[] ids) { NetworkObjects = new GameObject[ids.Length]; while (!AllLoaded(ids)) { yield return YieldHelper.EndOfFrame; } } private bool AllLoaded(NetworkInstanceId[] ids) { for (int i = 0; i < ids.Length; i++) { GameObject obj = ClientScene.FindLocalObject(ids[i]); if (obj == null) { return false; } NetworkObjects[i] = obj; } return true; } }
Print more info if the message times out while waiting
Print more info if the message times out while waiting
C#
agpl-3.0
MrLeebo/unitystation,MrLeebo/unitystation,fomalsd/unitystation,fomalsd/unitystation,MrLeebo/unitystation,Necromunger/unitystation,krille90/unitystation,Necromunger/unitystation,MrLeebo/unitystation,fomalsd/unitystation,fomalsd/unitystation,Lancemaker/unitystation,Necromunger/unitystation,krille90/unitystation,Lancemaker/unitystation,Necromunger/unitystation,MrLeebo/unitystation,MrLeebo/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation,Necromunger/unitystation,fomalsd/unitystation
4ce3b07ba1fa4ef07a6d6f910050e134d56c6bf0
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; if (!extractor.TryExtract(context.Request.Headers, out trace)) { trace = Trace.Create(); } Trace.Current = trace; using (new ServerTrace(serviceName, context.Request.Method)) { await TraceHelper.TracedActionAsync(next()); } }); } } }
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()); } }); } } }
Add http path under http.uri tag
Add http path under http.uri tag
C#
apache-2.0
criteo/zipkin4net,criteo/zipkin4net
dc8fae7d8fa18f545f9dfb055dad58409a4dcaca
Src/TensorSharp/Operations/DivideDoubleDoubleOperation.cs
Src/TensorSharp/Operations/DivideDoubleDoubleOperation.cs
namespace TensorSharp.Operations { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class DivideDoubleDoubleOperation : IBinaryOperation<double, double, double> { public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2) { Tensor<double> result = new Tensor<double>(); result.SetValue(tensor1.GetValue() / tensor2.GetValue()); return result; } } }
namespace TensorSharp.Operations { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class DivideDoubleDoubleOperation : IBinaryOperation<double, double, double> { public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2) { double[] values1 = tensor1.GetValues(); int l = values1.Length; double value2 = tensor2.GetValue(); double[] newvalues = new double[l]; for (int k = 0; k < l; k++) newvalues[k] = values1[k] / value2; return tensor1.CloneWithNewValues(newvalues); } } }
Refactor Divide Doubles operation to use GetValues and CloneWithValues
Refactor Divide Doubles operation to use GetValues and CloneWithValues
C#
mit
ajlopez/TensorSharp
823e2079dd1d06bbf666a5187b4faefbc5cda46c
core/Akka.Interfaced-Base/InterfacedActorRefExtensions.cs
core/Akka.Interfaced-Base/InterfacedActorRefExtensions.cs
namespace Akka.Interfaced { public static class InterfacedActorRefExtensions { // Cast (not type-safe) public static TRef Cast<TRef>(this InterfacedActorRef actorRef) where TRef : InterfacedActorRef, new() { if (actorRef == null) return null; return new TRef() { Target = actorRef.Target, RequestWaiter = actorRef.RequestWaiter, Timeout = actorRef.Timeout }; } // Wrap target into TRef (not type-safe) public static TRef Cast<TRef>(this BoundActorTarget target) where TRef : InterfacedActorRef, new() { if (target == null) return null; return new TRef() { Target = target, RequestWaiter = target.DefaultRequestWaiter }; } } }
namespace Akka.Interfaced { public static class InterfacedActorRefExtensions { // Cast (not type-safe) public static TRef Cast<TRef>(this InterfacedActorRef actorRef) where TRef : InterfacedActorRef, new() { if (actorRef == null) return null; return new TRef() { Target = actorRef.Target, RequestWaiter = actorRef.RequestWaiter, Timeout = actorRef.Timeout }; } // Wrap target into TRef (not type-safe) public static TRef Cast<TRef>(this IRequestTarget target) where TRef : InterfacedActorRef, new() { if (target == null) return null; return new TRef() { Target = target, RequestWaiter = target.DefaultRequestWaiter }; } } }
Add IRequestTarget.Cast instead of BoundActorTarget.*
Add IRequestTarget.Cast instead of BoundActorTarget.*
C#
mit
SaladLab/Akka.Interfaced,SaladbowlCreative/Akka.Interfaced,SaladLab/Akka.Interfaced,SaladbowlCreative/Akka.Interfaced
874034d109b74125d87b8d1d6c44fae54476339b
src/IdentityModel/Client/BasicAuthenticationHeaderValue.cs
src/IdentityModel/Client/BasicAuthenticationHeaderValue.cs
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System.Net.Http.Headers; using System.Text; namespace System.Net.Http { public class BasicAuthenticationHeaderValue : AuthenticationHeaderValue { public BasicAuthenticationHeaderValue(string userName, string password) : base("Basic", EncodeCredential(userName, password)) { } private static string EncodeCredential(string userName, string password) { Encoding encoding = Encoding.UTF8; string credential = String.Format("{0}:{1}", userName, password); return Convert.ToBase64String(encoding.GetBytes(credential)); } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System.Net.Http.Headers; using System.Text; namespace System.Net.Http { public class BasicAuthenticationHeaderValue : AuthenticationHeaderValue { public BasicAuthenticationHeaderValue(string userName, string password) : base("Basic", EncodeCredential(userName, password)) { } private static string EncodeCredential(string userName, string password) { if (string.IsNullOrWhiteSpace(userName)) throw new ArgumentNullException(nameof(userName)); if (password == null) password = ""; Encoding encoding = Encoding.UTF8; string credential = String.Format("{0}:{1}", userName, password); return Convert.ToBase64String(encoding.GetBytes(credential)); } } }
Add error checking to basic auth header
Add error checking to basic auth header
C#
apache-2.0
IdentityModel/IdentityModelv2,IdentityModel/IdentityModel,IdentityModel/IdentityModelv2,IdentityModel/IdentityModel2,IdentityModel/IdentityModel,IdentityModel/IdentityModel2
c2ba47821a69993412a93c012c39ce8d90ff2b1e
Battery-Commander.Web/Queries/GetCurrentUser.cs
Battery-Commander.Web/Queries/GetCurrentUser.cs
using System.Linq; using System.Threading; using System.Threading.Tasks; using BatteryCommander.Web.Models; using MediatR; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; namespace BatteryCommander.Web.Queries { public class GetCurrentUser : IRequest<Soldier> { private class Handler : IRequestHandler<GetCurrentUser, Soldier> { private readonly Database db; private readonly IHttpContextAccessor http; public Handler(Database db, IHttpContextAccessor http) { this.db = db; this.http = http; } public async Task<Soldier> Handle(GetCurrentUser request, CancellationToken cancellationToken) { var email = http .HttpContext .User? .Identity? .Name; var soldier = await db .Soldiers .Include(s => s.Supervisor) .Include(s => s.SSDSnapshots) .Include(s => s.ABCPs) .Include(s => s.ACFTs) .Include(s => s.APFTs) .Include(s => s.Unit) .Where(s => s.CivilianEmail == email) .AsNoTracking() .SingleOrDefaultAsync(cancellationToken); return soldier; } } } }
using System.Linq; using System.Threading; using System.Threading.Tasks; using BatteryCommander.Web.Models; using MediatR; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; namespace BatteryCommander.Web.Queries { public class GetCurrentUser : IRequest<Soldier> { private class Handler : IRequestHandler<GetCurrentUser, Soldier> { private readonly Database db; private readonly IHttpContextAccessor http; public Handler(Database db, IHttpContextAccessor http) { this.db = db; this.http = http; } public async Task<Soldier> Handle(GetCurrentUser request, CancellationToken cancellationToken) { var email = http .HttpContext .User? .Identity? .Name; if (string.IsNullOrWhiteSpace(email)) return default(Soldier); var soldier = await db .Soldiers .Include(s => s.Supervisor) .Include(s => s.SSDSnapshots) .Include(s => s.ABCPs) .Include(s => s.ACFTs) .Include(s => s.APFTs) .Include(s => s.Unit) .Where(s => s.CivilianEmail == email) .AsNoTracking() .SingleOrDefaultAsync(cancellationToken); return soldier; } } } }
Fix for get current user on anon page
Fix for get current user on anon page
C#
mit
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
b6788916856c16d1246450bd1308c16c504eb7f9
src/Cake.Common/Tools/NuGet/NuGetMSBuildVersion.cs
src/Cake.Common/Tools/NuGet/NuGetMSBuildVersion.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Cake.Common.Tools.NuGet { /// <summary> /// NuGet MSBuild version /// </summary> public enum NuGetMSBuildVersion { /// <summary> /// MSBuildVersion : <c>4</c> /// </summary> MSBuild4 = 4, /// <summary> /// MSBuildVersion : <c>12</c> /// </summary> MSBuild12 = 12, /// <summary> /// MSBuildVersion : <c>14</c> /// </summary> MSBuild14 = 14 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Cake.Common.Tools.NuGet { /// <summary> /// NuGet MSBuild version /// </summary> public enum NuGetMSBuildVersion { /// <summary> /// MSBuildVersion : <c>4</c> /// </summary> MSBuild4 = 4, /// <summary> /// MSBuildVersion : <c>12</c> /// </summary> MSBuild12 = 12, /// <summary> /// MSBuildVersion : <c>14</c> /// </summary> MSBuild14 = 14, /// <summary> /// MSBuildVersion : <c>15</c> /// </summary> MSBuild15 = 15 } }
Update enum for VS 2017
Update enum for VS 2017
C#
mit
Sam13/cake,cake-build/cake,mholo65/cake,gep13/cake,robgha01/cake,daveaglick/cake,gep13/cake,mholo65/cake,Sam13/cake,vlesierse/cake,cake-build/cake,Julien-Mialon/cake,phenixdotnet/cake,adamhathcock/cake,patriksvensson/cake,robgha01/cake,ferventcoder/cake,devlead/cake,patriksvensson/cake,thomaslevesque/cake,adamhathcock/cake,devlead/cake,ferventcoder/cake,phenixdotnet/cake,daveaglick/cake,vlesierse/cake,thomaslevesque/cake,Julien-Mialon/cake,DixonD-git/cake
9bdbd17964ea71ea1c51a4b7c94f942483a835ce
Updater/Program.cs
Updater/Program.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Updater { class Program { static void Main(string[] args) { if (args.Length == 0) { TryStartSc(); } if (args.Length != 2) return; var setupExe= args[0]; var setupExeArgs = args[1]; if (!File.Exists(setupExe)) { Environment.ExitCode = -1; return; } //Console.WriteLine("Updating..."); var p = Process.Start(setupExe, setupExeArgs); if (p.WaitForExit(10000)) { TryStartSc(); } } public static bool TryStartSc() { var scExe = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "osu!StreamCompanion.exe"); if (File.Exists(scExe)) { Process.Start(scExe); return true; } return false; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Updater { class Program { static void Main(string[] args) { if (args.Length == 0) { TryStartSc(); } if (args.Length != 2) return; var setupExe= args[0]; var setupExeArgs = args[1]; if (!File.Exists(setupExe)) { Environment.ExitCode = -1; return; } //Console.WriteLine("Updating..."); var p = Process.Start(setupExe, setupExeArgs); } public static bool TryStartSc() { var scExe = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "osu!StreamCompanion.exe"); if (File.Exists(scExe)) { Process.Start(scExe); return true; } return false; } } }
Fix setup not being able to start for first 10s
Fix setup not being able to start for first 10s
C#
mit
Piotrekol/StreamCompanion,Piotrekol/StreamCompanion
8965d1c6f8e2b2bc9d1eb2882b2029769200da4d
src/Nest/Cat/CatSnapshots/CatSnapshotsRecord.cs
src/Nest/Cat/CatSnapshots/CatSnapshotsRecord.cs
using System.Runtime.Serialization; using Elasticsearch.Net.Utf8Json; namespace Nest { [DataContract] public class CatSnapshotsRecord : ICatRecord { [DataMember(Name ="duration")] public Time Duration { get; set; } [DataMember(Name ="end_epoch")] [JsonFormatter(typeof(StringLongFormatter))] public long EndEpoch { get; set; } [DataMember(Name ="end_time")] public string EndTime { get; set; } [DataMember(Name ="failed_shards")] [JsonFormatter(typeof(StringLongFormatter))] public long FailedShards { get; set; } // duration indices successful_shards failed_shards total_shards [DataMember(Name ="id")] public string Id { get; set; } [DataMember(Name ="indices")] [JsonFormatter(typeof(StringLongFormatter))] public long Indices { get; set; } [DataMember(Name ="start_epoch")] [JsonFormatter(typeof(StringLongFormatter))] public long StartEpoch { get; set; } [DataMember(Name ="start_time")] public string StartTime { get; set; } [DataMember(Name ="status")] public string Status { get; set; } [DataMember(Name ="succesful_shards")] [JsonFormatter(typeof(StringLongFormatter))] public long SuccesfulShards { get; set; } [DataMember(Name ="total_shards")] [JsonFormatter(typeof(StringLongFormatter))] public long TotalShards { get; set; } } }
using System.Runtime.Serialization; using Elasticsearch.Net.Utf8Json; namespace Nest { [DataContract] public class CatSnapshotsRecord : ICatRecord { [DataMember(Name ="duration")] public Time Duration { get; set; } [DataMember(Name ="end_epoch")] [JsonFormatter(typeof(StringLongFormatter))] public long EndEpoch { get; set; } [DataMember(Name ="end_time")] public string EndTime { get; set; } [DataMember(Name ="failed_shards")] [JsonFormatter(typeof(StringLongFormatter))] public long FailedShards { get; set; } // duration indices successful_shards failed_shards total_shards [DataMember(Name ="id")] public string Id { get; set; } [DataMember(Name ="indices")] [JsonFormatter(typeof(StringLongFormatter))] public long Indices { get; set; } [DataMember(Name ="start_epoch")] [JsonFormatter(typeof(StringLongFormatter))] public long StartEpoch { get; set; } [DataMember(Name ="start_time")] public string StartTime { get; set; } [DataMember(Name ="status")] public string Status { get; set; } [DataMember(Name ="successful_shards")] [JsonFormatter(typeof(StringLongFormatter))] public long SuccessfulShards { get; set; } [DataMember(Name ="total_shards")] [JsonFormatter(typeof(StringLongFormatter))] public long TotalShards { get; set; } } }
Fix spelling of SuccessfulShards in CatSnapshots
Fix spelling of SuccessfulShards in CatSnapshots
C#
apache-2.0
elastic/elasticsearch-net,elastic/elasticsearch-net
ad16632c8ebfc781c9cfdd63b7c1080096da2c98
3-Editing/1-Code_completion/1.3-Smart_completion.cs
3-Editing/1-Code_completion/1.3-Smart_completion.cs
namespace JetBrains.ReSharper.Koans.Editing { // Smart Completion // // Narrows candidates to those that best suit the current context // // Ctrl+Alt+Space (VS) // Ctrl+Shift+Space (IntelliJ) public class SmartCompletion { // 1. Start typing: string s = // Automatic Completion offers Smart Completion items first (string items) // (followed by local Basic items, wider Basic and then Import items) // 2. Uncomment: string s2 = // Invoke Smart Completion at the end of the line // Smart Completion only shows string based candidates // (Including methods that return string, such as String.Concat) // 3. Uncomment: string s3 = this. // Invoke Smart Completion at the end of the line // Smart Completion only shows string based candidates for the this parameter // Note that the Age property isn't used public void SmartUseString(string stringParameter) { //string s2 = string s3 = this. } public int Age { get; set; } #region Implementation details public string Name { get; set; } public string GetGreeting() { return "hello"; } #endregion } }
namespace JetBrains.ReSharper.Koans.Editing { // Smart Completion // // Narrows candidates to those that best suit the current context // // Ctrl+Alt+Space (VS) // Ctrl+Shift+Space (IntelliJ) public class SmartCompletion { // 1. Start typing: string s = // Automatic Completion offers Smart Completion items first (string items) // (followed by local Basic items, wider Basic and then Import items) // 2. Uncomment: string s2 = // Invoke Smart Completion at the end of the line // Smart Completion only shows string based candidates // (Including methods that return string, such as String.Concat) // 3. Uncomment: string s3 = this. // Invoke Smart Completion at the end of the line // Smart Completion only shows string based candidates for the this parameter // Note that the Age property isn't used public void SmartUseString(string stringParameter) { //string s2 = //string s3 = this. } public int Age { get; set; } #region Implementation details public string Name { get; set; } public string GetGreeting() { return "hello"; } #endregion } }
Comment code that should be commented
Comment code that should be commented
C#
apache-2.0
JetBrains/resharper-workshop,yskatsumata/resharper-workshop,yskatsumata/resharper-workshop,JetBrains/resharper-workshop,gorohoroh/resharper-workshop,gorohoroh/resharper-workshop,yskatsumata/resharper-workshop,gorohoroh/resharper-workshop,JetBrains/resharper-workshop
1e9a5f462ad5e5db4ed29dc9c4c0f477453cbc83
src/Tests/Data.NHibernate4.Tests/CompileTests.cs
src/Tests/Data.NHibernate4.Tests/CompileTests.cs
using System; using System.Data; using System.Linq; using Cobweb.Data; using Cobweb.Data.NHibernate; using NHibernate; namespace Data.NHibernate.Tests { /// <summary> /// These tests are not executed by NUnit. They are here for compile-time checking. 'If it builds, ship it.' /// </summary> public class CompileTests { internal class SessionBuilder : NHibernateSessionBuilder { public override IDataTransaction BeginTransaction() { return new NHibernateTransactionHandler(GetCurrentSession().BeginTransaction()); } public override IDataTransaction BeginTransaction(IsolationLevel isolationLevel) { return new NHibernateTransactionHandler(GetCurrentSession().BeginTransaction()); } public override ISession GetCurrentSession() { throw new NotImplementedException(); } } } }
using System; using System.Data; using System.Linq; using NHibernate; namespace Cobweb.Data.NHibernate.Tests { /// <summary> /// These tests are not executed by NUnit. They are here for compile-time checking. 'If it builds, ship it.' /// </summary> public class CompileTests { internal class SessionBuilder : NHibernateSessionBuilder { public override IDataTransaction BeginTransaction() { return new NHibernateTransactionHandler(GetCurrentSession().BeginTransaction()); } public override IDataTransaction BeginTransaction(IsolationLevel isolationLevel) { return new NHibernateTransactionHandler(GetCurrentSession().BeginTransaction()); } public override ISession GetCurrentSession() { throw new NotImplementedException(); } } } }
Adjust namespaces for Data.NHibernate4 unit tests.
fix(tests): Adjust namespaces for Data.NHibernate4 unit tests.
C#
bsd-3-clause
aranasoft/cobweb
59d4744c84c2fa35b26b54722f0c9f650587e9e5
tests/cs/boxing/Boxing.cs
tests/cs/boxing/Boxing.cs
using System; public struct Foo : ICloneable { public int CloneCounter { get; private set; } public object Clone() { CloneCounter++; return this; } } public static class Program { public static ICloneable BoxAndCast<T>(T Value) { return (ICloneable)Value; } public static void Main(string[] Args) { var foo = default(Foo); Console.WriteLine(((Foo)foo.Clone()).CloneCounter); Console.WriteLine(((Foo)BoxAndCast<Foo>(foo).Clone()).CloneCounter); Console.WriteLine(foo.CloneCounter); } }
using System; public struct Foo : ICloneable { public int CloneCounter { get; private set; } public object Clone() { CloneCounter++; return this; } } public static class Program { public static ICloneable BoxAndCast<T>(T Value) { return (ICloneable)Value; } public static void Main(string[] Args) { var foo = default(Foo); Console.WriteLine(((Foo)foo.Clone()).CloneCounter); Console.WriteLine(((Foo)BoxAndCast<Foo>(foo).Clone()).CloneCounter); Console.WriteLine(foo.CloneCounter); object i = 42; Console.WriteLine((int)i); } }
Extend the boxing/unboxing test with a primitive value unbox
Extend the boxing/unboxing test with a primitive value unbox
C#
mit
jonathanvdc/ecsc
48887ebf49e0bdd33581bb587385bc63897a7e57
Smoother.IoC.Dapper.Repository.UnitOfWork.Tests/TestClasses/Migrations/MigrateDb.cs
Smoother.IoC.Dapper.Repository.UnitOfWork.Tests/TestClasses/Migrations/MigrateDb.cs
using System.Data; using System.Data.SQLite; using System.Reflection; using FakeItEasy; using FakeItEasy.Core; using SimpleMigrations; using SimpleMigrations.VersionProvider; using Smoother.IoC.Dapper.Repository.UnitOfWork.Data; using Smoother.IoC.Dapper.Repository.UnitOfWork.UoW; namespace Smoother.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestClasses.Migrations { public class MigrateDb { public ISession Connection { get; } public MigrateDb() { var migrationsAssembly = Assembly.GetExecutingAssembly(); var versionProvider = new SqliteVersionProvider(); var factory = A.Fake<IDbFactory>(); Connection = new TestSession(factory, "Data Source=:memory:;Version=3;New=True;"); A.CallTo(() => factory.CreateUnitOwWork<IUnitOfWork>(A<IDbFactory>._, A<ISession>._)) .ReturnsLazily(CreateUnitOrWork); var migrator = new SimpleMigrator(migrationsAssembly, Connection, versionProvider); migrator.Load(); migrator.MigrateToLatest(); } private IUnitOfWork CreateUnitOrWork(IFakeObjectCall arg) { return new Dapper.Repository.UnitOfWork.Data.UnitOfWork((IDbFactory) arg.FakedObject, Connection); } } public class TestSession : SqliteSession<SQLiteConnection> { public TestSession(IDbFactory factory, string connectionString) : base(factory, connectionString) { } } }
using System.Data; using System.Data.SQLite; using System.Reflection; using FakeItEasy; using FakeItEasy.Core; using SimpleMigrations; using SimpleMigrations.VersionProvider; using Smoother.IoC.Dapper.Repository.UnitOfWork.Data; using Smoother.IoC.Dapper.Repository.UnitOfWork.UoW; namespace Smoother.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestClasses.Migrations { public class MigrateDb { public ISession Connection { get; } public MigrateDb() { var migrationsAssembly = Assembly.GetExecutingAssembly(); var versionProvider = new SqliteVersionProvider(); var factory = A.Fake<IDbFactory>(); Connection = new TestSession(factory, "Data Source=:memory:;Version=3;New=True;"); A.CallTo(() => factory.CreateUnitOwWork<IUnitOfWork>(A<IDbFactory>._, A<ISession>._)) .ReturnsLazily(CreateUnitOrWork); var migrator = new SimpleMigrator(migrationsAssembly, Connection, versionProvider); migrator.Load(); migrator.MigrateToLatest(); } private IUnitOfWork CreateUnitOrWork(IFakeObjectCall arg) { return new Dapper.Repository.UnitOfWork.Data.UnitOfWork((IDbFactory) arg.FakedObject, Connection); } } internal class TestSession : SqliteSession<SQLiteConnection> { public TestSession(IDbFactory factory, string connectionString) : base(factory, connectionString) { } } }
Fix issue with test class
Fix issue with test class
C#
mit
generik0/Smooth.IoC.Dapper.Repository.UnitOfWork,generik0/Smooth.IoC.Dapper.Repository.UnitOfWork
37611b467b6dec0f659eee2b9b127170668e0e97
DisplayCurrentTime/DisplayCurrentTime/Program.cs
DisplayCurrentTime/DisplayCurrentTime/Program.cs
using System; class Program { static void Main() { Console.WriteLine("Hello, C#!"); } }
using System; class Program { static void Main() { Console.WriteLine(DateTime.Now); } }
Repair error in Console Writeline
Repair error in Console Writeline
C#
mit
pkindalov/beginner_exercises
c809b662c08b0c843d3b8d2360ddd027e93b0dcc
src/GitHub.Exports/Services/ITeamExplorerContext.cs
src/GitHub.Exports/Services/ITeamExplorerContext.cs
using System; using System.ComponentModel; using GitHub.Models; namespace GitHub.Services { /// <summary> /// Responsible for watching the active repository in Team Explorer. /// </summary> /// <remarks> /// A <see cref="PropertyChanged"/> event is fired when moving to a new repository. /// A <see cref="StatusChanged"/> event is fired when the CurrentBranch or HeadSha changes. /// </remarks> public interface ITeamExplorerContext : INotifyPropertyChanged { /// <summary> /// The active Git repository in Team Explorer. /// This will be null if no repository is active. /// </summary> ILocalRepositoryModel ActiveRepository { get; } /// <summary> /// Fired when the CurrentBranch or HeadSha changes. /// </summary> event EventHandler StatusChanged; } }
using System; using System.ComponentModel; using GitHub.Models; namespace GitHub.Services { /// <summary> /// Responsible for watching the active repository in Team Explorer. /// </summary> /// <remarks> /// A <see cref="PropertyChanged"/> event is fired when moving to a new repository. /// A <see cref="StatusChanged"/> event is fired when the CurrentBranch or HeadSha changes. /// </remarks> public interface ITeamExplorerContext : INotifyPropertyChanged { /// <summary> /// The active Git repository in Team Explorer. /// This will be null if no repository is active. /// </summary> /// <remarks> /// This property might be changed by a non-UI thread. /// </remarks> ILocalRepositoryModel ActiveRepository { get; } /// <summary> /// Fired when the CurrentBranch or HeadSha changes. /// </summary> /// <remarks> /// This event might fire on a non-UI thread. /// </remarks> event EventHandler StatusChanged; } }
Add remarks about non-UI thread
Add remarks about non-UI thread
C#
mit
github/VisualStudio,github/VisualStudio,github/VisualStudio
0ccfa73a6a1e51ab01ec0ff8f0b8e7a916cf36f2
twitch-tv-viewer/ViewModels/SettingsViewModel.cs
twitch-tv-viewer/ViewModels/SettingsViewModel.cs
using System; using System.Collections.ObjectModel; using System.Windows.Input; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using twitch_tv_viewer.Repositories; namespace twitch_tv_viewer.ViewModels { internal class SettingsViewModel : ViewModelBase { private ObservableCollection<string> _items; private string _selected; private readonly ISettingsRepository _settings; // public SettingsViewModel() { _settings = new SettingsRepository(); Items = new ObservableCollection<string> {"Source", "Low"}; Selected = _settings.Quality; ApplyCommand = new RelayCommand(Apply); CancelCommand = new RelayCommand(Cancel); } // public Action Close { get; set; } public ObservableCollection<string> Items { get { return _items; } set { _items = value; RaisePropertyChanged(); } } public string Selected { get { return _selected; } set { _selected = value; RaisePropertyChanged(); } } public ICommand ApplyCommand { get; set; } public ICommand CancelCommand { get; set; } // private void Cancel() => Close(); private void Apply() { _settings.Quality = Selected; Close(); } } }
using System; using System.Collections.ObjectModel; using System.Windows.Input; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using twitch_tv_viewer.Repositories; namespace twitch_tv_viewer.ViewModels { internal class SettingsViewModel : ViewModelBase { private ObservableCollection<string> _items; private string _selected; private readonly ISettingsRepository _settings; private bool _checked; // public SettingsViewModel() { _settings = new SettingsRepository(); Items = new ObservableCollection<string> {"Source", "Low"}; Selected = _settings.Quality; Checked = _settings.UserAlert; ApplyCommand = new RelayCommand(Apply); CancelCommand = new RelayCommand(Cancel); } // public Action Close { get; set; } public ObservableCollection<string> Items { get { return _items; } set { _items = value; RaisePropertyChanged(); } } public string Selected { get { return _selected; } set { _selected = value; RaisePropertyChanged(); } } public bool Checked { get { return _checked; } set { _checked = value; RaisePropertyChanged(); } } public ICommand ApplyCommand { get; set; } public ICommand CancelCommand { get; set; } // private void Cancel() => Close(); private void Apply() { _settings.UserAlert = Checked; _settings.Quality = Selected; Close(); } } }
Add bindings in settings viewmodel for user alert
Add bindings in settings viewmodel for user alert
C#
mit
dukemiller/twitch-tv-viewer
3575d9847cd120941ad3737ff140c01184edd4e5
osu.Game.Tests/Visual/Ranking/TestSceneStarRatingDisplay.cs
osu.Game.Tests/Visual/Ranking/TestSceneStarRatingDisplay.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.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Utils; using osu.Game.Beatmaps; using osu.Game.Screens.Ranking.Expanded; namespace osu.Game.Tests.Visual.Ranking { public class TestSceneStarRatingDisplay : OsuTestScene { [SetUp] public void SetUp() => Schedule(() => { StarRatingDisplay changingStarRating; Child = new FillFlowContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, Children = new Drawable[] { new StarRatingDisplay(new StarDifficulty(1.23, 0)), new StarRatingDisplay(new StarDifficulty(2.34, 0)), new StarRatingDisplay(new StarDifficulty(3.45, 0)), new StarRatingDisplay(new StarDifficulty(4.56, 0)), new StarRatingDisplay(new StarDifficulty(5.67, 0)), new StarRatingDisplay(new StarDifficulty(6.78, 0)), new StarRatingDisplay(new StarDifficulty(10.11, 0)), changingStarRating = new StarRatingDisplay(), } }; Scheduler.AddDelayed(() => { changingStarRating.Current.Value = new StarDifficulty(RNG.NextDouble(0, 10), RNG.Next()); }, 500, true); }); } }
// 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.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Utils; using osu.Game.Beatmaps; using osu.Game.Screens.Ranking.Expanded; namespace osu.Game.Tests.Visual.Ranking { public class TestSceneStarRatingDisplay : OsuTestScene { [Test] public void TestDisplay() { StarRatingDisplay changingStarRating = null; AddStep("load displays", () => Child = new FillFlowContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, Children = new Drawable[] { new StarRatingDisplay(new StarDifficulty(1.23, 0)), new StarRatingDisplay(new StarDifficulty(2.34, 0)), new StarRatingDisplay(new StarDifficulty(3.45, 0)), new StarRatingDisplay(new StarDifficulty(4.56, 0)), new StarRatingDisplay(new StarDifficulty(5.67, 0)), new StarRatingDisplay(new StarDifficulty(6.78, 0)), new StarRatingDisplay(new StarDifficulty(10.11, 0)), changingStarRating = new StarRatingDisplay(), } }); AddRepeatStep("change bottom rating", () => { changingStarRating.Current.Value = new StarDifficulty(RNG.NextDouble(0, 10), RNG.Next()); }, 10); } } }
Use regular test steps rather than one-time set up and scheduling
Use regular test steps rather than one-time set up and scheduling
C#
mit
peppy/osu-new,peppy/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,smoogipooo/osu,peppy/osu
c044e795a19070ea770a90b4ffe2d272e3d52eac
DioLive.Cache/src/DioLive.Cache.WebUI/Views/Categories/_GlobalCategoriesPartial.cshtml
DioLive.Cache/src/DioLive.Cache.WebUI/Views/Categories/_GlobalCategoriesPartial.cshtml
@using Microsoft.AspNetCore.Builder @using Microsoft.Extensions.Options @model IEnumerable<Category> @inject IOptions<RequestLocalizationOptions> LocOptions @{ var cultures = LocOptions.Value.SupportedUICultures .Skip(1) .Select(culture => new { Culture = culture.Name, Name = culture.EnglishName }) .ToArray(); } <h2>Global categories</h2> <table class="table"> <thead> <tr> <th>Default name</th> @foreach (var culture in cultures) { <th>@culture.Name translate</th> } </tr> </thead> <tbody> @foreach (var category in Model) { <tr> <td> @category.Name <div class="input-group colorpicker colorpicker-component" data-id="@category.Id"> <input type="text" value="name" class="form-control" /> <input type="hidden" value="#@category.Color.ToString("X6")" /> <span class="input-group-addon"><i></i></span> </div> </td> @foreach (var culture in cultures) { var locName = category.Localizations.SingleOrDefault(loc => loc.Culture == culture.Culture); if (locName != null) { <td>@locName.Name</td> } else { <td class="empty">@category.Name</td> } } </tr> } </tbody> </table>
@using Microsoft.AspNetCore.Builder @using Microsoft.Extensions.Options @model IEnumerable<Category> @inject IOptions<RequestLocalizationOptions> LocOptions @{ var cultures = LocOptions.Value.SupportedUICultures .Skip(1) .Select(culture => new { Culture = culture.Name, Name = culture.EnglishName }) .ToArray(); } <h2>Global categories</h2> <table class="table"> <thead> <tr> <th class="fit"></th> <th>Default name</th> @foreach (var culture in cultures) { <th>@culture.Name translate</th> } </tr> </thead> <tbody> @foreach (var category in Model) { <tr> <td> <span class="label category-color" style="background-color: #@(category.Color.ToString("X6"))">&nbsp;</span> </td> <td> @category.Name </td> @foreach (var culture in cultures) { var locName = category.Localizations.SingleOrDefault(loc => loc.Culture == culture.Culture); if (locName != null) { <td>@locName.Name</td> } else { <td class="empty">@category.Name</td> } } </tr> } </tbody> </table>
Make global categories colors are display only
Make global categories colors are display only
C#
mit
diolive/cache,diolive/cache
e34c9599dc56a151670fba4dc05fcc10172d21e3
FBExtendedEvents/PluginInfo.cs
FBExtendedEvents/PluginInfo.cs
using FogCreek.Plugins; [assembly: AssemblyFogCreekPluginId("FBExtendedEvents@goit.io")] [assembly: AssemblyFogCreekMajorVersion(3)] [assembly: AssemblyFogCreekMinorVersionMin(5)] [assembly: AssemblyFogCreekEmailAddress("jozef.izso@gmail.com")] [assembly: AssemblyFogCreekWebsite("https://github.com/jozefizso/FBExtendedEvents")]
using FogCreek.Plugins; [assembly: AssemblyFogCreekPluginId("FBExtendedEvents@goit.io")] [assembly: AssemblyFogCreekMajorVersion(3)] [assembly: AssemblyFogCreekMinorVersionMin(5)] [assembly: AssemblyFogCreekEmailAddress("jozef.izso@gmail.com")] [assembly: AssemblyFogCreekWebsite("https://github.com/jozefizso/FogBugz-ExtendedEvents")]
Add new plugin repository URL
Add new plugin repository URL
C#
mit
jozefizso/FogBugz-ExtendedEvents,jozefizso/FogBugz-ExtendedEvents
9a7c5806c6137501d709629d503b7b91e4607d66
Battery-Commander.Web/Controllers/AdminController.cs
Battery-Commander.Web/Controllers/AdminController.cs
using BatteryCommander.Web.Models; using FluentScheduler; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.IO; namespace BatteryCommander.Web.Controllers { [ApiExplorerSettings(IgnoreApi = true)] public class AdminController : Controller { // Admin Tasks: // Add/Remove Users // Backup SQLite Db // Scrub Soldier Data private readonly Database db; public AdminController(Database db) { this.db = db; } public IActionResult Index() { return View(); } public IActionResult Backup() { var data = System.IO.File.ReadAllBytes("Data.db"); var mimeType = "application/octet-stream"; return File(data, mimeType); } public IActionResult Jobs() { return View(JobManager.AllSchedules); } } }
using BatteryCommander.Web.Models; using FluentScheduler; using Microsoft.AspNetCore.Mvc; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers { [ApiExplorerSettings(IgnoreApi = true)] public class AdminController : Controller { // Admin Tasks: // Add/Remove Users // Backup SQLite Db // Scrub Soldier Data private readonly Database db; public AdminController(Database db) { this.db = db; } public IActionResult Index() { return View(); } public IActionResult Backup() { var data = System.IO.File.ReadAllBytes("Data.db"); var mimeType = "application/octet-stream"; return File(data, mimeType); } public IActionResult Jobs() { return View(JobManager.AllSchedules); } public async Task<IActionResult> Users() { var soldiers_with_access = await db .Soldiers .Where(soldier => soldier.CanLogin) .Select(soldier => new { soldier.FirstName, soldier.LastName, soldier.CivilianEmail }) .ToListAsync(); return Json(soldiers_with_access); } } }
Add simple JSON endpoint for soldiers with access
Add simple JSON endpoint for soldiers with access Fixes #412
C#
mit
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
b719da53f65ac33afa072e2c84e57dcb42a1b29d
BleLab/Services/CharacteristicSubscriptionService.cs
BleLab/Services/CharacteristicSubscriptionService.cs
using System; using System.Collections.Generic; using System.Linq; using Windows.Devices.Bluetooth; using Windows.Devices.Bluetooth.GenericAttributeProfile; using Windows.Foundation; namespace BleLab.Services { public class CharacteristicSubscriptionService { private readonly Dictionary<Guid, GattCharacteristic> _subscribedCharacteristics = new Dictionary<Guid, GattCharacteristic>(); public event TypedEventHandler<GattCharacteristic, GattValueChangedEventArgs> ValueChanged; public bool Subscribe(GattCharacteristic characteristic) { if (_subscribedCharacteristics.ContainsKey(characteristic.Uuid)) return false; characteristic.ValueChanged += CharacteristicOnValueChanged; _subscribedCharacteristics.Add(characteristic.Uuid, characteristic); return true; } public bool Unsubscribe(GattCharacteristic characteristic) { if (!_subscribedCharacteristics.TryGetValue(characteristic.Uuid, out characteristic)) return false; characteristic.ValueChanged -= CharacteristicOnValueChanged; _subscribedCharacteristics.Remove(characteristic.Uuid); return true; } public bool IsSubscribed(GattCharacteristic characteristic) { return _subscribedCharacteristics.ContainsKey(characteristic.Uuid); } public void DeviceDisconnected(BluetoothLEDevice device) { if (device == null) return; var deviceId = device.DeviceId; var characteristics = _subscribedCharacteristics.Values.Where(t => t.Service.DeviceId == deviceId).ToList(); foreach (var characteristic in characteristics) { try { Unsubscribe(characteristic); } catch { } } } private void CharacteristicOnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args) { ValueChanged?.Invoke(sender, args); } } }
using System; using System.Collections.Generic; using System.Linq; using Windows.Devices.Bluetooth; using Windows.Devices.Bluetooth.GenericAttributeProfile; using Windows.Foundation; namespace BleLab.Services { public class CharacteristicSubscriptionService { private readonly Dictionary<Guid, GattCharacteristic> _subscribedCharacteristics = new Dictionary<Guid, GattCharacteristic>(); public event TypedEventHandler<GattCharacteristic, GattValueChangedEventArgs> ValueChanged; public bool Subscribe(GattCharacteristic characteristic) { if (_subscribedCharacteristics.ContainsKey(characteristic.Uuid)) return false; characteristic.ValueChanged += CharacteristicOnValueChanged; _subscribedCharacteristics.Add(characteristic.Uuid, characteristic); return true; } public bool Unsubscribe(GattCharacteristic characteristic) { if (!_subscribedCharacteristics.TryGetValue(characteristic.Uuid, out characteristic)) return false; characteristic.ValueChanged -= CharacteristicOnValueChanged; _subscribedCharacteristics.Remove(characteristic.Uuid); return true; } public bool IsSubscribed(GattCharacteristic characteristic) { return _subscribedCharacteristics.ContainsKey(characteristic.Uuid); } public void DeviceDisconnected(BluetoothLEDevice device) { if (device == null) return; var deviceId = device.DeviceId; var characteristics = _subscribedCharacteristics.Values.Where(t => t.Service.Device.DeviceId == deviceId).ToList(); foreach (var characteristic in characteristics) { try { Unsubscribe(characteristic); } catch { } } } private void CharacteristicOnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args) { ValueChanged?.Invoke(sender, args); } } }
Fix of not unsubscribing to characteristics on disconnect
Fix of not unsubscribing to characteristics on disconnect
C#
mit
IanSavchenko/BleLab
f983e3b7d7b122175f557c9c6eb5dc1a2770129b
samples/ConsoleApplication/ConsoleApplication/Program.cs
samples/ConsoleApplication/ConsoleApplication/Program.cs
using System; using Bartender; using ConsoleApplication.Domain.Personne.Create; using ConsoleApplication.Domain.Personne.Read; using ConsoleApplication.Registries; using StructureMap; namespace ConsoleApplication { class Program { static void Main(string[] args) { var registry = new Registry(); registry.IncludeRegistry<InfrastructureRegistry>(); var container = new Container(registry); var createPersonCommandHandler = container.GetInstance<IHandler<CreatePersonCommand>>(); createPersonCommandHandler.Handle(new CreatePersonCommand()); var getPersonQueryHandler = container.GetInstance<IHandler<GetPersonQuery, GetPersonReadModel>>(); var person = getPersonQueryHandler.Handle(new GetPersonQuery()); Console.WriteLine($"Hello {person.Name} !"); Console.ReadKey(); } } }
using System; using Bartender; using ConsoleApplication.Domain.Personne.Create; using ConsoleApplication.Domain.Personne.Read; using ConsoleApplication.Registries; using StructureMap; namespace ConsoleApplication { class Program { static void Main() { var registry = new Registry(); registry.IncludeRegistry<InfrastructureRegistry>(); var container = new Container(registry); var dispatcher = container.GetInstance<IDispatcher>(); dispatcher.Dispatch(new CreatePersonCommand()); var person = dispatcher.Dispatch<GetPersonQuery, GetPersonReadModel>(new GetPersonQuery()); Console.WriteLine($"Hello {person.Name} !"); Console.ReadKey(); } } }
Switch direct handling by a syncrhonous dispatching in console sample
Switch direct handling by a syncrhonous dispatching in console sample
C#
mit
Vtek/Bartender
135c9cb9e473a36f929113fa9806bcfe2bc5da73
Santa/Common/Alogs/GiftExtensions.cs
Santa/Common/Alogs/GiftExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Common.Alogs { public static class GiftExtensions { public static double DistanceTo(this Gift one, Gift two) { var phyOne = one.Latitude / 360 * Math.PI * 2; //var phyTwo return 0; } private static double ToRadiant(double degrees) { return degrees / 360 * Math.PI * 2; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Common.Alogs { public static class GiftExtensions { public static double DistanceTo(this Gift one, Gift two) { const double radius = 6371000; var phyOne = ToRadiant(one.Latitude); var phyTwo = ToRadiant(two.Latitude); var lambdaOne = ToRadiant(one.Longitude); var lambdaTwo = ToRadiant(two.Longitude); var underRoot = PowTwo(Math.Sin((phyTwo - phyOne)/2)) + Math.Cos(phyOne) * Math.Cos(phyTwo) * PowTwo(Math.Sin((lambdaTwo - lambdaOne)/2)); var arg = Math.Sqrt(underRoot); return 2 * radius * Math.Asin(arg); } private static double PowTwo(double input) { return Math.Pow(input, 2); } private static double ToRadiant(double degrees) { return degrees / 360 * Math.PI * 2; } } }
Create algo to calculate distance between gift points
Create algo to calculate distance between gift points
C#
mit
kw90/SantasSledge
7059476dacbbddb61ba4a40f5acf2d9f016b0555
src/Glimpse.Host.Web.AspNet/GlimpseMiddleware.cs
src/Glimpse.Host.Web.AspNet/GlimpseMiddleware.cs
using System.Threading.Tasks; using Microsoft.AspNet.Builder; using Glimpse.Host.Web.AspNet.Framework; namespace Glimpse.Host.Web.AspNet { public class GlimpseMiddleware { private readonly RequestDelegate _innerNext; public GlimpseMiddleware(RequestDelegate innerNext) { _innerNext = innerNext; } public async Task Invoke(Microsoft.AspNet.Http.HttpContext context) { var newContext = new HttpContext(context); await _innerNext(context); } } }
using System.Threading.Tasks; using Microsoft.AspNet.Builder; using Glimpse.Host.Web.AspNet.Framework; using Glimpse.Agent.Web; namespace Glimpse.Host.Web.AspNet { public class GlimpseMiddleware { private readonly RequestDelegate _innerNext; private readonly WebAgentRuntime _runtime; public GlimpseMiddleware(RequestDelegate innerNext) { _innerNext = innerNext; _runtime = new WebAgentRuntime(); // TODO: This shouldn't have this direct depedency } public async Task Invoke(Microsoft.AspNet.Http.HttpContext context) { var newContext = new HttpContext(context); _runtime.Begin(newContext); await _innerNext(context); _runtime.End(newContext); } } }
Add agent to the web middleware
Add agent to the web middleware
C#
mit
mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype
e75b738d0e520cb9b0ed6684f4eceeb5436ba355
IdParser/Enums/Version.cs
IdParser/Enums/Version.cs
// ReSharper disable once CheckNamespace namespace IdParser { public enum Version : byte { PreStandard = 0, Aamva2000 = 1, Aamva2003 = 2, Aamva2005 = 3, Aamva2009 = 4, Aamva2010 = 5, Aamva2011 = 6, Aamva2012 = 7, Aamva2013 = 8, Aamva2016 = 9, Future = 99 } }
// ReSharper disable once CheckNamespace namespace IdParser { public enum Version : byte { PreStandard = 0, Aamva2000 = 1, Aamva2003 = 2, Aamva2005 = 3, Aamva2009 = 4, Aamva2010 = 5, Aamva2011 = 6, Aamva2012 = 7, Aamva2013 = 8, Aamva2016 = 9, Aamva2020 = 10, Future = 99 } }
Add 2020 standard to version enum
Add 2020 standard to version enum
C#
mit
c0shea/IdParser
860214c22a11fb5107161c5bb59bb6a6ba734a02
osu.Game/Rulesets/Edit/ExpandingToolboxContainer.cs
osu.Game/Rulesets/Edit/ExpandingToolboxContainer.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. #nullable disable using osu.Framework.Graphics; using osu.Framework.Input.Events; using osu.Game.Graphics.Containers; using osuTK; namespace osu.Game.Rulesets.Edit { public class ExpandingToolboxContainer : ExpandingContainer { protected override double HoverExpansionDelay => 250; public ExpandingToolboxContainer(float contractedWidth, float expandedWidth) : base(contractedWidth, expandedWidth) { RelativeSizeAxes = Axes.Y; FillFlow.Spacing = new Vector2(10); } protected override bool ReceivePositionalInputAtSubTree(Vector2 screenSpacePos) => base.ReceivePositionalInputAtSubTree(screenSpacePos) && anyToolboxHovered(screenSpacePos); public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => base.ReceivePositionalInputAt(screenSpacePos) && anyToolboxHovered(screenSpacePos); private bool anyToolboxHovered(Vector2 screenSpacePos) => FillFlow.ScreenSpaceDrawQuad.Contains(screenSpacePos); protected override bool OnMouseDown(MouseDownEvent e) => true; protected override bool OnClick(ClickEvent e) => true; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using osu.Framework.Graphics; using osu.Framework.Input.Events; using osu.Game.Graphics.Containers; using osuTK; namespace osu.Game.Rulesets.Edit { public class ExpandingToolboxContainer : ExpandingContainer { protected override double HoverExpansionDelay => 250; public ExpandingToolboxContainer(float contractedWidth, float expandedWidth) : base(contractedWidth, expandedWidth) { RelativeSizeAxes = Axes.Y; FillFlow.Spacing = new Vector2(5); Padding = new MarginPadding { Vertical = 5 }; } protected override bool ReceivePositionalInputAtSubTree(Vector2 screenSpacePos) => base.ReceivePositionalInputAtSubTree(screenSpacePos) && anyToolboxHovered(screenSpacePos); public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => base.ReceivePositionalInputAt(screenSpacePos) && anyToolboxHovered(screenSpacePos); private bool anyToolboxHovered(Vector2 screenSpacePos) => FillFlow.ScreenSpaceDrawQuad.Contains(screenSpacePos); protected override bool OnMouseDown(MouseDownEvent e) => true; protected override bool OnClick(ClickEvent e) => true; } }
Adjust paddings to feel better now that backgrounds are visible of toolboxes
Adjust paddings to feel better now that backgrounds are visible of toolboxes
C#
mit
ppy/osu,ppy/osu,peppy/osu,peppy/osu,peppy/osu,ppy/osu
e5d9d3c19e3f39e2ddc37449e0a54809aa79a5fb
test/AWTY.Http.IntegrationTests/DumbMemoryStream.cs
test/AWTY.Http.IntegrationTests/DumbMemoryStream.cs
using System.IO; namespace AWTY.Http.IntegrationTests { /// <summary> /// A non-optimised version of <see cref="MemoryStream"/> for use in tests. /// </summary> /// <remarks> /// <see cref="MemoryStream"/> performs a bunch of optimisations unless subclassed. /// /// Unfortunately, these optimisations break the tests. /// Although you obviously wouldn't use a MemoryStream in real life, it's the simplest options for these tests. /// </remarks> public sealed class DumbMemoryStream : MemoryStream { public DumbMemoryStream() : base() { } } }
using System.IO; namespace AWTY.Http.IntegrationTests { /// <summary> /// A non-optimised version of <see cref="MemoryStream"/> for use in tests. /// </summary> /// <remarks> /// <see cref="MemoryStream"/>'s CopyToAsync performs a bunch of optimisations unless subclassed. /// https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/io/memorystream.cs#L450 /// /// Unfortunately, these optimisations break some of our tests. /// Although you obviously wouldn't use a MemoryStream in real life, it's the simplest options for these tests. /// </remarks> public sealed class DumbMemoryStream : MemoryStream { public DumbMemoryStream() : base() { } } }
Add link to MemoryStream.CopyToAsync source link.
Add link to MemoryStream.CopyToAsync source link.
C#
mit
tintoy/AWTY
3aaf66d52cb47b142c31e2ccfe0f9fb8e09c0900
GitReview/Global.asax.cs
GitReview/Global.asax.cs
// ----------------------------------------------------------------------- // <copyright file="Global.asax.cs" company="(none)"> // Copyright © 2015 John Gietzen. All Rights Reserved. // This source is subject to the MIT license. // Please see license.md for more information. // </copyright> // ----------------------------------------------------------------------- namespace GitReview { using System.Configuration; using System.Web; using System.Web.Mvc; using System.Web.Routing; /// <summary> /// The GitReview application. /// </summary> public class GitReviewApplication : HttpApplication { /// <summary> /// Gets the path of the shared repository. /// </summary> public static string RepositoryPath { get { return ConfigurationManager.AppSettings["RepositoryPath"]; } } /// <summary> /// Starts the application. /// </summary> protected virtual void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); } } }
// ----------------------------------------------------------------------- // <copyright file="Global.asax.cs" company="(none)"> // Copyright © 2015 John Gietzen. All Rights Reserved. // This source is subject to the MIT license. // Please see license.md for more information. // </copyright> // ----------------------------------------------------------------------- namespace GitReview { using System.Configuration; using System.IO; using System.Web; using System.Web.Hosting; using System.Web.Mvc; using System.Web.Routing; using LibGit2Sharp; /// <summary> /// The GitReview application. /// </summary> public class GitReviewApplication : HttpApplication { /// <summary> /// Gets the path of the shared repository. /// </summary> public static string RepositoryPath { get { return HostingEnvironment.MapPath(ConfigurationManager.AppSettings["RepositoryPath"]); } } /// <summary> /// Starts the application. /// </summary> protected virtual void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); var path = GitReviewApplication.RepositoryPath; if (!Directory.Exists(path)) { Repository.Init(path, isBare: true); } } } }
Initialize git repo on startup.
Initialize git repo on startup.
C#
mit
otac0n/GitReview,otac0n/GitReview,otac0n/GitReview
d9d38b8f1eb3ae66297bad2aaef596c5cb89dc1a
CRP.Mvc/Views/ItemManagement/_TabTransactions.cshtml
CRP.Mvc/Views/ItemManagement/_TabTransactions.cshtml
@using CRP.Controllers @using Microsoft.Web.Mvc @model IEnumerable<CRP.Core.Domain.Transaction> <div class="tab-pane active" id="Transactions"> <table id="table-Transactions"> <thead> <tr> <th></th> <th>Transaction</th> <th>Quantity</th> <th>Amount</th> <th>Payment Type</th> <th>Paid</th> <th>Active Eh</th> </tr> </thead> <tbody> @foreach (var item in Model.Where(a => a.ParentTransaction == null)) { <tr> <td> @using (Html.BeginForm<ItemManagementController> (x => x.ToggleTransactionIsActive(item.Id, Request.QueryString["Transactions-orderBy"], Request.QueryString["Transactions-page"]))) { @Html.AntiForgeryToken() <a href="javascript:;" class="FormSubmit">@(item.IsActive ? "Deactivate" : "Activate")</a> } </td> <td>@Html.DisplayFor(modelItem => item.TransactionNumber)</td> <td>@Html.DisplayFor(modelItem => item.Quantity)</td> <td>@Html.DisplayFor(modelItem => item.Amount)</td> <td>@Html.DisplayFor(modelItem => item.Credit)</td> <td>@Html.DisplayFor(modelItem => item.Paid)</td> <td>@Html.DisplayFor(modelItem => item.IsActive)</td> </tr> } </tbody> </table> </div>
@using CRP.Controllers @using Microsoft.Web.Mvc @model IEnumerable<CRP.Core.Domain.Transaction> <div class="tab-pane active" id="Transactions"> <table id="table-Transactions"> <thead> <tr> <th></th> <th>Transaction</th> <th>Quantity</th> <th>Amount</th> <th>Payment Type</th> <th>Paid</th> <th>Active</th> </tr> </thead> <tbody> @foreach (var item in Model.Where(a => a.ParentTransaction == null)) { <tr> <td> @using (Html.BeginForm<ItemManagementController> (x => x.ToggleTransactionIsActive(item.Id, Request.QueryString["Transactions-orderBy"], Request.QueryString["Transactions-page"]))) { @Html.AntiForgeryToken() <a href="javascript:;" class="FormSubmit">@(item.IsActive ? "Deactivate" : "Activate")</a> } </td> <td>@Html.DisplayFor(modelItem => item.TransactionNumber)</td> <td>@Html.DisplayFor(modelItem => item.Quantity)</td> <td>@Html.DisplayFor(modelItem => item.Amount)</td> <td>@Html.DisplayFor(modelItem => item.Credit)</td> <td>@Html.DisplayFor(modelItem => item.Paid)</td> <td>@Html.DisplayFor(modelItem => item.IsActive)</td> </tr> } </tbody> </table> </div>
Remove Canadian Styling of bool
Remove Canadian Styling of bool
C#
mit
ucdavis/CRP,ucdavis/CRP,ucdavis/CRP
00f7e8bf2b441173d76d7770fdab8d8ccd951ec6
src/ZobShop.Tests/Models/UserTests/UserConstructorTests.cs
src/ZobShop.Tests/Models/UserTests/UserConstructorTests.cs
using Microsoft.AspNet.Identity.EntityFramework; using NUnit.Framework; using ZobShop.Models; namespace ZobShop.Tests.Models.UserTests { [TestFixture] public class UserConstructorTests { [Test] public void Constructor_Should_InitializeUserCorrectly() { var user = new User(); Assert.IsNotNull(user); } [Test] public void Constructor_Should_BeInstanceOfIdentityUser() { var user = new User(); Assert.IsInstanceOf<IdentityUser>(user); } } }
using Microsoft.AspNet.Identity.EntityFramework; using NUnit.Framework; using ZobShop.Models; namespace ZobShop.Tests.Models.UserTests { [TestFixture] public class UserConstructorTests { [Test] public void Constructor_Should_InitializeUserCorrectly() { var user = new User(); Assert.IsNotNull(user); } [Test] public void Constructor_Should_BeInstanceOfIdentityUser() { var user = new User(); Assert.IsInstanceOf<IdentityUser>(user); } [TestCase("pesho", "pesho@pesho.com", "Peter", "0881768356", "1 Peshova street")] public void Constructor_ShouldSetUsernameCorrectly(string username, string email, string name, string phoneNumber, string address) { var user = new User(username, email, name, phoneNumber, address); Assert.AreEqual(username, user.UserName); } [TestCase("pesho", "pesho@pesho.com", "Peter", "0881768356", "1 Peshova street")] public void Constructor_ShouldSetNameCorrectly(string username, string email, string name, string phoneNumber, string address) { var user = new User(username, email, name, phoneNumber, address); Assert.AreEqual(name, user.Name); } [TestCase("pesho", "pesho@pesho.com", "Peter", "0881768356", "1 Peshova street")] public void Constructor_ShouldSeEmailCorrectly(string username, string email, string name, string phoneNumber, string address) { var user = new User(username, email, name, phoneNumber, address); Assert.AreEqual(email, user.Email); } [TestCase("pesho", "pesho@pesho.com", "Peter", "0881768356", "1 Peshova street")] public void Constructor_ShouldSetPhoneNumberCorrectly(string username, string email, string name, string phoneNumber, string address) { var user = new User(username, email, name, phoneNumber, address); Assert.AreEqual(phoneNumber, user.PhoneNumber); } [TestCase("pesho", "pesho@pesho.com", "Peter", "0881768356", "1 Peshova street")] public void Constructor_ShouldSetAddressCorrectly(string username, string email, string name, string phoneNumber, string address) { var user = new User(username, email, name, phoneNumber, address); Assert.AreEqual(address, user.Address); } } }
Add new user constructor tests
Add new user constructor tests
C#
mit
Branimir123/ZobShop,Branimir123/ZobShop,Branimir123/ZobShop
b35a936f4e03f88cc3e79ed8b56534263839f315
Naos.Database.MessageBus.Handlers/BackupMessageHandler.cs
Naos.Database.MessageBus.Handlers/BackupMessageHandler.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="BackupMessageHandler.cs" company="Naos"> // Copyright 2015 Naos // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Naos.Database.MessageBus.Handlers { using System; using Its.Configuration; using Naos.Database.MessageBus.Contract; using Naos.Database.Tools; using Naos.Database.Tools.Backup; using Naos.MessageBus.HandlingContract; /// <summary> /// Naos.MessageBus handler for BackupMessages. /// </summary> public class BackupMessageHandler : IHandleMessages<BackupDatabaseMessage> { /// <inheritdoc /> public void Handle(BackupDatabaseMessage message) { Action<string> logAction = s => { }; var settings = Settings.Get<MessageHandlerSettings>(); var backupDetails = new BackupDetails() { Name = message.BackupName, BackupTo = new Uri(settings.BackupDirectory), ChecksumOption = ChecksumOption.Checksum, Cipher = Cipher.NoEncryption, CompressionOption = CompressionOption.NoCompression, Description = message.Description, Device = Device.Disk, ErrorHandling = ErrorHandling.StopOnError, }; DatabaseManager.BackupFull( settings.LocalhostConnectionString, message.DatabaseName, backupDetails, settings.DefaultTimeout, logAction); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="BackupMessageHandler.cs" company="Naos"> // Copyright 2015 Naos // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Naos.Database.MessageBus.Handlers { using System; using System.IO; using Its.Configuration; using Naos.Database.MessageBus.Contract; using Naos.Database.Tools; using Naos.Database.Tools.Backup; using Naos.MessageBus.HandlingContract; /// <summary> /// Naos.MessageBus handler for BackupMessages. /// </summary> public class BackupMessageHandler : IHandleMessages<BackupDatabaseMessage> { /// <inheritdoc /> public void Handle(BackupDatabaseMessage message) { Action<string> logAction = s => { }; var settings = Settings.Get<MessageHandlerSettings>(); var backupFileName = Path.Combine(settings.BackupDirectory, message.BackupName) + ".bak"; var backupDetails = new BackupDetails() { Name = message.BackupName, BackupTo = new Uri(backupFileName), ChecksumOption = ChecksumOption.Checksum, Cipher = Cipher.NoEncryption, CompressionOption = CompressionOption.NoCompression, Description = message.Description, Device = Device.Disk, ErrorHandling = ErrorHandling.StopOnError, }; DatabaseManager.BackupFull( settings.LocalhostConnectionString, message.DatabaseName, backupDetails, settings.DefaultTimeout, logAction); } } }
Fix issue where the file name wasn't getting specified.
Fix issue where the file name wasn't getting specified.
C#
mit
NaosFramework/Naos.Database,NaosProject/Naos.Database
b0d62fd9a3921edaf744412b2bde5e061a5a2171
PlayerRank/PlayerScore.cs
PlayerRank/PlayerScore.cs
using System; using System.Runtime.InteropServices; namespace PlayerRank { public class PlayerScore { public string Name { get; set; } public Points Points { get; internal set; } public PlayerScore(string name) { Name = name; Points = new Points(0); } internal void AddPoints(Points points) { Points += points; } /// Obsolete V1 API [Obsolete("Please use Points instead")] public double Score { get { return Points.GetValue(); } internal set { Points = new Points(value); } } } }
using System; using System.Runtime.InteropServices; namespace PlayerRank { public class PlayerScore { public string Name { get; set; } public Points Points { get; internal set; } public PlayerScore(string name) { Name = name; Points = new Points(0); } internal void AddPoints(Points points) { Points += points; } internal void SubtractPoints(Points points) { Points -= points; } /// Obsolete V1 API [Obsolete("Please use Points instead")] public double Score { get { return Points.GetValue(); } internal set { Points = new Points(value); } } } }
Add method to subtract points from player
Add method to subtract points from player
C#
mit
TheEadie/PlayerRank,TheEadie/PlayerRank
7f44dca0401ceb035fcce0c6a72ceec853ac79f3
Source/ZXing.Net.Mobile.WindowsRT/NotSupported.cs
Source/ZXing.Net.Mobile.WindowsRT/NotSupported.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Media.Capture; namespace ZXing.Net.Mobile { public class NotSupported { // Windows Phone 8.1 Native and Windows 8 RT are not supported // Microsoft left out the ability to (easily) marshal Camera Preview frames to managed code // Which is what ZXing.Net.Mobile needs to work // You should upgrade your wpa81 / win8 projects to use Windows Universal (UWP) instead! } } namespace ZXing.Mobile { public class MobileBarcodeScanner : MobileBarcodeScannerBase { NotSupportedException ex = new NotSupportedException("Windows Phone 8.1 Native (wpa81) and Windows 8 Store (win8) are not supported, please use Windows Universal (UWP) instead!"); public override Task<Result> Scan(MobileBarcodeScanningOptions options) { throw ex; } public override void ScanContinuously(MobileBarcodeScanningOptions options, Action<Result> scanHandler) { throw ex; } public override void Cancel() { throw ex; } public override void AutoFocus() { throw ex; } public override void Torch(bool on) { throw ex; } public override void ToggleTorch() { throw ex; } public override bool IsTorchOn { get { throw ex; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Media.Capture; namespace ZXing.Net.Mobile { public class NotSupported { // Windows Phone 8.1 Native and Windows 8 RT are not supported // Microsoft left out the ability to (easily) marshal Camera Preview frames to managed code // Which is what ZXing.Net.Mobile needs to work // You should upgrade your wpa81 / win8 projects to use Windows Universal (UWP) instead! } } namespace ZXing.Mobile { public class MobileBarcodeScanner : MobileBarcodeScannerBase { NotSupportedException ex = new NotSupportedException("Windows Phone 8.1 Native (wpa81) and Windows 8 Store (win8) are not supported, please use Windows Universal (UWP) instead!"); public override Task<Result> Scan(MobileBarcodeScanningOptions options) { throw ex; } public override void ScanContinuously(MobileBarcodeScanningOptions options, Action<Result> scanHandler) { throw ex; } public override void Cancel() { throw ex; } public override void AutoFocus() { throw ex; } public override void Torch(bool on) { throw ex; } public override void ToggleTorch() { throw ex; } public override void PauseAnalysis() { throw ex; } public override void ResumeAnalysis() { throw ex; } public override bool IsTorchOn { get { throw ex; } } } }
Fix PCL contract for Pause/Resume analysis change
Fix PCL contract for Pause/Resume analysis change
C#
apache-2.0
syphe/ZXing.Net.Mobile,Redth/ZXing.Net.Mobile
8073fe5ffee14acd237003bbbd876b59b814a85e
src/PerfView.Tests/Properties/AssemblyInfo.cs
src/PerfView.Tests/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("PerfView.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PerfView.Tests")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Xunit; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("PerfView.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PerfView.Tests")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: CollectionBehavior(DisableTestParallelization = true)]
Disable test parallelization for PerfView tests
Disable test parallelization for PerfView tests
C#
mit
vancem/perfview,vancem/perfview,vancem/perfview,vancem/perfview,vancem/perfview
8cff384a385f85dc193f09982c8b4eff6e0ada44
Admo/Utilities/SoftwareUtils.cs
Admo/Utilities/SoftwareUtils.cs
using System; using System.Diagnostics; using Microsoft.Win32; namespace Admo.Utilities { public class SoftwareUtils { public static string GetChromeVersion() { var path = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", "", null); if (path != null) return FileVersionInfo.GetVersionInfo(path.ToString()).FileVersion; return String.Empty; } } }
using System; using System.Diagnostics; using Microsoft.Win32; namespace Admo.Utilities { public class SoftwareUtils { public static string GetChromeVersion() { //Handle both system wide and user installs of chrome var pathLocal = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", "", null); var pathMachine = Registry.GetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", "", null); if (pathLocal != null) { return FileVersionInfo.GetVersionInfo(pathLocal.ToString()).FileVersion; } if (pathMachine != null) { return FileVersionInfo.GetVersionInfo(pathMachine.ToString()).FileVersion; } return String.Empty; } } }
Handle system wide installs of chrome
Handle system wide installs of chrome
C#
mit
admoexperience/admo-kinect,admoexperience/admo-kinect
f321fc86b1c7b423119f916b41c1c37f570855b7
Core/Services/CSharpExecutor.cs
Core/Services/CSharpExecutor.cs
using System; using System.IO; using Compilify.Models; namespace Compilify.Services { public class CSharpExecutor { public CSharpExecutor() : this(new CSharpCompilationProvider()) { } public CSharpExecutor(ICSharpCompilationProvider compilationProvider) { compiler = compilationProvider; } private readonly ICSharpCompilationProvider compiler; public ExecutionResult Execute(Post post) { var compilation = compiler.Compile(post); byte[] compiledAssembly; using (var stream = new MemoryStream()) using (var fileStream = new FileStream("C:\\output2.dll", FileMode.Truncate)) { var emitResult = compilation.Emit(stream); if (!emitResult.Success) { return new ExecutionResult { Result = "[Compilation failed]" }; } compilation.Emit(fileStream); compiledAssembly = stream.ToArray(); } using (var sandbox = new Sandbox(compiledAssembly)) { return sandbox.Run("EntryPoint", "Result", TimeSpan.FromSeconds(5)); } } } }
using System; using System.IO; using Compilify.Models; namespace Compilify.Services { public class CSharpExecutor { public CSharpExecutor() : this(new CSharpCompilationProvider()) { } public CSharpExecutor(ICSharpCompilationProvider compilationProvider) { compiler = compilationProvider; } private readonly ICSharpCompilationProvider compiler; public ExecutionResult Execute(Post post) { var compilation = compiler.Compile(post); byte[] compiledAssembly; using (var stream = new MemoryStream()) { var emitResult = compilation.Emit(stream); if (!emitResult.Success) { return new ExecutionResult { Result = "[Compilation failed]" }; } compiledAssembly = stream.ToArray(); } using (var sandbox = new Sandbox(compiledAssembly)) { return sandbox.Run("EntryPoint", "Result", TimeSpan.FromSeconds(5)); } } } }
Remove fileStream used for debugging
Remove fileStream used for debugging
C#
mit
jrusbatch/compilify,jrusbatch/compilify,vendettamit/compilify,vendettamit/compilify
112818fb409e7ce0182e4a37c3447cdb78613935
JSNLog/PublicFacing/Configuration/Owin/AppBuilderExtensions.cs
JSNLog/PublicFacing/Configuration/Owin/AppBuilderExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Owin; namespace JSNLog { public static class AppBuilderExtensions { public static void UseJSNLog(this IAppBuilder app, string loggerUrlRegex = null) { app.Use<JsnlogMiddlewareComponent>(loggerUrlRegex); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Owin; namespace JSNLog { public static class AppBuilderExtensions { public static void UseJSNLog(this IAppBuilder app) { app.Use<JsnlogMiddlewareComponent>(); } } }
Remove second parameter, bug not picked up by compiler
Remove second parameter, bug not picked up by compiler
C#
mit
mperdeck/jsnlog
18923709c322965948feb3f05c143d9a0ad5cf0a
CakeMail.RestClient/Properties/AssemblyInfo.cs
CakeMail.RestClient/Properties/AssemblyInfo.cs
using System.Reflection; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CakeMail.RestClient")] [assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jeremie Desautels")] [assembly: AssemblyProduct("CakeMail.RestClient")] [assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0-beta05")]
using System.Reflection; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CakeMail.RestClient")] [assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jeremie Desautels")] [assembly: AssemblyProduct("CakeMail.RestClient")] [assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0.0")]
Set nuget package version to 1.0.0
Set nuget package version to 1.0.0
C#
mit
Jericho/CakeMail.RestClient
6318ca0b158c94f7546dffbb2dc0d369b0bf6759
Portal.CMS.Web/Views/Shared/_DOMScripts.cshtml
Portal.CMS.Web/Views/Shared/_DOMScripts.cshtml
@Scripts.Render("~/Resources/JavaScript/Bootstrap") @Scripts.Render("~/Resources/JavaScript/Bootstrap/Popover") @Scripts.Render("~/Resources/JavaScript/Framework") @if (UserHelper.IsAdmin) { @Scripts.Render("~/Resources/JavaScript/Bootstrap/Tour") @Scripts.Render("~/Resources/JavaScript/Bootstrap/Confirmation") }
@Scripts.Render("~/Resources/JavaScript/Bootstrap") @Scripts.Render("~/Resources/JavaScript/Bootstrap/Confirmation") @Scripts.Render("~/Resources/JavaScript/Bootstrap/Popover") @Scripts.Render("~/Resources/JavaScript/Framework") @if (UserHelper.IsAdmin) { @Scripts.Render("~/Resources/JavaScript/Bootstrap/Tour") }
Load Confirmation plugin in PageBuilder
Load Confirmation plugin in PageBuilder
C#
mit
tommcclean/PortalCMS,tommcclean/PortalCMS,tommcclean/PortalCMS
cdb3dc93851638bb6f721c302d5237e366258fc0
osu.Framework.Benchmarks/BenchmarkTransformUpdate.cs
osu.Framework.Benchmarks/BenchmarkTransformUpdate.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. #nullable disable using BenchmarkDotNet.Attributes; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Framework.Timing; using osuTK; namespace osu.Framework.Benchmarks { public class BenchmarkTransformUpdate : BenchmarkTest { private TestBox target; public override void SetUp() { base.SetUp(); const int transforms_count = 10000; ManualClock clock; target = new TestBox { Clock = new FramedClock(clock = new ManualClock()) }; // transform one target member over a long period target.RotateTo(360, transforms_count * 2); // transform another over the same period many times for (int i = 0; i < transforms_count; i++) target.Delay(i).MoveTo(new Vector2(0.01f), 1f); clock.CurrentTime = target.LatestTransformEndTime; target.Clock.ProcessFrame(); } [Benchmark] public void UpdateTransformsWithManyPresent() { for (int i = 0; i < 10000; i++) target.UpdateTransforms(); } private class TestBox : Box { public override bool RemoveCompletedTransforms => false; public new void UpdateTransforms() => base.UpdateTransforms(); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using BenchmarkDotNet.Attributes; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Framework.Timing; using osuTK; namespace osu.Framework.Benchmarks { public class BenchmarkTransformUpdate : BenchmarkTest { private TestBox target; private TestBox targetNoTransforms; public override void SetUp() { base.SetUp(); const int transforms_count = 10000; ManualClock clock; targetNoTransforms = new TestBox { Clock = new FramedClock(clock = new ManualClock()) }; target = new TestBox { Clock = new FramedClock(clock) }; // transform one target member over a long period target.RotateTo(360, transforms_count * 2); // transform another over the same period many times for (int i = 0; i < transforms_count; i++) target.Delay(i).MoveTo(new Vector2(0.01f), 1f); clock.CurrentTime = target.LatestTransformEndTime; target.Clock.ProcessFrame(); } [Benchmark] public void UpdateTransformsWithNonePresent() { for (int i = 0; i < 10000; i++) targetNoTransforms.UpdateTransforms(); } [Benchmark] public void UpdateTransformsWithManyPresent() { for (int i = 0; i < 10000; i++) target.UpdateTransforms(); } private class TestBox : Box { public override bool RemoveCompletedTransforms => false; public new void UpdateTransforms() => base.UpdateTransforms(); } } }
Add benchmark of updating transforms when none are added
Add benchmark of updating transforms when none are added
C#
mit
ppy/osu-framework,ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework
7842f499a800b2b329be2313fd883e0c4b86fd7c
PathfinderAPI/BaseGameFixes/Performance/NodeLookup.cs
PathfinderAPI/BaseGameFixes/Performance/NodeLookup.cs
using Hacknet; using HarmonyLib; using Pathfinder.Util; namespace Pathfinder.BaseGameFixes.Performance { [HarmonyPatch] internal static class NodeLookup { [HarmonyPostfix] [HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.loadComputer))] internal static void PopulateOnComputerCreation(object __result) { ComputerLookup.PopulateLookups((Computer) __result); } [HarmonyPostfix] [HarmonyPatch(typeof(Computer), nameof(Computer.load))] internal static void PopulateOnComputerLoad(Computer __result) { ComputerLookup.PopulateLookups(__result); } [HarmonyPrefix] [HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.findComp))] internal static bool ModifyComputerLoaderLookup(out Computer __result, string target) { __result = ComputerLookup.FindById(target); return false; } [HarmonyPrefix] [HarmonyPatch(typeof(Programs), nameof(Programs.getComputer))] internal static bool ModifyProgramsLookup(out Computer __result, string ip_Or_ID_or_Name) { __result = ComputerLookup.Find(ip_Or_ID_or_Name); return false; } [HarmonyPostfix] [HarmonyPatch(typeof(OS), nameof(OS.quitGame))] internal static void ClearOnQuitGame() { ComputerLookup.ClearLookups(); } } }
using Hacknet; using HarmonyLib; using Pathfinder.Event; using Pathfinder.Event.Loading; using Pathfinder.Util; namespace Pathfinder.BaseGameFixes.Performance { [HarmonyPatch] internal static class NodeLookup { [Util.Initialize] internal static void Initialize() { EventManager<SaveComputerLoadedEvent>.AddHandler(PopulateOnComputerLoad); } [HarmonyPostfix] [HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.loadComputer))] internal static void PopulateOnComputerCreation(object __result) { if (__result == null) return; ComputerLookup.PopulateLookups((Computer) __result); } internal static void PopulateOnComputerLoad(SaveComputerLoadedEvent args) { ComputerLookup.PopulateLookups(args.Comp); } [HarmonyPrefix] [HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.findComp))] internal static bool ModifyComputerLoaderLookup(out Computer __result, string target) { __result = ComputerLookup.FindById(target); return false; } [HarmonyPrefix] [HarmonyPatch(typeof(Programs), nameof(Programs.getComputer))] internal static bool ModifyProgramsLookup(out Computer __result, string ip_Or_ID_or_Name) { __result = ComputerLookup.Find(ip_Or_ID_or_Name); return false; } [HarmonyPostfix] [HarmonyPatch(typeof(OS), nameof(OS.quitGame))] internal static void ClearOnQuitGame() { ComputerLookup.ClearLookups(); } } }
Fix node lookup not adding saved computers to dict
Fix node lookup not adding saved computers to dict
C#
mit
Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder
6a658025282aa4d52360ec75858fa966b5e46a23
osu.Game.Rulesets.Osu/Edit/Masks/HitCircleSelectionMask.cs
osu.Game.Rulesets.Osu/Edit/Masks/HitCircleSelectionMask.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Objects.Drawables; namespace osu.Game.Rulesets.Osu.Edit.Masks { public class HitCircleSelectionMask : SelectionMask { public HitCircleSelectionMask(DrawableHitCircle hitCircle) : base(hitCircle) { Origin = Anchor.Centre; AutoSizeAxes = Axes.Both; Position = hitCircle.Position; InternalChild = new HitCircleMask((HitCircle)hitCircle.HitObject); hitCircle.HitObject.PositionChanged += _ => Position = hitCircle.Position; } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Objects.Drawables; namespace osu.Game.Rulesets.Osu.Edit.Masks { public class HitCircleSelectionMask : SelectionMask { public HitCircleSelectionMask(DrawableHitCircle hitCircle) : base(hitCircle) { Origin = Anchor.Centre; AutoSizeAxes = Axes.Both; Position = hitCircle.Position; InternalChild = new HitCircleMask((HitCircle)hitCircle.HitObject); hitCircle.HitObject.PositionChanged += _ => Position = hitCircle.HitObject.StackedPosition; hitCircle.HitObject.StackHeightChanged += _ => Position = hitCircle.HitObject.StackedPosition; } } }
Fix hitcircle selections not responding to stacking changes
Fix hitcircle selections not responding to stacking changes
C#
mit
naoey/osu,EVAST9919/osu,smoogipoo/osu,2yangk23/osu,UselessToucan/osu,peppy/osu,ppy/osu,DrabWeb/osu,naoey/osu,smoogipoo/osu,peppy/osu-new,peppy/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,EVAST9919/osu,2yangk23/osu,DrabWeb/osu,smoogipoo/osu,smoogipooo/osu,naoey/osu,ZLima12/osu,peppy/osu,NeoAdonis/osu,johnneijzen/osu,johnneijzen/osu,ppy/osu,ZLima12/osu,NeoAdonis/osu,UselessToucan/osu,DrabWeb/osu
67a1ff5a6ff110de9e8590235bd92e298f2feeb9
source/FFImageLoading.Shared/Helpers/MD5Helper.cs
source/FFImageLoading.Shared/Helpers/MD5Helper.cs
using System; using System.Text; using System.Security.Cryptography; using System.IO; namespace FFImageLoading.Helpers { public class MD5Helper : IMD5Helper { public string MD5(Stream stream) { var hashProvider = new MD5CryptoServiceProvider(); var bytes = hashProvider.ComputeHash(stream); return BitConverter.ToString(bytes)?.ToSanitizedKey(); } public string MD5(string input) { var hashProvider = new MD5CryptoServiceProvider(); var bytes = hashProvider.ComputeHash(Encoding.UTF8.GetBytes(input)); return BitConverter.ToString(bytes)?.ToSanitizedKey(); } } }
using System; using System.Text; using System.Security.Cryptography; using System.IO; namespace FFImageLoading.Helpers { public class MD5Helper : IMD5Helper { public string MD5(Stream stream) { using (var hashProvider = new MD5CryptoServiceProvider()) { var bytes = hashProvider.ComputeHash(stream); return BitConverter.ToString(bytes)?.ToSanitizedKey(); } } public string MD5(string input) { using (var hashProvider = new MD5CryptoServiceProvider()) { var bytes = hashProvider.ComputeHash(Encoding.UTF8.GetBytes(input)); return BitConverter.ToString(bytes)?.ToSanitizedKey(); } } } }
Put MD5CryptoServiceProvider into using clause
Put MD5CryptoServiceProvider into using clause
C#
mit
AndreiMisiukevich/FFImageLoading,luberda-molinet/FFImageLoading,daniel-luberda/FFImageLoading,molinch/FFImageLoading
d777bef2ca9f4bd54a1397ea1654e5f5ab9cfd73
TeamTracker/App_Code/Person.cs
TeamTracker/App_Code/Person.cs
using System.Collections.Generic; public class Person { //--------------------------------------------------------------------------- public int Id { get; set; } public string Name { get; set; } public string Extension { get; set; } public List<Status> Status { get; set; } //--------------------------------------------------------------------------- public Person() { Status = new List<Status>(); } //--------------------------------------------------------------------------- }
using System.Collections.Generic; public class Person { //--------------------------------------------------------------------------- public int Id { get; set; } public string Name { get; set; } public string Contact { get; set; } public List<Status> Status { get; set; } //--------------------------------------------------------------------------- public Person() { Status = new List<Status>(); } //--------------------------------------------------------------------------- }
Update code references: extension -> contact
Update code references: extension -> contact
C#
mit
grae22/TeamTracker
351ee751215b9898ff13ddc0840822e1e7812b33
poshring/CredentialsManager.cs
poshring/CredentialsManager.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.InteropServices; namespace poshring { public class CredentialsManager { public IEnumerable<Credential> GetCredentials() { int count; IntPtr ptr; if (!UnsafeAdvapi32.CredEnumerateW(null, 0x1, out count, out ptr)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } var credentials = Enumerable.Range(0, count) .Select(i => Marshal.ReadIntPtr(ptr, i*IntPtr.Size)) .Select(p => new Credential((NativeCredential)Marshal.PtrToStructure(p, typeof(NativeCredential)))); return credentials; } public void AddPasswordCredential(string targetName, string userName, string password, string comment) { using (var credential = new Credential { TargetName = targetName, UserName = userName, CredentialBlob = password, Comment = comment }) { credential.Save(); } } public void DeleteCredential(Credential credential) { if (!UnsafeAdvapi32.CredDeleteW(credential.TargetName, credential.Type, 0)) { var error = (CredentialErrors)Marshal.GetLastWin32Error(); throw new CredentialManagerException(error, "Could not delete credential."); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.InteropServices; namespace poshring { public class CredentialsManager { public IEnumerable<Credential> GetCredentials() { int count; IntPtr ptr; if (!UnsafeAdvapi32.CredEnumerateW(null, 0x1, out count, out ptr)) { var error = (CredentialErrors) Marshal.GetLastWin32Error(); switch (error) { case CredentialErrors.NotFound: return Enumerable.Empty<Credential>(); case CredentialErrors.NoSuchLogonSession: case CredentialErrors.InvalidFlags: throw new Win32Exception((int)error); default: throw new InvalidOperationException("Unexpected error while fetching credentials."); } } var credentials = Enumerable.Range(0, count) .Select(i => Marshal.ReadIntPtr(ptr, i*IntPtr.Size)) .Select(p => new Credential((NativeCredential)Marshal.PtrToStructure(p, typeof(NativeCredential)))); return credentials; } public void AddPasswordCredential(string targetName, string userName, string password, string comment) { using (var credential = new Credential { TargetName = targetName, UserName = userName, CredentialBlob = password, Comment = comment }) { credential.Save(); } } public void DeleteCredential(Credential credential) { if (!UnsafeAdvapi32.CredDeleteW(credential.TargetName, credential.Type, 0)) { var error = (CredentialErrors)Marshal.GetLastWin32Error(); throw new CredentialManagerException(error, "Could not delete credential."); } } } }
Return empty result when there are no credentials on the system.
Return empty result when there are no credentials on the system.
C#
mit
skyguy94/poshring
6bb9c291c7e92aee8c9a1c99b3fb097fc3e8524f
modules/Module1/Program.cs
modules/Module1/Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; namespace Module1 { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .Build(); host.Run(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.AspNetCore.Modules; namespace Module1 { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureServices(services => { services.AddSingleton(new ModuleInstanceIdProvider("Module1")); }) .UseStartup<Startup>() .Build(); host.Run(); } } }
Fix Module1 to run as independent app
Fix Module1 to run as independent app
C#
mit
danroth27/AspNetCoreModules,danroth27/AspNetCoreModules
353636893d08b2effab340a33dda853e091c55bf
src/UrlShortenerApi/Repositories/IHeaderRepository.cs
src/UrlShortenerApi/Repositories/IHeaderRepository.cs
using System.Collections.Generic; using UrlShortenerApi.Models; namespace UrlShortenerApi.Repositories { public interface IHeaderRepository { void Add(Microsoft.AspNetCore.Http.IHeaderDictionary request, int urlID); void Add(Header item); } }
using System.Collections.Generic; using UrlShortenerApi.Models; namespace UrlShortenerApi.Repositories { public interface IHeaderRepository { void Add(Microsoft.AspNetCore.Http.IHeaderDictionary headers, int urlID); void Add(Header item); } }
Update variable name on Header Repository Interface
Update variable name on Header Repository Interface This name is more representative.
C#
agpl-3.0
jimbeaudoin/dotnet-core-urlshortener,jimbeaudoin/dotnet-core-urlshortener,jimbeaudoin/dotnet-core-urlshortener
451770cae3400db157bffefb25d5598688cf8009
Voxalia/ServerGame/EntitySystem/EntityLiving.cs
Voxalia/ServerGame/EntitySystem/EntityLiving.cs
using Voxalia.ServerGame.WorldSystem; namespace Voxalia.ServerGame.EntitySystem { public abstract class EntityLiving: PhysicsEntity, EntityDamageable { public EntityLiving(Region tregion, bool ticks, float maxhealth) : base(tregion, ticks) { MaxHealth = maxhealth; Health = maxhealth; } public float Health = 100; public float MaxHealth = 100; public virtual float GetHealth() { return Health; } public virtual float GetMaxHealth() { return MaxHealth; } public virtual void SetHealth(float health) { Health = health; if (MaxHealth != 0 && Health <= 0) { Die(); } } public virtual void Damage(float amount) { SetHealth(GetHealth() - amount); } public virtual void SetMaxHealth(float maxhealth) { MaxHealth = maxhealth; } public abstract void Die(); } }
using System; using Voxalia.ServerGame.WorldSystem; namespace Voxalia.ServerGame.EntitySystem { public abstract class EntityLiving: PhysicsEntity, EntityDamageable { public EntityLiving(Region tregion, bool ticks, float maxhealth) : base(tregion, ticks) { MaxHealth = maxhealth; Health = maxhealth; } public float Health = 100; public float MaxHealth = 100; public virtual float GetHealth() { return Health; } public virtual float GetMaxHealth() { return MaxHealth; } public virtual void SetHealth(float health) { Health = Math.Min(health, MaxHealth); if (MaxHealth != 0 && Health <= 0) { Die(); } } public virtual void Damage(float amount) { SetHealth(GetHealth() - amount); } public virtual void SetMaxHealth(float maxhealth) { MaxHealth = maxhealth; } public abstract void Die(); } }
CLean a potential hole in entityliving
CLean a potential hole in entityliving
C#
mit
Morphan1/Voxalia,Morphan1/Voxalia,Morphan1/Voxalia
16dd98407e077dad395572cb702a4b53caabb47c
src/AppGet/Installers/InstallerWhispererBase.cs
src/AppGet/Installers/InstallerWhispererBase.cs
using AppGet.Commands.Install; using AppGet.Commands.Uninstall; using AppGet.Manifests; using AppGet.Processes; using NLog; namespace AppGet.Installers { public abstract class InstallerWhispererBase : IInstallerWhisperer { private readonly IProcessController _processController; private readonly Logger _logger; protected InstallerWhispererBase(IProcessController processController, Logger logger) { _processController = processController; _logger = logger; } public abstract void Install(string installerLocation, PackageManifest packageManifest, InstallOptions installOptions); public abstract void Uninstall(PackageManifest packageManifest, UninstallOptions installOptions); public abstract bool CanHandle(InstallMethodType installMethod); protected virtual int Execute(string exectuable, string args) { var process = _processController.Start(exectuable, args, OnOutputDataReceived, OnErrorDataReceived); _processController.WaitForExit(process); return process.ExitCode; } protected virtual void OnOutputDataReceived(string message) { _logger.Info(message); } protected virtual void OnErrorDataReceived(string message) { _logger.Error(message); } } }
using System.ComponentModel; using AppGet.Commands.Install; using AppGet.Commands.Uninstall; using AppGet.Exceptions; using AppGet.Manifests; using AppGet.Processes; using NLog; namespace AppGet.Installers { public abstract class InstallerWhispererBase : IInstallerWhisperer { private readonly IProcessController _processController; private readonly Logger _logger; protected InstallerWhispererBase(IProcessController processController, Logger logger) { _processController = processController; _logger = logger; } public abstract void Install(string installerLocation, PackageManifest packageManifest, InstallOptions installOptions); public abstract void Uninstall(PackageManifest packageManifest, UninstallOptions installOptions); public abstract bool CanHandle(InstallMethodType installMethod); protected virtual void Execute(string executable, string args) { try { var process = _processController.Start(executable, args, OnOutputDataReceived, OnErrorDataReceived); _processController.WaitForExit(process); if (process.ExitCode != 0) { throw new AppGetException($"Installer '{process.ProcessName}' returned with a non-zero exit code. code: {process.ExitCode}"); } } catch (Win32Exception e) { _logger.Error($"{e.Message}, try running AppGet as an administartor"); throw; } } protected virtual void OnOutputDataReceived(string message) { _logger.Info(message); } protected virtual void OnErrorDataReceived(string message) { _logger.Error(message); } } }
Throw error if installer returns a non-zero exist code.
Throw error if installer returns a non-zero exist code.
C#
apache-2.0
AppGet/AppGet
a265d877e4f9e14d5a6c54feba9f87ea108debb4
Assets/NetworkManager.cs
Assets/NetworkManager.cs
using UnityEngine; using UnityEngine.UI; using System.Collections.Generic; public class NetworkManager : MonoBehaviour { public List<string> ChatMessages; // Goal #1: Create a reasonable chat system using the NEW UI System public void AddChatMessage(string message) { PhotonView.Get(this).RPC("AddChatMessageRPC", PhotonTargets.All, message); } [RPC] private void AddChatMessageRPC(string message) { // TODO: If message is longer than x characters, split it into multiple messages so that it fits inside the textbox while (ChatMessages.Count >= maxChatMessages) { ChatMessages.RemoveAt(0); } ChatMessages.Add(message); } void Start() { PhotonNetwork.player.name = PlayerPrefs.GetString("Username", "Matt"); ChatMessages = new List<string>(); Connect(); } void Update() { } void Connect() { PhotonNetwork.ConnectUsingSettings("FPS Test v001"); } void OnGUI() { GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString()); } void OnJoinedLobby() { Debug.Log("OnJoinedLobby"); PhotonNetwork.JoinRandomRoom(); } void OnPhotonRandomJoinFailed() { Debug.Log("OnPhotonRandomJoinFailed"); PhotonNetwork.CreateRoom(null); } void OnJoinedRoom() { Debug.Log("OnJoinedRoom"); AddChatMessage("[SYSTEM] OnJoinedRoom!"); } const int maxChatMessages = 7; }
using UnityEngine; using UnityEngine.UI; using System.Collections.Generic; public class NetworkManager : MonoBehaviour { public List<string> ChatMessages; public bool IsOfflineMode; // Goal #1: Create a reasonable chat system using the NEW UI System public void AddChatMessage(string message) { PhotonView.Get(this).RPC("AddChatMessageRPC", PhotonTargets.All, message); } [RPC] private void AddChatMessageRPC(string message) { // TODO: If message is longer than x characters, split it into multiple messages so that it fits inside the textbox while (ChatMessages.Count >= maxChatMessages) { ChatMessages.RemoveAt(0); } ChatMessages.Add(message); } void Start() { PhotonNetwork.player.name = PlayerPrefs.GetString("Username", "Matt"); ChatMessages = new List<string>(); if (IsOfflineMode) { PhotonNetwork.offlineMode = true; OnJoinedLobby(); } else { Connect(); } } void Update() { } void Connect() { PhotonNetwork.ConnectUsingSettings("FPS Test v001"); } void OnGUI() { GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString()); } void OnJoinedLobby() { Debug.Log("OnJoinedLobby"); PhotonNetwork.JoinRandomRoom(); } void OnPhotonRandomJoinFailed() { Debug.Log("OnPhotonRandomJoinFailed"); PhotonNetwork.CreateRoom(null); } void OnJoinedRoom() { Debug.Log("OnJoinedRoom"); AddChatMessage("[SYSTEM] OnJoinedRoom!"); } const int maxChatMessages = 7; }
Enable offline mode by default.
Enable offline mode by default.
C#
mit
PlanetLotus/FPS-Sandbox,PlanetLotus/FPS-Sandbox
b355047bf92a236eb804b50f234bfbe9d9b59114
Client/API/Students/Experiences/ExperienceModel.cs
Client/API/Students/Experiences/ExperienceModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CareerHub.Client.API.Students.Experiences { public class ExperienceModel { public int ID { get; set; } public string Title { get; set; } public string Organisation { get; set; } public string Description { get; set; } public string ContactName { get; set; } public string ContactEmail { get; set; } public string ContactPhone { get; set; } public DateTime StartUtc { get; set; } public DateTime? EndUtc { get; set; } public DateTime Start { get; set; } public DateTime? End { get; set; } public string Type { get; set; } public string Hours { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CareerHub.Client.API.Students.Experiences { public class ExperienceModel { public int ID { get; set; } public string Title { get; set; } public string Organisation { get; set; } public string Description { get; set; } public string ContactName { get; set; } public string ContactEmail { get; set; } public string ContactPhone { get; set; } public DateTime StartUtc { get; set; } public DateTime? EndUtc { get; set; } public DateTime Start { get; set; } public DateTime? End { get; set; } public int? TypeID { get; set; } public string Type { get; set; } public int? HoursID { get; set; } public string Hours { get; set; } } }
Add extra properties to experience model
Add extra properties to experience model
C#
mit
CareerHub/.NET-CareerHub-API-Client,CareerHub/.NET-CareerHub-API-Client
954a5887bdeb288024a288cfcb2bd2b455d15420
Phoebe.FormClient/Program.cs
Phoebe.FormClient/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using Phoebe.Base; using Phoebe.Common; using Phoebe.Model; namespace Phoebe.FormClient { static class Program { /// <summary> /// 全局操作 /// </summary> public static GlobalControl GC = new GlobalControl(); /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { DevExpress.UserSkins.BonusSkins.Register(); DevExpress.Skins.SkinManager.EnableFormSkins(); DevExpress.Skins.SkinManager.EnableMdiFormSkins(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); LoginForm login = new LoginForm(); if (login.ShowDialog() == DialogResult.OK) { Program.GC.CurrentUser = Program.GC.ConvertToLoginUser(login.User); Cache.Instance.Add("CurrentUser", Program.GC.CurrentUser); //缓存用户信息 Application.Run(new MainForm()); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using Phoebe.Base; using Phoebe.Common; using Phoebe.Model; namespace Phoebe.FormClient { static class Program { /// <summary> /// 全局操作 /// </summary> public static GlobalControl GC = new GlobalControl(); /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { DevExpress.UserSkins.BonusSkins.Register(); DevExpress.Skins.SkinManager.EnableFormSkins(); DevExpress.Skins.SkinManager.EnableMdiFormSkins(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); LoginForm login = new LoginForm(); if (login.ShowDialog() == DialogResult.OK) { Program.GC.CurrentUser = Program.GC.ConvertToLoginUser(login.User); Cache.Instance.Add("CurrentUser", Program.GC.CurrentUser); //缓存用户信息 Application.Run(new MainForm()); } } /// <summary> /// 异常消息处理 /// </summary> /// <param name="sender"></param> /// <param name="ex"></param> private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs ex) { string message = string.Format("{0}\r\n操作发生错误,您需要退出系统么?", ex.Exception.Message); if (MessageUtil.ConfirmYesNo(message) == DialogResult.Yes) { Application.Exit(); } } } }
Add global exception handle, not enable.
Add global exception handle, not enable. Signed-off-by: robertzml <321e7786a406a136366094c578d0f1193a3468e1@126.com>
C#
mit
robertzml/Phoebe
a7e1749347ac2334412eb9fb8ed1cdbb0a3e1bb9
UnityProject/Assets/Scripts/Items/Dice/RollFudgeDie.cs
UnityProject/Assets/Scripts/Items/Dice/RollFudgeDie.cs
using UnityEngine; public class RollFudgeDie : RollSpecialDie { public override string Examine(Vector3 worldPos = default) { return $"It is showing side {GetFudgeMessage()}"; } protected override string GetMessage() { return $"The {dieName} lands a {GetFudgeMessage()}"; } private string GetFudgeMessage() { if (result == 2) { return specialFaces[1].ToString(); } return $"{specialFaces[result - 1]}."; } }
using UnityEngine; public class RollFudgeDie : RollSpecialDie { public override string Examine(Vector3 worldPos = default) { return $"It is showing {GetFudgeMessage()}"; } protected override string GetMessage() { return $"The {dieName} lands {GetFudgeMessage()}"; } private string GetFudgeMessage() { // Result 2 is a strange side, we modify the formatting such that it reads "a... what?". if (result == 2) { return $"a{specialFaces[1]}"; } return $"a {specialFaces[result - 1]}."; } }
Clarify FudgeDie special case's formatting
Clarify FudgeDie special case's formatting
C#
agpl-3.0
fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation
cb77a5bd2c90c1fcee09fd922ab9e9afa5f36d55
src/OmniSharp/Utilities/DirectoryEnumerator.cs
src/OmniSharp/Utilities/DirectoryEnumerator.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Framework.Logging; namespace OmniSharp.Utilities { public class DirectoryEnumerator { private ILogger _logger; public DirectoryEnumerator(ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger<DirectoryEnumerator>(); } public IEnumerable<string> SafeEnumerateFiles(string target, string pattern = "*.*") { var allFiles = Enumerable.Empty<string>(); var directoryStack = new Stack<string>(); directoryStack.Push(target); while (directoryStack.Any()) { var current = directoryStack.Pop(); try { allFiles = allFiles.Concat(GetFiles(current, pattern)); foreach (var subdirectory in GetSubdirectories(current)) { directoryStack.Push(subdirectory); } } catch (UnauthorizedAccessException) { _logger.LogWarning(string.Format("Unauthorized access to {0}, skipping", current)); } } return allFiles; } private IEnumerable<string> GetFiles(string path, string pattern) { try { return Directory.GetFiles(path, pattern, SearchOption.TopDirectoryOnly); } catch (PathTooLongException) { _logger.LogWarning(string.Format("Path {0} is too long, skipping", path)); return Enumerable.Empty<string>(); } } private IEnumerable<string> GetSubdirectories(string path) { try { return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly); } catch (PathTooLongException) { _logger.LogWarning(string.Format("Path {0} is too long, skipping", path)); return Enumerable.Empty<string>(); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Framework.Logging; namespace OmniSharp.Utilities { public class DirectoryEnumerator { private ILogger _logger; public DirectoryEnumerator(ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger<DirectoryEnumerator>(); } public IEnumerable<string> SafeEnumerateFiles(string target, string pattern = "*.*") { var allFiles = Enumerable.Empty<string>(); var directoryStack = new Stack<string>(); directoryStack.Push(target); while (directoryStack.Any()) { var current = directoryStack.Pop(); try { var files = Directory.GetFiles(current, pattern); allFiles = allFiles.Concat(files); foreach (var subdirectory in Directory.EnumerateDirectories(current)) { directoryStack.Push(subdirectory); } } catch (UnauthorizedAccessException) { _logger.LogWarning(string.Format("Unauthorized access to {0}, skipping", current)); } catch (PathTooLongException) { _logger.LogWarning(string.Format("Path {0} is too long, skipping", current)); } } return allFiles; } } }
Simplify file enumeration and correctly handle path too long exceptions when enumerating sub directories
Simplify file enumeration and correctly handle path too long exceptions when enumerating sub directories
C#
mit
DustinCampbell/omnisharp-roslyn,ianbattersby/omnisharp-roslyn,RichiCoder1/omnisharp-roslyn,sreal/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,david-driscoll/omnisharp-roslyn,sriramgd/omnisharp-roslyn,nabychan/omnisharp-roslyn,haled/omnisharp-roslyn,hitesh97/omnisharp-roslyn,sreal/omnisharp-roslyn,khellang/omnisharp-roslyn,ChrisHel/omnisharp-roslyn,hal-ler/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,nabychan/omnisharp-roslyn,fishg/omnisharp-roslyn,jtbm37/omnisharp-roslyn,haled/omnisharp-roslyn,RichiCoder1/omnisharp-roslyn,hal-ler/omnisharp-roslyn,hach-que/omnisharp-roslyn,hach-que/omnisharp-roslyn,ChrisHel/omnisharp-roslyn,khellang/omnisharp-roslyn,fishg/omnisharp-roslyn,hitesh97/omnisharp-roslyn,jtbm37/omnisharp-roslyn,xdegtyarev/omnisharp-roslyn,sriramgd/omnisharp-roslyn,xdegtyarev/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,ianbattersby/omnisharp-roslyn,david-driscoll/omnisharp-roslyn
2ba639c53a7d049fe2969225b03cd93e1311bad3
MonoHaven.Client/Audio.cs
MonoHaven.Client/Audio.cs
using System; using System.IO; using MonoHaven.Resources; using MonoHaven.Resources.Layers; using MonoHaven.Utils; using NVorbis.OpenTKSupport; using OpenTK.Audio; namespace MonoHaven { public class Audio : IDisposable { private readonly AudioContext context; private readonly OggStreamer streamer; public Audio() { context = new AudioContext(); streamer = new OggStreamer(); } public void Play(Delayed<Resource> res) { if (res.Value == null) return; var audio = res.Value.GetLayer<AudioData>(); var ms = new MemoryStream(audio.Bytes); var oggStream = new OggStream(ms); oggStream.Play(); } public void Dispose() { if (streamer != null) streamer.Dispose(); if (context != null) context.Dispose(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Threading; using MonoHaven.Resources; using MonoHaven.Resources.Layers; using MonoHaven.Utils; using NVorbis.OpenTKSupport; using OpenTK.Audio; namespace MonoHaven { public class Audio : IDisposable { private readonly AudioContext context; private readonly OggStreamer streamer; private readonly AudioPlayer player; public Audio() { context = new AudioContext(); streamer = new OggStreamer(); player = new AudioPlayer(); player.Run(); } public void Play(Delayed<Resource> res) { player.Queue(res); } public void Dispose() { player.Stop(); if (streamer != null) streamer.Dispose(); if (context != null) context.Dispose(); } private class AudioPlayer : BackgroundTask { private readonly Queue<Delayed<Resource>> queue; public AudioPlayer() : base("Audio Player") { queue = new Queue<Delayed<Resource>>(); } protected override void OnStart() { while (!IsCancelled) { lock (queue) { var item = queue.Count > 0 ? queue.Peek() : null; if (item != null && item.Value != null) { queue.Dequeue(); var audio = item.Value.GetLayer<AudioData>(); if (audio != null) { var ms = new MemoryStream(audio.Bytes); var oggStream = new OggStream(ms); oggStream.Play(); } } Monitor.Wait(queue, TimeSpan.FromMilliseconds(100)); } } } public void Queue(Delayed<Resource> res) { lock (queue) { queue.Enqueue(res); Monitor.PulseAll(queue); } } } } }
Use separate task to queue sound effects so they can be played when they're loaded
Use separate task to queue sound effects so they can be played when they're loaded
C#
mit
k-t/SharpHaven
de856965ade2cfaecbb8f24dc17ad623363ca549
Braintree/VenmoAccount.cs
Braintree/VenmoAccount.cs
using System; namespace Braintree { public class VenmoAccount : PaymentMethod { public string Token { get; protected set; } public string Username { get; protected set; } public string VenmoUserId { get; protected set; } public string SourceDescription { get; protected set; } public string ImageUrl { get; protected set; } public bool? IsDefault { get; protected set; } public string CustomerId { get; protected set; } public DateTime? CreatedAt { get; protected set; } public DateTime? UpdatedAt { get; protected set; } public Subscription[] Subscriptions { get; protected set; } protected internal VenmoAccount(NodeWrapper node, BraintreeGateway gateway) { Token = node.GetString("token"); Username = node.GetString("username"); VenmoUserId = node.GetString("venmo-user-id"); SourceDescription = node.GetString("source-description"); ImageUrl = node.GetString("image-url"); IsDefault = node.GetBoolean("default"); CustomerId = node.GetString("customer-id"); CreatedAt = node.GetDateTime("created-at"); UpdatedAt = node.GetDateTime("updated-at"); var subscriptionXmlNodes = node.GetList("subscriptions/subscription"); Subscriptions = new Subscription[subscriptionXmlNodes.Count]; for (int i = 0; i < subscriptionXmlNodes.Count; i++) { Subscriptions[i] = new Subscription(subscriptionXmlNodes[i], gateway); } } } }
using System; namespace Braintree { public class VenmoAccount : PaymentMethod { public string Token { get; protected set; } public string Username { get; protected set; } public string VenmoUserId { get; protected set; } public string SourceDescription { get; protected set; } public string ImageUrl { get; protected set; } public bool? IsDefault { get; protected set; } public string CustomerId { get; protected set; } public DateTime? CreatedAt { get; protected set; } public DateTime? UpdatedAt { get; protected set; } public Subscription[] Subscriptions { get; protected set; } protected internal VenmoAccount(NodeWrapper node, IBraintreeGateway gateway) { Token = node.GetString("token"); Username = node.GetString("username"); VenmoUserId = node.GetString("venmo-user-id"); SourceDescription = node.GetString("source-description"); ImageUrl = node.GetString("image-url"); IsDefault = node.GetBoolean("default"); CustomerId = node.GetString("customer-id"); CreatedAt = node.GetDateTime("created-at"); UpdatedAt = node.GetDateTime("updated-at"); var subscriptionXmlNodes = node.GetList("subscriptions/subscription"); Subscriptions = new Subscription[subscriptionXmlNodes.Count]; for (int i = 0; i < subscriptionXmlNodes.Count; i++) { Subscriptions[i] = new Subscription(subscriptionXmlNodes[i], gateway); } } [Obsolete("Mock Use Only")] protected internal VenmoAccount() { } } }
Add mock changes to new Venmo class
Add mock changes to new Venmo class
C#
mit
scottmeyer/braintree_dotnet,scottmeyer/braintree_dotnet,braintree/braintree_dotnet,scottmeyer/braintree_dotnet,braintree/braintree_dotnet,scottmeyer/braintree_dotnet
fcaee6604b6e3b2bac681fe9307795098a92d133
ChessDotNet/GameStatus.cs
ChessDotNet/GameStatus.cs
namespace ChessDotNet { public enum Event { Check, Checkmate, Stalemate, Draw, Custom, Resign, VariantEnd, // to be used for chess variants, which can be derived from ChessGame None } public class GameStatus { public Event Event { get; private set; } public Player PlayerWhoCausedEvent { get; private set; } public string EventExplanation { get; private set; } public GameStatus(Event _event, Player whoCausedEvent, string eventExplanation) { Event = _event; PlayerWhoCausedEvent = whoCausedEvent; EventExplanation = eventExplanation; } } }
namespace ChessDotNet { public enum Event { Check, Checkmate, Stalemate, Draw, Custom, Resign, VariantEnd, // to be used for chess variants, which can be derived from ChessGame None } public class GameStatus { public Event Event { get; private set; } public Player PlayerWhoCausedEvent { get; private set; } public string EventExplanation { get; private set; } public GameStatus(Event @event, Player whoCausedEvent, string eventExplanation) { Event = @event; PlayerWhoCausedEvent = whoCausedEvent; EventExplanation = eventExplanation; } } }
Remove underscore from parameter name
Remove underscore from parameter name
C#
mit
ProgramFOX/Chess.NET
49a03f1c06ca6824fc8e131ddd1e8f845c4ea1f2
osu.Game/IO/OsuStorage.cs
osu.Game/IO/OsuStorage.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.Logging; using osu.Framework.Platform; using osu.Game.Configuration; namespace osu.Game.IO { public class OsuStorage : WrappedStorage { public OsuStorage(GameHost host) : base(host.Storage, string.Empty) { var storageConfig = new StorageConfigManager(host.Storage); var customStoragePath = storageConfig.Get<string>(StorageConfig.FullPath); if (!string.IsNullOrEmpty(customStoragePath)) { ChangeTargetStorage(host.GetStorage(customStoragePath)); Logger.Storage = UnderlyingStorage.GetStorageForDirectory("logs"); } } } }
// 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.IO; using osu.Framework.Logging; using osu.Framework.Platform; using osu.Game.Configuration; namespace osu.Game.IO { public class OsuStorage : WrappedStorage { private readonly GameHost host; private readonly StorageConfigManager storageConfig; public OsuStorage(GameHost host) : base(host.Storage, string.Empty) { this.host = host; storageConfig = new StorageConfigManager(host.Storage); var customStoragePath = storageConfig.Get<string>(StorageConfig.FullPath); if (!string.IsNullOrEmpty(customStoragePath)) { ChangeTargetStorage(host.GetStorage(customStoragePath)); Logger.Storage = UnderlyingStorage.GetStorageForDirectory("logs"); } } public void Migrate(string newLocation) { string oldLocation = GetFullPath("."); // ensure the new location has no files present, else hard abort if (Directory.Exists(newLocation)) { if (Directory.GetFiles(newLocation).Length > 0) throw new InvalidOperationException("Migration destination already has files present"); Directory.Delete(newLocation, true); } Directory.Move(oldLocation, newLocation); Directory.CreateDirectory(newLocation); // temporary Directory.CreateDirectory(oldLocation); // move back exceptions for now Directory.Move(Path.Combine(newLocation, "cache"), Path.Combine(oldLocation, "cache")); File.Move(Path.Combine(newLocation, "framework.ini"), Path.Combine(oldLocation, "framework.ini")); ChangeTargetStorage(host.GetStorage(newLocation)); storageConfig.Set(StorageConfig.FullPath, newLocation); storageConfig.Save(); } } }
Add basic blocking migration, move not copy
Add basic blocking migration, move not copy
C#
mit
peppy/osu,peppy/osu,peppy/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu-new,ppy/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu
fe025043bd59d8164710cce507c16589ad439c98
osu.Game.Tests/Visual/Gameplay/TestSceneParticleExplosion.cs
osu.Game.Tests/Visual/Gameplay/TestSceneParticleExplosion.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.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Textures; using osu.Game.Graphics; using osuTK; namespace osu.Game.Tests.Visual.Gameplay { [TestFixture] public class TestSceneParticleExplosion : OsuTestScene { [BackgroundDependencyLoader] private void load(TextureStore textures) { AddStep(@"display", () => { Child = new ParticleExplosion(textures.Get("Cursor/cursortrail"), 150, 1200) { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(200) }; }); } } }
// 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.Graphics; using osu.Framework.Graphics.Textures; using osu.Game.Graphics; using osuTK; namespace osu.Game.Tests.Visual.Gameplay { [TestFixture] public class TestSceneParticleExplosion : OsuTestScene { [BackgroundDependencyLoader] private void load(TextureStore textures) { AddRepeatStep(@"display", () => { Child = new ParticleExplosion(textures.Get("Cursor/cursortrail"), 150, 1200) { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(400) }; }, 10); } } }
Make test run multiple times
Make test run multiple times
C#
mit
smoogipooo/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,ppy/osu,peppy/osu-new,peppy/osu,peppy/osu
342c4c44f6fa2053acec1c7271d796f9e0f98265
src/Microsoft.AspNetCore.Sockets.Abstractions/DuplexPipe.cs
src/Microsoft.AspNetCore.Sockets.Abstractions/DuplexPipe.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace System.IO.Pipelines { public class DuplexPipe : IDuplexPipe { public DuplexPipe(PipeReader reader, PipeWriter writer) { Input = reader; Output = writer; } public PipeReader Input { get; } public PipeWriter Output { get; } public void Dispose() { } public static DuplexPipePair CreateConnectionPair(PipeOptions inputOptions, PipeOptions outputOptions) { var input = new Pipe(inputOptions); var output = new Pipe(outputOptions); var transportToApplication = new DuplexPipe(output.Reader, input.Writer); var applicationToTransport = new DuplexPipe(input.Reader, output.Writer); return new DuplexPipePair(applicationToTransport, transportToApplication); } // This class exists to work around issues with value tuple on .NET Framework public struct DuplexPipePair { public IDuplexPipe Transport { get; private set; } public IDuplexPipe Application { get; private set; } public DuplexPipePair(IDuplexPipe transport, IDuplexPipe application) { Transport = transport; Application = application; } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.IO.Pipelines; namespace Microsoft.AspNetCore.Sockets { public class DuplexPipe : IDuplexPipe { public DuplexPipe(PipeReader reader, PipeWriter writer) { Input = reader; Output = writer; } public PipeReader Input { get; } public PipeWriter Output { get; } public void Dispose() { } public static DuplexPipePair CreateConnectionPair(PipeOptions inputOptions, PipeOptions outputOptions) { var input = new Pipe(inputOptions); var output = new Pipe(outputOptions); var transportToApplication = new DuplexPipe(output.Reader, input.Writer); var applicationToTransport = new DuplexPipe(input.Reader, output.Writer); return new DuplexPipePair(applicationToTransport, transportToApplication); } // This class exists to work around issues with value tuple on .NET Framework public struct DuplexPipePair { public IDuplexPipe Transport { get; private set; } public IDuplexPipe Application { get; private set; } public DuplexPipePair(IDuplexPipe transport, IDuplexPipe application) { Transport = transport; Application = application; } } } }
Change namespace to avoid conflict
Change namespace to avoid conflict
C#
apache-2.0
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
f8fa78deb93ab0226a69ed78a391f4e38f8998ae
source/Handlebars/ObjectDescriptors/ObjectAccessor.cs
source/Handlebars/ObjectDescriptors/ObjectAccessor.cs
using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using HandlebarsDotNet.MemberAccessors; using HandlebarsDotNet.ObjectDescriptors; using HandlebarsDotNet.PathStructure; namespace HandlebarsDotNet { public readonly ref struct ObjectAccessor { private readonly object _data; private readonly ObjectDescriptor _descriptor; private readonly IMemberAccessor _memberAccessor; [MethodImpl(MethodImplOptions.AggressiveInlining)] public ObjectAccessor(object data, ObjectDescriptor descriptor) { _data = data; _descriptor = descriptor; _memberAccessor = _descriptor.MemberAccessor; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ObjectAccessor(object data) { _data = data; if (data == null || !ObjectDescriptorFactory.Current.TryGetDescriptor(data.GetType(), out _descriptor)) { _descriptor = ObjectDescriptor.Empty; _memberAccessor = null; } else { _memberAccessor = _descriptor.MemberAccessor; } } public IEnumerable<ChainSegment> Properties => _descriptor .GetProperties(_descriptor, _data) .OfType<object>() .Select(ChainSegment.Create); public object this[ChainSegment segment] => _memberAccessor != null && _memberAccessor.TryGetValue(_data, segment, out var value) ? value : null; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryGetValue(ChainSegment segment, out object value) => _memberAccessor.TryGetValue(_data, segment, out value); } }
using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using HandlebarsDotNet.MemberAccessors; using HandlebarsDotNet.ObjectDescriptors; using HandlebarsDotNet.PathStructure; namespace HandlebarsDotNet { public readonly ref struct ObjectAccessor { private readonly object _data; private readonly ObjectDescriptor _descriptor; private readonly IMemberAccessor _memberAccessor; [MethodImpl(MethodImplOptions.AggressiveInlining)] public ObjectAccessor(object data, ObjectDescriptor descriptor) { _data = data; _descriptor = descriptor; _memberAccessor = _descriptor.MemberAccessor; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ObjectAccessor(object data) { _data = data; if (data == null || !ObjectDescriptorFactory.Current.TryGetDescriptor(data.GetType(), out _descriptor)) { _descriptor = ObjectDescriptor.Empty; _memberAccessor = null; } else { _memberAccessor = _descriptor.MemberAccessor; } } public IEnumerable<ChainSegment> Properties => _descriptor .GetProperties(_descriptor, _data) .OfType<object>() .Select(ChainSegment.Create); public object this[ChainSegment segment] => _memberAccessor != null && _memberAccessor.TryGetValue(_data, segment, out var value) ? value : null; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryGetValue(ChainSegment segment, out object value) { if (_memberAccessor == null) { value = null; return false; } return _memberAccessor.TryGetValue(_data, segment, out value); } } }
Fix `NullReferenceException` when `IMemberAccessor` was not resolved Related to Handlebars-Net/Handlebars.Net/issues/399
Fix `NullReferenceException` when `IMemberAccessor` was not resolved Related to Handlebars-Net/Handlebars.Net/issues/399
C#
mit
rexm/Handlebars.Net,rexm/Handlebars.Net
1a2db87668d254315cbd2a1d52cbb9dc902354a3
osu.Game.Modes.Osu/Scoring/OsuScoreProcessor.cs
osu.Game.Modes.Osu/Scoring/OsuScoreProcessor.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Modes.Objects.Drawables; using osu.Game.Modes.Osu.Judgements; using osu.Game.Modes.Osu.Objects; using osu.Game.Modes.Scoring; using osu.Game.Modes.UI; namespace osu.Game.Modes.Osu.Scoring { internal class OsuScoreProcessor : ScoreProcessor<OsuHitObject, OsuJudgement> { public OsuScoreProcessor() { } public OsuScoreProcessor(HitRenderer<OsuHitObject, OsuJudgement> hitRenderer) : base(hitRenderer) { } protected override void Reset() { base.Reset(); Health.Value = 1; Accuracy.Value = 1; } protected override void OnNewJudgement(OsuJudgement judgement) { if (judgement != null) { switch (judgement.Result) { case HitResult.Hit: Combo.Value++; Health.Value += 0.1f; break; case HitResult.Miss: Combo.Value = 0; Health.Value -= 0.2f; break; } } int score = 0; int maxScore = 0; foreach (var j in Judgements) { score += j.ScoreValue; maxScore += j.MaxScoreValue; } TotalScore.Value = score; Accuracy.Value = (double)score / maxScore; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Modes.Objects.Drawables; using osu.Game.Modes.Osu.Judgements; using osu.Game.Modes.Osu.Objects; using osu.Game.Modes.Scoring; using osu.Game.Modes.UI; namespace osu.Game.Modes.Osu.Scoring { internal class OsuScoreProcessor : ScoreProcessor<OsuHitObject, OsuJudgement> { public OsuScoreProcessor() { } public OsuScoreProcessor(HitRenderer<OsuHitObject, OsuJudgement> hitRenderer) : base(hitRenderer) { } protected override void Reset() { base.Reset(); Health.Value = 1; Accuracy.Value = 1; } protected override void OnNewJudgement(OsuJudgement judgement) { int score = 0; int maxScore = 0; foreach (var j in Judgements) { score += j.ScoreValue; maxScore += j.MaxScoreValue; } TotalScore.Value = score; Accuracy.Value = (double)score / maxScore; } } }
Fix osu! mode adding combos twice.
Fix osu! mode adding combos twice.
C#
mit
ppy/osu,ppy/osu,smoogipoo/osu,osu-RP/osu-RP,EVAST9919/osu,smoogipoo/osu,johnneijzen/osu,Nabile-Rahmani/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu-new,ppy/osu,Damnae/osu,UselessToucan/osu,NeoAdonis/osu,NeoAdonis/osu,NeoAdonis/osu,naoey/osu,2yangk23/osu,Drezi126/osu,DrabWeb/osu,DrabWeb/osu,smoogipoo/osu,EVAST9919/osu,RedNesto/osu,DrabWeb/osu,naoey/osu,ZLima12/osu,ZLima12/osu,2yangk23/osu,smoogipooo/osu,tacchinotacchi/osu,peppy/osu,naoey/osu,peppy/osu,Frontear/osuKyzer,peppy/osu,johnneijzen/osu,nyaamara/osu
efbd168347ea74a4d9c02e6099bbd0d394c80fcf
src/VisualStudio/ProjectSystems/JsProjectSystem.cs
src/VisualStudio/ProjectSystems/JsProjectSystem.cs
using System.IO; using EnvDTE; namespace NuGet.VisualStudio { /// <summary> /// This project system represents the JavaScript Metro project in Windows8 /// </summary> public class JsProjectSystem : VsProjectSystem { public JsProjectSystem(Project project, IFileSystemProvider fileSystemProvider) : base(project, fileSystemProvider) { } public override string ProjectName { get { return Project.GetName(); } } public override void AddFile(string path, Stream stream) { Project.GetProjectItems(path, createIfNotExists: true); base.AddFile(path, stream); } protected override void AddFileToContainer(string fullPath, ProjectItems container) { container.AddFromFile(fullPath); } } }
using System.IO; using EnvDTE; namespace NuGet.VisualStudio { /// <summary> /// This project system represents the JavaScript Metro project in Windows8 /// </summary> public class JsProjectSystem : VsProjectSystem { public JsProjectSystem(Project project, IFileSystemProvider fileSystemProvider) : base(project, fileSystemProvider) { } public override string ProjectName { get { return Project.GetName(); } } public override void AddFile(string path, Stream stream) { // ensure the parent folder is created before adding file to the project Project.GetProjectItems(Path.GetDirectoryName(path), createIfNotExists: true); base.AddFile(path, stream); } protected override void AddFileToContainer(string fullPath, ProjectItems container) { container.AddFromFile(fullPath); } } }
Fix bug not able to install packages to JS Metro project. Work items: 1986
Fix bug not able to install packages to JS Metro project. Work items: 1986 --HG-- branch : 1.7
C#
apache-2.0
alluran/node.net,indsoft/NuGet2,mrward/nuget,jmezach/NuGet2,OneGet/nuget,dolkensp/node.net,indsoft/NuGet2,oliver-feng/nuget,ctaggart/nuget,oliver-feng/nuget,RichiCoder1/nuget-chocolatey,anurse/NuGet,mrward/NuGet.V2,xoofx/NuGet,zskullz/nuget,jmezach/NuGet2,themotleyfool/NuGet,ctaggart/nuget,RichiCoder1/nuget-chocolatey,xoofx/NuGet,dolkensp/node.net,indsoft/NuGet2,GearedToWar/NuGet2,zskullz/nuget,RichiCoder1/nuget-chocolatey,oliver-feng/nuget,ctaggart/nuget,xoofx/NuGet,rikoe/nuget,mrward/nuget,xoofx/NuGet,rikoe/nuget,jholovacs/NuGet,kumavis/NuGet,indsoft/NuGet2,chocolatey/nuget-chocolatey,oliver-feng/nuget,RichiCoder1/nuget-chocolatey,alluran/node.net,mono/nuget,antiufo/NuGet2,akrisiun/NuGet,chocolatey/nuget-chocolatey,pratikkagda/nuget,pratikkagda/nuget,pratikkagda/nuget,GearedToWar/NuGet2,jmezach/NuGet2,xoofx/NuGet,antiufo/NuGet2,indsoft/NuGet2,chester89/nugetApi,akrisiun/NuGet,atheken/nuget,pratikkagda/nuget,mono/nuget,mono/nuget,atheken/nuget,chocolatey/nuget-chocolatey,OneGet/nuget,mrward/NuGet.V2,pratikkagda/nuget,mrward/nuget,alluran/node.net,GearedToWar/NuGet2,jholovacs/NuGet,zskullz/nuget,rikoe/nuget,mrward/NuGet.V2,jholovacs/NuGet,mono/nuget,chester89/nugetApi,antiufo/NuGet2,antiufo/NuGet2,mrward/NuGet.V2,kumavis/NuGet,OneGet/nuget,RichiCoder1/nuget-chocolatey,chocolatey/nuget-chocolatey,jmezach/NuGet2,oliver-feng/nuget,jmezach/NuGet2,GearedToWar/NuGet2,jholovacs/NuGet,dolkensp/node.net,GearedToWar/NuGet2,OneGet/nuget,pratikkagda/nuget,chocolatey/nuget-chocolatey,xero-github/Nuget,zskullz/nuget,chocolatey/nuget-chocolatey,indsoft/NuGet2,antiufo/NuGet2,mrward/nuget,anurse/NuGet,xoofx/NuGet,themotleyfool/NuGet,jholovacs/NuGet,jmezach/NuGet2,mrward/NuGet.V2,antiufo/NuGet2,RichiCoder1/nuget-chocolatey,dolkensp/node.net,mrward/NuGet.V2,mrward/nuget,themotleyfool/NuGet,ctaggart/nuget,rikoe/nuget,alluran/node.net,jholovacs/NuGet,GearedToWar/NuGet2,mrward/nuget,oliver-feng/nuget
3ccdd1d76b31779ed9fbceac00462f5b241cb289
PhotoStoryToBloomConverter/BloomModel/BloomHtmlModel/Body.cs
PhotoStoryToBloomConverter/BloomModel/BloomHtmlModel/Body.cs
using System.Collections.Generic; using System.Xml.Serialization; namespace PhotoStoryToBloomConverter.BloomModel.BloomHtmlModel { public class Body { [XmlAttribute("bookcreationtype")] public string BookCreationType; [XmlAttribute("class")] public string Class; [XmlElement("div")] public List<Div> Divs; } }
using System.Collections.Generic; using System.Xml.Serialization; namespace PhotoStoryToBloomConverter.BloomModel.BloomHtmlModel { public class Body { // REVIEW: I don't think these two are necessary/useful [XmlAttribute("bookcreationtype")] public string BookCreationType; [XmlAttribute("class")] public string Class; // Features used to make this a "motion book" [XmlAttribute("data-bfautoadvance")] public string BloomFeature_AutoAdvance = "landscape;bloomReader"; [XmlAttribute("data-bfcanrotate")] public string BloomFeature_CanRotate = "allOrientations;bloomReader"; [XmlAttribute("data-bfplayanimations")] public string BloomFeature_PlayAnimations = "landscape;bloomReader"; [XmlAttribute("data-bfplaymusic")] public string BloomFeature_PlayMusic = "landscape;bloomReader"; [XmlAttribute("data-bfplaynarration")] public string BloomFeature_PlayNarration = "landscape;bloomReader"; [XmlAttribute("data-bffullscreenpicture")] public string BloomFeature_FullScreenPicture = "landscape;bloomReader"; [XmlElement("div")] public List<Div> Divs; } }
Make published books "motion book"s
Make published books "motion book"s
C#
mit
BloomBooks/PhotoStoryToBloomConverter,BloomBooks/PhotoStoryToBloomConverter
4da1acb83bc3d46d81ffdb0727453b0b13bb6bea
src/Rainbow/Formatting/FieldFormatters/MultilistFormatter.cs
src/Rainbow/Formatting/FieldFormatters/MultilistFormatter.cs
using System; using System.Collections.Generic; using Rainbow.Model; using Sitecore.Data; namespace Rainbow.Formatting.FieldFormatters { public class MultilistFormatter : FieldTypeBasedFormatter { public override string[] SupportedFieldTypes { get { return new[] { "Checklist", "Multilist", "Multilist with Search", "Treelist", "Treelist with Search", "TreelistEx" }; } } public override string Format(IItemFieldValue field) { var values = ID.ParseArray(field.Value); if (values.Length == 0 && field.Value.Length > 0) return field.Value; return string.Join(Environment.NewLine, (IEnumerable<ID>)values); } public override string Unformat(string value) { if (value == null) return null; return value.Trim().Replace(Environment.NewLine, "|"); } } }
using System; using System.Collections.Generic; using Rainbow.Model; using Sitecore.Data; namespace Rainbow.Formatting.FieldFormatters { public class MultilistFormatter : FieldTypeBasedFormatter { public override string[] SupportedFieldTypes { get { return new[] { "Checklist", "Multilist", "Multilist with Search", "Treelist", "Treelist with Search", "TreelistEx", "tree list" }; } } public override string Format(IItemFieldValue field) { var values = ID.ParseArray(field.Value); if (values.Length == 0 && field.Value.Length > 0) return field.Value; return string.Join(Environment.NewLine, (IEnumerable<ID>)values); } public override string Unformat(string value) { if (value == null) return null; return value.Trim().Replace(Environment.NewLine, "|"); } } }
Add deprecated 'tree list' type to formatter, because that's what __base templates still is :)
Add deprecated 'tree list' type to formatter, because that's what __base templates still is :)
C#
mit
kamsar/Rainbow,MacDennis76/Rainbow,PetersonDave/Rainbow
0d4ab54d7edc697f7877e9b088af948bdab215ab
labs/ch1/HelloIndigo/Host.Specs/RunServiceHostSteps.cs
labs/ch1/HelloIndigo/Host.Specs/RunServiceHostSteps.cs
 using System; using System.Diagnostics; using System.ServiceModel; using NUnit.Framework; using TechTalk.SpecFlow; namespace Host.Specs { /// <summary> /// An **copy** of the interface specifying the contract for this service. /// </summary> [ServiceContract( Namespace = "http://www.thatindigogirl.com/samples/2006/06")] public interface IHelloIndigoService { [OperationContract] string HelloIndigo(); } [Binding] public class RunServiceHostSteps { [Given(@"that I have started the host")] public void GivenThatIHaveStartedTheHost() { Process.Start(@"..\..\..\Host\bin\Debug\Host.exe"); } [When(@"I execute the ""(.*)"" method of the service")] public void WhenIExecuteTheMethodOfTheService(string p0) { var endPointAddress = new EndpointAddress( "http://localhost:8000/HelloIndigo/HelloIndigoService"); var proxy = ChannelFactory<IHelloIndigoService>.CreateChannel( new BasicHttpBinding(), endPointAddress); ScenarioContext.Current.Set(proxy); } [Then(@"I receive ""(.*)"" as a result")] public void ThenIReceiveAsAResult(string p0) { var proxy = ScenarioContext.Current.Get<IHelloIndigoService>(); var result = proxy.HelloIndigo(); Assert.That(result, Is.EqualTo("Hello Indigo")); } } }
 using System; using System.Diagnostics; using System.ServiceModel; using NUnit.Framework; using TechTalk.SpecFlow; namespace Host.Specs { /// <summary> /// An **copy** of the interface specifying the contract for this service. /// </summary> [ServiceContract( Namespace = "http://www.thatindigogirl.com/samples/2006/06")] public interface IHelloIndigoService { [OperationContract] string HelloIndigo(); } [Binding] public class RunServiceHostSteps { [Given(@"that I have started the host")] public void GivenThatIHaveStartedTheHost() { Process.Start(@"..\..\..\Host\bin\Debug\Host.exe"); } [When(@"I execute the ""(.*)"" method of the service")] public void WhenIExecuteTheMethodOfTheService(string p0) { var endPointAddress = new EndpointAddress( "http://localhost:8733/Design_Time_Addresses/Host/HelloIndigoService"); var proxy = ChannelFactory<IHelloIndigoService>.CreateChannel( new BasicHttpBinding(), endPointAddress); ScenarioContext.Current.Set(proxy); } [Then(@"I receive ""(.*)"" as a result")] public void ThenIReceiveAsAResult(string p0) { var proxy = ScenarioContext.Current.Get<IHelloIndigoService>(); var result = proxy.HelloIndigo(); Assert.That(result, Is.EqualTo("Hello Indigo")); } } }
Correct test client endpoint address. It worked!
Correct test client endpoint address. It worked! Changed the endpoint address to which the test client connects to the endpoint address specified in `Host\App.config`. The test now passes. Now that I am "green," I can move on to other work. :)
C#
epl-1.0
mrwizard82d1/learning_wcf,mrwizard82d1/learning_wcf
a5c23e7cf793c91d91bd2b67b536f107e10a8ec2
osu.Game/Overlays/OverlayHeaderBreadcrumbControl.cs
osu.Game/Overlays/OverlayHeaderBreadcrumbControl.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.Game.Graphics.UserInterface; using osu.Framework.Graphics; using osu.Framework.Graphics.UserInterface; namespace osu.Game.Overlays { public class OverlayHeaderBreadcrumbControl : BreadcrumbControl<string> { public OverlayHeaderBreadcrumbControl() { RelativeSizeAxes = Axes.X; } protected override TabItem<string> CreateTabItem(string value) => new ControlTabItem(value); private class ControlTabItem : BreadcrumbTabItem { protected override float ChevronSize => 8; public ControlTabItem(string value) : base(value) { Text.Font = Text.Font.With(size: 14); Chevron.Y = 3; } } } }
// 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.Game.Graphics.UserInterface; using osu.Framework.Graphics; using osu.Framework.Graphics.UserInterface; namespace osu.Game.Overlays { public class OverlayHeaderBreadcrumbControl : BreadcrumbControl<string> { public OverlayHeaderBreadcrumbControl() { RelativeSizeAxes = Axes.X; } protected override TabItem<string> CreateTabItem(string value) => new ControlTabItem(value); private class ControlTabItem : BreadcrumbTabItem { protected override float ChevronSize => 8; public ControlTabItem(string value) : base(value) { Text.Font = Text.Font.With(size: 14); Chevron.Y = 3; Bar.Height = 0; } } } }
Remove underline from breadcrumb display
Remove underline from breadcrumb display
C#
mit
johnneijzen/osu,EVAST9919/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,smoogipooo/osu,2yangk23/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,peppy/osu-new,NeoAdonis/osu,EVAST9919/osu,2yangk23/osu,ppy/osu,ppy/osu,UselessToucan/osu,johnneijzen/osu
ce9c63970cce934caa8b06303780160251d7ff72
osu.Game.Tests/Visual/SongSelect/TestSceneBeatmapOptionsOverlay.cs
osu.Game.Tests/Visual/SongSelect/TestSceneBeatmapOptionsOverlay.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; using osu.Framework.Graphics.Sprites; using osu.Game.Screens.Select.Options; using osuTK.Graphics; namespace osu.Game.Tests.Visual.SongSelect { [Description("bottom beatmap details")] public class TestSceneBeatmapOptionsOverlay : OsuTestScene { public TestSceneBeatmapOptionsOverlay() { var overlay = new BeatmapOptionsOverlay(); overlay.AddButton(@"Remove", @"from unplayed", FontAwesome.Regular.TimesCircle, Color4.Purple, null); overlay.AddButton(@"Clear", @"local scores", FontAwesome.Solid.Eraser, Color4.Purple, null); overlay.AddButton(@"Delete", @"all difficulties", FontAwesome.Solid.Trash, Color4.Pink, null); overlay.AddButton(@"Edit", @"beatmap", FontAwesome.Solid.PencilAlt, Color4.Yellow, null); Add(overlay); AddStep(@"Toggle", overlay.ToggleVisibility); } } }
// 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; using osu.Framework.Graphics.Sprites; using osu.Game.Graphics; using osu.Game.Screens.Select.Options; namespace osu.Game.Tests.Visual.SongSelect { [Description("bottom beatmap details")] public class TestSceneBeatmapOptionsOverlay : OsuTestScene { public TestSceneBeatmapOptionsOverlay() { var overlay = new BeatmapOptionsOverlay(); var colours = new OsuColour(); overlay.AddButton(@"Remove", @"from unplayed", FontAwesome.Regular.TimesCircle, colours.Purple, null); overlay.AddButton(@"Clear", @"local scores", FontAwesome.Solid.Eraser, colours.Purple, null); overlay.AddButton(@"Delete", @"all difficulties", FontAwesome.Solid.Trash, colours.Pink, null); overlay.AddButton(@"Edit", @"beatmap", FontAwesome.Solid.PencilAlt, colours.Yellow, null); Add(overlay); AddStep(@"Toggle", overlay.ToggleVisibility); } } }
Fix button colors in beatmap options test
Fix button colors in beatmap options test
C#
mit
UselessToucan/osu,peppy/osu,smoogipooo/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu-new,ppy/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu
b1f6b3f04c882d0c123a482ce0ee2caf2965ec15
src/SqlStreamStore.MsSql.V3.Tests/MigrationTests.cs
src/SqlStreamStore.MsSql.V3.Tests/MigrationTests.cs
namespace SqlStreamStore { using System.Threading; using System.Threading.Tasks; using Shouldly; using SqlStreamStore.Streams; using Xunit; public class MigrationTests { [Fact] public async Task Can_migrate() { // Set up an old schema + data. var schema = "baz"; var v2Fixture = new MsSqlStreamStoreFixture(schema, deleteDatabaseOnDispose: false); var v2Store = await v2Fixture.GetMsSqlStreamStore(); await v2Store.AppendToStream("stream-1", ExpectedVersion.NoStream, StreamStoreAcceptanceTests.CreateNewStreamMessages(1, 2, 3)); await v2Store.AppendToStream("stream-2", ExpectedVersion.NoStream, StreamStoreAcceptanceTests.CreateNewStreamMessages(1, 2, 3)); await v2Store.SetStreamMetadata("stream-1", ExpectedVersion.Any, maxAge: 10, maxCount: 20); v2Store.Dispose(); v2Fixture.Dispose(); // Migrate with V3 schema. var v3Fixture = new MsSqlStreamStoreV3Fixture(schema, databaseNameOverride: v2Fixture.DatabaseName); var v3Store = await v3Fixture.GetMsSqlStreamStore(); var checkSchemaResult = await v3Store.CheckSchema(); checkSchemaResult.IsMatch().ShouldBeFalse(); await v3Store.Migrate(CancellationToken.None); checkSchemaResult = await v3Store.CheckSchema(); checkSchemaResult.IsMatch().ShouldBeTrue(); v3Store.Dispose(); v3Fixture.Dispose(); } } }
namespace SqlStreamStore { using System.Threading; using System.Threading.Tasks; using Shouldly; using SqlStreamStore.Streams; using Xunit; public class MigrationTests { [Fact] public async Task Can_migrate() { // Set up an old schema + data. var schema = "baz"; var v2Fixture = new MsSqlStreamStoreFixture(schema, deleteDatabaseOnDispose: false); var v2Store = await v2Fixture.GetMsSqlStreamStore(); await v2Store.AppendToStream("stream-1", ExpectedVersion.NoStream, StreamStoreAcceptanceTests.CreateNewStreamMessages(1, 2, 3)); await v2Store.AppendToStream("stream-2", ExpectedVersion.NoStream, StreamStoreAcceptanceTests.CreateNewStreamMessages(1, 2, 3)); await v2Store.SetStreamMetadata("stream-1", ExpectedVersion.Any, maxAge: 10, maxCount: 20); v2Store.Dispose(); v2Fixture.Dispose(); var settings = new MsSqlStreamStoreV3Settings(v2Fixture.ConnectionString) { Schema = schema, }; var v3Store = new MsSqlStreamStoreV3(settings); var checkSchemaResult = await v3Store.CheckSchema(); checkSchemaResult.IsMatch().ShouldBeFalse(); await v3Store.Migrate(CancellationToken.None); checkSchemaResult = await v3Store.CheckSchema(); checkSchemaResult.IsMatch().ShouldBeTrue(); v3Store.Dispose(); } } }
Fix migration test - use correct database from v2 fixture.
Fix migration test - use correct database from v2 fixture.
C#
mit
SQLStreamStore/SQLStreamStore,damianh/Cedar.EventStore,SQLStreamStore/SQLStreamStore
a1b8fa09921666ee65531cea264aeade2aa5718b
osu.Game/Overlays/Mods/SelectAllModsButton.cs
osu.Game/Overlays/Mods/SelectAllModsButton.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.Input; using osu.Framework.Input.Bindings; using osu.Framework.Input.Events; using osu.Game.Graphics.UserInterface; using osu.Game.Localisation; using osu.Game.Screens.OnlinePlay; namespace osu.Game.Overlays.Mods { public class SelectAllModsButton : ShearedButton, IKeyBindingHandler<PlatformAction> { public SelectAllModsButton(FreeModSelectOverlay modSelectOverlay) : base(ModSelectOverlay.BUTTON_WIDTH) { Text = CommonStrings.SelectAll; Action = modSelectOverlay.SelectAll; } public bool OnPressed(KeyBindingPressEvent<PlatformAction> e) { if (e.Repeat || e.Action != PlatformAction.SelectAll) return false; TriggerClick(); return true; } public void OnReleased(KeyBindingReleaseEvent<PlatformAction> e) { } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Framework.Bindables; using osu.Framework.Input; using osu.Framework.Input.Bindings; using osu.Framework.Input.Events; using osu.Game.Graphics.UserInterface; using osu.Game.Localisation; using osu.Game.Rulesets.Mods; using osu.Game.Screens.OnlinePlay; namespace osu.Game.Overlays.Mods { public class SelectAllModsButton : ShearedButton, IKeyBindingHandler<PlatformAction> { private readonly Bindable<IReadOnlyList<Mod>> selectedMods = new Bindable<IReadOnlyList<Mod>>(); private readonly Bindable<Dictionary<ModType, IReadOnlyList<ModState>>> availableMods = new Bindable<Dictionary<ModType, IReadOnlyList<ModState>>>(); public SelectAllModsButton(FreeModSelectOverlay modSelectOverlay) : base(ModSelectOverlay.BUTTON_WIDTH) { Text = CommonStrings.SelectAll; Action = modSelectOverlay.SelectAll; selectedMods.BindTo(modSelectOverlay.SelectedMods); availableMods.BindTo(modSelectOverlay.AvailableMods); } protected override void LoadComplete() { base.LoadComplete(); selectedMods.BindValueChanged(_ => Scheduler.AddOnce(updateEnabledState)); availableMods.BindValueChanged(_ => Scheduler.AddOnce(updateEnabledState)); updateEnabledState(); } private void updateEnabledState() { Enabled.Value = availableMods.Value .SelectMany(pair => pair.Value) .Any(modState => !modState.Active.Value && !modState.Filtered.Value); } public bool OnPressed(KeyBindingPressEvent<PlatformAction> e) { if (e.Repeat || e.Action != PlatformAction.SelectAll) return false; TriggerClick(); return true; } public void OnReleased(KeyBindingReleaseEvent<PlatformAction> e) { } } }
Disable "select all mods" button if all are selected
Disable "select all mods" button if all are selected
C#
mit
NeoAdonis/osu,peppy/osu,peppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,ppy/osu,ppy/osu
6c2f31b1f048e02c38358a3f621f61a71490f30a
src/System.Private.CoreLib/src/System/DateTime.Unix.CoreRT.cs
src/System.Private.CoreLib/src/System/DateTime.Unix.CoreRT.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System { public readonly partial struct DateTime { public static DateTime UtcNow { get { // For performance, use a private constructor that does not validate arguments. return new DateTime(((ulong)(Interop.Sys.GetSystemTimeAsTicks() + TicksTo1970)) | KindUtc); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System { public readonly partial struct DateTime { public static DateTime UtcNow { get { // For performance, use a private constructor that does not validate arguments. return new DateTime(((ulong)(Interop.Sys.GetSystemTimeAsTicks() + DateTime.UnixEpochTicks)) | KindUtc); } } } }
Fix build error with mirroring
Fix build error with mirroring
C#
mit
gregkalapos/corert,gregkalapos/corert,gregkalapos/corert,gregkalapos/corert
60d1e44e01a00e42674d92b263269192996d14b8
Solution/CodeProject.Data/Properties/AssemblyInfo.cs
Solution/CodeProject.Data/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("CodeProject - EF Library")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("AREBIS")] [assembly: AssemblyProduct("CodeProject - EF")] [assembly: AssemblyCopyright("Copyright © Rudi Breedenraedt 2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: System.CLSCompliant(true)]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("CodeProject - EF Library")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("AREBIS")] [assembly: AssemblyProduct("CodeProject - EF")] [assembly: AssemblyCopyright("Copyright © Rudi Breedenraedt 2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] // voorlopig geen CLS-compliante code. // [assembly: System.CLSCompliant(true)]
Check voor CLS-compliante code verwijderd uit project CodeProject.Data
Check voor CLS-compliante code verwijderd uit project CodeProject.Data git-svn-id: 0ffdc289f568b1e7493e560395a00d06174c8a92@344 99b415e2-69d1-4072-8d93-0ed3a15484ab
C#
apache-2.0
Chirojeugd-Vlaanderen/gap,Chirojeugd-Vlaanderen/gap,Chirojeugd-Vlaanderen/gap
7147fc81658d35721c6f6edfebfa5150aa88c826
Zermelo/Zermelo.API.Tests/Services/JsonServiceTests.cs
Zermelo/Zermelo.API.Tests/Services/JsonServiceTests.cs
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; using Zermelo.API.Services; namespace Zermelo.API.Tests.Services { public class JsonServiceTests { [Fact] public void ShouldDeserializeDataInResponeData() { var sut = new JsonService(); ObservableCollection<TestClass> expected = new ObservableCollection<TestClass> { new TestClass(5), new TestClass(3) }; string testData = "{ \"response\": { \"data\": [ { \"Number\": 5 }, { \"Number\": 3 } ] } }"; ObservableCollection<TestClass> result = sut.DeserializeCollection<TestClass>(testData); Assert.Equal(expected.Count, result.Count); for (int i = 0; i < expected.Count; i++) Assert.Equal(expected[i].Number, result[i].Number); } [Fact] public void ShouldReturnValue() { var sut = new JsonService(); string expected = "value"; string testData = "{ \"key\": \"value\" }"; string result = sut.GetValue<string>(testData, "key"); Assert.Equal(expected, result); } } internal class TestClass { public TestClass(int number) { this.Number = number; } public int Number { get; set; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; using Zermelo.API.Services; namespace Zermelo.API.Tests.Services { public class JsonServiceTests { [Fact] public void ShouldDeserializeDataInResponeData() { var sut = new JsonService(); List<TestClass> expected = new List<TestClass> { new TestClass(5), new TestClass(3) }; string testData = "{ \"response\": { \"data\": [ { \"Number\": 5 }, { \"Number\": 3 } ] } }"; List<TestClass> result = sut.DeserializeCollection<TestClass>(testData).ToList(); Assert.Equal(expected.Count, result.Count); for (int i = 0; i < expected.Count; i++) Assert.Equal(expected[i].Number, result[i].Number); } [Fact] public void ShouldReturnValue() { var sut = new JsonService(); string expected = "value"; string testData = "{ \"key\": \"value\" }"; string result = sut.GetValue<string>(testData, "key"); Assert.Equal(expected, result); } } internal class TestClass { public TestClass(int number) { this.Number = number; } public int Number { get; set; } } }
Update Json tests to reflect change to IEnumerable
[API] Update Json tests to reflect change to IEnumerable
C#
mit
arthurrump/Zermelo.API
26a1e34c72afd6b9d92d171e0d5b376af616ffd4
Source/ExcelDna.IntelliSense/UIMonitor/FormulaParser.cs
Source/ExcelDna.IntelliSense/UIMonitor/FormulaParser.cs
using System; using System.Linq; using System.Text.RegularExpressions; namespace ExcelDna.IntelliSense { static class FormulaParser { // Set from IntelliSenseDisplay.Initialize public static char ListSeparator = ','; internal static bool TryGetFormulaInfo(string formulaPrefix, out string functionName, out int currentArgIndex) { formulaPrefix = Regex.Replace(formulaPrefix, "(\"[^\"]*\")|(\\([^\\(\\)]*\\))| ", string.Empty); while (Regex.IsMatch(formulaPrefix, "\\([^\\(\\)]*\\)")) { formulaPrefix = Regex.Replace(formulaPrefix, "\\([^\\(\\)]*\\)", string.Empty); } int lastOpeningParenthesis = formulaPrefix.LastIndexOf("(", formulaPrefix.Length - 1, StringComparison.Ordinal); if (lastOpeningParenthesis > -1) { var match = Regex.Match(formulaPrefix.Substring(0, lastOpeningParenthesis), @"[^\w](?<functionName>\w*)$"); if (match.Success) { functionName = match.Groups["functionName"].Value; currentArgIndex = formulaPrefix.Substring(lastOpeningParenthesis, formulaPrefix.Length - lastOpeningParenthesis).Count(c => c == ListSeparator); return true; } } functionName = null; currentArgIndex = -1; return false; } } }
using System; using System.Linq; using System.Text.RegularExpressions; namespace ExcelDna.IntelliSense { static class FormulaParser { // Set from IntelliSenseDisplay.Initialize public static char ListSeparator = ','; internal static bool TryGetFormulaInfo(string formulaPrefix, out string functionName, out int currentArgIndex) { formulaPrefix = Regex.Replace(formulaPrefix, "(\"[^\"]*\")|(\\([^\\(\\)]*\\))| ", string.Empty); while (Regex.IsMatch(formulaPrefix, "\\([^\\(\\)]*\\)")) { formulaPrefix = Regex.Replace(formulaPrefix, "\\([^\\(\\)]*\\)", string.Empty); } int lastOpeningParenthesis = formulaPrefix.LastIndexOf("(", formulaPrefix.Length - 1, StringComparison.Ordinal); if (lastOpeningParenthesis > -1) { var match = Regex.Match(formulaPrefix.Substring(0, lastOpeningParenthesis), @"[^\w.](?<functionName>[\w.]*)$"); if (match.Success) { functionName = match.Groups["functionName"].Value; currentArgIndex = formulaPrefix.Substring(lastOpeningParenthesis, formulaPrefix.Length - lastOpeningParenthesis).Count(c => c == ListSeparator); return true; } } functionName = null; currentArgIndex = -1; return false; } } }
Extend character set of function names (including ".")
Extend character set of function names (including ".")
C#
mit
Excel-DNA/IntelliSense
d2cea6818c5bdecef3a9426d198c9a9103b3a083
src/CommandLine/Common/CommandLineRepositoryFactory.cs
src/CommandLine/Common/CommandLineRepositoryFactory.cs
 namespace NuGet.Common { public class CommandLineRepositoryFactory : PackageRepositoryFactory { public static readonly string UserAgent = "NuGet Command Line"; private readonly IConsole _console; public CommandLineRepositoryFactory(IConsole console) { _console = console; } public override IPackageRepository CreateRepository(string packageSource) { var repository = base.CreateRepository(packageSource); var httpClientEvents = repository as IHttpClientEvents; if (httpClientEvents != null) { httpClientEvents.SendingRequest += (sender, args) => { if (_console.Verbosity == Verbosity.Detailed) { _console.WriteLine( System.ConsoleColor.Green, "{0} {1}", args.Request.Method, args.Request.RequestUri); } string userAgent = HttpUtility.CreateUserAgentString(CommandLineConstants.UserAgent); HttpUtility.SetUserAgent(args.Request, userAgent); }; } return repository; } } }
 using System.Windows; namespace NuGet.Common { public class CommandLineRepositoryFactory : PackageRepositoryFactory, IWeakEventListener { public static readonly string UserAgent = "NuGet Command Line"; private readonly IConsole _console; public CommandLineRepositoryFactory(IConsole console) { _console = console; } public override IPackageRepository CreateRepository(string packageSource) { var repository = base.CreateRepository(packageSource); var httpClientEvents = repository as IHttpClientEvents; if (httpClientEvents != null) { SendingRequestEventManager.AddListener(httpClientEvents, this); } return repository; } public bool ReceiveWeakEvent(System.Type managerType, object sender, System.EventArgs e) { if (managerType == typeof(SendingRequestEventManager)) { var args = (WebRequestEventArgs)e; if (_console.Verbosity == Verbosity.Detailed) { _console.WriteLine( System.ConsoleColor.Green, "{0} {1}", args.Request.Method, args.Request.RequestUri); } string userAgent = HttpUtility.CreateUserAgentString(CommandLineConstants.UserAgent); HttpUtility.SetUserAgent(args.Request, userAgent); return true; } else { return false; } } } }
Fix the problem that the web request is displayed twice when -Verbosity is set to detailed.
Fix the problem that the web request is displayed twice when -Verbosity is set to detailed. The cause of the duplicate output is the change to fix issue 3801 (which was caused by incorrect use of the weak event handler pattern). With that fix, the SendingRequest handler will be called twice. The fix is to use the weak event handler pattern here too.
C#
apache-2.0
chocolatey/nuget-chocolatey,jmezach/NuGet2,chocolatey/nuget-chocolatey,mrward/nuget,xoofx/NuGet,GearedToWar/NuGet2,antiufo/NuGet2,RichiCoder1/nuget-chocolatey,GearedToWar/NuGet2,jmezach/NuGet2,antiufo/NuGet2,rikoe/nuget,oliver-feng/nuget,xoofx/NuGet,rikoe/nuget,oliver-feng/nuget,akrisiun/NuGet,jholovacs/NuGet,pratikkagda/nuget,antiufo/NuGet2,RichiCoder1/nuget-chocolatey,mono/nuget,pratikkagda/nuget,mrward/nuget,mrward/NuGet.V2,xoofx/NuGet,jholovacs/NuGet,pratikkagda/nuget,RichiCoder1/nuget-chocolatey,jmezach/NuGet2,antiufo/NuGet2,RichiCoder1/nuget-chocolatey,xoofx/NuGet,mono/nuget,mrward/NuGet.V2,mrward/nuget,indsoft/NuGet2,indsoft/NuGet2,indsoft/NuGet2,antiufo/NuGet2,chocolatey/nuget-chocolatey,mrward/NuGet.V2,GearedToWar/NuGet2,GearedToWar/NuGet2,mrward/NuGet.V2,chocolatey/nuget-chocolatey,OneGet/nuget,rikoe/nuget,OneGet/nuget,indsoft/NuGet2,mono/nuget,xoofx/NuGet,akrisiun/NuGet,pratikkagda/nuget,mrward/nuget,mrward/NuGet.V2,rikoe/nuget,indsoft/NuGet2,pratikkagda/nuget,jholovacs/NuGet,jmezach/NuGet2,RichiCoder1/nuget-chocolatey,GearedToWar/NuGet2,antiufo/NuGet2,mrward/NuGet.V2,jholovacs/NuGet,chocolatey/nuget-chocolatey,jmezach/NuGet2,oliver-feng/nuget,indsoft/NuGet2,OneGet/nuget,jholovacs/NuGet,oliver-feng/nuget,OneGet/nuget,xoofx/NuGet,oliver-feng/nuget,mrward/nuget,jholovacs/NuGet,jmezach/NuGet2,RichiCoder1/nuget-chocolatey,pratikkagda/nuget,chocolatey/nuget-chocolatey,mrward/nuget,mono/nuget,GearedToWar/NuGet2,oliver-feng/nuget
2197506200da01792e29ff9447cea18722b9d9d7
samples/macdoc/AppleDocWizard/AppleDocWizardDelegate.cs
samples/macdoc/AppleDocWizard/AppleDocWizardDelegate.cs
using System; using MonoMac.AppKit; namespace macdoc { public class AppleDocWizardDelegate : NSApplicationDelegate { AppleDocWizardController wizard; public override bool ApplicationShouldOpenUntitledFile (NSApplication sender) { return false; } public override void DidFinishLaunching (MonoMac.Foundation.NSNotification notification) { wizard = new AppleDocWizardController (); wizard.Window.Center (); NSApplication.SharedApplication.ArrangeInFront (this); NSApplication.SharedApplication.RunModalForWindow (wizard.Window); } } }
using System; using MonoMac.AppKit; namespace macdoc { public class AppleDocWizardDelegate : NSApplicationDelegate { AppleDocWizardController wizard; public override bool ApplicationShouldOpenUntitledFile (NSApplication sender) { return false; } public override void DidFinishLaunching (MonoMac.Foundation.NSNotification notification) { wizard = new AppleDocWizardController (); NSApplication.SharedApplication.ActivateIgnoringOtherApps (true); wizard.Window.MakeMainWindow (); wizard.Window.MakeKeyWindow (); wizard.Window.MakeKeyAndOrderFront (this); wizard.Window.Center (); wizard.VerifyFreshnessAndLaunchDocProcess (); NSApplication.SharedApplication.RunModalForWindow (wizard.Window); } } }
Make the application and its window come in front when launched
[AppleDocWizard] Make the application and its window come in front when launched
C#
apache-2.0
PlayScriptRedux/monomac,dlech/monomac
b9f7c65c0552acb4e9b8ea1e20f8a99cbf2e7d42
Content.Client/Construction/ConstructionButton.cs
Content.Client/Construction/ConstructionButton.cs
using Content.Client.GameObjects.Components.Construction; using Robust.Client.Interfaces.Graphics; using Robust.Client.UserInterface.Controls; using Robust.Shared.Maths; using Robust.Shared.Utility; namespace Content.Client.Construction { public class ConstructionButton : Button { private readonly IDisplayManager _displayManager; public ConstructorComponent Owner { get => Menu.Owner; set => Menu.Owner = value; } ConstructionMenu Menu; public ConstructionButton(IDisplayManager displayManager) { _displayManager = displayManager; PerformLayout(); } protected override void Initialize() { base.Initialize(); AnchorLeft = 1.0f; AnchorTop = 1.0f; AnchorRight = 1.0f; AnchorBottom = 1.0f; MarginLeft = -110.0f; MarginTop = -70.0f; MarginRight = -50.0f; MarginBottom = -50.0f; Text = "Crafting"; OnPressed += IWasPressed; } private void PerformLayout() { Menu = new ConstructionMenu(_displayManager); Menu.AddToScreen(); } void IWasPressed(ButtonEventArgs args) { Menu.Open(); } public void AddToScreen() { UserInterfaceManager.StateRoot.AddChild(this); } public void RemoveFromScreen() { if (Parent != null) { Parent.RemoveChild(this); } } protected override void Dispose(bool disposing) { if (disposing) { Menu.Dispose(); } base.Dispose(disposing); } } }
using Content.Client.GameObjects.Components.Construction; using Robust.Client.Interfaces.Graphics; using Robust.Client.UserInterface.Controls; using Robust.Shared.Maths; using Robust.Shared.Utility; namespace Content.Client.Construction { public class ConstructionButton : Button { private readonly IDisplayManager _displayManager; public ConstructorComponent Owner { get => Menu.Owner; set => Menu.Owner = value; } ConstructionMenu Menu; public ConstructionButton(IDisplayManager displayManager) { _displayManager = displayManager; PerformLayout(); } protected override void Initialize() { base.Initialize(); SetAnchorPreset(LayoutPreset.BottomRight); MarginLeft = -110.0f; MarginTop = -70.0f; MarginRight = -50.0f; MarginBottom = -50.0f; Text = "Crafting"; OnPressed += IWasPressed; } private void PerformLayout() { Menu = new ConstructionMenu(_displayManager); Menu.AddToScreen(); } void IWasPressed(ButtonEventArgs args) { Menu.Open(); } public void AddToScreen() { UserInterfaceManager.StateRoot.AddChild(this); } public void RemoveFromScreen() { if (Parent != null) { Parent.RemoveChild(this); } } protected override void Dispose(bool disposing) { if (disposing) { Menu.Dispose(); } base.Dispose(disposing); } } }
Use SetAnchorPreset instead of manually setting each anchor
Use SetAnchorPreset instead of manually setting each anchor
C#
mit
space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14
dd4c10ec1e5fe19c238b3ddf3c8db243d13d9dd2
PhotoStoryToBloomConverter/Ps3Model/PhotoStoryProject.cs
PhotoStoryToBloomConverter/Ps3Model/PhotoStoryProject.cs
using System.Linq; using System.Text.RegularExpressions; using System.Xml.Serialization; namespace PhotoStoryToBloomConverter.PS3Model { [XmlRoot("MSPhotoStoryProject", Namespace="MSPhotoStory")] public class PhotoStoryProject { [XmlAttribute("schemaVersion")] public string SchemaVersion; [XmlAttribute("appVersion")] public string AppVersion; [XmlAttribute("linkOnly")] public bool LinkOnly; [XmlAttribute("defaultImageDuration")] public int DefaultImageDuration; [XmlAttribute("visualUnitCount")] public int VisualUnitCount; [XmlAttribute("codecVersion")] public string CodecVersion; [XmlAttribute("sessionSeed")] public int SessionSeed; [XmlElement("VisualUnit")] public VisualUnit[] VisualUnits; public string GetProjectName() { var bookName = ""; foreach (var vunit in VisualUnits.Where(vu => vu.Image?.Edits != null)) { foreach (var edit in vunit.Image.Edits) { if (edit.TextOverlays.Length <= 0) continue; bookName = edit.TextOverlays[0].Text.Trim(); bookName = Regex.Replace(bookName, @"\s+", " "); break; } if (bookName != "") break; } return bookName; } } }
using System.Linq; using System.Text.RegularExpressions; using System.Xml.Serialization; namespace PhotoStoryToBloomConverter.PS3Model { [XmlRoot("MSPhotoStoryProject", Namespace="MSPhotoStory")] public class PhotoStoryProject { [XmlAttribute("schemaVersion")] public string SchemaVersion; [XmlAttribute("appVersion")] public string AppVersion; [XmlAttribute("linkOnly")] public bool LinkOnly; [XmlAttribute("defaultImageDuration")] public int DefaultImageDuration; [XmlAttribute("visualUnitCount")] public int VisualUnitCount; [XmlAttribute("codecVersion")] public string CodecVersion; [XmlAttribute("sessionSeed")] public int SessionSeed; [XmlElement("VisualUnit")] public VisualUnit[] VisualUnits; public string GetProjectName() { var bookName = ""; foreach (var vunit in VisualUnits.Where(vu => vu.Image?.Edits != null)) { foreach (var edit in vunit.Image.Edits) { if (edit.TextOverlays == null || edit.TextOverlays.Length <= 0) continue; bookName = edit.TextOverlays[0].Text.Trim(); bookName = Regex.Replace(bookName, @"\s+", " "); break; } if (bookName != "") break; } return bookName; } } }
Handle PS3 covers with no text
Handle PS3 covers with no text
C#
mit
BloomBooks/PhotoStoryToBloomConverter,BloomBooks/PhotoStoryToBloomConverter
165df6e1175898c4f3af1d3c55153cb26d759561
Rant.Tests/Richard/Lists.cs
Rant.Tests/Richard/Lists.cs
using System.Linq; using NUnit.Framework; namespace Rant.Tests.Richard { [TestFixture] public class Lists { private readonly RantEngine rant = new RantEngine(); [Test] public void ListInitBare() { Assert.AreEqual("5", rant.Do("[@ x = 1, 2, 3, 4, 5; x.length ]").Main); } [Test] public void ListInitBrackets() { Assert.AreEqual("5", rant.Do("[@ x = [1, 2, 3, 4, 5]; x.length ]").Main); } [Test] public void ListInitConcat() { Assert.AreEqual("5", rant.Do("[@ x = 1, 2, 3; y = x, 4, 5; y.length ]").Main); } [Test] public void ListAsBlock() { string[] possibleResults = new string[] { "1", "2", "3", "4" }; Assert.GreaterOrEqual(possibleResults.ToList().IndexOf(rant.Do("[@ 1, 2, 3, 4 ]").Main), 0); } [Test] public void ListInitializer() { Assert.AreEqual("12", rant.Do("[@ x = list 12; x.length ]").Main); } } }
using System.Linq; using NUnit.Framework; namespace Rant.Tests.Richard { [TestFixture] public class Lists { private readonly RantEngine rant = new RantEngine(); [Test] public void ListInitBare() { Assert.AreEqual("5", rant.Do("[@ x = 1, 2, 3, 4, 5; x.length ]").Main); } [Test] public void ListInitBrackets() { Assert.AreEqual("5", rant.Do("[@ x = [1, 2, 3, 4, 5]; x.length ]").Main); } [Test] public void ListInitConcat() { Assert.AreEqual("5", rant.Do("[@ x = 1, 2, 3; y = x, 4, 5; y.length ]").Main); } [Test] public void ListAsBlock() { string[] possibleResults = new string[] { "1", "2", "3", "4" }; Assert.GreaterOrEqual(possibleResults.ToList().IndexOf(rant.Do("[@ 1, 2, 3, 4 ]").Main), 0); } [Test] public void ListInitializer() { Assert.AreEqual("12", rant.Do("[@ x = list 12; x.length ]").Main); } [Test] public void ListEmptyAsBlock() { Assert.AreEqual("", rant.Do(@"[@ [] ]")); } } }
Add test for returning empty list from script
Add test for returning empty list from script
C#
mit
TheBerkin/Rant
0d7a0dddfbc300793d185c8edc3ac85d4da1bb51
Program.cs
Program.cs
using System; namespace TDDUnit { class TestTestCase : TestCase { public TestTestCase(string name) : base(name) { } public void TestTemplateMethod() { WasRunObj test = new WasRunObj("TestMethod"); test.Run(); Assert.That(test.Log == "SetUp TestMethod TearDown "); } public void TestResult() { WasRunObj test = new WasRunObj("TestMethod"); TestResult result = test.Run(); Assert.That("1 run, 0 failed" == result.Summary); } public void TestFailedResult() { WasRunObj test = new WasRunObj("TestBrokenMethod"); TestResult result = test.Run(); Assert.That("1 run, 1 failed" == result.Summary); } public void TestFailedResultFormatting() { TestResult result = new TestResult(); result.TestStarted(); result.TestFailed(); Assert.That("1 run, 1 failed" == result.Summary); } } class Program { static void Main() { new TestTestCase("TestTemplateMethod").Run(); new TestTestCase("TestResult").Run(); new TestTestCase("TestFailedResult").Run(); new TestTestCase("TestFailedResultFormatting").Run(); } } }
using System; namespace TDDUnit { class TestTestCase : TestCase { public TestTestCase(string name) : base(name) { } public void TestTemplateMethod() { WasRunObj test = new WasRunObj("TestMethod"); test.Run(); Assert.That(test.Log == "SetUp TestMethod TearDown "); } public void TestResult() { WasRunObj test = new WasRunObj("TestMethod"); TestResult result = test.Run(); Assert.That("1 run, 0 failed" == result.Summary); } public void TestFailedResult() { WasRunObj test = new WasRunObj("TestBrokenMethod"); TestResult result = test.Run(); Assert.That("1 run, 1 failed" == result.Summary); } public void TestFailedResultFormatting() { TestResult result = new TestResult(); result.TestStarted(); result.TestFailed(); Assert.That("1 run, 1 failed" == result.Summary); } } class Program { static void Main() { Console.WriteLine(new TestTestCase("TestTemplateMethod").Run().Summary); Console.WriteLine(new TestTestCase("TestResult").Run().Summary); Console.WriteLine(new TestTestCase("TestFailedResult").Run().Summary); Console.WriteLine(new TestTestCase("TestFailedResultFormatting").Run().Summary); } } }
Print results of running tests
Print results of running tests
C#
apache-2.0
yawaramin/TDDUnit
0e223146934a62ed9e3de863f51fde1085b71f5e
osu.Framework.Tests/Platform/UserInputManagerTest.cs
osu.Framework.Tests/Platform/UserInputManagerTest.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.Graphics; using osu.Framework.Platform; using osu.Framework.Testing; namespace osu.Framework.Tests.Platform { [TestFixture] public class UserInputManagerTest : TestCase { [Test] public void IsAliveTest() { AddAssert("UserInputManager is alive", () => { using (var client = new TestHeadlessGameHost(@"client", true)) { return client.CurrentRoot.IsAlive; } }); } private class TestHeadlessGameHost : HeadlessGameHost public Drawable CurrentRoot => Root; public TestHeadlessGameHost(string hostname, bool bindIPC) : base(hostname, bindIPC) { using (var game = new TestGame()) { Root = game.CreateUserInputManager(); } } } } }
// 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.Graphics; using osu.Framework.Platform; using osu.Framework.Testing; namespace osu.Framework.Tests.Platform { [TestFixture] public class UserInputManagerTest : TestCase { [Test] public void IsAliveTest() { AddAssert("UserInputManager is alive", () => { using (var client = new TestHeadlessGameHost(@"client", true)) { return client.CurrentRoot.IsAlive; } }); } private class TestHeadlessGameHost : HeadlessGameHost { public Drawable CurrentRoot => Root; public TestHeadlessGameHost(string hostname, bool bindIPC) : base(hostname, bindIPC) { using (var game = new TestGame()) { Root = game.CreateUserInputManager(); } } } } }
Add a bracket that somehow did not get comitted
Add a bracket that somehow did not get comitted
C#
mit
peppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,ZLima12/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework
c632864e7570f5a7b035b4f01703bc518d8ba462
test/Stormpath.Owin.UnitTest/ConfigurationHelper.cs
test/Stormpath.Owin.UnitTest/ConfigurationHelper.cs
using System.Collections.Generic; using Stormpath.Configuration.Abstractions; using Stormpath.Owin.Abstractions.Configuration; namespace Stormpath.Owin.UnitTest { public static class ConfigurationHelper { public static IntegrationConfiguration CreateFakeConfiguration(StormpathConfiguration config) { var compiledConfig = Configuration.ConfigurationLoader.Initialize().Load(config); var integrationConfig = new IntegrationConfiguration( compiledConfig, new TenantConfiguration("foo", false, false), new KeyValuePair<string, ProviderConfiguration>[0]); return integrationConfig; } } }
using System.Collections.Generic; using Stormpath.Configuration.Abstractions; using Stormpath.Owin.Abstractions.Configuration; namespace Stormpath.Owin.UnitTest { public static class ConfigurationHelper { public static IntegrationConfiguration CreateFakeConfiguration(StormpathConfiguration config) { if (config.Client?.ApiKey == null) { if (config.Client == null) { config.Client = new ClientConfiguration(); } config.Client.ApiKey = new ClientApiKeyConfiguration() { Id = "foo", Secret = "bar" }; }; var compiledConfig = Configuration.ConfigurationLoader.Initialize().Load(config); var integrationConfig = new IntegrationConfiguration( compiledConfig, new TenantConfiguration("foo", false, false), new KeyValuePair<string, ProviderConfiguration>[0]); return integrationConfig; } } }
Fix missing API key error on AppVeyor
Fix missing API key error on AppVeyor
C#
apache-2.0
stormpath/stormpath-dotnet-owin-middleware
332104801aa0ec44b5d70dff6a91b716f0b432aa
Oogstplanner.Web/Controllers/HomeController.cs
Oogstplanner.Web/Controllers/HomeController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using System.Web.Routing; using Oogstplanner.Common; using Oogstplanner.Models; using Oogstplanner.Services; namespace Oogstplanner.Web.Controllers { [AllowAnonymous] public class HomeController : Controller { readonly ICalendarService calendarService; public HomeController(ICalendarService calendarService) { if (calendarService == null) { throw new ArgumentNullException("calendarService"); } this.calendarService = calendarService; } // // GET: /welkom public ActionResult Index() { return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using System.Web.Routing; using Oogstplanner.Common; using Oogstplanner.Models; using Oogstplanner.Services; namespace Oogstplanner.Web.Controllers { [AllowAnonymous] public class HomeController : Controller { readonly ICalendarService calendarService; public HomeController() { } // // GET: /welkom public ActionResult Index() { return View(); } // // GET: /veelgesteldevragen public ActionResult Faq() { return View(); } } }
Remove dependency of home controller since it is no longer needed
Remove dependency of home controller since it is no longer needed
C#
mit
erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner
1f9db3bda6a457f019c301208e9fa3bf4f5197fb
Core/Utils/WindowsUtils.cs
Core/Utils/WindowsUtils.cs
using System.Diagnostics; using System.IO; using System.Linq; using System.Security.AccessControl; using System.Security.Principal; namespace TweetDck.Core.Utils{ static class WindowsUtils{ public static bool CheckFolderPermission(string path, FileSystemRights right){ try{ AuthorizationRuleCollection rules = Directory.GetAccessControl(path).GetAccessRules(true, true, typeof(SecurityIdentifier)); WindowsIdentity identity = WindowsIdentity.GetCurrent(); if (identity.Groups == null){ return false; } bool accessAllow = false, accessDeny = false; foreach(FileSystemAccessRule rule in rules.Cast<FileSystemAccessRule>().Where(rule => identity.Groups.Contains(rule.IdentityReference) && (right & rule.FileSystemRights) == right)){ switch(rule.AccessControlType){ case AccessControlType.Allow: accessAllow = true; break; case AccessControlType.Deny: accessDeny = true; break; } } return accessAllow && !accessDeny; } catch{ return false; } } public static Process StartProcess(string file, string arguments, bool runElevated){ ProcessStartInfo processInfo = new ProcessStartInfo{ FileName = file, Arguments = arguments }; if (runElevated){ processInfo.Verb = "runas"; } return Process.Start(processInfo); } } }
using System.Diagnostics; using System.IO; using System.Security.AccessControl; using System.Security.Principal; namespace TweetDck.Core.Utils{ static class WindowsUtils{ public static bool CheckFolderPermission(string path, FileSystemRights right){ try{ AuthorizationRuleCollection collection = Directory.GetAccessControl(path).GetAccessRules(true, true, typeof(NTAccount)); foreach(FileSystemAccessRule rule in collection){ if ((rule.FileSystemRights & right) == right){ return true; } } return false; } catch{ return false; } } public static Process StartProcess(string file, string arguments, bool runElevated){ ProcessStartInfo processInfo = new ProcessStartInfo{ FileName = file, Arguments = arguments }; if (runElevated){ processInfo.Verb = "runas"; } return Process.Start(processInfo); } } }
Rewrite folder write permission check to hopefully make it more reliable
Rewrite folder write permission check to hopefully make it more reliable
C#
mit
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
e512df4bd20587110ba2df1ead4dde9e3ecc2a38
Mlabs.Ogg/src/OggReader.cs
Mlabs.Ogg/src/OggReader.cs
using System; using System.IO; using System.Linq; namespace Mlabs.Ogg { public class OggReader { private readonly Stream m_fileStream; private readonly bool m_owns; public OggReader(string fileName) { if (fileName == null) throw new ArgumentNullException("fileName"); m_fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); m_owns = true; } public OggReader(Stream fileStream) { if (fileStream == null) throw new ArgumentNullException("fileStream"); m_fileStream = fileStream; m_owns = false; } public IOggInfo Read() { long originalOffset = m_fileStream.Position; var p = new PageReader(); //read pages and break them down to streams var pages = p.ReadPages(m_fileStream).GroupBy(e => e.StreamSerialNumber); if (m_owns) { m_fileStream.Dispose(); } else { //if we didn't create stream rewind it, so that user won't get any surprise :) m_fileStream.Seek(originalOffset, SeekOrigin.Begin); } return null; } } }
using System; using System.IO; using System.Linq; namespace Mlabs.Ogg { public class OggReader { private readonly Stream m_fileStream; private readonly bool m_owns; public OggReader(string fileName) { if (fileName == null) throw new ArgumentNullException("fileName"); m_fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); m_owns = true; } public OggReader(Stream fileStream) { if (fileStream == null) throw new ArgumentNullException("fileStream"); if (!fileStream.CanSeek) throw new ArgumentException("Stream must be seekable", "fileStream"); if (!fileStream.CanRead) throw new ArgumentException("Stream must be readable", "fileStream"); m_fileStream = fileStream; m_owns = false; } public IOggInfo Read() { long originalOffset = m_fileStream.Position; var p = new PageReader(); //read pages and break them down to streams var pages = p.ReadPages(m_fileStream).GroupBy(e => e.StreamSerialNumber); if (m_owns) { m_fileStream.Dispose(); } else { //if we didn't create stream rewind it, so that user won't get any surprise :) m_fileStream.Seek(originalOffset, SeekOrigin.Begin); } return null; } } }
Make sure that the stream passed in ctor can be seeked and read
Make sure that the stream passed in ctor can be seeked and read
C#
mit
paszczi/MLabs.Ogg
46513a76073e2f2deb69f9aed902efba53cd937d
LINQToTTree/LINQToTTreeLib/Variables/VarSimple.cs
LINQToTTree/LINQToTTreeLib/Variables/VarSimple.cs
using System; using LinqToTTreeInterfacesLib; using LINQToTTreeLib.Utils; namespace LINQToTTreeLib.Variables { /// <summary> /// A simple variable (like int, etc.). /// </summary> public class VarSimple : IVariable { public string VariableName { get; private set; } public string RawValue { get; private set; } public Type Type { get; private set; } public VarSimple(System.Type type) { if (type == null) throw new ArgumentNullException("Must have a good type!"); Type = type; VariableName = type.CreateUniqueVariableName(); RawValue = VariableName; } public IValue InitialValue { get; set; } /// <summary> /// Get/Set if this variable needs to be declared. /// </summary> public bool Declare { get; set; } } }
using System; using LinqToTTreeInterfacesLib; using LINQToTTreeLib.Utils; namespace LINQToTTreeLib.Variables { /// <summary> /// A simple variable (like int, etc.). /// </summary> public class VarSimple : IVariable { public string VariableName { get; private set; } public string RawValue { get; private set; } public Type Type { get; private set; } public VarSimple(System.Type type) { if (type == null) throw new ArgumentNullException("Must have a good type!"); Type = type; VariableName = type.CreateUniqueVariableName(); RawValue = VariableName; } public IValue InitialValue { get; set; } /// <summary> /// Get/Set if this variable needs to be declared. /// </summary> public bool Declare { get; set; } /// <summary> /// TO help with debugging... /// </summary> /// <returns></returns> public override string ToString() { return "(" + Type.Name + ") " + RawValue; } } }
Add ToString to help with debuggign... :-)
Add ToString to help with debuggign... :-)
C#
lgpl-2.1
gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT
8c8bdbcd024abfde299d207178961964172f1527
src/serilog-generator/Configuration/CurrentDirectoryAssemblyLoader.cs
src/serilog-generator/Configuration/CurrentDirectoryAssemblyLoader.cs
using System; using System.IO; using System.Reflection; namespace Serilog.Generator.Configuration { static class CurrentDirectoryAssemblyLoader { public static void Install() { AppDomain.CurrentDomain.AssemblyResolve += (s, e) => { var assemblyPath = Path.Combine(Environment.CurrentDirectory, e.Name + ".dll"); return !File.Exists(assemblyPath) ? null : Assembly.LoadFrom(assemblyPath); }; } } }
using System; using System.IO; using System.Reflection; namespace Serilog.Generator.Configuration { static class CurrentDirectoryAssemblyLoader { public static void Install() { AppDomain.CurrentDomain.AssemblyResolve += (s, e) => { var assemblyPath = Path.Combine(Environment.CurrentDirectory, new AssemblyName(e.Name).Name + ".dll"); return !File.Exists(assemblyPath) ? null : Assembly.LoadFrom(assemblyPath); }; } } }
Fix assembly loading name format
Fix assembly loading name format
C#
apache-2.0
serilog/serilog-generator,kensykora/serilog-generator,serilog/serilog-generator
9a05857a93412135a2a73d3c73144f95ede3cad1
osu.Framework/Localisation/LocalisationParameters.cs
osu.Framework/Localisation/LocalisationParameters.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. #nullable enable namespace osu.Framework.Localisation { /// <summary> /// A set of parameters that control the way strings are localised. /// </summary> public class LocalisationParameters { /// <summary> /// The <see cref="ILocalisationStore"/> to be used for string lookups and culture-specific formatting. /// </summary> public readonly ILocalisationStore? Store; /// <summary> /// Whether to prefer the "original" script of <see cref="RomanisableString"/>s. /// </summary> public readonly bool PreferOriginalScript; /// <summary> /// Creates a new instance of <see cref="LocalisationParameters"/>. /// </summary> /// <param name="store">The <see cref="ILocalisationStore"/> to be used for string lookups and culture-specific formatting.</param> /// <param name="preferOriginalScript">Whether to prefer the "original" script of <see cref="RomanisableString"/>s.</param> public LocalisationParameters(ILocalisationStore? store, bool preferOriginalScript) { Store = store; PreferOriginalScript = preferOriginalScript; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable namespace osu.Framework.Localisation { /// <summary> /// A set of parameters that control the way strings are localised. /// </summary> public class LocalisationParameters { /// <summary> /// The <see cref="ILocalisationStore"/> to be used for string lookups and culture-specific formatting. /// </summary> public readonly ILocalisationStore? Store; /// <summary> /// Whether to prefer the "original" script of <see cref="RomanisableString"/>s. /// </summary> public readonly bool PreferOriginalScript; /// <summary> /// Creates a new instance of <see cref="LocalisationParameters"/> based off another <see cref="LocalisationParameters"/>. /// </summary> /// <param name="parameters">The <see cref="LocalisationParameters"/> to copy values from.</param> protected LocalisationParameters(LocalisationParameters parameters) : this(parameters.Store, parameters.PreferOriginalScript) { } /// <summary> /// Creates a new instance of <see cref="LocalisationParameters"/>. /// </summary> /// <param name="store">The <see cref="ILocalisationStore"/> to be used for string lookups and culture-specific formatting.</param> /// <param name="preferOriginalScript">Whether to prefer the "original" script of <see cref="RomanisableString"/>s.</param> public LocalisationParameters(ILocalisationStore? store, bool preferOriginalScript) { Store = store; PreferOriginalScript = preferOriginalScript; } } }
Add protected copy constructor to avoid breaking changes
Add protected copy constructor to avoid breaking changes
C#
mit
ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework