commit
stringlengths
40
40
subject
stringlengths
4
1.73k
repos
stringlengths
5
127k
old_file
stringlengths
2
751
new_file
stringlengths
2
751
new_contents
stringlengths
1
8.98k
old_contents
stringlengths
0
6.59k
license
stringclasses
13 values
lang
stringclasses
23 values
94635ec5edff5b1ecbb8a2a56e54f28653e3b4df
Fix the obsolete message on UseIdentity() (#1322)
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.AspNetCore.Identity/BuilderExtensions.cs
src/Microsoft.AspNetCore.Identity/BuilderExtensions.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. using System; namespace Microsoft.AspNetCore.Builder { /// <summary> /// Identity extensions for <see cref="IApplicationBuilder"/>. /// </summary> public static class BuilderExtensions { /// <summary> /// <para> /// This method is obsolete and will be removed in a future version. /// The recommended alternative is <see cref="AuthAppBuilderExtensions.UseAuthentication(IApplicationBuilder)" /> /// </para> /// <para> /// Enables ASP.NET identity for the current application. /// </para> /// </summary> /// <param name="app">The <see cref="IApplicationBuilder"/> instance this method extends.</param> /// <returns>The <see cref="IApplicationBuilder"/> instance this method extends.</returns> [Obsolete( "This method is obsolete and will be removed in a future version. " + "The recommended alternative is UseAuthentication(). " + "See https://go.microsoft.com/fwlink/?linkid=845470")] public static IApplicationBuilder UseIdentity(this IApplicationBuilder app) => app.UseAuthentication(); } }
// 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; namespace Microsoft.AspNetCore.Builder { /// <summary> /// Identity extensions for <see cref="IApplicationBuilder"/>. /// </summary> public static class BuilderExtensions { /// <summary> /// Enables ASP.NET identity for the current application. /// </summary> /// <param name="app">The <see cref="IApplicationBuilder"/> instance this method extends.</param> /// <returns>The <see cref="IApplicationBuilder"/> instance this method extends.</returns> [Obsolete("See https://go.microsoft.com/fwlink/?linkid=845470")] public static IApplicationBuilder UseIdentity(this IApplicationBuilder app) => app.UseAuthentication(); } }
apache-2.0
C#
a2b3d5651bb69d86a4a46d368715b680b1eac988
remove unused PurchaseState
jamesmontemagno/InAppBillingPlugin
src/Plugin.InAppBilling/Shared/PurchaseState.shared.cs
src/Plugin.InAppBilling/Shared/PurchaseState.shared.cs
using System; namespace Plugin.InAppBilling { /// <summary> /// Gets the current status of the purchase /// </summary> public enum PurchaseState { /// <summary> /// Purchased and in good standing /// </summary> Purchased, /// <summary> /// Purchase was canceled /// </summary> Canceled, /// <summary> /// In the process of being processed /// </summary> Purchasing, /// <summary> /// Transaction has failed /// </summary> Failed, /// <summary> /// Was restored. /// </summary> Restored, /// <summary> /// In queue, pending external action /// </summary> Deferred, /// <summary> /// Pending Purchase /// </summary> PaymentPending, /// <summary> /// Purchase state unknown /// </summary> Unknown } }
using System; namespace Plugin.InAppBilling { /// <summary> /// Gets the current status of the purchase /// </summary> public enum PurchaseState { /// <summary> /// Purchased and in good standing /// </summary> Purchased = 0, /// <summary> /// Purchase was canceled /// </summary> Canceled = 1, /// <summary> /// Purchase was refunded /// </summary> Refunded = 2, /// <summary> /// In the process of being processed /// </summary> Purchasing, /// <summary> /// Transaction has failed /// </summary> Failed, /// <summary> /// Was restored. /// </summary> Restored, /// <summary> /// In queue, pending external action /// </summary> Deferred, /// <summary> /// In free trial /// </summary> FreeTrial, /// <summary> /// Pending Purchase /// </summary> PaymentPending, /// <summary> /// /// </summary> [Obsolete("Please use PaymentPending")] Pending, /// <summary> /// Purchase state unknown /// </summary> Unknown } }
mit
C#
c8da4e56ccfda522f54c1ab1e5ff8071f18e3771
Implement send method
danielmundt/csremote
source/Remoting.Server/Command.cs
source/Remoting.Server/Command.cs
#region Header // Copyright (C) 2012 Daniel Schubert // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE // AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #endregion Header using System; using System.Collections.Generic; using System.Linq; using System.Text; using Remoting.Interface; namespace Remoting.Server { public class Command : MarshalByRefObject, ICommand { public bool SendCommand(Remoting.Interface.Enums.Command command) { Console.WriteLine(string.Format("Command: {0}", command)); return false; } } }
#region Header // Copyright (C) 2012 Daniel Schubert // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE // AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #endregion Header using System; using System.Collections.Generic; using System.Linq; using System.Text; using Remoting.Interface; namespace Remoting.Server { public class Command : MarshalByRefObject, ICommand { public void SendCommand(Remoting.Interface.Enums.Command command) { int i = 0; } } }
mit
C#
69454f48ae9629b161bd93805b480def1dc23e41
Bump version to 0.10.1
quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot
CactbotOverlay/Properties/AssemblyInfo.cs
CactbotOverlay/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("CactbotOverlay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CactbotOverlay")] [assembly: AssemblyCopyright("Copyright 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")] // Version: // - Major Version // - Minor Version // - Build Number // - Revision // GitHub has only 3 version components, so Revision should always be 0. [assembly: AssemblyVersion("0.10.1.0")] [assembly: AssemblyFileVersion("0.10.1.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("CactbotOverlay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CactbotOverlay")] [assembly: AssemblyCopyright("Copyright 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")] // Version: // - Major Version // - Minor Version // - Build Number // - Revision // GitHub has only 3 version components, so Revision should always be 0. [assembly: AssemblyVersion("0.10.0.0")] [assembly: AssemblyFileVersion("0.10.0.0")]
apache-2.0
C#
bcb6ce49ecfd46163c761d841b8d09d7714fd2fc
PUT and POST for User
Bcpoole/ClubLife,Bcpoole/ClubLife,Bcpoole/ClubLife,Bcpoole/ClubLife,Bcpoole/ClubLife
web/clublife/src/skeleton/Controllers/UsersController.cs
web/clublife/src/skeleton/Controllers/UsersController.cs
using System; using System.Collections.Generic; using System.Globalization; using Microsoft.AspNetCore.Mvc; using skeleton.Data; using skeleton.Models; using MongoDB.Bson; namespace skeleton.Controllers { [Route("api/[controller]")] public class UsersController : Controller { public IUsersRepository Repo { get; set; } public UsersController([FromServices] IUsersRepository repo) { Repo = repo; } // GET api/users [HttpGet] public IEnumerable<User> Get() { return Repo.GetAllUsers(); } // GET api/users/5824e62917b44627c34fa66e [HttpGet("{id}")] [Route("{id}")] public User Get(string id) { return Repo.GetUserById(new ObjectId(id)); } // PUT api/users/newUser [HttpPost("newUser")] public void CreateNewUser() { throw new NotImplementedException(); //Repo.CreateNewUser("); } // POST api/users/5824e62917b44627c34fa66e /// <param name="id">user id</param> [HttpPost("{id}")] [Route("{id}")] public void UpdateUser(string id) { throw new NotImplementedException(); //Repo.UpdateUserName(); } // GET api/users/username?username=bcpoole [Route("username")] public IActionResult GetUserByUsername(string username) { var orgs = Repo.FindUserByUsername(username); if (orgs == null) { return NotFound(); } return Ok(orgs); } // GET api/users/name?name=brandon [Route("name")] public IActionResult GetUserByName(string name) { var orgs = Repo.FindUserByName(name); if (orgs == null) { return NotFound(); } return Ok(orgs); } // GET api/users/club?id=581b77c29534b37d50c51b6c [Route("club")] public IActionResult GetUsersInClubById(string id) { var events = Repo.FindUsersInClubById(new ObjectId(id)); if (events == null) { return NotFound(); } return Ok(events); } } }
using System; using System.Collections.Generic; using System.Globalization; using Microsoft.AspNetCore.Mvc; using skeleton.Data; using skeleton.Models; using MongoDB.Bson; namespace skeleton.Controllers { [Route("api/[controller]")] public class UsersController : Controller { public IUsersRepository Repo { get; set; } public UsersController([FromServices] IUsersRepository repo) { Repo = repo; } // GET api/users [HttpGet] public IEnumerable<User> Get() { return Repo.GetAllUsers(); } // GET api/users/5824e62917b44627c34fa66e [HttpGet("{id}")] [Route("{id}")] public User Get(string id) { return Repo.GetUserById(new ObjectId(id)); } // POST api/users/5824e62917b44627c34fa66e [HttpPost("{id}")] [Route("{id}")] public void Post(string id) { //Repo.UpdateUserName(new ObjectId(id), "Bob"); } // GET api/users/username?username=bcpoole [Route("username")] public IActionResult GetUserByUsername(string username) { var orgs = Repo.FindUserByUsername(username); if (orgs == null) { return NotFound(); } return Ok(orgs); } // GET api/users/name?name=brandon [Route("name")] public IActionResult GetUserByName(string name) { var orgs = Repo.FindUserByName(name); if (orgs == null) { return NotFound(); } return Ok(orgs); } // GET api/users/club?id=581b77c29534b37d50c51b6c [Route("club")] public IActionResult GetUsersInClubById(string id) { var events = Repo.FindUsersInClubById(new ObjectId(id)); if (events == null) { return NotFound(); } return Ok(events); } } }
mit
C#
337d8a67ddd26a43f966150f9942aeb14991b259
Fix line endings.
JeroMiya/Managed-OSVR,OSVR/Managed-OSVR
ExampleClients/TrackerCallback/Properties/AssemblyInfo.cs
ExampleClients/TrackerCallback/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Managed-OSVR Tracker Callback Example")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany("Sensics, Inc.")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright("Copyright © 2014 Sensics, Inc.")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.0.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")] [assembly: AssemblyFileVersionAttribute("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Managed-OSVR Tracker Callback Example")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany("Sensics, Inc.")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright("Copyright © 2014 Sensics, Inc.")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.0.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")] [assembly: AssemblyFileVersionAttribute("1.0.0.0")]
apache-2.0
C#
d899f13f71c675affbf378973a7b2a4ac415e4b2
Update SelfCommands.cs
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,ShadowNoire/NadekoBot,Reiuiji/NadekoBot,powered-by-moe/MikuBot,Midnight-Myth/Mitternacht-NEW,N1SMOxGT-R/NeoBot,dtshady/NadekoBot,blitz4694/NadekoBot,Uleyethis/FightBot,rumlefisk/NadekoBot,Midnight-Myth/Mitternacht-NEW,Taknok/NadekoBot,Grinjr/NadekoBot,dtshady/NadekoBot,justinkruit/DiscordBot,ScarletKuro/NadekoBot,kyoryo/DiscordBot,N1SMOxGT-R/NeoBot,kyoryo/DiscordBot,PravEF/EFNadekoBot,kyoryo/DiscordBot,Youngsie1997/NadekoBot,gfrewqpoiu/NadekoBot,WoodenGlaze/NadekoBot,shikhir-arora/NadekoBot,justinkruit/WIABot,halitalf/NadekoMods,Nielk1/NadekoBot,Blacnova/NadekoBot,blitz4694/NadekoBot,miraai/NadekoBot,Track44/Nadeko
NadekoBot/Modules/Administration/Commands/SelfCommands.cs
NadekoBot/Modules/Administration/Commands/SelfCommands.cs
using NadekoBot.Classes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Discord.Commands; using NadekoBot.Modules.Permissions.Classes; namespace NadekoBot.Modules.Administration.Commands { class SelfCommands : DiscordCommand { public SelfCommands(DiscordModule module) : base(module) { } internal override void Init(CommandGroupBuilder cgb) { cgb.CreateCommand(Module.Prefix + "leave") .Description("Makes Nadeko leave the server. Either name or id required.\n**Usage**:.leave NSFW") .Parameter("arg", ParameterType.Required) .AddCheck(SimpleCheckers.OwnerOnly()) .Do(async e => { var arg = e.GetArg("arg")?.Trim(); var server = NadekoBot.Client.Servers.FirstOrDefault(s => s.Id.ToString() == arg) ?? NadekoBot.Client.FindServers(arg.Trim()).FirstOrDefault(); if (server == null) { await e.Channel.SendMessage("Cannot find that server").ConfigureAwait(false); return; } if (!server.IsOwner) { await server.Leave(); } else { await server.Delete(); } await NadekoBot.SendMessageToOwner("Left server " + server.Name); }); } } }
using NadekoBot.Classes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Discord.Commands; using NadekoBot.Modules.Permissions.Classes; namespace NadekoBot.Modules.Administration.Commands { class SelfCommands : DiscordCommand { public SelfCommands(DiscordModule module) : base(module) { } internal override void Init(CommandGroupBuilder cgb) { cgb.CreateCommand(Module.Prefix + "leave") .Description("Makes Nadeko leave the server. Either name or id required.\n**Usage**:.leave NSFW") .Parameter("arg", ParameterType.Required) .AddCheck(SimpleCheckers.OwnerOnly()) .Do(async e => { var arg = e.GetArg("arg")?.Trim(); if (string.IsNullOrWhiteSpace(arg)) return; var server = NadekoBot.Client.Servers.FirstOrDefault(s => s.Id.ToString() == arg) ?? NadekoBot.Client.FindServers(arg.Trim()).FirstOrDefault(); if (server == null) { await e.Channel.SendMessage("Cannot find that server").ConfigureAwait(false); return; } var serverId = server.Id; if (!server.IsOwner) { await server.Leave(); } else { await server.Delete(); } await NadekoBot.SendMessageToOwner("Left server " + server.Name); }); } } }
mit
C#
2f46e52be23bb03356a2e9c4c46c94dbb1f42707
Fix issues due to merge conflict.
henrikfroehling/TraktApiSharp
Source/Tests/TraktApiSharp.Tests/TraktConfigurationTests.cs
Source/Tests/TraktApiSharp.Tests/TraktConfigurationTests.cs
namespace TraktApiSharp.Tests { using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class TraktConfigurationTests { [TestMethod] public void TestTraktConfigurationDefaultConstructor() { var client = new TraktClient(); client.Configuration.ApiVersion.Should().Be(2); client.Configuration.UseStagingUrl.Should().BeFalse(); client.Configuration.BaseUrl.Should().Be("https://api-v2launch.trakt.tv/"); client.Configuration.UseStagingUrl = true; client.Configuration.BaseUrl.Should().Be("https://api-staging.trakt.tv/"); } } }
namespace TraktApiSharp.Tests { using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class TraktConfigurationTests { [TestMethod] public void TestTraktConfigurationDefaultConstructor() { var client = new TraktClient(); client.Configuration.ApiVersion.Should().Be(2); client.Configuration.UseStagingApi.Should().BeFalse(); client.Configuration.BaseUrl.Should().Be("https://api-v2launch.trakt.tv/"); client.Configuration.UseStagingApi = true; client.Configuration.BaseUrl.Should().Be("https://api-staging.trakt.tv/"); } } }
mit
C#
7242a1c748d452c078886ae5367ef2faf417fb55
Modify tests
SmartStepGroup/AgileCamp2015_Master,SmartStepGroup/AgileCamp2015_Master,SmartStepGroup/AgileCamp2015_Master
UnitTests/UnitTest1.cs
UnitTests/UnitTest1.cs
#region Usings using NUnit.Framework; using WebApplication.Models; #endregion namespace UnitTests { [TestFixture] public class UnitTest1 { [Test] public void TestMethod1() { var habit = new Habit {Name = "Habit", Count = 1}; Assert.AreEqual("Habit", habit.Name); } } }
#region Usings using NUnit.Framework; using WebApplication.Controllers; #endregion namespace UnitTests { [TestFixture] public class UnitTest1 { [Test] public void TestMethod1() { var controller = new HabitController(); Assert.True(true); } } }
mit
C#
dec1ad5ca01894d5280dc00fca4b03fb9f898622
Update ApplicationInsightsHelper.cs
tiksn/TIKSN-Framework
TIKSN.Core/Analytics/Telemetry/ApplicationInsightsHelper.cs
TIKSN.Core/Analytics/Telemetry/ApplicationInsightsHelper.cs
using System; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.DataContracts; namespace TIKSN.Analytics.Telemetry { internal static class ApplicationInsightsHelper { internal static SeverityLevel? ConvertSeverityLevel(TelemetrySeverityLevel? severityLevel) { if (severityLevel.HasValue) { switch (severityLevel.Value) { case TelemetrySeverityLevel.Verbose: return SeverityLevel.Verbose; case TelemetrySeverityLevel.Information: return SeverityLevel.Information; case TelemetrySeverityLevel.Warning: return SeverityLevel.Warning; case TelemetrySeverityLevel.Error: return SeverityLevel.Error; case TelemetrySeverityLevel.Critical: return SeverityLevel.Critical; default: throw new NotSupportedException(); } } return null; } internal static void TrackEvent(EventTelemetry telemetry) { var client = new TelemetryClient(); client.TrackEvent(telemetry); } internal static void TrackException(ExceptionTelemetry telemetry) { var client = new TelemetryClient(); client.TrackException(telemetry); } internal static void TrackMetric(MetricTelemetry telemetry) { var client = new TelemetryClient(); client.TrackMetric(telemetry); } internal static void TrackTrace(TraceTelemetry telemetry) { var client = new TelemetryClient(); client.TrackTrace(telemetry); } } }
using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.DataContracts; using System; namespace TIKSN.Analytics.Telemetry { internal static class ApplicationInsightsHelper { internal static SeverityLevel? ConvertSeverityLevel(TelemetrySeverityLevel? severityLevel) { if (severityLevel.HasValue) { switch (severityLevel.Value) { case TelemetrySeverityLevel.Verbose: return SeverityLevel.Verbose; case TelemetrySeverityLevel.Information: return SeverityLevel.Information; case TelemetrySeverityLevel.Warning: return SeverityLevel.Warning; case TelemetrySeverityLevel.Error: return SeverityLevel.Error; case TelemetrySeverityLevel.Critical: return SeverityLevel.Critical; default: throw new NotSupportedException(); } } return null; } internal static void TrackEvent(EventTelemetry telemetry) { var client = new TelemetryClient(); client.TrackEvent(telemetry); } internal static void TrackException(ExceptionTelemetry telemetry) { var client = new TelemetryClient(); client.TrackException(telemetry); } internal static void TrackMetric(MetricTelemetry telemetry) { var client = new TelemetryClient(); client.TrackMetric(telemetry); } internal static void TrackTrace(TraceTelemetry telemetry) { var client = new TelemetryClient(); client.TrackTrace(telemetry); } } }
mit
C#
0de55caee492dee41aa9af5ef9cd8c393e2d6bc8
Fix bug in Assert.NotEqual error message
yawaramin/TDDUnit
Assert.cs
Assert.cs
using System; namespace TDDUnit { class Assert { private static void Fail(object expected, object actual, bool equal) { string message = string.Format("Expected: {2} '{0}'\nActual: '{1}'", expected, actual, (equal ? "" : "Not")); Console.WriteLine(message); throw new TestRunException(message); } public static void Equal(object expected, object actual) { if (!expected.Equals(actual)) { Fail(expected, actual, true); } } public static void NotEqual(object expected, object actual) { if (expected.Equals(actual)) { Fail(expected, actual, false); } } public static void That(bool condition) { Equal(true, condition); } } }
using System; namespace TDDUnit { class Assert { private static void Fail(object expected, object actual) { string message = string.Format("Expected: '{0}'\nActual: '{1}'", expected, actual); Console.WriteLine(message); throw new TestRunException(message); } public static void Equal(object expected, object actual) { if (!expected.Equals(actual)) { Fail(expected, actual); } } public static void NotEqual(object expected, object actual) { if (expected.Equals(actual)) { Fail(expected, actual); } } public static void That(bool condition) { Equal(true, condition); } } }
apache-2.0
C#
4ebd1fdd2badad045817b070d2a227a851912c78
Update ApplicationPasswords_Tests.cs
cobalto/WordPressPCL,cobalto/WordPressPCL,wp-net/WordPressPCL,wp-net/WordPressPCL
WordPressPCL.Tests.Selfhosted/ApplicationPasswords_Tests.cs
WordPressPCL.Tests.Selfhosted/ApplicationPasswords_Tests.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Diagnostics; using System.Threading.Tasks; using WordPressPCL.Models; using WordPressPCL.Tests.Selfhosted.Utility; namespace WordPressPCL.Tests.Selfhosted { [TestClass] public class ApplicationPasswords_Tests { private static WordPressClient _client; private static WordPressClient _clientAuth; [ClassInitialize] public static async Task Init(TestContext testContext) { _client = ClientHelper.GetWordPressClient(); _clientAuth = await ClientHelper.GetAuthenticatedWordPressClient(testContext); } [TestMethod] public async Task Application_Passwords_Create() { var password = await _clientAuth.Users.CreateApplicationPassword(System.Guid.NewGuid().ToString()); Debug.WriteLine(password.AppId); Assert.IsNotNull(password.Password); } [TestMethod] public async Task Read() { await _clientAuth.Users.CreateApplicationPassword(System.Guid.NewGuid().ToString()); var passwords = await _clientAuth.Users.GetApplicationPasswords(); Assert.IsNotNull(passwords); Assert.AreNotEqual(0, passwords.Count); } [TestMethod] public async Task Application_Password_Auth() { var appPassword = await _clientAuth.Users.CreateApplicationPassword(System.Guid.NewGuid().ToString()); var appPasswordClient = new WordPressClient(ApiCredentials.WordPressUri) { AuthMethod = AuthMethod.ApplicationPassword, UserName = ApiCredentials.Username }; appPasswordClient.SetApplicationPassword(appPassword.Password); var post = new Post() { Title = new Title("Title 1"), Content = new Content("Content PostCreate") }; var postCreated = await appPasswordClient.Posts.Create(post); Assert.IsNotNull(postCreated); Assert.AreEqual("Title 1", postCreated.Title.Raw); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Diagnostics; using System.Threading.Tasks; using WordPressPCL.Models; using WordPressPCL.Tests.Selfhosted.Utility; namespace WordPressPCL.Tests.Selfhosted { [TestClass] public class ApplicationPasswords_Tests { private static WordPressClient _client; private static WordPressClient _clientAuth; [ClassInitialize] public static async Task Init(TestContext testContext) { _client = ClientHelper.GetWordPressClient(); _clientAuth = await ClientHelper.GetAuthenticatedWordPressClient(testContext); } [TestMethod] public async Task Application_Passwords_Create() { var password = await _clientAuth.Users.CreateApplicationPassword("TestApp1"); Debug.WriteLine(password.AppId); Assert.IsNotNull(password.Password); } [TestMethod] public async Task Read() { await _clientAuth.Users.CreateApplicationPassword("TestApp1"); var passwords = await _clientAuth.Users.GetApplicationPasswords(); Assert.IsNotNull(passwords); Assert.AreNotEqual(0, passwords.Count); } [TestMethod] public async Task Application_Password_Auth() { var appPassword = await _clientAuth.Users.CreateApplicationPassword("TestApp1"); var appPasswordClient = new WordPressClient(ApiCredentials.WordPressUri) { AuthMethod = AuthMethod.ApplicationPassword, UserName = ApiCredentials.Username }; appPasswordClient.SetApplicationPassword(appPassword.Password); var post = new Post() { Title = new Title("Title 1"), Content = new Content("Content PostCreate") }; var postCreated = await appPasswordClient.Posts.Create(post); Assert.IsNotNull(postCreated); Assert.AreEqual("Title 1", postCreated.Title.Raw); } } }
mit
C#
bebca882efbcb834af0a433c7785b4f7d0901c85
Bump version number for date/enum utils
Smartrak/Smartrak.Library
System.Contrib/Properties/AssemblyInfo.cs
System.Contrib/Properties/AssemblyInfo.cs
using System.Reflection; 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("System.Contrib")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Smartrak")] [assembly: AssemblyProduct("System.Contrib")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ac97934a-bbbc-488b-b337-a11bf4c98e97")] // 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.7.0")] [assembly: AssemblyFileVersion("1.7.0")] [assembly: AssemblyInformationalVersion("1.7.0")]
using System.Reflection; 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("System.Contrib")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Smartrak")] [assembly: AssemblyProduct("System.Contrib")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ac97934a-bbbc-488b-b337-a11bf4c98e97")] // 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.6.0")] [assembly: AssemblyFileVersion("1.6.0")] [assembly: AssemblyInformationalVersion("1.6.0")]
mit
C#
2cd9da5c9682c2a711f69cad19b48434697fb493
Add sample of data trigger
jamesmontemagno/xamarin.forms-toolkit
ToolkitTests/ToolkitTests/ToolkitTests.cs
ToolkitTests/ToolkitTests/ToolkitTests.cs
using System; using FormsToolkit; using Xamarin.Forms; namespace ToolkitTests { public class App : Application { public App() { var messagingCenter = new Button { Text = "Messaging Center", Command = new Command(()=>MainPage.Navigation.PushAsync(new MessagingServicePage())) }; var line = new EntryLine { Placeholder = "This nifty place for entering text!", HorizontalTextAlignment = TextAlignment.Center, HorizontalOptions = LayoutOptions.FillAndExpand, Text = "", FontSize = 30, BorderColor = Color.Red }; var trigger = new Trigger(typeof(EntryLine)); trigger.Property = EntryLine.IsFocusedProperty; trigger.Value = true; Setter setter = new Setter(); setter.Property = EntryLine.BorderColorProperty; setter.Value = Color.Yellow; trigger.Setters.Add(setter); line.Triggers.Add(trigger); var line2 = new EntryLine { PlaceholderColor = Color.Orange, Placeholder = "This nifty place for entering text!", HorizontalTextAlignment = TextAlignment.Center, HorizontalOptions = LayoutOptions.FillAndExpand, Text = "", FontSize = 10, BorderColor = Color.Red }; // The root page of your application MainPage = new NavigationPage(new ContentPage { Content = new StackLayout { VerticalOptions = LayoutOptions.Center, Padding = new Thickness(32,32,32,32), Children = { messagingCenter, line, line2 } } }); } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } }
using System; using FormsToolkit; using Xamarin.Forms; namespace ToolkitTests { public class App : Application { public App() { var messagingCenter = new Button { Text = "Messaging Center", Command = new Command(()=>MainPage.Navigation.PushAsync(new MessagingServicePage())) }; var line = new EntryLine { Placeholder = "This nifty place for entering text!", HorizontalTextAlignment = TextAlignment.Center, HorizontalOptions = LayoutOptions.FillAndExpand, Text = "", FontSize = 30, BorderColor = Color.Red }; // The root page of your application MainPage = new NavigationPage(new ContentPage { Content = new StackLayout { VerticalOptions = LayoutOptions.Center, Padding = new Thickness(32,32,32,32), Children = { messagingCenter, line } } }); } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } }
mit
C#
7f0ddcd0df3d369e6cd67c5dd438c430f8910b21
Update ModalitaPagamento validator with MP18..21 values
FatturaElettronicaPA/FatturaElettronicaPA,sirmmo/FatturaElettronicaPA
Validators/FModalitaPagamentoValidator.cs
Validators/FModalitaPagamentoValidator.cs
using BusinessObjects.Validators; namespace FatturaElettronicaPA.Validators { /// <summary> /// Validates FatturaElettronicaBody.DatiPagamento.DettaglioPagamento.ModalitaPagamento. /// </summary> public class FModalitaPagamentoValidator : DomainValidator { private const string BrokenDescription = "Valori ammessi [MP01], [MP02], [..], [MP21]."; /// <summary> /// Validates FatturaElettronicaBody.DatiPagamento.DettaglioPagamento.ModalitaPagamento. /// </summary> public FModalitaPagamentoValidator() : this(null, BrokenDescription) { } public FModalitaPagamentoValidator(string propertyName) : this(propertyName, BrokenDescription) { } public FModalitaPagamentoValidator(string propertyName, string description) : base(propertyName, description) { Domain = new[] { "MP01", "MP02", "MP03", "MP04", "MP06", "MP07", "MP08", "MP09", "MP10", "MP11", "MP12", "MP13", "MP14", "MP15", "MP16", "MP17", "MP18", "MP19", "MP20", "MP21" }; } } }
using BusinessObjects.Validators; namespace FatturaElettronicaPA.Validators { /// <summary> /// Validates FatturaElettronicaBody.DatiPagamento.DettaglioPagamento.ModalitaPagamento. /// </summary> public class FModalitaPagamentoValidator : DomainValidator { private const string BrokenDescription = "Valori ammessi [MP01], [MP02], [..], [MP17]."; /// <summary> /// Validates FatturaElettronicaBody.DatiPagamento.DettaglioPagamento.ModalitaPagamento. /// </summary> public FModalitaPagamentoValidator() : this(null, BrokenDescription) { } public FModalitaPagamentoValidator(string propertyName) : this(propertyName, BrokenDescription) { } public FModalitaPagamentoValidator(string propertyName, string description) : base(propertyName, description) { Domain = new[] { "MP01", "MP02", "MP03", "MP04", "MP06", "MP07", "MP08", "MP09", "MP10", "MP11", "MP12", "MP13", "MP14", "MP15", "MP16", "MP17" }; } } }
bsd-3-clause
C#
665ae54afc96e248e101e531866812cf20264be2
add range test
m5knt/ThunderEgg.Extensions
test/Misc.cs
test/Misc.cs
 using System; using System.Collections; using System.Collections.Generic; using System.Linq; using ThunderEgg.Extentions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace test { [TestClass] public partial class Misc { [TestMethod] public void Repeat() { Assert.IsTrue(new[] { 0, 0, 0 }.SequenceEqual(0.Repeat(3))); } [TestMethod] public void Range() { Assert.IsTrue(new[] { 0, 1, 2 }.SequenceEqual(A.Range(3).ToList())); Assert.IsTrue(new[] { 0, 2, 4 }.SequenceEqual(A.Range(0, 5, 2).ToList())); Assert.IsTrue(new[] { 0, -1, -2 }.SequenceEqual(A.Range(0, -3, -1).ToList())); Assert.IsTrue(new[] { 0, 1, 2 }.SequenceEqual(A.Range(0, i => i < 3, i => i + 1).ToList())); } [TestMethod] public void ForEach() { List<int> ret; ret = new List<int>(); A.Range(3).ForEach(_ => ret.Add(_)); Assert.IsTrue(new[] { 0, 1, 2 }.SequenceEqual(ret)); } } }
 using System; using System.Collections; using System.Collections.Generic; using System.Linq; using ThunderEgg.Extentions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace test { [TestClass] public partial class Misc { [TestMethod] public void Repeat() { Assert.IsTrue(new[] { 0, 0, 0 }.SequenceEqual(0.Repeat(3))); } [TestMethod] public void Range() { Assert.IsTrue(new[] { 0, 1, 2 }.SequenceEqual(A.Range(3).ToList())); Assert.IsTrue(new[] { 0, 2, 4 }.SequenceEqual(A.Range(0, 5, 2).ToList())); Assert.IsTrue(new[] { 0, -1, -2 }.SequenceEqual(A.Range(0, -3, -1).ToList())); } [TestMethod] public void ForEach() { List<int> ret; ret = new List<int>(); A.Range(3).ForEach(_ => ret.Add(_)); Assert.IsTrue(new[] { 0, 1, 2 }.SequenceEqual(ret)); } } }
mit
C#
24444cd7dae46bd5e8cf2f1c9da61c87f00b358d
change the version
tugberkugurlu/BonVoyage,tugberkugurlu/BonVoyage
src/BonVoyage/BonVoyageContext.cs
src/BonVoyage/BonVoyageContext.cs
using BonVoyage.Infrastructure; using System; using System.Net.Http; namespace BonVoyage { public class BonVoyageContext : IDisposable { private readonly HttpMessageHandler _handler; public BonVoyageContext() : this(CreateHandler()) { } public BonVoyageContext(HttpMessageHandler handler) { _handler = handler ?? throw new ArgumentNullException(nameof(handler)); } public FoursquareContext CreateFoursquareContext(string accessToken) { if (accessToken == null) { throw new ArgumentNullException(nameof(accessToken)); } return new FoursquareContext(_handler, accessToken); } public void Dispose() { _handler?.Dispose(); } /// <remarks> /// <seealso href="https://developer.foursquare.com/overview/versioning" /> for versioning. /// </remarks>> private static HttpMessageHandler CreateHandler() { return HttpClientFactory.CreatePipeline(new HttpClientHandler(), new DelegatingHandler[] { new OAuthTokenSwitchHandler(), new QueryAppenderHandler("v", "20170523") }); } } }
using BonVoyage.Infrastructure; using System; using System.Net.Http; namespace BonVoyage { public class BonVoyageContext : IDisposable { private readonly HttpMessageHandler _handler; public BonVoyageContext() : this(CreateHandler()) { } public BonVoyageContext(HttpMessageHandler handler) { _handler = handler ?? throw new ArgumentNullException(nameof(handler)); } public FoursquareContext CreateFoursquareContext(string accessToken) { if (accessToken == null) { throw new ArgumentNullException(nameof(accessToken)); } return new FoursquareContext(_handler, accessToken); } public void Dispose() { _handler?.Dispose(); } /// <remarks> /// <seealso href="https://developer.foursquare.com/overview/versioning" /> for versioning. /// </remarks>> private static HttpMessageHandler CreateHandler() { return HttpClientFactory.CreatePipeline(new HttpClientHandler(), new DelegatingHandler[] { new OAuthTokenSwitchHandler(), new QueryAppenderHandler("v", "20151111") }); } } }
mit
C#
7a4a8bab4e9577aebfc934137f2f28677396803b
Fix MonoMac/MonoTouch (for MonoMac builds)
mono/maccore
src/Foundation/NSUrlCredential.cs
src/Foundation/NSUrlCredential.cs
// Copyright 2013 Xamarin Inc. using System; using System.Reflection; using System.Collections; using System.Runtime.InteropServices; using MonoMac.ObjCRuntime; namespace MonoMac.Foundation { public partial class NSUrlCredential { public NSUrlCredential (IntPtr trust, bool ignored) : base (NSObjectFlag.Empty) { if (IsDirectBinding) { Handle = Messaging.IntPtr_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle ("initWithTrust:"), trust); } else { Handle = Messaging.IntPtr_objc_msgSendSuper_IntPtr (this.SuperHandle, Selector.GetHandle ("initWithTrust:"), trust); } } } }
// Copyright 2013 Xamarin Inc. using System; using System.Reflection; using System.Collections; using System.Runtime.InteropServices; using MonoMac.ObjCRuntime; namespace MonoMac.Foundation { public partial class NSUrlCredential { public NSUrlCredential (IntPtr trust, bool ignored) : base (NSObjectFlag.Empty) { if (IsDirectBinding) { Handle = MonoTouch.ObjCRuntime.Messaging.IntPtr_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle ("initWithTrust:"), trust); } else { Handle = MonoTouch.ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_IntPtr (this.SuperHandle, Selector.GetHandle ("initWithTrust:"), trust); } } } }
apache-2.0
C#
4477058c9c82c95c727f91d4a4eaa243f00f7ce1
Change field type
vazgriz/CSharpGameLibrary,vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary
CSGL.Vulkan/ShaderModule.cs
CSGL.Vulkan/ShaderModule.cs
using System; using System.Collections.Generic; using System.IO; using CSGL.Vulkan.Unmanaged; namespace CSGL.Vulkan { public class ShaderModuleCreateInfo { public IList<byte> data; } public class ShaderModule : IDisposable, INative<VkShaderModule> { VkShaderModule shaderModule; bool disposed = false; Device device; vkCreateShaderModuleDelegate createShaderModule; vkDestroyShaderModuleDelegate destroyShaderModule; public VkShaderModule Native { get { return shaderModule; } } public ShaderModule(Device device, ShaderModuleCreateInfo info) { if (device == null) throw new ArgumentNullException(nameof(device)); if (info == null) throw new ArgumentNullException(nameof(info)); if (info.data == null) throw new ArgumentNullException(nameof(info.data)); this.device = device; createShaderModule = device.Commands.createShaderModule; destroyShaderModule = device.Commands.destroyShaderModule; CreateShader(info); } void CreateShader(ShaderModuleCreateInfo mInfo) { VkShaderModuleCreateInfo info = new VkShaderModuleCreateInfo(); info.sType = VkStructureType.ShaderModuleCreateInfo; info.codeSize = (IntPtr)mInfo.data.Count; var dataPinned = new NativeArray<byte>(mInfo.data); info.pCode = dataPinned.Address; using (dataPinned) { var result = createShaderModule(device.Native, ref info, device.Instance.AllocationCallbacks, out shaderModule); if (result != VkResult.Success) throw new ShaderModuleException(result, string.Format("Error creating shader module: {0}")); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } void Dispose(bool disposing) { if (disposed) return; destroyShaderModule(device.Native, shaderModule, device.Instance.AllocationCallbacks); disposed = true; } ~ShaderModule() { Dispose(false); } } public class ShaderModuleException : VulkanException { public ShaderModuleException(VkResult result, string message) : base(result, message) { } } }
using System; using System.Collections.Generic; using System.IO; using CSGL.Vulkan.Unmanaged; namespace CSGL.Vulkan { public class ShaderModuleCreateInfo { public byte[] data; } public class ShaderModule : IDisposable, INative<VkShaderModule> { VkShaderModule shaderModule; bool disposed = false; Device device; vkCreateShaderModuleDelegate createShaderModule; vkDestroyShaderModuleDelegate destroyShaderModule; public VkShaderModule Native { get { return shaderModule; } } public ShaderModule(Device device, ShaderModuleCreateInfo info) { if (device == null) throw new ArgumentNullException(nameof(device)); if (info == null) throw new ArgumentNullException(nameof(info)); if (info.data == null) throw new ArgumentNullException(nameof(info.data)); this.device = device; createShaderModule = device.Commands.createShaderModule; destroyShaderModule = device.Commands.destroyShaderModule; CreateShader(info); } void CreateShader(ShaderModuleCreateInfo mInfo) { VkShaderModuleCreateInfo info = new VkShaderModuleCreateInfo(); info.sType = VkStructureType.ShaderModuleCreateInfo; info.codeSize = (IntPtr)mInfo.data.Length; var dataPinned = new PinnedArray<byte>(mInfo.data); info.pCode = dataPinned.Address; using (dataPinned) { var result = createShaderModule(device.Native, ref info, device.Instance.AllocationCallbacks, out shaderModule); if (result != VkResult.Success) throw new ShaderModuleException(result, string.Format("Error creating shader module: {0}")); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } void Dispose(bool disposing) { if (disposed) return; destroyShaderModule(device.Native, shaderModule, device.Instance.AllocationCallbacks); disposed = true; } ~ShaderModule() { Dispose(false); } } public class ShaderModuleException : VulkanException { public ShaderModuleException(VkResult result, string message) : base(result, message) { } } }
mit
C#
0e2ab20ccf1e2f8c9f680ba72be87aea5bd59dd2
Change "Countdown" syncing priority order
danielchalmers/DesktopWidgets
DesktopWidgets/Helpers/DateTimeSyncHelper.cs
DesktopWidgets/Helpers/DateTimeSyncHelper.cs
using System; namespace DesktopWidgets.Helpers { public static class DateTimeSyncHelper { public static DateTime SyncNext(this DateTime dateTime, bool syncYear, bool syncMonth, bool syncDay, bool syncHour, bool syncMinute, bool syncSecond) { var endDateTime = dateTime; endDateTime = new DateTime( syncYear ? DateTime.Now.Year : endDateTime.Year, syncMonth ? DateTime.Now.Month : endDateTime.Month, syncDay ? DateTime.Now.Day : endDateTime.Day, syncHour ? DateTime.Now.Hour : endDateTime.Hour, syncMinute ? DateTime.Now.Minute : endDateTime.Minute, syncSecond ? DateTime.Now.Second : endDateTime.Second, endDateTime.Kind); if (syncSecond && endDateTime < DateTime.Now) endDateTime = endDateTime.AddSeconds(1); if (syncMinute && endDateTime < DateTime.Now) endDateTime = endDateTime.AddMinutes(1); if (syncHour && endDateTime < DateTime.Now) endDateTime = endDateTime.AddHours(1); if (syncDay && endDateTime < DateTime.Now) endDateTime = endDateTime.AddDays(1); if (syncMonth && endDateTime < DateTime.Now) endDateTime = endDateTime.AddMonths(1); if (syncYear && endDateTime < DateTime.Now) endDateTime = endDateTime.AddYears(1); return endDateTime; } } }
using System; namespace DesktopWidgets.Helpers { public static class DateTimeSyncHelper { public static DateTime SyncNext(this DateTime dateTime, bool syncYear, bool syncMonth, bool syncDay, bool syncHour, bool syncMinute, bool syncSecond) { var endDateTime = dateTime; endDateTime = new DateTime( syncYear ? DateTime.Now.Year : endDateTime.Year, syncMonth ? DateTime.Now.Month : endDateTime.Month, syncDay ? DateTime.Now.Day : endDateTime.Day, syncHour ? DateTime.Now.Hour : endDateTime.Hour, syncMinute ? DateTime.Now.Minute : endDateTime.Minute, syncSecond ? DateTime.Now.Second : endDateTime.Second, endDateTime.Kind); if (syncYear && endDateTime < DateTime.Now) endDateTime = endDateTime.AddYears(1); if (syncMonth && endDateTime < DateTime.Now) endDateTime = endDateTime.AddMonths(1); if (syncDay && endDateTime < DateTime.Now) endDateTime = endDateTime.AddDays(1); if (syncHour && endDateTime < DateTime.Now) endDateTime = endDateTime.AddHours(1); if (syncMinute && endDateTime < DateTime.Now) endDateTime = endDateTime.AddMinutes(1); if (syncSecond && endDateTime < DateTime.Now) endDateTime = endDateTime.AddSeconds(1); return endDateTime; } } }
apache-2.0
C#
587ff6d2fca51a6b9e613f3fd33a1057bab3bfe6
Remove the constructor
flagbug/Espera.Network
Espera.Network/ConnectionInfo.cs
Espera.Network/ConnectionInfo.cs
using System; namespace Espera.Network { public class ConnectionInfo { public NetworkAccessPermission AccessPermission { get; set; } public Version ServerVersion { get; set; } } }
using System; namespace Espera.Network { public class ConnectionInfo { public ConnectionInfo(NetworkAccessPermission permission, Version serverVersion) { this.AccessPermission = permission; this.ServerVersion = serverVersion; } public NetworkAccessPermission AccessPermission { get; private set; } public Version ServerVersion { get; private set; } } }
mit
C#
3ffceda5fb5ca782b1b031c6c26710ee6f7e8bb4
Add get top to service
Branimir123/PhotoLife,Branimir123/PhotoLife,Branimir123/PhotoLife
PhotoLife/PhotoLife.Services/PostsService.cs
PhotoLife/PhotoLife.Services/PostsService.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PhotoLife.Data.Contracts; using PhotoLife.Models; using PhotoLife.Services.Contracts; namespace PhotoLife.Services { public class PostsService : IPostService { private readonly IRepository<Post> postsRepository; private readonly IUnitOfWork unitOfWork; public PostsService( IRepository<Post> postsRepository, IUnitOfWork unitOfWork) { if (postsRepository == null) { throw new ArgumentNullException("postsRepository"); } if (unitOfWork == null) { throw new ArgumentNullException("unitOfWorks"); } this.postsRepository = postsRepository; this.unitOfWork = unitOfWork; } public Post GetPostById(string id) { return this.postsRepository.GetById(id); } public IEnumerable<Post> GetTopPosts(int countOfPosts) { var res = this.postsRepository.GetAll( (Post post) => true, (Post post) => post.Votes, true) .Take(countOfPosts); return res; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PhotoLife.Data.Contracts; using PhotoLife.Models; using PhotoLife.Services.Contracts; namespace PhotoLife.Services { public class PostsService: IPostService { private readonly IRepository<Post> postsRepository; private readonly IUnitOfWork unitOfWork; public PostsService( IRepository<Post> postsRepository, IUnitOfWork unitOfWork) { if (postsRepository == null) { throw new ArgumentNullException("postsRepository"); } if (unitOfWork == null) { throw new ArgumentNullException("unitOfWorks"); } this.postsRepository = postsRepository; this.unitOfWork = unitOfWork; } public Post GetPostById(string id) { return this.postsRepository.GetById(id); } } }
mit
C#
cd91183a9787d9295efe4e252af2b7535ff21d5a
Use ISO encoding, for cross platform
skwasjer/SilentHunter
src/SilentHunter.Core/Encoding.cs
src/SilentHunter.Core/Encoding.cs
namespace SilentHunter { public static class Encoding { /// <summary> /// The default encoding to use for parsing Silent Hunter game files. /// </summary> public static System.Text.Encoding ParseEncoding { get; } = System.Text.Encoding.GetEncoding("ISO-8859-1"); } }
namespace SilentHunter { public static class Encoding { /// <summary> /// The default encoding to use for parsing Silent Hunter game files. /// </summary> public static System.Text.Encoding ParseEncoding { get; } = System.Text.Encoding.GetEncoding(1252); } }
apache-2.0
C#
242b96fe76e0e1b69b89bf401c9aa1109bc1c29d
Update MainActivity.cs
iperezmx87/Xamarin30Labs
Lab03/AndroidApp/MainActivity.cs
Lab03/AndroidApp/MainActivity.cs
using Android.App; using Android.Widget; using Android.OS; namespace AndroidApp { [Activity(Label = "Lab 03", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource // SetContentView (Resource.Layout.Main); //var helper = new SharedProject.MySharedCode(); //new AlertDialog.Builder(this) // .SetMessage(helper.GetFilePath("demo.dat")) // .Show(); Validate(); } private async void Validate() { var serviceClient = new SALLab03.ServiceClient(); string email = ""; string password = ""; string myDevice = Android.Provider.Settings.Secure.GetString(ContentResolver, Android.Provider.Settings.Secure.AndroidId ); var result = await serviceClient.ValidateAsync(email, password, myDevice); var dialog = new AlertDialog.Builder(this); AlertDialog alert = dialog.Create(); alert.SetMessage($"{result.Status}\n{result.Fullname}\n{result.Token}"); alert.SetButton("Ok", (s, ev) => { }); alert.Show(); } } }
using Android.App; using Android.Widget; using Android.OS; namespace AndroidApp { [Activity(Label = "Lab 03", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource // SetContentView (Resource.Layout.Main); //var helper = new SharedProject.MySharedCode(); //new AlertDialog.Builder(this) // .SetMessage(helper.GetFilePath("demo.dat")) // .Show(); Validate(); } private async void Validate() { var serviceClient = new SALLab03.ServiceClient(); string email = "[email protected]"; string password = "Isra-mx87"; string myDevice = Android.Provider.Settings.Secure.GetString(ContentResolver, Android.Provider.Settings.Secure.AndroidId ); var result = await serviceClient.ValidateAsync(email, password, myDevice); var dialog = new AlertDialog.Builder(this); AlertDialog alert = dialog.Create(); alert.SetMessage($"{result.Status}\n{result.Fullname}\n{result.Token}"); alert.SetButton("Ok", (s, ev) => { }); alert.Show(); } } }
mit
C#
60ebfe297ecd564fa6cf750a55400b002757f5bc
Bump 0.15.0
pysco68/Nowin,et1975/Nowin,pysco68/Nowin,Bobris/Nowin,modulexcite/Nowin,lstefano71/Nowin,lstefano71/Nowin,modulexcite/Nowin,et1975/Nowin,lstefano71/Nowin,Bobris/Nowin,et1975/Nowin,pysco68/Nowin,modulexcite/Nowin,Bobris/Nowin
Nowin/Properties/AssemblyInfo.cs
Nowin/Properties/AssemblyInfo.cs
using System.Reflection; 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("Nowin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Boris Letocha")] [assembly: AssemblyProduct("Nowin")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fd085b68-3766-42af-ab6d-351b7741c685")] // 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("0.15.0.0")] [assembly: AssemblyFileVersion("0.15.0.0")]
using System.Reflection; 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("Nowin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Boris Letocha")] [assembly: AssemblyProduct("Nowin")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fd085b68-3766-42af-ab6d-351b7741c685")] // 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("0.14.0.0")] [assembly: AssemblyFileVersion("0.14.0.0")]
mit
C#
be34b5c2ee5416495a8fa89d8eb2f28cf95bbe53
Fix SetupSequentialContext to increment counter also after using Throws
JohanLarsson/moq4,HelloKitty/moq4,madcapsoftware/moq4,chkpnt/moq4,LeonidLevin/moq4,kulkarnisachin07/moq4,RobSiklos/moq4,iskiselev/moq4,ocoanet/moq4,cgourlay/moq4,AhmedAssaf/moq4,kolomanschaft/moq4,breyed/moq4,AhmedAssaf/moq4,ramanraghur/moq4,Moq/moq4,jeremymeng/moq4
Source/SetupSequentialContext.cs
Source/SetupSequentialContext.cs
using System; using System.Linq.Expressions; using Moq.Language; using Moq.Language.Flow; namespace Moq { internal class SetupSequentialContext<TMock, TResult> : ISetupSequentialResult<TResult> where TMock : class { private int currentStep; private int expectationsCount; private Mock<TMock> mock; private Expression<Func<TMock, TResult>> expression; public SetupSequentialContext( Mock<TMock> mock, Expression<Func<TMock, TResult>> expression) { this.mock = mock; this.expression = expression; } private ISetup<TMock, TResult> GetSetup() { var expectationStep = this.expectationsCount; this.expectationsCount++; return this.mock .When(() => currentStep == expectationStep) .Setup<TResult>(expression); } private void EndSetup(ICallback callback) { callback.Callback(() => currentStep++); } public ISetupSequentialResult<TResult> Returns(TResult value) { this.EndSetup(GetSetup().Returns(value)); return this; } public void Throws(Exception exception) { var setup = this.GetSetup(); setup.Throws(exception); setup.Callback(() => currentStep++); } public void Throws<TException>() where TException : Exception, new() { this.GetSetup().Throws<TException>(); } } }
using System; using System.Linq.Expressions; using Moq.Language; using Moq.Language.Flow; namespace Moq { internal class SetupSequentialContext<TMock, TResult> : ISetupSequentialResult<TResult> where TMock : class { private int currentStep; private int expectationsCount; private Mock<TMock> mock; private Expression<Func<TMock, TResult>> expression; public SetupSequentialContext( Mock<TMock> mock, Expression<Func<TMock, TResult>> expression) { this.mock = mock; this.expression = expression; } private ISetup<TMock, TResult> GetSetup() { var expectationStep = this.expectationsCount; this.expectationsCount++; return this.mock .When(() => currentStep == expectationStep) .Setup<TResult>(expression); } private void EndSetup(ICallback callback) { callback.Callback(() => currentStep++); } public ISetupSequentialResult<TResult> Returns(TResult value) { this.EndSetup(GetSetup().Returns(value)); return this; } public void Throws(Exception exception) { this.GetSetup().Throws(exception); } public void Throws<TException>() where TException : Exception, new() { this.GetSetup().Throws<TException>(); } } }
bsd-3-clause
C#
97d6de7f9dfbc3eaf87bf94c0aca35eb2aff34aa
Make StructuredBufferManager work with a count of 0
virtuallynaked/virtually-naked,virtuallynaked/virtually-naked
Viewer/src/common/StructuredBufferManager.cs
Viewer/src/common/StructuredBufferManager.cs
using SharpDX.Direct3D11; using System; using SharpDX; using System.Runtime.InteropServices; using Buffer = SharpDX.Direct3D11.Buffer; //Optimized for occasional update (ResourceUsage.Default + UpdateSubresource) public class StructuredBufferManager<T> : IDisposable where T : struct { private readonly Device device; private readonly Buffer buffer; private readonly ShaderResourceView view; public StructuredBufferManager(Device device, int count) { this.device = device; int elementSizeInBytes = Marshal.SizeOf<T>(); if (count > 0) { //buffers cannot have size 0, but I want to hide this detail from StructuredBufferManager consumers BufferDescription description = new BufferDescription { SizeInBytes = count * elementSizeInBytes, Usage = ResourceUsage.Default, BindFlags = BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.BufferStructured, StructureByteStride = elementSizeInBytes }; this.buffer = new Buffer(device, description); this.view = new ShaderResourceView(device, buffer); } } public void Dispose() { buffer?.Dispose(); view?.Dispose(); } public ShaderResourceView View => view; public void Update(DeviceContext context, T[] data) { if (buffer != null) { context.UpdateSubresource(data, buffer); } } }
using SharpDX.Direct3D11; using System; using SharpDX; using System.Runtime.InteropServices; using Buffer = SharpDX.Direct3D11.Buffer; //Optimized for occasional update (ResourceUsage.Default + UpdateSubresource) public class StructuredBufferManager<T> : IDisposable where T : struct { private readonly Device device; private readonly Buffer buffer; private readonly ShaderResourceView view; public StructuredBufferManager(Device device, int count) { this.device = device; int elementSizeInBytes = Marshal.SizeOf<T>(); BufferDescription description = new BufferDescription { SizeInBytes = count * elementSizeInBytes, Usage = ResourceUsage.Default, BindFlags = BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.BufferStructured, StructureByteStride = elementSizeInBytes }; this.buffer = new Buffer(device, description); this.view = new ShaderResourceView(device, buffer); } public void Dispose() { buffer.Dispose(); view.Dispose(); } public ShaderResourceView View => view; public void Update(DeviceContext context, T[] data) { context.UpdateSubresource(data, buffer); } }
mit
C#
a4821ca5485622ea826645ea2cb8b65dd9df2ba5
add and remove the paste item to context menu as ReadOnly property changes.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/Controls/ExtendedTextBox.cs
WalletWasabi.Gui/Controls/ExtendedTextBox.cs
using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Styling; using ReactiveUI; using System; using System.Reactive.Linq; namespace WalletWasabi.Gui.Controls { public class ExtendedTextBox : TextBox, IStyleable { private MenuItem _pasteItem; public ExtendedTextBox() { CopyCommand = ReactiveCommand.Create(() => { CopyAsync(); }); PasteCommand = ReactiveCommand.Create(() => { PasteAsync(); }); this.GetObservable(IsReadOnlyProperty).Subscribe(ro => { if (_pasteItem != null) { var items = ContextMenu.Items as Avalonia.Controls.Controls; if (ro) { if (items.Contains(_pasteItem)) { items.Remove(_pasteItem); } } else { if (!items.Contains(_pasteItem)) { items.Add(_pasteItem); } } } }); } Type IStyleable.StyleKey => typeof(TextBox); private ReactiveCommand CopyCommand { get; } private ReactiveCommand PasteCommand { get; } private async void PasteAsync() { var text = await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard))).GetTextAsync(); if (text == null) { return; } OnTextInput(new TextInputEventArgs { Text = text }); } private string GetSelection() { var text = Text; if (string.IsNullOrEmpty(text)) return ""; var selectionStart = SelectionStart; var selectionEnd = SelectionEnd; var start = Math.Min(selectionStart, selectionEnd); var end = Math.Max(selectionStart, selectionEnd); if (start == end || (Text?.Length ?? 0) < end) { return ""; } return text.Substring(start, end - start); } private async void CopyAsync() { var selection = GetSelection(); if (string.IsNullOrWhiteSpace(selection)) { selection = Text; } if (!string.IsNullOrWhiteSpace(selection)) { await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard))) .SetTextAsync(selection); } } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) { base.OnTemplateApplied(e); ContextMenu = new ContextMenu { DataContext = this, }; _pasteItem = new MenuItem { Header = "Paste", Command = PasteCommand }; ContextMenu.Items = new Avalonia.Controls.Controls { new MenuItem { Header = "Copy", Command = CopyCommand } }; if(!IsReadOnly) { (ContextMenu.Items as Avalonia.Controls.Controls).Add(_pasteItem); } } } }
using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Styling; using ReactiveUI; using System; using System.Reactive.Linq; namespace WalletWasabi.Gui.Controls { public class ExtendedTextBox : TextBox, IStyleable { public ExtendedTextBox() { CopyCommand = ReactiveCommand.Create(() => { CopyAsync(); }); PasteCommand = ReactiveCommand.Create(() => { PasteAsync(); }, this.GetObservable(IsReadOnlyProperty).Select(x => !x)); } Type IStyleable.StyleKey => typeof(TextBox); private ReactiveCommand CopyCommand { get; } private ReactiveCommand PasteCommand { get; } private async void PasteAsync() { var text = await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard))).GetTextAsync(); if (text == null) { return; } OnTextInput(new TextInputEventArgs { Text = text }); } private string GetSelection() { var text = Text; if (string.IsNullOrEmpty(text)) return ""; var selectionStart = SelectionStart; var selectionEnd = SelectionEnd; var start = Math.Min(selectionStart, selectionEnd); var end = Math.Max(selectionStart, selectionEnd); if (start == end || (Text?.Length ?? 0) < end) { return ""; } return text.Substring(start, end - start); } private async void CopyAsync() { var selection = GetSelection(); if (string.IsNullOrWhiteSpace(selection)) { selection = Text; } if (!string.IsNullOrWhiteSpace(selection)) { await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard))) .SetTextAsync(selection); } } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) { base.OnTemplateApplied(e); ContextMenu = new ContextMenu { DataContext = this, }; ContextMenu.Items = new Avalonia.Controls.Controls { new MenuItem { Header = "Copy", Command = CopyCommand }, new MenuItem { Header = "Paste", Command = PasteCommand} }; } } }
mit
C#
c4895af81a5d21842f47df7b3ee16ddec223d04e
Add shutdown and clean up GhostSystem
space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
Content.Server/GameObjects/EntitySystems/GhostSystem.cs
Content.Server/GameObjects/EntitySystems/GhostSystem.cs
using Content.Server.GameObjects.Components.Mobs; using Content.Server.GameObjects.Components.Observer; using JetBrains.Annotations; using Robust.Shared.GameObjects; namespace Content.Server.GameObjects.EntitySystems { [UsedImplicitly] public class GhostSystem : EntitySystem { public override void Initialize() { base.Initialize(); SubscribeLocalEvent<GhostComponent, MindRemovedMessage>(OnMindRemovedMessage); SubscribeLocalEvent<GhostComponent, MindUnvisitedMessage>(OnMindUnvisitedMessage); } public override void Shutdown() { base.Shutdown(); UnsubscribeLocalEvent<GhostComponent, MindRemovedMessage>(OnMindRemovedMessage); UnsubscribeLocalEvent<GhostComponent, MindUnvisitedMessage>(OnMindUnvisitedMessage); } private void OnMindRemovedMessage(EntityUid uid, GhostComponent component, MindRemovedMessage args) { if (!EntityManager.TryGetEntity(uid, out var entity)) return; DeleteEntity(entity); } private void OnMindUnvisitedMessage(EntityUid uid, GhostComponent component, MindUnvisitedMessage args) { if (!EntityManager.TryGetEntity(uid, out var entity)) return; DeleteEntity(entity); } private void DeleteEntity(IEntity? entity) { if (entity?.Deleted == true) return; entity?.Delete(); } } }
#nullable enable using Content.Server.GameObjects.Components.Mobs; using Content.Server.GameObjects.Components.Observer; using JetBrains.Annotations; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; using System; namespace Content.Server.GameObjects.EntitySystems { [UsedImplicitly] public class GhostSystem : EntitySystem { public override void Initialize() { base.Initialize(); SubscribeLocalEvent<GhostComponent, MindRemovedMessage>(OnMindRemovedMessage); SubscribeLocalEvent<GhostComponent, MindUnvisitedMessage>(OnMindUnvisitedMessage); } private void OnMindRemovedMessage(EntityUid uid, GhostComponent component, MindRemovedMessage args) { if (!EntityManager.TryGetEntity(uid, out var entity)) return; DeleteEntity(entity); } private void OnMindUnvisitedMessage(EntityUid uid, GhostComponent component, MindUnvisitedMessage args) { if (!EntityManager.TryGetEntity(uid, out var entity)) return; DeleteEntity(entity); } private void DeleteEntity(IEntity? entity) { if (entity?.Deleted == true) return; entity?.Delete(); } } }
mit
C#
1fa7f88f1dfd567d9efed4282a3e1d6172885f95
remove extra comments
xclayl/orleans,xclayl/orleans
test/Tester/RelationalUtilities/PostgreSqlStorageForTesting.cs
test/Tester/RelationalUtilities/PostgreSqlStorageForTesting.cs
using System.Collections.Generic; using Orleans.SqlUtils; using UnitTests.General; namespace Tester.RelationalUtilities { class PostgreSqlStorageForTesting : RelationalStorageForTesting { public PostgreSqlStorageForTesting(string connectionString) : base(AdoNetInvariants.InvariantNamePostgreSql, connectionString) { } public override string DefaultConnectionString { get { return @"Server=127.0.0.1;Port=5432;Database=postgres;Integrated Security=true;Pooling=false;"; } } public override string CancellationTestQuery { get { return "SELECT pg_sleep(10); SELECT 1; "; } } public override string CreateStreamTestTable { get { return "CREATE TABLE StreamingTest(Id integer NOT NULL, StreamData bytea NOT NULL);"; } } protected override string SetupSqlScriptFileName { get { return "CreateOrleansTables_PostgreSql.sql"; } } protected override string CreateDatabaseTemplate { get { return @"CREATE DATABASE ""{0}"" WITH ENCODING='UTF8' CONNECTION LIMIT=-1;"; } } protected override string DropDatabaseTemplate { get { return @"SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = '{0}' AND pid <> pg_backend_pid(); DROP DATABASE ""{0}"";"; } } protected override string ExistsDatabaseTemplate { get { return "SELECT COUNT(1)::int::boolean FROM pg_database WHERE datname = '{0}';"; } } protected override IEnumerable<string> ConvertToExecutableBatches(string setupScript, string dataBaseName) { var batches = new List<string> { setupScript, CreateStreamTestTable }; return batches; } } }
using System.Collections.Generic; using Orleans.SqlUtils; using UnitTests.General; namespace Tester.RelationalUtilities { class PostgreSqlStorageForTesting : RelationalStorageForTesting { public PostgreSqlStorageForTesting(string connectionString) : base(AdoNetInvariants.InvariantNamePostgreSql, connectionString) { } public override string DefaultConnectionString { get { return @"Server=127.0.0.1;Port=5432;Database=postgres;Integrated Security=true;Pooling=false;"; } } public override string CancellationTestQuery { get { return "SELECT pg_sleep(10); SELECT 1; "; } } public override string CreateStreamTestTable { get { return "CREATE TABLE StreamingTest(Id integer NOT NULL, StreamData bytea NOT NULL);"; } } protected override string SetupSqlScriptFileName { get { return "CreateOrleansTables_PostgreSql.sql"; } } protected override string CreateDatabaseTemplate { get { return @"CREATE DATABASE ""{0}"" WITH ENCODING='UTF8' CONNECTION LIMIT=-1;"; } } protected override string DropDatabaseTemplate { get { return @"SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = '{0}' AND pid <> pg_backend_pid(); DROP DATABASE ""{0}"";"; } } protected override string ExistsDatabaseTemplate { get { return "SELECT COUNT(1)::int::boolean FROM pg_database WHERE datname = '{0}';"; } } protected override IEnumerable<string> ConvertToExecutableBatches(string setupScript, string dataBaseName) { var batches = new List<string> { setupScript, CreateStreamTestTable }; // setupScript.Split(new[] { "GO" }, StringSplitOptions.RemoveEmptyEntries).ToList(); //This removes the use of recovery log in case of database crashes, which //improves performance to some degree, depending on usage. For non-performance testing only. return batches; } } }
mit
C#
b1559a8fa55aea86d4704a23961c143f10b4a77d
Correct to print right result
chkr1011/MQTTnet,chkr1011/MQTTnet,chkr1011/MQTTnet,chkr1011/MQTTnet,chkr1011/MQTTnet
Source/MQTTnet/Adapter/MqttConnectingFailedException.cs
Source/MQTTnet/Adapter/MqttConnectingFailedException.cs
using MQTTnet.Client.Connecting; using MQTTnet.Exceptions; namespace MQTTnet.Adapter { public class MqttConnectingFailedException : MqttCommunicationException { public MqttConnectingFailedException(MqttClientAuthenticateResult resultCode) : base($"Connecting with MQTT server failed ({resultCode.ResultCode.ToString()}).") { Result = resultCode; } public MqttClientAuthenticateResult Result { get; } public MqttClientConnectResultCode ResultCode => Result.ResultCode; } }
using MQTTnet.Client.Connecting; using MQTTnet.Exceptions; namespace MQTTnet.Adapter { public class MqttConnectingFailedException : MqttCommunicationException { public MqttConnectingFailedException(MqttClientAuthenticateResult resultCode) : base($"Connecting with MQTT server failed ({resultCode.ToString()}).") { Result = resultCode; } public MqttClientAuthenticateResult Result { get; } public MqttClientConnectResultCode ResultCode => Result.ResultCode; } }
mit
C#
b102158eb980fee2ec41adf7be0639469b8c8ca4
Remove TODO, no longer pluralizing method names
TheFireCookie/elasticsearch-net,CSGOpenSource/elasticsearch-net,adam-mccoy/elasticsearch-net,UdiBen/elasticsearch-net,cstlaurent/elasticsearch-net,cstlaurent/elasticsearch-net,cstlaurent/elasticsearch-net,adam-mccoy/elasticsearch-net,TheFireCookie/elasticsearch-net,elastic/elasticsearch-net,elastic/elasticsearch-net,RossLieberman/NEST,UdiBen/elasticsearch-net,CSGOpenSource/elasticsearch-net,RossLieberman/NEST,CSGOpenSource/elasticsearch-net,TheFireCookie/elasticsearch-net,UdiBen/elasticsearch-net,RossLieberman/NEST,azubanov/elasticsearch-net,azubanov/elasticsearch-net,adam-mccoy/elasticsearch-net,azubanov/elasticsearch-net
src/Nest/Indices/IndexSettings/IndexTemplates/GetIndexTemplate/ElasticClient-GetIndexTemplate.cs
src/Nest/Indices/IndexSettings/IndexTemplates/GetIndexTemplate/ElasticClient-GetIndexTemplate.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Elasticsearch.Net; namespace Nest { using GetIndexTemplateConverter = Func<IApiCallDetails, Stream, GetIndexTemplateResponse>; public partial interface IElasticClient { /// <summary> /// Gets an index template /// <para> </para>http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-templates.html#getting /// </summary> /// <param name="name">The name of the template to get</param> /// <param name="selector">An optional selector specifying additional parameters for the get template operation</param> IGetIndexTemplateResponse GetIndexTemplate(Func<GetIndexTemplateDescriptor, IGetIndexTemplateRequest> selector = null); /// <inheritdoc/> IGetIndexTemplateResponse GetIndexTemplate(IGetIndexTemplateRequest request); /// <inheritdoc/> Task<IGetIndexTemplateResponse> GetIndexTemplateAsync(Func<GetIndexTemplateDescriptor, IGetIndexTemplateRequest> selector = null); /// <inheritdoc/> Task<IGetIndexTemplateResponse> GetIndexTemplateAsync(IGetIndexTemplateRequest request); } public partial class ElasticClient { /// <inheritdoc/> public IGetIndexTemplateResponse GetIndexTemplate(Func<GetIndexTemplateDescriptor, IGetIndexTemplateRequest> selector = null) => this.GetIndexTemplate(selector.InvokeOrDefault(new GetIndexTemplateDescriptor())); /// <inheritdoc/> public IGetIndexTemplateResponse GetIndexTemplate(IGetIndexTemplateRequest request) { return this.Dispatcher.Dispatch<IGetIndexTemplateRequest, GetIndexTemplateRequestParameters, GetIndexTemplateResponse>( request, (p, d) => this.LowLevelDispatch.IndicesGetTemplateDispatch<GetIndexTemplateResponse>(p) ); } /// <inheritdoc/> public Task<IGetIndexTemplateResponse> GetIndexTemplateAsync(Func<GetIndexTemplateDescriptor, IGetIndexTemplateRequest> selector = null) => this.GetIndexTemplateAsync(selector.InvokeOrDefault(new GetIndexTemplateDescriptor())); /// <inheritdoc/> public Task<IGetIndexTemplateResponse> GetIndexTemplateAsync(IGetIndexTemplateRequest request) => this.Dispatcher.DispatchAsync<IGetIndexTemplateRequest, GetIndexTemplateRequestParameters, GetIndexTemplateResponse, IGetIndexTemplateResponse>( request, (p, d) => this.LowLevelDispatch.IndicesGetTemplateDispatchAsync<GetIndexTemplateResponse>(p) ); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Elasticsearch.Net; namespace Nest { using GetIndexTemplateConverter = Func<IApiCallDetails, Stream, GetIndexTemplateResponse>; public partial interface IElasticClient { /// <summary> /// Gets an index template /// <para> </para>http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-templates.html#getting /// </summary> /// <param name="name">The name of the template to get</param> /// <param name="selector">An optional selector specifying additional parameters for the get template operation</param> IGetIndexTemplateResponse GetIndexTemplate(Func<GetIndexTemplateDescriptor, IGetIndexTemplateRequest> selector = null); /// <inheritdoc/> IGetIndexTemplateResponse GetIndexTemplate(IGetIndexTemplateRequest request); /// <inheritdoc/> Task<IGetIndexTemplateResponse> GetIndexTemplateAsync(Func<GetIndexTemplateDescriptor, IGetIndexTemplateRequest> selector = null); /// <inheritdoc/> Task<IGetIndexTemplateResponse> GetIndexTemplateAsync(IGetIndexTemplateRequest request); } //TODO High Priority: changing this and other methods that can actually return multiple to plural form e.g GetIndexTemplates/GetIndexTemplates public partial class ElasticClient { /// <inheritdoc/> public IGetIndexTemplateResponse GetIndexTemplate(Func<GetIndexTemplateDescriptor, IGetIndexTemplateRequest> selector = null) => this.GetIndexTemplate(selector.InvokeOrDefault(new GetIndexTemplateDescriptor())); /// <inheritdoc/> public IGetIndexTemplateResponse GetIndexTemplate(IGetIndexTemplateRequest request) { return this.Dispatcher.Dispatch<IGetIndexTemplateRequest, GetIndexTemplateRequestParameters, GetIndexTemplateResponse>( request, (p, d) => this.LowLevelDispatch.IndicesGetTemplateDispatch<GetIndexTemplateResponse>(p) ); } /// <inheritdoc/> public Task<IGetIndexTemplateResponse> GetIndexTemplateAsync(Func<GetIndexTemplateDescriptor, IGetIndexTemplateRequest> selector = null) => this.GetIndexTemplateAsync(selector.InvokeOrDefault(new GetIndexTemplateDescriptor())); /// <inheritdoc/> public Task<IGetIndexTemplateResponse> GetIndexTemplateAsync(IGetIndexTemplateRequest request) => this.Dispatcher.DispatchAsync<IGetIndexTemplateRequest, GetIndexTemplateRequestParameters, GetIndexTemplateResponse, IGetIndexTemplateResponse>( request, (p, d) => this.LowLevelDispatch.IndicesGetTemplateDispatchAsync<GetIndexTemplateResponse>(p) ); } }
apache-2.0
C#
2c7da651a099bf60ee5d72cdbd66afb133c0369e
update version
prodot/ReCommended-Extension
Sources/ReCommendedExtension/Properties/AssemblyInfo.cs
Sources/ReCommendedExtension/Properties/AssemblyInfo.cs
using System.Reflection; using ReCommendedExtension; // 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(ZoneMarker.ExtensionName)] [assembly: AssemblyDescription(ZoneMarker.ExtensionDescription)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("prodot GmbH")] [assembly: AssemblyProduct(ZoneMarker.ExtensionId)] [assembly: AssemblyCopyright("© 2012-2020 prodot GmbH")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("4.2.0.0")] [assembly: AssemblyFileVersion("4.2.0")]
using System.Reflection; using ReCommendedExtension; // 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(ZoneMarker.ExtensionName)] [assembly: AssemblyDescription(ZoneMarker.ExtensionDescription)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("prodot GmbH")] [assembly: AssemblyProduct(ZoneMarker.ExtensionId)] [assembly: AssemblyCopyright("© 2012-2020 prodot GmbH")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("4.1.0.0")] [assembly: AssemblyFileVersion("4.1.0")]
apache-2.0
C#
6249ff9a2eb54bac1bebe4e4ebcec4d2a24ae1f0
Use more proper name for test
Ky7m/DemoCode,Ky7m/DemoCode,Ky7m/DemoCode,Ky7m/DemoCode
CSharpInternals/1.CSharpInternals.ExceptionHandling/a.Basics.cs
CSharpInternals/1.CSharpInternals.ExceptionHandling/a.Basics.cs
using System; using Xunit; namespace CSharpInternals.ExceptionHandling { public class Basics { [Fact] public void ThrowsNull() { Assert.Throws<NullReferenceException>(() => ThrowsNullReferenceException()); } // Fact - ToString allocates a lot, especially with AggregateException // http://referencesource.microsoft.com/#mscorlib/system/AggregateException.cs,448 private static void ThrowsNullReferenceException() => throw null; } }
using System; using Xunit; namespace CSharpInternals.ExceptionHandling { public class Basics { [Fact] public void Test() { Assert.Throws<NullReferenceException>(() => ThrowsNullReferenceException()); } // Fact - ToString allocates a lot, especially with AggregateException // http://referencesource.microsoft.com/#mscorlib/system/AggregateException.cs,448 private static void ThrowsNullReferenceException() => throw null; } }
mit
C#
9af4f764648f3215c74d33851ca72f48fe28455e
Make IsOrganization nullable
acron0/AsanaNet,jfjcn/AsanaNet,niieani/AsanaNet
AsanaNet/Objects/AsanaWorkspace.cs
AsanaNet/Objects/AsanaWorkspace.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AsanaNet { [Serializable] public class AsanaWorkspace : AsanaObject, IAsanaData { [AsanaDataAttribute("name")] public string Name { get; private set; } [AsanaDataAttribute("is_organization")] public bool? IsOrganization { get; private set; } // ------------------------------------------------------ public bool IsObjectLocal { get { return true; } } public void Complete() { throw new NotImplementedException(); } public override Task Refresh() { return Host.GetWorkspaceById(ID, workspace => { Name = (workspace as AsanaWorkspace).Name; IsOrganization = (workspace as AsanaWorkspace).IsOrganization; }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AsanaNet { [Serializable] public class AsanaWorkspace : AsanaObject, IAsanaData { [AsanaDataAttribute("name")] public string Name { get; private set; } [AsanaDataAttribute("is_organization")] public bool IsOrganization { get; private set; } // ------------------------------------------------------ public bool IsObjectLocal { get { return true; } } public void Complete() { throw new NotImplementedException(); } public override Task Refresh() { return Host.GetWorkspaceById(ID, workspace => { Name = (workspace as AsanaWorkspace).Name; IsOrganization = (workspace as AsanaWorkspace).IsOrganization; }); } } }
mit
C#
6d597cb17a0283f57cd95b0b2de12b1fa39247f7
fix ReadSingle (manual merge https://github.com/xamarin/urho/pull/160)
florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho
Bindings/Portable/MarshalHelper.cs
Bindings/Portable/MarshalHelper.cs
using System; using System.Runtime.InteropServices; namespace Urho { public static class MarshalHelper { public static unsafe float ReadSingle(this IntPtr ptr, int offset = 0) { return *(float*)((byte*)ptr + offset); } public static float[] ToFloatsArray(this IntPtr ptr, int size) { float[] result = new float[size]; Marshal.Copy(ptr, result, 0, size); return result; } public static byte[] ToBytesArray(this IntPtr ptr, int size) { byte[] result = new byte[size]; Marshal.Copy(ptr, result, 0, size); return result; } public static int[] ToIntsArray(this IntPtr ptr, int size) { int[] result = new int[size]; Marshal.Copy(ptr, result, 0, size); return result; } public static T[] ToStructsArray<T>(this IntPtr ptr, int size) where T : struct { T[] result = new T[size]; var typeSize = Marshal.SizeOf(typeof (T)); for (int i = 0; i < size; i++) { var currentPtr = Marshal.ReadIntPtr(ptr, typeSize*i); result[i] = (T)Marshal.PtrToStructure(currentPtr, typeof (T)); } return result; } } }
using System; using System.Runtime.InteropServices; namespace Urho { public static class MarshalHelper { public static unsafe float ReadSingle(this IntPtr ptr, int offset = 0) { if (sizeof (IntPtr) == sizeof (int)) { var value32 = Marshal.ReadInt32(ptr, offset); return *(float*)&value32; } var value64 = Marshal.ReadInt64(ptr, offset); return (float)*(double*) &value64; } public static float[] ToFloatsArray(this IntPtr ptr, int size) { float[] result = new float[size]; Marshal.Copy(ptr, result, 0, size); return result; } public static byte[] ToBytesArray(this IntPtr ptr, int size) { byte[] result = new byte[size]; Marshal.Copy(ptr, result, 0, size); return result; } public static int[] ToIntsArray(this IntPtr ptr, int size) { int[] result = new int[size]; Marshal.Copy(ptr, result, 0, size); return result; } public static T[] ToStructsArray<T>(this IntPtr ptr, int size) where T : struct { T[] result = new T[size]; var typeSize = Marshal.SizeOf(typeof (T)); for (int i = 0; i < size; i++) { var currentPtr = Marshal.ReadIntPtr(ptr, typeSize*i); result[i] = (T)Marshal.PtrToStructure(currentPtr, typeof (T)); } return result; } } }
mit
C#
ea8ad79bcf193a47c42b875419686b9db32602c8
Update AssemblyInfo.cs
Shy07/Desktop
Desktop/Properties/AssemblyInfo.cs
Desktop/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Desktop")] [assembly: AssemblyDescription("An assistant who helps your Windows 8 or 8.1 desktop more clean.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Lynch Sherry")] [assembly: AssemblyProduct("Desktop")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("724da098-6785-4081-830b-ab9d9205ef99")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.0.1")] [assembly: AssemblyFileVersion("1.2.0.1")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Desktop")] [assembly: AssemblyDescription("An assistant who makes your Windows 8 or 8.1 desktop more clean")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Lynch Sherry")] [assembly: AssemblyProduct("Desktop")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("724da098-6785-4081-830b-ab9d9205ef99")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.0.1")] [assembly: AssemblyFileVersion("1.2.0.1")]
mit
C#
1fd524ada1078de4afd694a0c95a25edfa6061ae
Fix resource leak that occurred when any GFX files were missing from GFX folder
ethanmoffat/EndlessClient
EOLib.Graphics/PEFileCollection.cs
EOLib.Graphics/PEFileCollection.cs
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System; using System.Collections.Generic; using System.IO; using PELoaderLib; namespace EOLib.Graphics { public sealed class PEFileCollection : Dictionary<GFXTypes, IPEFile>, IPEFileCollection { public void PopulateCollectionWithStandardGFX() { var gfxTypes = (GFXTypes[])Enum.GetValues(typeof(GFXTypes)); foreach (var type in gfxTypes) Add(type, CreateGFXFile(type)); } private IPEFile CreateGFXFile(GFXTypes file) { var number = ((int)file).ToString("D3"); var fName = Path.Combine("gfx", "gfx" + number + ".egf"); return new PEFile(fName); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~PEFileCollection() { Dispose(false); } private void Dispose(bool disposing) { if (disposing) foreach (var pair in this) pair.Value.Dispose(); } } public interface IPEFileCollection : IDictionary<GFXTypes, IPEFile>, IDisposable { void PopulateCollectionWithStandardGFX(); } }
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System; using System.Collections.Generic; using System.IO; using System.Linq; using PELoaderLib; namespace EOLib.Graphics { public sealed class PEFileCollection : Dictionary<GFXTypes, IPEFile>, IPEFileCollection { public void PopulateCollectionWithStandardGFX() { var gfxTypes = Enum.GetValues(typeof(GFXTypes)).OfType<GFXTypes>(); var modules = gfxTypes.ToDictionary(type => type, CreateGFXFile); foreach(var modulePair in modules) Add(modulePair.Key, modulePair.Value); } private IPEFile CreateGFXFile(GFXTypes file) { var number = ((int)file).ToString("D3"); var fName = Path.Combine("gfx", "gfx" + number + ".egf"); return new PEFile(fName); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~PEFileCollection() { Dispose(false); } private void Dispose(bool disposing) { if (disposing) foreach (var pair in this) pair.Value.Dispose(); } } public interface IPEFileCollection : IDictionary<GFXTypes, IPEFile>, IDisposable { void PopulateCollectionWithStandardGFX(); } }
mit
C#
7d969bfb3dda5cf8abc7da89641f4fd9be69b048
add route
zhouyongtao/my_aspnetmvc_learning,zhouyongtao/my_aspnetmvc_learning
my_aspnetmvc_learning/Controllers/RouteController.cs
my_aspnetmvc_learning/Controllers/RouteController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace my_aspnetmvc_learning.Controllers { /// <summary> /// http://diaosbook.com/Post/2013/10/22/attribute-routing-in-asp-net-mvc-5 /// </summary> public class RouteController : Controller { // // GET: /Route/ public ActionResult Index() { return View(); } // eg: /books // eg: /books/1430210079 [Route("books/{isbn?}")] public ActionResult View(string isbn) { return View(); } // eg: /books/lang // eg: /books/lang/en // eg: /books/lang/he [Route("books/lang/{lang=en}")] public ActionResult ViewByLanguage(string lang) { return View(); } [Route("attribute-routing-in-asp-net-mvc-5")] public ActionResult Hotel() { return Content("http://diaosbook.com/Post/2013/10/22/attribute-routing-in-asp-net-mvc-5"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace my_aspnetmvc_learning.Controllers { /// <summary> /// http://diaosbook.com/Post/2013/10/22/attribute-routing-in-asp-net-mvc-5 /// </summary> public class RouteController : Controller { // // GET: /Route/ public ActionResult Index() { return View(); } // eg: /books // eg: /books/1430210079 [Route("books/{isbn?}")] public ActionResult View(string isbn) { return View(); } // eg: /books/lang // eg: /books/lang/en // eg: /books/lang/he [Route("books/lang/{lang=en}")] public ActionResult ViewByLanguage(string lang) { return View(); } [Route("attribute-routing-in-asp-net-mvc-5")] public ActionResult Hotel() { return Content("http://diaosbook.com/Post/2013/10/22/attribute-routing-in-asp-net-mvc-5"); } } }
mit
C#
a9ff0b5317f19ec3e7257f1a21c7b613b06f3730
Make SlimMenu more opaque.
UselessToucan/osu,UselessToucan/osu,johnneijzen/osu,smoogipooo/osu,DrabWeb/osu,ZLima12/osu,DrabWeb/osu,NeoAdonis/osu,Frontear/osuKyzer,DrabWeb/osu,peppy/osu-new,naoey/osu,Nabile-Rahmani/osu,peppy/osu,ZLima12/osu,EVAST9919/osu,naoey/osu,smoogipoo/osu,ppy/osu,ppy/osu,peppy/osu,smoogipoo/osu,johnneijzen/osu,ppy/osu,naoey/osu,NeoAdonis/osu,EVAST9919/osu,peppy/osu,2yangk23/osu,Drezi126/osu,UselessToucan/osu,smoogipoo/osu,Damnae/osu,2yangk23/osu,NeoAdonis/osu
osu.Game/Overlays/SearchableList/SlimEnumDropdown.cs
osu.Game/Overlays/SearchableList/SlimEnumDropdown.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using OpenTK.Graphics; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays.SearchableList { public class SlimEnumDropdown<T> : OsuEnumDropdown<T> { protected override DropdownHeader CreateHeader() => new SlimDropdownHeader { AccentColour = AccentColour }; protected override Menu CreateMenu() => new SlimMenu(); private class SlimDropdownHeader : OsuDropdownHeader { public SlimDropdownHeader() { Height = 25; Icon.TextSize = 16; Foreground.Padding = new MarginPadding { Top = 4, Bottom = 4, Left = 8, Right = 4 }; } protected override void LoadComplete() { base.LoadComplete(); BackgroundColour = Color4.Black.Opacity(0.25f); } } private class SlimMenu : OsuMenu { public SlimMenu() { Background.Colour = Color4.Black.Opacity(0.7f); } } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using OpenTK.Graphics; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays.SearchableList { public class SlimEnumDropdown<T> : OsuEnumDropdown<T> { protected override DropdownHeader CreateHeader() => new SlimDropdownHeader { AccentColour = AccentColour }; protected override Menu CreateMenu() => new SlimMenu(); private class SlimDropdownHeader : OsuDropdownHeader { public SlimDropdownHeader() { Height = 25; Icon.TextSize = 16; Foreground.Padding = new MarginPadding { Top = 4, Bottom = 4, Left = 8, Right = 4 }; } protected override void LoadComplete() { base.LoadComplete(); BackgroundColour = Color4.Black.Opacity(0.25f); } } private class SlimMenu : OsuMenu { public SlimMenu() { Background.Colour = Color4.Black.Opacity(0.25f); } } } }
mit
C#
f0ebbb1807aaf293751bce16c6c08c7bae15ea6d
Rewrite toolbar test scene and add test cases
peppy/osu,ppy/osu,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu-new,UselessToucan/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu
osu.Game.Tests/Visual/Menus/TestSceneToolbar.cs
osu.Game.Tests/Visual/Menus/TestSceneToolbar.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics.Containers; using osu.Framework.Testing; using osu.Game.Overlays.Toolbar; using osu.Game.Rulesets; using osuTK.Input; namespace osu.Game.Tests.Visual.Menus { [TestFixture] public class TestSceneToolbar : OsuManualInputManagerTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(ToolbarButton), typeof(ToolbarRulesetSelector), typeof(ToolbarRulesetTabButton), typeof(ToolbarNotificationButton), }; private Toolbar toolbar; [Resolved] private RulesetStore rulesets { get; set; } [SetUp] public void SetUp() => Schedule(() => { Child = toolbar = new Toolbar { State = { Value = Visibility.Visible } }; }); [Test] public void TestNotificationCounter() { ToolbarNotificationButton notificationButton = null; AddStep("retrieve notification button", () => notificationButton = toolbar.ChildrenOfType<ToolbarNotificationButton>().Single()); setNotifications(1); setNotifications(2); setNotifications(3); setNotifications(0); setNotifications(144); void setNotifications(int count) => AddStep($"set notification count to {count}", () => notificationButton.NotificationCount.Value = count); } [TestCase(false)] [TestCase(true)] public void TestRulesetSwitchingShortcut(bool toolbarHidden) { ToolbarRulesetSelector rulesetSelector = null; if (toolbarHidden) AddStep("hide toolbar", () => toolbar.Hide()); AddStep("retrieve ruleset selector", () => rulesetSelector = toolbar.ChildrenOfType<ToolbarRulesetSelector>().Single()); for (int i = 0; i < 4; i++) { var expected = rulesets.AvailableRulesets.ElementAt(i); var numberKey = Key.Number1 + i; AddStep($"switch to ruleset {i} via shortcut", () => { InputManager.PressKey(Key.ControlLeft); InputManager.PressKey(numberKey); InputManager.ReleaseKey(Key.ControlLeft); InputManager.ReleaseKey(numberKey); }); AddUntilStep("ruleset switched", () => rulesetSelector.Current.Value.Equals(expected)); } } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Graphics.Containers; using osu.Game.Overlays.Toolbar; namespace osu.Game.Tests.Visual.Menus { [TestFixture] public class TestSceneToolbar : OsuTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(ToolbarButton), typeof(ToolbarRulesetSelector), typeof(ToolbarRulesetTabButton), typeof(ToolbarNotificationButton), }; public TestSceneToolbar() { var toolbar = new Toolbar { State = { Value = Visibility.Visible } }; ToolbarNotificationButton notificationButton = null; AddStep("create toolbar", () => { Add(toolbar); notificationButton = toolbar.Children.OfType<FillFlowContainer>().Last().Children.OfType<ToolbarNotificationButton>().First(); }); void setNotifications(int count) => AddStep($"set notification count to {count}", () => notificationButton.NotificationCount.Value = count); setNotifications(1); setNotifications(2); setNotifications(3); setNotifications(0); setNotifications(144); } } }
mit
C#
9a466d97ede2d44095df61c468455861f8b20104
Add texts to make test more visually confirmable, add no parallax screen.
EVAST9919/osu,DrabWeb/osu,2yangk23/osu,ppy/osu,smoogipooo/osu,peppy/osu-new,johnneijzen/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,ZLima12/osu,EVAST9919/osu,johnneijzen/osu,2yangk23/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,DrabWeb/osu,peppy/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,peppy/osu,ZLima12/osu,DrabWeb/osu
osu.Game.Tests/Visual/TestCaseOsuScreenStack.cs
osu.Game.Tests/Visual/TestCaseOsuScreenStack.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. 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.Sprites; using osu.Framework.Screens; using osu.Framework.Testing; using osu.Game.Graphics.Containers; using osu.Game.Screens; using osu.Game.Screens.Play; using osuTK.Graphics; namespace osu.Game.Tests.Visual { [TestFixture] public class TestCaseOsuScreenStack : OsuTestCase { private NoParallaxTestScreen baseScreen; private TestOsuScreenStack stack; [SetUpSteps] public void Setup() { AddStep("Create new screen stack", () => { Child = stack = new TestOsuScreenStack { RelativeSizeAxes = Axes.Both }; }); AddStep("Push new base screen", () => stack.Push(baseScreen = new NoParallaxTestScreen("THIS IS SCREEN 1. THIS SCREEN SHOULD HAVE NO PARALLAX."))); } [Test] public void ParallaxAssignmentTest() { AddStep("Push new screen to base screen", () => baseScreen.Push(new TestScreen("THIS IS SCREEN 2. THIS SCREEN SHOULD HAVE PARALLAX."))); AddAssert("Parallax is correct", () => stack.IsParallaxSet); AddStep("Exit from new screen", () => { baseScreen.MakeCurrent(); }); AddAssert("Parallax is correct", () => stack.IsParallaxSet); } private class TestScreen : ScreenWithBeatmapBackground { private readonly string screenText; public TestScreen(string screenText) { this.screenText = screenText; } [BackgroundDependencyLoader] private void load() { AddInternal(new SpriteText { Text = screenText, Colour = Color4.White }); } } private class NoParallaxTestScreen : TestScreen { public NoParallaxTestScreen(string screenText) : base(screenText) { } public override float BackgroundParallaxAmount => 0.0f; } private class TestOsuScreenStack : OsuScreenStack { public bool IsParallaxSet => ParallaxAmount == ((TestScreen)CurrentScreen).BackgroundParallaxAmount * ParallaxContainer.DEFAULT_PARALLAX_AMOUNT; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. 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.Screens; using osu.Framework.Testing; using osu.Game.Graphics.Containers; using osu.Game.Screens; using osu.Game.Screens.Play; namespace osu.Game.Tests.Visual { [TestFixture] public class TestCaseOsuScreenStack : OsuTestCase { private TestScreen baseScreen; private TestOsuScreenStack stack; [SetUpSteps] public void Setup() { AddStep("Create new screen stack", () => { Child = stack = new TestOsuScreenStack { RelativeSizeAxes = Axes.Both }; }); AddStep("Push new base screen", () => stack.Push(baseScreen = new TestScreen())); } [Test] public void ParallaxAssignmentTest() { AddStep("Push new screen to base screen", () => baseScreen.Push(new TestScreen())); AddAssert("Parallax is correct", () => stack.IsParallaxSet); AddStep("Exit from new screen", () => { baseScreen.MakeCurrent(); }); AddAssert("Parallax is correct", () => stack.IsParallaxSet); } private class TestScreen : ScreenWithBeatmapBackground { } private class TestOsuScreenStack : OsuScreenStack { public bool IsParallaxSet => ParallaxAmount == ((TestScreen)CurrentScreen).BackgroundParallaxAmount * ParallaxContainer.DEFAULT_PARALLAX_AMOUNT; } } }
mit
C#
512be2a1dc63716c2a8f0d69359abde7445af76b
add override for webhook name
Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns
TCC.Core/Interop/Discord.cs
TCC.Core/Interop/Discord.cs
using System; using System.Net; using System.Text; using FoglioUtils; using Newtonsoft.Json.Linq; using TCC.Utils; namespace TCC.Interop { public static class Discord { public static async void FireWebhook(string webhook, string message, string usernameOverride = "") { if (!await Firebase.RequestWebhookExecution(webhook)) return; var msg = new JObject { {"content", message}, {"username", string.IsNullOrEmpty(usernameOverride) ? App.AppVersion : usernameOverride}, {"avatar_url", "http://i.imgur.com/8IltuVz.png" } }; try { using (var client = MiscUtils.GetDefaultWebClient()) { client.Encoding = Encoding.UTF8; client.Headers.Add(HttpRequestHeader.ContentType, "application/json"); client.UploadString(webhook, "POST", msg.ToString()); } } catch (Exception e) { WindowManager.ViewModels.NotificationAreaVM.Enqueue("TCC Discord notifier", "Failed to send Discord notification.", NotificationType.Error); Log.F($"Failed to execute webhook: {e}"); } } } }
using System; using System.Net; using System.Text; using FoglioUtils; using Newtonsoft.Json.Linq; using TCC.Utils; namespace TCC.Interop { public static class Discord { public static async void FireWebhook(string webhook, string message) { if (!await Firebase.RequestWebhookExecution(webhook)) return; var msg = new JObject { {"content", message}, {"username", App.AppVersion }, {"avatar_url", "http://i.imgur.com/8IltuVz.png" } }; try { using (var client = MiscUtils.GetDefaultWebClient()) { client.Encoding = Encoding.UTF8; client.Headers.Add(HttpRequestHeader.ContentType, "application/json"); client.UploadString(webhook, "POST", msg.ToString()); } } catch (Exception e) { WindowManager.ViewModels.NotificationAreaVM.Enqueue("TCC Discord notifier", "Failed to send Discord notification.", NotificationType.Error); Log.F($"Failed to execute webhook: {e}"); } } } }
mit
C#
a751a17cce6ce3889c6b72f94a377f2105af0184
update version
DerAtrox/Beer.NET
Beer.NET/Properties/AssemblyInfo.cs
Beer.NET/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("Beer.NET")] [assembly: AssemblyDescription("Beer implementation for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("DerAtrox.de")] [assembly: AssemblyProduct("Beer.NET")] [assembly: AssemblyCopyright("Copyright by DerAtrox.de")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a6323a30-ca72-4366-9a0a-89f11aa4ab85")] // 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("0.2.0")] [assembly: AssemblyFileVersion("0.2.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Beer.NET")] [assembly: AssemblyDescription("Beer implementation for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("DerAtrox.de")] [assembly: AssemblyProduct("Beer.NET")] [assembly: AssemblyCopyright("Copyright by DerAtrox.de")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a6323a30-ca72-4366-9a0a-89f11aa4ab85")] // 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("0.1.7")] [assembly: AssemblyFileVersion("0.1.7")]
mit
C#
321920bc857b07f1359ac0407a080c56f2815a6c
Remove one more nullable disable
ppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu,peppy/osu
osu.Game/Overlays/Settings/Sections/MaintenanceSection.cs
osu.Game/Overlays/Settings/Sections/MaintenanceSection.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Localisation; using osu.Game.Localisation; using osu.Game.Overlays.Settings.Sections.Maintenance; namespace osu.Game.Overlays.Settings.Sections { public class MaintenanceSection : SettingsSection { public override LocalisableString Header => MaintenanceSettingsStrings.MaintenanceSectionHeader; public override Drawable CreateIcon() => new SpriteIcon { Icon = FontAwesome.Solid.Wrench }; public MaintenanceSection() { Children = new Drawable[] { new BeatmapSettings(), new SkinSettings(), new CollectionsSettings(), new ScoreSettings() }; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. 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.Graphics.Sprites; using osu.Framework.Localisation; using osu.Game.Localisation; using osu.Game.Overlays.Settings.Sections.Maintenance; namespace osu.Game.Overlays.Settings.Sections { public class MaintenanceSection : SettingsSection { public override LocalisableString Header => MaintenanceSettingsStrings.MaintenanceSectionHeader; public override Drawable CreateIcon() => new SpriteIcon { Icon = FontAwesome.Solid.Wrench }; public MaintenanceSection() { Children = new Drawable[] { new BeatmapSettings(), new SkinSettings(), new CollectionsSettings(), new ScoreSettings() }; } } }
mit
C#
143cf6d87ec81851551a50cea3dbfa3d5261fd1f
Remove dangling references when deleting pooled objects from editor.
dimixar/audio-controller-unity
AudioController/Assets/Source/ObjectPool.cs
AudioController/Assets/Source/ObjectPool.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectPool : MonoBehaviour { #region Public fields public List<PrefabBasedPool> pools; #endregion #region Public methods and properties public GameObject GetFreeObject(GameObject prefab = null) { if (prefab == null) return null; PrefabBasedPool pool = pools.Find((x) => { return x.prefab == prefab; }); if (pool != null) return pool.GetFreeObject(); pool = new PrefabBasedPool(prefab); GameObject parent = new GameObject(); parent.transform.parent = this.gameObject.transform; pool.parent = parent.transform; pools.Add(pool); return pool.GetFreeObject(); } #endregion #region Monobehaviour methods /// <summary> /// Awake is called when the script instance is being loaded. /// </summary> void Awake() { pools = new List<PrefabBasedPool>(); } #endregion } [System.Serializable] public class PrefabBasedPool { public PrefabBasedPool(GameObject prefab) { pool = new List<GameObject>(); this.prefab = prefab; } public GameObject prefab; public List<GameObject> pool; /// <summary> /// Where pooled objects will reside. /// </summary> public Transform parent; public GameObject GetFreeObject() { GameObject freeObj = pool.Find((x) => { if (x == null) { pool.Remove(x); return false; } var poolable = x.GetComponent<IPoolable>(); return poolable.IsFree(); }); if (freeObj != null) return freeObj; var obj = GameObject.Instantiate(prefab, Vector3.zero, Quaternion.identity, parent); pool.Add(obj); return obj; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectPool : MonoBehaviour { #region Public fields public List<PrefabBasedPool> pools; #endregion #region Public methods and properties public GameObject GetFreeObject(GameObject prefab = null) { if (prefab == null) return null; PrefabBasedPool pool = pools.Find((x) => { return x.prefab == prefab; }); if (pool != null) return pool.GetFreeObject(); pool = new PrefabBasedPool(prefab); GameObject parent = new GameObject(); parent.transform.parent = this.gameObject.transform; pool.parent = parent.transform; pools.Add(pool); return pool.GetFreeObject(); } #endregion #region Monobehaviour methods /// <summary> /// Awake is called when the script instance is being loaded. /// </summary> void Awake() { pools = new List<PrefabBasedPool>(); } #endregion } [System.Serializable] public class PrefabBasedPool { public PrefabBasedPool(GameObject prefab) { pool = new List<GameObject>(); this.prefab = prefab; } public GameObject prefab; public List<GameObject> pool; /// <summary> /// Where pooled objects will reside. /// </summary> public Transform parent; public GameObject GetFreeObject() { GameObject freeObj = pool.Find((x) => { var poolable = x.GetComponent<IPoolable>(); return poolable.IsFree(); }); if (freeObj != null) return freeObj; var obj = GameObject.Instantiate(prefab, Vector3.zero, Quaternion.identity, parent); pool.Add(obj); return obj; } }
mit
C#
b8a4524d3a9178bcb70dbe0f541be425cd33b9a9
fix missing useragent header
kaedei/aliyun-ddns-client-csharp
Kaedei.AliyunDDNSClient/Program.cs
Kaedei.AliyunDDNSClient/Program.cs
using System; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text.RegularExpressions; using System.Threading; using Aliyun.Api; using Aliyun.Api.DNS.DNS20150109.Request; using Newtonsoft.Json; namespace Kaedei.AliyunDDNSClient { class Program { private static void Main(string[] args) { try { var configs = File.ReadAllLines("config.txt"); var accessKeyId = configs[0].Trim(); //Access Key ID,如 DR2DPjKmg4ww0e79 var accessKeySecret = configs[1].Trim(); //Access Key Secret,如 ysHnd1dhWvoOmbdWKx04evlVEdXEW7 var domainName = configs[2].Trim(); //域名,如 google.com var rr = configs[3].Trim(); //子域名,如 www Console.WriteLine("Updating {0} of domain {1}", rr, domainName); var aliyunClient = new DefaultAliyunClient("http://dns.aliyuncs.com/", accessKeyId, accessKeySecret); var req = new DescribeDomainRecordsRequest() { DomainName = domainName }; var response = aliyunClient.Execute(req); var updateRecord = response.DomainRecords.FirstOrDefault(rec => rec.RR == rr && rec.Type == "A"); if (updateRecord == null) return; Console.WriteLine("Domain record IP is " + updateRecord.Value); //获取IP var httpClient = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.None, }); httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(new ProductHeaderValue("aliyun-ddns-client-csharp"))); var htmlSource = httpClient.GetStringAsync("http://www.ip.cn/").Result; var ip = Regex.Match(htmlSource, @"(?<=<code>)[\d\.]+(?=</code>)", RegexOptions.IgnoreCase).Value; Console.WriteLine("Current IP is " + ip); if (updateRecord.Value != ip) { var changeValueRequest = new UpdateDomainRecordRequest() { RecordId = updateRecord.RecordId, Value = ip, Type = "A", RR = rr }; aliyunClient.Execute(changeValueRequest); Console.WriteLine("Update finished."); } else { Console.WriteLine("IPs are same now. Exiting"); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Thread.Sleep(5000); } } }
using System; using System.IO; using System.Linq; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading; using Aliyun.Api; using Aliyun.Api.DNS.DNS20150109.Request; using Newtonsoft.Json; namespace Kaedei.AliyunDDNSClient { class Program { private static void Main(string[] args) { try { var configs = File.ReadAllLines("config.txt"); var accessKeyId = configs[0].Trim(); //Access Key ID,如 DR2DPjKmg4ww0e79 var accessKeySecret = configs[1].Trim(); //Access Key Secret,如 ysHnd1dhWvoOmbdWKx04evlVEdXEW7 var domainName = configs[2].Trim(); //域名,如 google.com var rr = configs[3].Trim(); //子域名,如 www Console.WriteLine("Updating {0} of domain {1}", rr, domainName); var aliyunClient = new DefaultAliyunClient("http://dns.aliyuncs.com/", accessKeyId, accessKeySecret); var req = new DescribeDomainRecordsRequest() { DomainName = domainName }; var response = aliyunClient.Execute(req); var updateRecord = response.DomainRecords.FirstOrDefault(rec => rec.RR == rr && rec.Type == "A"); if (updateRecord == null) return; Console.WriteLine("Domain record IP is " + updateRecord.Value); //获取IP var htmlSource = new HttpClient().GetStringAsync("http://www.ip.cn/").Result; var ip = Regex.Match(htmlSource, @"(?<=<code>)[\d\.]+(?=</code>)", RegexOptions.IgnoreCase).Value; Console.WriteLine("Current IP is " + ip); if (updateRecord.Value != ip) { var changeValueRequest = new UpdateDomainRecordRequest() { RecordId = updateRecord.RecordId, Value = ip, Type = "A", RR = rr }; aliyunClient.Execute(changeValueRequest); Console.WriteLine("Update finished."); } else { Console.WriteLine("IPs are same now. Exiting"); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Thread.Sleep(5000); } } }
apache-2.0
C#
c212f53d196ba6a3f60a84fe69e20ad1337b8301
Add missing xmldoc
ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework
osu.Framework/Threading/GameThreadSynchronizationContext.cs
osu.Framework/Threading/GameThreadSynchronizationContext.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Diagnostics; using System.Threading; #nullable enable namespace osu.Framework.Threading { /// <summary> /// A synchronisation context which posts all continuations to an isolated scheduler instance. /// </summary> /// <remarks> /// This implementation roughly follows the expectations set out for winforms/WPF as per /// https://docs.microsoft.com/en-us/archive/msdn-magazine/2011/february/msdn-magazine-parallel-computing-it-s-all-about-the-synchronizationcontext. /// - Calls to <see cref="Post"/> are guaranteed to run asynchronously. /// - Calls to <see cref="Send"/> will run inline when they can. /// - Order of execution is guaranteed (in our case, it is guaranteed over <see cref="Send"/> and <see cref="Post"/> calls alike). /// - To enforce the above, calling <see cref="Send"/> will flush any pending work until the newly queued item has been completed. /// </remarks> internal class GameThreadSynchronizationContext : SynchronizationContext { /// <summary> /// The total tasks this synchronization context has run. /// </summary> public int TotalTasksRun => scheduler.TotalTasksRun; private readonly Scheduler scheduler; public GameThreadSynchronizationContext(GameThread gameThread) { scheduler = new GameThreadScheduler(gameThread); } public override void Send(SendOrPostCallback callback, object? state) { var scheduledDelegate = scheduler.Add(() => callback(state)); Debug.Assert(scheduledDelegate != null); while (scheduledDelegate.State < ScheduledDelegate.RunState.Complete) { if (scheduler.IsMainThread) scheduler.Update(); else Thread.Sleep(1); } } public override void Post(SendOrPostCallback callback, object? state) => scheduler.Add(() => callback(state)); /// <summary> /// Run any pending work queued against this synchronization context. /// </summary> public void RunWork() => scheduler.Update(); } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Diagnostics; using System.Threading; #nullable enable namespace osu.Framework.Threading { /// <summary> /// A synchronisation context which posts all continuations to an isolated scheduler instance. /// </summary> /// <remarks> /// This implementation roughly follows the expectations set out for winforms/WPF as per /// https://docs.microsoft.com/en-us/archive/msdn-magazine/2011/february/msdn-magazine-parallel-computing-it-s-all-about-the-synchronizationcontext. /// - Calls to <see cref="Post"/> are guaranteed to run asynchronously. /// - Calls to <see cref="Send"/> will run inline when they can. /// - Order of execution is guaranteed (in our case, it is guaranteed over <see cref="Send"/> and <see cref="Post"/> calls alike). /// - To enforce the above, calling <see cref="Send"/> will flush any pending work until the newly queued item has been completed. /// </remarks> internal class GameThreadSynchronizationContext : SynchronizationContext { private readonly Scheduler scheduler; public int TotalTasksRun => scheduler.TotalTasksRun; public GameThreadSynchronizationContext(GameThread gameThread) { scheduler = new GameThreadScheduler(gameThread); } public override void Send(SendOrPostCallback callback, object? state) { var scheduledDelegate = scheduler.Add(() => callback(state)); Debug.Assert(scheduledDelegate != null); while (scheduledDelegate.State < ScheduledDelegate.RunState.Complete) { if (scheduler.IsMainThread) scheduler.Update(); else Thread.Sleep(1); } } public override void Post(SendOrPostCallback callback, object? state) => scheduler.Add(() => callback(state)); public void RunWork() => scheduler.Update(); } }
mit
C#
e3e64a818f67e57b851ee81aa1d5a6cd7cf8bf2a
fix typo
joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net
Joinrpg/App_Code/RouteHelper.cshtml
Joinrpg/App_Code/RouteHelper.cshtml
@using JoinRpg.Web.App_Code @using JoinRpg.Web.Helpers @helper GetUrl(RouteTarget target) { @target.GetUri(MvcIntrinsics.Url) } @functions { public static HtmlString GetFullHostName() { return new HtmlString(Request.Url.Scheme + "://" + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port)); } }
@using JoinRpg.Web.App_Code @using JoinRpg.Web.Helpers @helper GetUrl(RouteTarget target) { @target.GetUri(MvcIntrinsics.Url) } @functions { public static HtmlString GetFullHostName() { return new HtmlString(Request.Url.Scheme + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port)); } }
mit
C#
f48ce18439c74354060d1d88cceb35543961e6c5
Update PBU-Main-Future.cs
win120a/ACClassRoomUtil,win120a/ACClassRoomUtil
ProcessBlockUtil/PBU-Main-Future.cs
ProcessBlockUtil/PBU-Main-Future.cs
/* THIS IS ONLY TO EASY CHANGE, NOT THE PROJECT CODE AT NOW. (I will use in the future.) Copyright (C) 2011-2014 AC Inc. (Andy Cheung) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.IO; using System.Diagnostics; using System.ServiceProcess; using System.Threading; using System.Collections; namespace ACProcessBlockUtil { class Run:ServiceBase { SteamReader sr; ArrayList<String> al; String[] list; public static void kill() { while (true) { Process[] ieProcArray = Process.GetProcessesByName("iexplore"); //Console.WriteLine(ieProcArray.Length); if (ieProcArray.Length == 0) { continue; } foreach(Process p in ieProcArray){ p.Kill(); } Thread.Sleep(2000); } } public static void Main(String[] a) { String userProfile = Environment.GetEnvironmentVariable("UserProfile"); String systemRoot = Environment.GetEnvironmentVariable("SystemRoot"); if(File.Exists(userProfile + "\\ACRules.txt")){ ar = new ArrayList<String>(); sr = new SteamReader(userProfile + "\\ACRules.txt"); while(true){ String tempLine = sr.ReadLine(); if(tempLine == null){ break; } else{ ar.Add(tempLine); } } list = (String) ar.ToArray(); } else{ list = {"iexplore", "360se", "qqbrowser"} } ServiceBase.Run(new Run()); } protected override void OnStart(String[] a){ Thread t = new Thread(new ThreadStart(kill)); t.IsBackground = true; t.Start(); } } }
/* THIS IS ONLY TO EASY CHANGE, NOT THE PROJECT CODE AT NOW. (I will use in the future.) Copyright (C) 2011-2014 AC Inc. (Andy Cheung) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.IO; using System.Diagnostics; using System.ServiceProcess; using System.Threading; using System.Collections; namespace ACProcessBlockUtil { class Run:ServiceBase { SteamReader sr; ArrayList<String> al; String[] list; public static void kill() { while (true) { Process[] ieProcArray = Process.GetProcessesByName("iexplore"); //Console.WriteLine(ieProcArray.Length); if (ieProcArray.Length == 0) { continue; } foreach(Process p in ieProcArray){ p.Kill(); } Thread.Sleep(2000); } } public static void Main(String[] a) { String userProfile = Environment.GetEnvironmentVariable("UserProfile"); String systemRoot = Environment.GetEnvironmentVariable("SystemRoot"); if(File.Exists(userProfile + "\\ACRules.txt")){ ar = new ArrayList<String>(); sr = new SteamReader(userProfile + "\\ACRules.txt"); while(true){ String tempLine = sr.ReadLine(); if(tempLine == null){ break; } else{ ar.Add(tempLine); } } list = (String) ar.ToArray(); } else{ list = {"iexplore", "360se", "qqbrowser"} } ServiceBase.Run(new Run()); } protected override void OnStart(String[] a){ Thread t = new Thread(new ThreadStart(kill)); t.IsBackground = true; t.Start(); } } }
apache-2.0
C#
1d4e5e0e150d4c481f221a8bd0ae45830374c4d1
Update example project
fedoaa/SimpleTwitchBot
SimpleTwitchBot.Example/Program.cs
SimpleTwitchBot.Example/Program.cs
using SimpleTwitchBot.Lib; using SimpleTwitchBot.Lib.Events; using System; using System.Threading.Tasks; namespace SimpleTwitchBot.Example { class Program { static void Main(string[] args) => MainAsync(args).GetAwaiter().GetResult(); private static async Task MainAsync(string[] args) { using (var client = new TwitchIrcClient("irc.chat.twitch.tv", 6667)) { client.LoggedIn += Client_LoggedIn; client.ChannelJoined += Client_ChannelJoined; client.UserJoined += Client_UserJoined; client.IrcMessageReceived += Client_IrcMessageReceived; client.ChatMessageReceived += Client_ChatMessageReceived; client.UserSubscribed += Client_UserSubscribed; client.Disconnected += Client_Disconnected; await client.ConnectAsync("username", "oauth:token"); Console.ReadLine(); client.Disconnect(); } Console.ReadLine(); } private static void Client_LoggedIn(object sender, EventArgs e) { var client = sender as TwitchIrcClient; client?.JoinChannel("#channelName"); } private static void Client_ChannelJoined(object sender, ChannelJoinedEventArgs e) { Console.WriteLine($"Joined {e.Channel}"); } private static void Client_UserJoined(object sender, UserJoinedEventArgs e) { Console.WriteLine($"{e.Username} has joined {e.Channel}"); } private static void Client_IrcMessageReceived(object sender, IrcMessageReceivedEventArgs e) { Console.WriteLine(e.Message.Raw); } private static void Client_ChatMessageReceived(object sender, ChatMessageReceivedEventArgs e) { Console.WriteLine($"{e.Message.Username}: {e.Message.Body}"); } private static void Client_UserSubscribed(object sender, UserSubscribedEventArgs e) { Console.WriteLine($"{e.Subscription.Username} just subscribed!"); } private static void Client_Disconnected(object sender, EventArgs e) { Console.WriteLine("Disconnected"); } } }
using SimpleTwitchBot.Lib; using SimpleTwitchBot.Lib.Events; using System; using System.Threading.Tasks; namespace SimpleTwitchBot.Example { class Program { static void Main(string[] args) { using (var client = new TwitchIrcClient("irc.chat.twitch.tv", 6667)) { client.LoggedIn += Client_LoggedIn; client.ChannelJoined += Client_ChannelJoined; client.UserJoined += Client_UserJoined; client.IrcMessageReceived += Client_IrcMessageReceived; client.ChatMessageReceived += Client_ChatMessageReceived; client.UserSubscribed += Client_UserSubscribed; client.Disconnected += Client_Disconnected; Task.Run(async () => await client.ConnectAsync("username", "oauth:token")); Console.ReadLine(); client.Disconnect(); } Console.ReadLine(); } private static void Client_LoggedIn(object sender, EventArgs e) { var client = sender as IrcClient; client?.JoinChannel("#channelName"); } private static void Client_ChannelJoined(object sender, ChannelJoinedEventArgs e) { Console.WriteLine($"Joined {e.Channel}"); } private static void Client_UserJoined(object sender, UserJoinedEventArgs e) { Console.WriteLine($"{e.Username} has joined {e.Channel}"); } private static void Client_IrcMessageReceived(object sender, IrcMessageReceivedEventArgs e) { Console.WriteLine(e.Message.Raw); } private static void Client_ChatMessageReceived(object sender, ChatMessageReceivedEventArgs e) { Console.WriteLine($"{e.Message.Username}: {e.Message.Body}"); } private static void Client_UserSubscribed(object sender, UserSubscribedEventArgs e) { Console.WriteLine($"{e.Subscription.Username} just subscribed!"); } private static void Client_Disconnected(object sender, EventArgs e) { Console.WriteLine("Disconnected"); } } }
mit
C#
1cd5f4eff446b5d7c1e7f7edad39936d0a0b8fa7
Use TOTAL_DAY_HOURS from TimeSlot
victoria92/university-program-generator,victoria92/university-program-generator
UniProgramGen/Data/Requirements.cs
UniProgramGen/Data/Requirements.cs
using System.Collections.Generic; using System.Linq; using UniProgramGen.Helpers; namespace UniProgramGen.Data { public class Requirements { public const uint TOTAL_WEEK_HOURS = 7 * TimeSlot.TOTAL_DAY_HOURS; public readonly double weight; public readonly List<Helpers.TimeSlot> availableTimeSlots; public readonly List<Room> requiredRooms; internal double internalWeight { get; private set; } public Requirements(double weight, List<Helpers.TimeSlot> availableTimeSlots, List<Room> requiredRooms) { this.weight = weight; this.availableTimeSlots = availableTimeSlots; this.requiredRooms = requiredRooms; } internal void CalculateInternalWeight(int roomsLength) { var availableTime = availableTimeSlots.Aggregate((uint) 0, (total, timeSlot) => total + timeSlot.EndHour - timeSlot.StartHour); internalWeight = ((availableTime / TOTAL_WEEK_HOURS) + (requiredRooms.Count / roomsLength)) / 2; } } }
using System.Collections.Generic; using UniProgramGen; using System.Linq; namespace UniProgramGen.Data { public class Requirements { public const uint TOTAL_HOURS = 15; public const uint TOTAL_WEEK_HOURS = 5 * TOTAL_HOURS; public readonly double weight; public readonly List<Helpers.TimeSlot> availableTimeSlots; public readonly List<Room> requiredRooms; internal double internalWeight { get; private set; } public Requirements(double weight, List<Helpers.TimeSlot> availableTimeSlots, List<Room> requiredRooms) { this.weight = weight; this.availableTimeSlots = availableTimeSlots; this.requiredRooms = requiredRooms; } internal void CalculateInternalWeight(int roomsLength) { var availableTime = availableTimeSlots.Aggregate((uint) 0, (total, timeSlot) => total + timeSlot.EndHour - timeSlot.StartHour); internalWeight = ((availableTime / TOTAL_WEEK_HOURS) + (requiredRooms.Count / roomsLength)) / 2; } } }
bsd-2-clause
C#
6d92745f661c90900f062bded2c8be7e3352687b
Add callback path for microsoft
umbraco/UmbracoIdentityExtensions
src/App_Start/UmbracoMicrosoftAuthExtensions.cs
src/App_Start/UmbracoMicrosoftAuthExtensions.cs
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System.Web; using Microsoft.Owin; using Owin; using Umbraco.Core; using Umbraco.Web.Security.Identity; using Microsoft.Owin.Security.MicrosoftAccount; namespace $rootnamespace$ { public static class UmbracoMicrosoftAuthExtensions { /// <summary> /// Configure microsoft account sign-in /// </summary> /// <param name="app"></param> /// <param name="clientId"></param> /// <param name="clientSecret"></param> /// <param name="caption"></param> /// <param name="style"></param> /// <param name="icon"></param> /// <remarks> /// /// Nuget installation: /// Microsoft.Owin.Security.MicrosoftAccount /// /// Microsoft account documentation for ASP.Net Identity can be found: /// /// http://www.asp.net/web-api/overview/security/external-authentication-services#MICROSOFT /// http://blogs.msdn.com/b/webdev/archive/2012/09/19/configuring-your-asp-net-application-for-microsoft-oauth-account.aspx /// /// Microsoft apps can be created here: /// /// http://go.microsoft.com/fwlink/?LinkID=144070 /// /// </remarks> public static void ConfigureBackOfficeMicrosoftAuth(this IAppBuilder app, string clientId, string clientSecret, string caption = "Microsoft", string style = "btn-microsoft", string icon = "fa-windows") { var msOptions = new MicrosoftAccountAuthenticationOptions { ClientId = clientId, ClientSecret = clientSecret, SignInAsAuthenticationType = Constants.Security.BackOfficeExternalAuthenticationType, CallbackPath = new PathString("/umbraco-microsoft-signin") }; msOptions.ForUmbracoBackOffice(style, icon); msOptions.Caption = caption; app.UseMicrosoftAccountAuthentication(msOptions); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System.Web; using Microsoft.Owin; using Owin; using Umbraco.Core; using Umbraco.Web.Security.Identity; using Microsoft.Owin.Security.MicrosoftAccount; namespace $rootnamespace$ { public static class UmbracoMicrosoftAuthExtensions { /// <summary> /// Configure microsoft account sign-in /// </summary> /// <param name="app"></param> /// <param name="clientId"></param> /// <param name="clientSecret"></param> /// <param name="caption"></param> /// <param name="style"></param> /// <param name="icon"></param> /// <remarks> /// /// Nuget installation: /// Microsoft.Owin.Security.MicrosoftAccount /// /// Microsoft account documentation for ASP.Net Identity can be found: /// /// http://www.asp.net/web-api/overview/security/external-authentication-services#MICROSOFT /// http://blogs.msdn.com/b/webdev/archive/2012/09/19/configuring-your-asp-net-application-for-microsoft-oauth-account.aspx /// /// Microsoft apps can be created here: /// /// http://go.microsoft.com/fwlink/?LinkID=144070 /// /// </remarks> public static void ConfigureBackOfficeMicrosoftAuth(this IAppBuilder app, string clientId, string clientSecret, string caption = "Microsoft", string style = "btn-microsoft", string icon = "fa-windows") { var msOptions = new MicrosoftAccountAuthenticationOptions { ClientId = clientId, ClientSecret = clientSecret, SignInAsAuthenticationType = Constants.Security.BackOfficeExternalAuthenticationType }; msOptions.ForUmbracoBackOffice(style, icon); msOptions.Caption = caption; app.UseMicrosoftAccountAuthentication(msOptions); } } }
mit
C#
982069f775f16e5969e4c007b2b7bd6a4e531445
delete unused files
dotnetcore/CAP,dotnetcore/CAP,ouraspnet/cap,dotnetcore/CAP
src/Cap.Consistency.Server/ConsistencyServer.cs
src/Cap.Consistency.Server/ConsistencyServer.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.Logging; namespace Cap.Consistency.Server { public class ConsistencyServer : IServer { public ConsistencyServer(IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory) { if (applicationLifetime == null) { throw new ArgumentNullException(nameof(applicationLifetime)); } if (loggerFactory==null) { throw new ArgumentNullException(nameof(loggerFactory)); } } public void Start<TContext>(IHttpApplication<TContext> application) { throw new NotImplementedException(); } public IFeatureCollection Features { get; } public void Dispose() { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.Logging; namespace Cap.Consistency.Server { public class ConsistencyServer : IServer { public ConsistencyServer(IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory) { if (applicationLifetime == null) { throw new ArgumentNullException(nameof(applicationLifetime)); } if (loggerFactory==null) { throw new ArgumentNullException(nameof(loggerFactory)); } } public void Start<TContext>(IHttpApplication<TContext> application) { throw new NotImplementedException(); } public IFeatureCollection Features { get; } public void Dispose() { throw new NotImplementedException(); } } }
mit
C#
8acffbbed612ba2e0eacbb011d9fcfb1ef61637d
Add constructor to DataType.cs
Ackara/Daterpillar
src/Daterpillar.Core/Transformation/DataType.cs
src/Daterpillar.Core/Transformation/DataType.cs
using System; using System.Xml.Serialization; namespace Gigobyte.Daterpillar.Transformation { /// <summary> /// Represents a SQL type. /// </summary> public struct DataType : IEquatable<DataType> { #region Operators public static bool operator ==(DataType left, DataType right) { return left.Equals(right); } public static bool operator !=(DataType left, DataType right) { return !left.Equals(right); } #endregion Operators /// <summary> /// Initializes a new instance of the <see cref="DataType"/> struct. /// </summary> /// <param name="typeName">Name of the type.</param> public DataType(string typeName) : this() { Name = typeName; } /// <summary> /// Initializes a new instance of the <see cref="DataType"/> struct. /// </summary> /// <param name="typeName">Name of the type.</param> /// <param name="scale">The scale.</param> /// <param name="precision">The precision.</param> public DataType(string typeName, int scale, int precision) { Name = typeName; Scale = scale; Precision = precision; } /// <summary> /// Gets or sets the scale. /// </summary> /// <value>The scale.</value> [XmlAttribute("scale")] public int Scale { get; set; } /// <summary> /// Gets or sets the precision. /// </summary> /// <value>The precision.</value> [XmlAttribute("precision")] public int Precision { get; set; } /// <summary> /// Gets or sets the name. /// </summary> /// <value>The name.</value> [XmlText] public string Name { get; set; } public bool Equals(DataType other) { return Name == other.Name && Precision == other.Precision && Scale == other.Scale; } public override bool Equals(object obj) { if (obj is DataType) return Equals((DataType)obj); else return false; } public override int GetHashCode() { return Name.GetHashCode() ^ Precision.GetHashCode() ^ Scale.GetHashCode(); } } }
using System; using System.Xml.Serialization; namespace Gigobyte.Daterpillar.Transformation { /// <summary> /// Represents a SQL type. /// </summary> public struct DataType : IEquatable<DataType> { #region Operators public static bool operator ==(DataType left, DataType right) { return left.Equals(right); } public static bool operator !=(DataType left, DataType right) { return !left.Equals(right); } #endregion Operators /// <summary> /// Initializes a new instance of the <see cref="DataType"/> struct. /// </summary> /// <param name="typeName">Name of the type.</param> public DataType(string typeName) : this() { Name = typeName; } /// <summary> /// Gets or sets the scale. /// </summary> /// <value>The scale.</value> [XmlAttribute("scale")] public int Scale { get; set; } /// <summary> /// Gets or sets the precision. /// </summary> /// <value>The precision.</value> [XmlAttribute("precision")] public int Precision { get; set; } /// <summary> /// Gets or sets the name. /// </summary> /// <value>The name.</value> [XmlText] public string Name { get; set; } public bool Equals(DataType other) { return Name == other.Name && Precision == other.Precision && Scale == other.Scale; } public override bool Equals(object obj) { if (obj is DataType) return Equals((DataType)obj); else return false; } public override int GetHashCode() { return Name.GetHashCode() ^ Precision.GetHashCode() ^ Scale.GetHashCode(); } } }
mit
C#
d8ebda35a2b21c4fd21734244a3e3383adfa1d19
Improve JsonService with LINQ
arthurrump/Zermelo.API
Zermelo.API/Services/JsonService.cs
Zermelo.API/Services/JsonService.cs
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Zermelo.API.Services.Interfaces; namespace Zermelo.API.Services { internal class JsonService : IJsonService { public IEnumerable<T> DeserializeCollection<T>(string json) { JObject jsonResult = JObject.Parse(json); return jsonResult["response"]["data"].Children() .Select(token => JsonConvert.DeserializeObject<T>(token.ToString())); } public T GetValue<T>(string json, string key) { return JObject.Parse(json).Value<T>(key); } } }
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Zermelo.API.Services.Interfaces; namespace Zermelo.API.Services { internal class JsonService : IJsonService { public IEnumerable<T> DeserializeCollection<T>(string json) { JObject jsonResult = JObject.Parse(json); IEnumerable<JToken> jsonResults = jsonResult["response"]["data"].Children(); List<T> collection = new List<T>(); foreach (JToken t in jsonResults) { collection.Add(JsonConvert.DeserializeObject<T>(t.ToString())); } return collection; } public T GetValue<T>(string json, string key) { return JObject.Parse(json).Value<T>(key); } } }
mit
C#
59e375eb35ff4f9317e562755e41384b2fdace46
Optimize authentication validation
NicatorBa/Porthor
src/Porthor/ResourceRequestValidators/AuthorizationValidator.cs
src/Porthor/ResourceRequestValidators/AuthorizationValidator.cs
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Porthor.ResourceRequestValidators { /// <summary> /// Request validator for authorization by poliyies. /// </summary> public class AuthorizationValidator : IResourceRequestValidator { private readonly IEnumerable<string> _policies; /// <summary> /// Constructs a new instance of <see cref="AuthorizationValidator"/>. /// </summary> /// <param name="policies">Collection of policy names.</param> public AuthorizationValidator(IEnumerable<string> policies) { _policies = policies; } /// <summary> /// Validates the current <see cref="HttpContext"/> against policies. /// </summary> /// <param name="context">Current context.</param> /// <returns> /// The <see cref="Task{HttpRequestMessage}"/> that represents the asynchronous validation process. /// Returns null if the current user meets any policy. /// </returns> public async Task<HttpResponseMessage> ValidateAsync(HttpContext context) { IAuthorizationService authorizationService = (IAuthorizationService)context.RequestServices.GetService(typeof(IAuthorizationService)); if (authorizationService == null) { throw new InvalidOperationException(nameof(IAuthorizationService)); } foreach (var policy in _policies) { var result = await authorizationService.AuthorizeAsync(context.User, policy); if (result.Succeeded) { return null; } } return new HttpResponseMessage(HttpStatusCode.Forbidden); } } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Porthor.ResourceRequestValidators { /// <summary> /// Request validator for authorization by poliyies. /// </summary> public class AuthorizationValidator : IResourceRequestValidator { private readonly IEnumerable<string> _policies; /// <summary> /// Constructs a new instance of <see cref="AuthorizationValidator"/>. /// </summary> /// <param name="policies">Collection of policy names.</param> public AuthorizationValidator(IEnumerable<string> policies) { _policies = policies; } /// <summary> /// Validates the current <see cref="HttpContext"/> against policies. /// </summary> /// <param name="context">Current context.</param> /// <returns> /// The <see cref="Task{HttpRequestMessage}"/> that represents the asynchronous validation process. /// Returns null if the current user meets any policy. /// </returns> public async Task<HttpResponseMessage> ValidateAsync(HttpContext context) { IAuthorizationService authorizationService = (IAuthorizationService)context.RequestServices.GetService(typeof(IAuthorizationService)); if (authorizationService == null) { throw new InvalidOperationException(nameof(IAuthorizationService)); } bool authorized = false; foreach (var policy in _policies) { var result = await authorizationService.AuthorizeAsync(context.User, policy); if (result.Succeeded) { authorized = true; break; } } if (!authorized) { return new HttpResponseMessage(HttpStatusCode.Forbidden); } return null; } } }
apache-2.0
C#
a3a4a6105392443966c061144e522599354f5f65
add validation to resource name param
takenet/blip-sdk-csharp
src/Take.Blip.Builder/Variables/BaseResourceVariableProvider.cs
src/Take.Blip.Builder/Variables/BaseResourceVariableProvider.cs
using Lime.Protocol; using Lime.Protocol.Network; using Lime.Protocol.Serialization; using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using Take.Blip.Client; namespace Take.Blip.Builder.Variables { public class BaseResourceVariableProvider : IVariableProvider { private readonly ISender _sender; private readonly IDocumentSerializer _documentSerializer; protected readonly string _resourceName; public VariableSource Source => throw new NotImplementedException(); public BaseResourceVariableProvider(ISender sender, IDocumentSerializer documentSerializer, string resourceName) { _sender = sender; _documentSerializer = documentSerializer; _resourceName = resourceName ?? throw new ArgumentNullException(nameof(resourceName)); } public async Task<string> GetVariableAsync(string name, IContext context, CancellationToken cancellationToken) { try { var resourceCommandResult = await ExecuteGetResourceCommandAsync(name, cancellationToken); if (resourceCommandResult.Status != CommandStatus.Success) { return null; } if (!resourceCommandResult.Resource.GetMediaType().IsJson) { return resourceCommandResult.Resource.ToString(); } return _documentSerializer.Serialize(resourceCommandResult.Resource); } catch (LimeException ex) when (ex.Reason.Code == ReasonCodes.COMMAND_RESOURCE_NOT_FOUND) { return null; } } private async Task<Command> ExecuteGetResourceCommandAsync(string name, CancellationToken cancellationToken) { // We are sending the command directly here because the Extension requires us to know the type. var getResourceCommand = new Command() { Uri = new LimeUri($"/{_resourceName}/{Uri.EscapeDataString(name)}"), Method = CommandMethod.Get, }; var resourceCommandResult = await _sender.ProcessCommandAsync( getResourceCommand, cancellationToken); return resourceCommandResult; } } }
using Lime.Protocol; using Lime.Protocol.Network; using Lime.Protocol.Serialization; using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using Take.Blip.Client; namespace Take.Blip.Builder.Variables { public class BaseResourceVariableProvider : IVariableProvider { private readonly ISender _sender; private readonly IDocumentSerializer _documentSerializer; protected readonly string _resourceName; public VariableSource Source => throw new NotImplementedException(); public BaseResourceVariableProvider(ISender sender, IDocumentSerializer documentSerializer, string resourceName) { _sender = sender; _documentSerializer = documentSerializer; _resourceName = resourceName; } public async Task<string> GetVariableAsync(string name, IContext context, CancellationToken cancellationToken) { try { var resourceCommandResult = await ExecuteGetResourceCommandAsync(name, cancellationToken); if (resourceCommandResult.Status != CommandStatus.Success) { return null; } if (!resourceCommandResult.Resource.GetMediaType().IsJson) { return resourceCommandResult.Resource.ToString(); } return _documentSerializer.Serialize(resourceCommandResult.Resource); } catch (LimeException ex) when (ex.Reason.Code == ReasonCodes.COMMAND_RESOURCE_NOT_FOUND) { return null; } } private async Task<Command> ExecuteGetResourceCommandAsync(string name, CancellationToken cancellationToken) { // We are sending the command directly here because the Extension requires us to know the type. var getResourceCommand = new Command() { Uri = new LimeUri($"/{_resourceName}/{Uri.EscapeDataString(name)}"), Method = CommandMethod.Get, }; var resourceCommandResult = await _sender.ProcessCommandAsync( getResourceCommand, cancellationToken); return resourceCommandResult; } } }
apache-2.0
C#
eda33b1ac4eec6f66ee1c20b71ef80615a253ad0
Update incorrect summary
Khamull/Umbraco-CMS,ehornbostel/Umbraco-CMS,DaveGreasley/Umbraco-CMS,gkonings/Umbraco-CMS,iahdevelop/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,kgiszewski/Umbraco-CMS,romanlytvyn/Umbraco-CMS,Pyuuma/Umbraco-CMS,KevinJump/Umbraco-CMS,zidad/Umbraco-CMS,abryukhov/Umbraco-CMS,arvaris/HRI-Umbraco,tcmorris/Umbraco-CMS,zidad/Umbraco-CMS,Pyuuma/Umbraco-CMS,mittonp/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,Phosworks/Umbraco-CMS,bjarnef/Umbraco-CMS,christopherbauer/Umbraco-CMS,lars-erik/Umbraco-CMS,corsjune/Umbraco-CMS,marcemarc/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,abryukhov/Umbraco-CMS,countrywide/Umbraco-CMS,bjarnef/Umbraco-CMS,abjerner/Umbraco-CMS,kasperhhk/Umbraco-CMS,mattbrailsford/Umbraco-CMS,mstodd/Umbraco-CMS,christopherbauer/Umbraco-CMS,zidad/Umbraco-CMS,Door3Dev/HRI-Umbraco,JimBobSquarePants/Umbraco-CMS,rasmusfjord/Umbraco-CMS,aaronpowell/Umbraco-CMS,dawoe/Umbraco-CMS,bjarnef/Umbraco-CMS,zidad/Umbraco-CMS,lingxyd/Umbraco-CMS,yannisgu/Umbraco-CMS,christopherbauer/Umbraco-CMS,tompipe/Umbraco-CMS,rasmuseeg/Umbraco-CMS,m0wo/Umbraco-CMS,marcemarc/Umbraco-CMS,neilgaietto/Umbraco-CMS,mittonp/Umbraco-CMS,marcemarc/Umbraco-CMS,rustyswayne/Umbraco-CMS,aadfPT/Umbraco-CMS,hfloyd/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,yannisgu/Umbraco-CMS,mstodd/Umbraco-CMS,engern/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,jchurchley/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,rustyswayne/Umbraco-CMS,timothyleerussell/Umbraco-CMS,DaveGreasley/Umbraco-CMS,lingxyd/Umbraco-CMS,Pyuuma/Umbraco-CMS,Phosworks/Umbraco-CMS,AzarinSergey/Umbraco-CMS,m0wo/Umbraco-CMS,DaveGreasley/Umbraco-CMS,rasmusfjord/Umbraco-CMS,zidad/Umbraco-CMS,madsoulswe/Umbraco-CMS,hfloyd/Umbraco-CMS,yannisgu/Umbraco-CMS,nvisage-gf/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,tcmorris/Umbraco-CMS,madsoulswe/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,rajendra1809/Umbraco-CMS,iahdevelop/Umbraco-CMS,christopherbauer/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,Khamull/Umbraco-CMS,abjerner/Umbraco-CMS,corsjune/Umbraco-CMS,leekelleher/Umbraco-CMS,timothyleerussell/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,rasmusfjord/Umbraco-CMS,timothyleerussell/Umbraco-CMS,mattbrailsford/Umbraco-CMS,kasperhhk/Umbraco-CMS,VDBBjorn/Umbraco-CMS,markoliver288/Umbraco-CMS,umbraco/Umbraco-CMS,Phosworks/Umbraco-CMS,NikRimington/Umbraco-CMS,rajendra1809/Umbraco-CMS,neilgaietto/Umbraco-CMS,ehornbostel/Umbraco-CMS,leekelleher/Umbraco-CMS,WebCentrum/Umbraco-CMS,countrywide/Umbraco-CMS,markoliver288/Umbraco-CMS,KevinJump/Umbraco-CMS,Khamull/Umbraco-CMS,rustyswayne/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,sargin48/Umbraco-CMS,markoliver288/Umbraco-CMS,madsoulswe/Umbraco-CMS,TimoPerplex/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,NikRimington/Umbraco-CMS,leekelleher/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,rasmusfjord/Umbraco-CMS,KevinJump/Umbraco-CMS,rajendra1809/Umbraco-CMS,DaveGreasley/Umbraco-CMS,gavinfaux/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,dawoe/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,lingxyd/Umbraco-CMS,DaveGreasley/Umbraco-CMS,gkonings/Umbraco-CMS,engern/Umbraco-CMS,Door3Dev/HRI-Umbraco,robertjf/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,tcmorris/Umbraco-CMS,arvaris/HRI-Umbraco,romanlytvyn/Umbraco-CMS,rustyswayne/Umbraco-CMS,TimoPerplex/Umbraco-CMS,neilgaietto/Umbraco-CMS,KevinJump/Umbraco-CMS,sargin48/Umbraco-CMS,lingxyd/Umbraco-CMS,m0wo/Umbraco-CMS,VDBBjorn/Umbraco-CMS,kasperhhk/Umbraco-CMS,corsjune/Umbraco-CMS,rajendra1809/Umbraco-CMS,base33/Umbraco-CMS,Door3Dev/HRI-Umbraco,nul800sebastiaan/Umbraco-CMS,robertjf/Umbraco-CMS,Pyuuma/Umbraco-CMS,umbraco/Umbraco-CMS,VDBBjorn/Umbraco-CMS,qizhiyu/Umbraco-CMS,Door3Dev/HRI-Umbraco,AzarinSergey/Umbraco-CMS,AzarinSergey/Umbraco-CMS,Door3Dev/HRI-Umbraco,nvisage-gf/Umbraco-CMS,romanlytvyn/Umbraco-CMS,yannisgu/Umbraco-CMS,hfloyd/Umbraco-CMS,dawoe/Umbraco-CMS,VDBBjorn/Umbraco-CMS,arknu/Umbraco-CMS,gregoriusxu/Umbraco-CMS,aaronpowell/Umbraco-CMS,aaronpowell/Umbraco-CMS,iahdevelop/Umbraco-CMS,TimoPerplex/Umbraco-CMS,base33/Umbraco-CMS,christopherbauer/Umbraco-CMS,Pyuuma/Umbraco-CMS,yannisgu/Umbraco-CMS,ehornbostel/Umbraco-CMS,tcmorris/Umbraco-CMS,abjerner/Umbraco-CMS,hfloyd/Umbraco-CMS,Spijkerboer/Umbraco-CMS,lars-erik/Umbraco-CMS,ehornbostel/Umbraco-CMS,TimoPerplex/Umbraco-CMS,Spijkerboer/Umbraco-CMS,Khamull/Umbraco-CMS,kgiszewski/Umbraco-CMS,engern/Umbraco-CMS,gkonings/Umbraco-CMS,timothyleerussell/Umbraco-CMS,Tronhus/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,gkonings/Umbraco-CMS,qizhiyu/Umbraco-CMS,romanlytvyn/Umbraco-CMS,dawoe/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,gregoriusxu/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,rajendra1809/Umbraco-CMS,jchurchley/Umbraco-CMS,ordepdev/Umbraco-CMS,kasperhhk/Umbraco-CMS,lingxyd/Umbraco-CMS,rasmuseeg/Umbraco-CMS,arvaris/HRI-Umbraco,mstodd/Umbraco-CMS,WebCentrum/Umbraco-CMS,nvisage-gf/Umbraco-CMS,lars-erik/Umbraco-CMS,countrywide/Umbraco-CMS,TimoPerplex/Umbraco-CMS,Tronhus/Umbraco-CMS,kasperhhk/Umbraco-CMS,engern/Umbraco-CMS,mittonp/Umbraco-CMS,gregoriusxu/Umbraco-CMS,WebCentrum/Umbraco-CMS,engern/Umbraco-CMS,qizhiyu/Umbraco-CMS,ordepdev/Umbraco-CMS,abryukhov/Umbraco-CMS,romanlytvyn/Umbraco-CMS,nvisage-gf/Umbraco-CMS,sargin48/Umbraco-CMS,arknu/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,robertjf/Umbraco-CMS,ordepdev/Umbraco-CMS,gavinfaux/Umbraco-CMS,markoliver288/Umbraco-CMS,sargin48/Umbraco-CMS,aadfPT/Umbraco-CMS,marcemarc/Umbraco-CMS,Tronhus/Umbraco-CMS,AzarinSergey/Umbraco-CMS,base33/Umbraco-CMS,arknu/Umbraco-CMS,m0wo/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,abryukhov/Umbraco-CMS,gavinfaux/Umbraco-CMS,corsjune/Umbraco-CMS,umbraco/Umbraco-CMS,kgiszewski/Umbraco-CMS,sargin48/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,leekelleher/Umbraco-CMS,tompipe/Umbraco-CMS,iahdevelop/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,tompipe/Umbraco-CMS,ehornbostel/Umbraco-CMS,mattbrailsford/Umbraco-CMS,Spijkerboer/Umbraco-CMS,aadfPT/Umbraco-CMS,rasmuseeg/Umbraco-CMS,Phosworks/Umbraco-CMS,markoliver288/Umbraco-CMS,qizhiyu/Umbraco-CMS,robertjf/Umbraco-CMS,gregoriusxu/Umbraco-CMS,leekelleher/Umbraco-CMS,iahdevelop/Umbraco-CMS,abjerner/Umbraco-CMS,Phosworks/Umbraco-CMS,AzarinSergey/Umbraco-CMS,arknu/Umbraco-CMS,gavinfaux/Umbraco-CMS,lars-erik/Umbraco-CMS,ordepdev/Umbraco-CMS,mattbrailsford/Umbraco-CMS,timothyleerussell/Umbraco-CMS,dawoe/Umbraco-CMS,neilgaietto/Umbraco-CMS,VDBBjorn/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,Tronhus/Umbraco-CMS,gregoriusxu/Umbraco-CMS,bjarnef/Umbraco-CMS,ordepdev/Umbraco-CMS,Spijkerboer/Umbraco-CMS,tcmorris/Umbraco-CMS,NikRimington/Umbraco-CMS,gkonings/Umbraco-CMS,jchurchley/Umbraco-CMS,corsjune/Umbraco-CMS,mstodd/Umbraco-CMS,countrywide/Umbraco-CMS,markoliver288/Umbraco-CMS,tcmorris/Umbraco-CMS,qizhiyu/Umbraco-CMS,nvisage-gf/Umbraco-CMS,Tronhus/Umbraco-CMS,mittonp/Umbraco-CMS,neilgaietto/Umbraco-CMS,lars-erik/Umbraco-CMS,countrywide/Umbraco-CMS,mstodd/Umbraco-CMS,rasmusfjord/Umbraco-CMS,Khamull/Umbraco-CMS,m0wo/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arvaris/HRI-Umbraco,gavinfaux/Umbraco-CMS,rustyswayne/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,mittonp/Umbraco-CMS,Spijkerboer/Umbraco-CMS
src/Umbraco.Core/Configuration/ClientDependencyConfiguration.cs
src/Umbraco.Core/Configuration/ClientDependencyConfiguration.cs
using System; using System.Linq; using System.Xml.Linq; using Umbraco.Core.IO; using Umbraco.Core.Logging; namespace Umbraco.Core.Configuration { internal class ClientDependencyConfiguration { private readonly string _fileName; public ClientDependencyConfiguration() { _fileName = IOHelper.MapPath(string.Format("{0}/ClientDependency.config", SystemDirectories.Config)); } /// <summary> /// Changes the version number in ClientDependency.config to a random value to avoid stale caches /// </summary> internal bool IncreaseVersionNumber() { try { var clientDependencyConfigXml = XDocument.Load(_fileName, LoadOptions.PreserveWhitespace); if (clientDependencyConfigXml.Root != null) { var versionAttribute = clientDependencyConfigXml.Root.Attribute("version"); //Set the new version to the hashcode of now var oldVersion = versionAttribute.Value; var newVersion = Math.Abs(DateTime.UtcNow.GetHashCode()); versionAttribute.SetValue(newVersion); clientDependencyConfigXml.Save(_fileName, SaveOptions.DisableFormatting); LogHelper.Info<ClientDependencyConfiguration>(string.Format("Updated version number from {0} to {1}", oldVersion, newVersion)); return true; } } catch (Exception ex) { LogHelper.Error<ClientDependencyConfiguration>("Couldn't update ClientDependency version number", ex); } return false; } } }
using System; using System.Linq; using System.Xml.Linq; using Umbraco.Core.IO; using Umbraco.Core.Logging; namespace Umbraco.Core.Configuration { internal class ClientDependencyConfiguration { private readonly string _fileName; public ClientDependencyConfiguration() { _fileName = IOHelper.MapPath(string.Format("{0}/ClientDependency.config", SystemDirectories.Config)); } /// <summary> /// Increases the version number in ClientDependency.config by 1 /// </summary> internal bool IncreaseVersionNumber() { try { var clientDependencyConfigXml = XDocument.Load(_fileName, LoadOptions.PreserveWhitespace); if (clientDependencyConfigXml.Root != null) { var versionAttribute = clientDependencyConfigXml.Root.Attribute("version"); //Set the new version to the hashcode of now var oldVersion = versionAttribute.Value; var newVersion = Math.Abs(DateTime.UtcNow.GetHashCode()); versionAttribute.SetValue(newVersion); clientDependencyConfigXml.Save(_fileName, SaveOptions.DisableFormatting); LogHelper.Info<ClientDependencyConfiguration>(string.Format("Updated version number from {0} to {1}", oldVersion, newVersion)); return true; } } catch (Exception ex) { LogHelper.Error<ClientDependencyConfiguration>("Couldn't update ClientDependency version number", ex); } return false; } } }
mit
C#
ac799aaf7a412db957203074b9110776ad61dfbf
Add missing newline
peppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,ppy/osu
osu.Game/Overlays/Mods/NestedVerticalScrollContainer.cs
osu.Game/Overlays/Mods/NestedVerticalScrollContainer.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using osu.Framework.Graphics; using osu.Framework.Input.Events; using osu.Game.Graphics.Containers; namespace osu.Game.Overlays.Mods { /// <summary> /// A scroll container that handles the case of vertically scrolling content inside a larger horizontally scrolling parent container. /// </summary> public class NestedVerticalScrollContainer : OsuScrollContainer { private OsuScrollContainer? parentScrollContainer; protected override void LoadComplete() { base.LoadComplete(); parentScrollContainer = this.FindClosestParent<OsuScrollContainer>(); } protected override bool OnScroll(ScrollEvent e) { if (parentScrollContainer == null) return base.OnScroll(e); bool topRightInView = parentScrollContainer.ScreenSpaceDrawQuad.Contains(ScreenSpaceDrawQuad.TopRight); bool bottomLeftInView = parentScrollContainer.ScreenSpaceDrawQuad.Contains(ScreenSpaceDrawQuad.BottomLeft); // If not completely on-screen, handle scroll but also allow parent to scroll at the same time (to hopefully bring our content into full view). if (!topRightInView || !bottomLeftInView) return false; bool scrollingPastEnd = e.ScrollDelta.Y < 0 && IsScrolledToEnd(); bool scrollingPastStart = e.ScrollDelta.Y > 0 && Target <= 0; // If at either of our extents, delegate scroll to the horizontal parent container. if (scrollingPastStart || scrollingPastEnd) return false; return base.OnScroll(e); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using osu.Framework.Graphics; using osu.Framework.Input.Events; using osu.Game.Graphics.Containers; namespace osu.Game.Overlays.Mods { /// <summary> /// A scroll container that handles the case of vertically scrolling content inside a larger horizontally scrolling parent container. /// </summary> public class NestedVerticalScrollContainer : OsuScrollContainer { private OsuScrollContainer? parentScrollContainer; protected override void LoadComplete() { base.LoadComplete(); parentScrollContainer = this.FindClosestParent<OsuScrollContainer>(); } protected override bool OnScroll(ScrollEvent e) { if (parentScrollContainer == null) return base.OnScroll(e); bool topRightInView = parentScrollContainer.ScreenSpaceDrawQuad.Contains(ScreenSpaceDrawQuad.TopRight); bool bottomLeftInView = parentScrollContainer.ScreenSpaceDrawQuad.Contains(ScreenSpaceDrawQuad.BottomLeft); // If not completely on-screen, handle scroll but also allow parent to scroll at the same time (to hopefully bring our content into full view). if (!topRightInView || !bottomLeftInView) return false; bool scrollingPastEnd = e.ScrollDelta.Y < 0 && IsScrolledToEnd(); bool scrollingPastStart = e.ScrollDelta.Y > 0 && Target <= 0; // If at either of our extents, delegate scroll to the horizontal parent container. if (scrollingPastStart || scrollingPastEnd) return false; return base.OnScroll(e); } } }
mit
C#
3deab026c82669e70daadcc09d35c8c62740ef3a
Stop spurious VS "cannot override ExecuteAsync" errors even if you don't specify a base class
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.Blazor/Components/RazorToolingWorkaround.cs
src/Microsoft.Blazor/Components/RazorToolingWorkaround.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. /* * Currently if you have a .cshtml file in a project with <Project Sdk="Microsoft.NET.Sdk.Web">, * Visual Studio will run design-time builds for the .cshtml file that assume certain ASP.NET MVC * APIs exist. Since those namespaces and types wouldn't normally exist for Blazor client apps, * this leads to spurious errors in the Errors List pane, even though there aren't actually any * errors on build. As a workaround, we define here a minimal set of namespaces/types that satisfy * the design-time build. * * TODO: Track down what is triggering the unwanted design-time build and find out how to disable it. * Then this file can be removed entirely. */ using System; using System.Threading.Tasks; namespace Microsoft.AspNetCore.Mvc { public interface IUrlHelper { } public interface IViewComponentHelper { } } namespace Microsoft.AspNetCore.Mvc.Razor { public class RazorPage<T> { // This needs to be defined otherwise the VS tooling complains that there's no ExecuteAsync method to override. public virtual Task ExecuteAsync() => throw new NotImplementedException($"Blazor components do not implement {nameof(ExecuteAsync)}."); } namespace Internal { public class RazorInjectAttributeAttribute : Attribute { } } } namespace Microsoft.AspNetCore.Mvc.Rendering { public interface IJsonHelper { } public interface IHtmlHelper<T> { } } namespace Microsoft.AspNetCore.Mvc.ViewFeatures { public interface IModelExpressionProvider { } }
// 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. /* * Currently if you have a .cshtml file in a project with <Project Sdk="Microsoft.NET.Sdk.Web">, * Visual Studio will run design-time builds for the .cshtml file that assume certain ASP.NET MVC * APIs exist. Since those namespaces and types wouldn't normally exist for Blazor client apps, * this leads to spurious errors in the Errors List pane, even though there aren't actually any * errors on build. As a workaround, we define here a minimal set of namespaces/types that satisfy * the design-time build. * * TODO: Track down what is triggering the unwanted design-time build and find out how to disable it. * Then this file can be removed entirely. */ using System; namespace Microsoft.AspNetCore.Mvc { public interface IUrlHelper { } public interface IViewComponentHelper { } } namespace Microsoft.AspNetCore.Mvc.Razor { public class RazorPage<T> { } namespace Internal { public class RazorInjectAttributeAttribute : Attribute { } } } namespace Microsoft.AspNetCore.Mvc.Rendering { public interface IJsonHelper { } public interface IHtmlHelper<T> { } } namespace Microsoft.AspNetCore.Mvc.ViewFeatures { public interface IModelExpressionProvider { } }
apache-2.0
C#
5b5282a3193990d01691b4bf8495cf0ece3f7ad2
Move method down.
fffej/BobTheBuilder,alastairs/BobTheBuilder
BobTheBuilder/DynamicBuilderBase.cs
BobTheBuilder/DynamicBuilderBase.cs
using System; using System.Dynamic; namespace BobTheBuilder { public abstract class DynamicBuilderBase<T> : DynamicObject, IDynamicBuilder<T> where T : class { protected internal readonly IArgumentStore argumentStore; protected DynamicBuilderBase(IArgumentStore argumentStore) { if (argumentStore == null) { throw new ArgumentNullException("argumentStore"); } this.argumentStore = argumentStore; } public abstract bool InvokeBuilderMethod(InvokeMemberBinder binder, object[] args, out object result); public T Build() { var instance = CreateInstanceOfType(); PopulatePublicSettableProperties(instance); return instance; } private static T CreateInstanceOfType() { var instance = Activator.CreateInstance<T>(); return instance; } private void PopulatePublicSettableProperties(T instance) { var knownMembers = argumentStore.GetAllStoredMembers(); foreach (var member in knownMembers) { var property = typeof (T).GetProperty(member.Name); property.SetValue(instance, member.Value); } } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { return InvokeBuilderMethod(binder, args, out result); } public static implicit operator T(DynamicBuilderBase<T> builder) { return builder.Build(); } } }
using System; using System.Dynamic; namespace BobTheBuilder { public abstract class DynamicBuilderBase<T> : DynamicObject, IDynamicBuilder<T> where T : class { protected internal readonly IArgumentStore argumentStore; protected DynamicBuilderBase(IArgumentStore argumentStore) { if (argumentStore == null) { throw new ArgumentNullException("argumentStore"); } this.argumentStore = argumentStore; } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { return InvokeBuilderMethod(binder, args, out result); } public abstract bool InvokeBuilderMethod(InvokeMemberBinder binder, object[] args, out object result); public T Build() { var instance = CreateInstanceOfType(); PopulatePublicSettableProperties(instance); return instance; } private static T CreateInstanceOfType() { var instance = Activator.CreateInstance<T>(); return instance; } private void PopulatePublicSettableProperties(T instance) { var knownMembers = argumentStore.GetAllStoredMembers(); foreach (var member in knownMembers) { var property = typeof (T).GetProperty(member.Name); property.SetValue(instance, member.Value); } } public static implicit operator T(DynamicBuilderBase<T> builder) { return builder.Build(); } } }
apache-2.0
C#
2d4674a19ea73b43d984401a0c12f9f17c306616
Set version to 0.1.0
aireq/NLog.Targets.SQS
NLog.Targets.SQS/Properties/AssemblyInfo.cs
NLog.Targets.SQS/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("NLog.Target.SQS")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NLog.Target.SQS")] [assembly: AssemblyCopyright("Copyright © 2016 Eric Anastas")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("120ec102-a20e-4c31-8151-73958392dbad")] // 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("0.1.0.*")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NLog.Target.SQS")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NLog.Target.SQS")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("120ec102-a20e-4c31-8151-73958392dbad")] // 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")]
mit
C#
bc068fe4921f64fa668eefb18e6b964be17e1e8f
Remove comment italicization.
marceloyuela/google-cloud-powershell,chrsmith/google-cloud-powershell,marceloyuela/google-cloud-powershell,ILMTitan/google-cloud-powershell,GoogleCloudPlatform/google-cloud-powershell,marceloyuela/google-cloud-powershell
Google.PowerShell/Dns/GcdProject.cs
Google.PowerShell/Dns/GcdProject.cs
// Copyright 2016 Google Inc. All Rights Reserved. // Licensed under the Apache License Version 2.0. using Google.Apis.Dns.v1; using Google.Apis.Dns.v1.Data; using Google.PowerShell.Common; using System.Management.Automation; namespace Google.PowerShell.Dns { /// <summary> /// <para type="synopsis"> /// Fetch the representation of an existing project. /// </para> /// <para type="description"> /// Returns the Project resource object. /// </para> /// <para type="description"> /// If a project is specified, will instead return the representation of that project. /// </para> /// <example> /// <para>Get the representation of the project "testing"</para> /// <para><code>Get-GcdProject -Project "testing" </code></para> /// </example> /// </summary> [Cmdlet(VerbsCommon.Get, "GcdProject")] public class GetGcdProjectCmdlet : GcdCmdlet { /// <summary> /// <para type="description"> /// Get the project to return the representation of. /// </para> /// </summary> [Parameter] [ConfigPropertyName(CloudSdkSettings.CommonProperties.Project)] public string Project { get; set; } protected override void ProcessRecord() { base.ProcessRecord(); ProjectsResource.GetRequest projectGetRequest = Service.Projects.Get(Project); Project projectResponse = projectGetRequest.Execute(); WriteObject(projectResponse); } } }
// Copyright 2016 Google Inc. All Rights Reserved. // Licensed under the Apache License Version 2.0. using Google.Apis.Dns.v1; using Google.Apis.Dns.v1.Data; using Google.PowerShell.Common; using System.Management.Automation; namespace Google.PowerShell.Dns { /// <summary> /// <para type="synopsis"> /// Fetch the representation of an existing project. /// </para> /// <para type="description"> /// Returns the Project resource object. /// </para> /// <para type="description"> /// If a project is specified, will instead return the representation of that project. /// </para> /// <example> /// <para>Get the representation of the project “testing”</para> /// <para><code>Get-GcdProject -Project "testing" </code></para> /// </example> /// </summary> [Cmdlet(VerbsCommon.Get, "GcdProject")] public class GetGcdProjectCmdlet : GcdCmdlet { /// <summary> /// <para type="description"> /// Get the project to return the representation of. /// </para> /// </summary> [Parameter] [ConfigPropertyName(CloudSdkSettings.CommonProperties.Project)] public string Project { get; set; } protected override void ProcessRecord() { base.ProcessRecord(); ProjectsResource.GetRequest projectGetRequest = Service.Projects.Get(Project); Project projectResponse = projectGetRequest.Execute(); WriteObject(projectResponse); } } }
apache-2.0
C#
f23cc40ad8e6a41354fb65405d4a3a1d2982ee94
Set thread culture to InvariantCulture on startup
feliwir/openSage,feliwir/openSage
src/OpenSage.DataViewer.Windows/App.xaml.cs
src/OpenSage.DataViewer.Windows/App.xaml.cs
using System.Windows; using System.Globalization; using System.Threading; namespace OpenSage.DataViewer { public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; base.OnStartup(e); } } }
using System.Windows; namespace OpenSage.DataViewer { public partial class App : Application { } }
mit
C#
6eacc80532edbd0ca97980a86d96a1363cf0a6ec
Implement job compatibility
LeBodro/super-salaryman-2044
Assets/Job.cs
Assets/Job.cs
using UnityEngine; using System.Collections.Generic; [System.Serializable] public class Job { [SerializeField] string name; [SerializeField] Texture2D icon; [SerializeField] SuperPower[] acceptedPowers; [SerializeField] SuperPower[] forbiddenPowers; public bool IsCompatibleWith(List<SuperPower> powers) { bool isCompatible; foreach (var power in forbiddenPowers) { if (powers.Contains(power)) { isCompatible = false; } } foreach (var power in acceptedPowers) { if (powers.Contains(power)) { isCompatible = true; } } isCompatible = false; return isCompatible; } }
using UnityEngine; using System.Collections.Generic; [System.Serializable] public class Job { [SerializeField] string name; [SerializeField] Texture2D icon; [SerializeField] SuperPower[] acceptedPowers; [SerializeField] SuperPower[] forbiddenPowers; public bool IsCompatibleWith(IList<SuperPower> powers) { return true; } }
mit
C#
40b7934404452749a8c716211a83df25d59d6921
add explanatory comment (#1672)
GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples
functions/helloworld/HelloGcs/Function.cs
functions/helloworld/HelloGcs/Function.cs
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START functions_helloworld_storage] using CloudNative.CloudEvents; using Google.Cloud.Functions.Framework; using Google.Events.Protobuf.Cloud.Storage.V1; using Microsoft.Extensions.Logging; using System.Threading; using System.Threading.Tasks; namespace HelloGcs { /// <summary> /// Example Cloud Storage-triggered function. /// This function can process any event from Cloud Storage. /// </summary> public class Function : ICloudEventFunction<StorageObjectData> { private readonly ILogger _logger; public Function(ILogger<Function> logger) => _logger = logger; public Task HandleAsync(CloudEvent cloudEvent, StorageObjectData data, CancellationToken cancellationToken) { _logger.LogInformation("Event: {event}", cloudEvent.Id); _logger.LogInformation("Event Type: {type}", cloudEvent.Type); _logger.LogInformation("Bucket: {bucket}", data.Bucket); _logger.LogInformation("File: {file}", data.Name); _logger.LogInformation("Metageneration: {metageneration}", data.Metageneration); _logger.LogInformation("Created: {created:s}", data.TimeCreated?.ToDateTimeOffset()); _logger.LogInformation("Updated: {updated:s}", data.Updated?.ToDateTimeOffset()); return Task.CompletedTask; } } } // [END functions_helloworld_storage]
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START functions_helloworld_storage] using CloudNative.CloudEvents; using Google.Cloud.Functions.Framework; using Google.Events.Protobuf.Cloud.Storage.V1; using Microsoft.Extensions.Logging; using System.Threading; using System.Threading.Tasks; namespace HelloGcs { public class Function : ICloudEventFunction<StorageObjectData> { private readonly ILogger _logger; public Function(ILogger<Function> logger) => _logger = logger; public Task HandleAsync(CloudEvent cloudEvent, StorageObjectData data, CancellationToken cancellationToken) { _logger.LogInformation("Event: {event}", cloudEvent.Id); _logger.LogInformation("Event Type: {type}", cloudEvent.Type); _logger.LogInformation("Bucket: {bucket}", data.Bucket); _logger.LogInformation("File: {file}", data.Name); _logger.LogInformation("Metageneration: {metageneration}", data.Metageneration); _logger.LogInformation("Created: {created:s}", data.TimeCreated?.ToDateTimeOffset()); _logger.LogInformation("Updated: {updated:s}", data.Updated?.ToDateTimeOffset()); return Task.CompletedTask; } } } // [END functions_helloworld_storage]
apache-2.0
C#
7c4d7c2098a99dd4f868fca885cd14dc1e24dc7f
Add field - avatar
jpush/jmessage-api-csharp-client
jmessage/user/UserPayload.cs
jmessage/user/UserPayload.cs
using Newtonsoft.Json; namespace jmessage.user { public class UserPayload { public string username; public string password; public string new_password; public string appkey; public string nickname; /// <summary> /// 生日。 /// 格式要求为 yyyy-MM-dd HH:mm:ss /// </summary> public string birthday; /// <summary> /// 用户性别。 /// 0:未知;1:男;2:女。 /// </summary> public int? gender; /// <summary> /// 用户个性签名。 /// </summary> public string signature; /// <summary> /// 用户所属地区。 /// </summary> public string region; /// <summary> /// 用户详细地址。 /// </summary> public string address; /// <summary> /// 用户创建时间。 /// </summary> public string ctime; /// <summary> /// 用户最后修改时间。 /// </summary> public string mtime; /// <summary> /// 需要填从文件上传接口获得的 media_id。 /// </summary> public string avatar; public UserPayload(string username, string password) { this.username = username; this.password = password; } public UserPayload(string username) { this.username = username; password = null; new_password = null; appkey = null; nickname = null; birthday = null; gender = null; signature = null; region = null; address = null; ctime = null; mtime = null; } public string ToString(UserPayload user) { return JsonConvert.SerializeObject(user, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); } public UserPayload Check() { return this; } } }
using Newtonsoft.Json; namespace jmessage.user { public class UserPayload { public string username; public string password; public string new_password; public string appkey; public string nickname; public string birthday; public int? gender; public string signature; public string region; public string address; public string ctime; public string mtime; public UserPayload(string username, string password) { this.username = username; this.password = password; } public UserPayload(string username) { this.username = username; password = null; new_password = null; appkey = null; nickname = null; birthday = null; gender = null; signature = null; region = null; address = null; ctime = null; mtime = null; } public string ToString(UserPayload user) { return JsonConvert.SerializeObject(user, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); } public UserPayload Check() { return this; } } }
mit
C#
6ef18904ad4da39d1d27ab08fa99d668466d08f9
test name changed to testRepository
Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist
Trappist/src/Promact.Trappist.Core/Controllers/TestController.cs
Trappist/src/Promact.Trappist.Core/Controllers/TestController.cs
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Test; using Promact.Trappist.Repository.Tests; using Promact.Trappist.Utility.Constants; namespace Promact.Trappist.Core.Controllers { [Produces("application/json")] [Route("api/tests")] public class TestsController : Controller { private readonly ITestsRepository _testRepository; private readonly IStringConstants _stringConstant; public TestsController(ITestsRepository testRepository, IStringConstants stringConstant) { _testRepository = testRepository; _stringConstant = stringConstant; } /// <summary> /// this method is used to add a new test /// </summary> /// <param name="test">object of the Test</param> /// <returns>string</returns> [HttpPost] public string CreateTest([FromBody] Test test) { if (_testRepository.UniqueTestName(test)) // verifying the test name is unique or not { _testRepository.CreateTest(test); return _stringConstant.Success; } else { return _stringConstant.InvalidTestName; } } /// <summary> /// Get All Tests /// </summary> /// <returns>List of Tests</returns> [HttpGet] public IActionResult GetAllTest() { var tests = _testRepository.GetAllTests(); return Ok(tests); } } }
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Test; using Promact.Trappist.Repository.Tests; using Promact.Trappist.Utility.Constants; namespace Promact.Trappist.Core.Controllers { [Produces("application/json")] [Route("api/tests")] public class TestsController : Controller { private readonly ITestsRepository _testRepository; private readonly IStringConstants _stringConstant; public TestsController(ITestsRepository test,IStringConstants stringConstant) { _testRepository = test; _stringConstant = stringConstant; } /// <summary> /// this method is used to add a new test /// </summary> /// <param name="test">object of the Test</param> /// <returns>string</returns> [HttpPost] public string CreateTest([FromBody] Test test) { if (_testRepository.UniqueTestName(test)) // verifying the test name is unique or not { _testRepository.CreateTest(test); return _stringConstant.Success; } else { return _stringConstant.InvalidTestName; } } /// <summary> /// Get All Tests /// </summary> /// <returns>List of Tests</returns> [HttpGet] public IActionResult GetAllTest() { var tests = _testRepository.GetAllTests(); return Json(tests); } } }
mit
C#
06f6bbdff806d3cc02d1012e55963638cd247e76
Throw excpetion when type is not found
Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D.Perspex/Presenters/CachedContentPresenter.cs
src/Core2D.Perspex/Presenters/CachedContentPresenter.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Perspex; using Perspex.Controls; using Perspex.Controls.Presenters; using System; using System.Collections.Generic; namespace Core2D.Perspex.Presenters { public class CachedContentPresenter : ContentPresenter { private static IDictionary<Type, Func<Control>> _factory = new Dictionary<Type, Func<Control>>(); private readonly IDictionary<Type, Control> _cache = new Dictionary<Type, Control>(); public static void Register(Type type, Func<Control> create) => _factory[type] = create; public CachedContentPresenter() { this.GetObservable(DataContextProperty).Subscribe((value) => SetContent(value)); } public Control GetControl(Type type) { Control control; _cache.TryGetValue(type, out control); if (control == null) { Func<Control> createInstance; _factory.TryGetValue(type, out createInstance); control = createInstance?.Invoke(); if (control != null) { _cache[type] = control; } else { throw new Exception($"Can not find factory method for type: {type}"); } } return control; } public void SetContent(object value) { Control control = null; if (value != null) { control = GetControl(value.GetType()); } this.Content = control; } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Perspex; using Perspex.Controls; using Perspex.Controls.Presenters; using System; using System.Collections.Generic; namespace Core2D.Perspex.Presenters { public class CachedContentPresenter : ContentPresenter { private static IDictionary<Type, Func<Control>> _factory = new Dictionary<Type, Func<Control>>(); private readonly IDictionary<Type, Control> _cache = new Dictionary<Type, Control>(); public static void Register(Type type, Func<Control> create) => _factory[type] = create; public CachedContentPresenter() { this.GetObservable(DataContextProperty).Subscribe((value) => SetContent(value)); } public Control GetControl(Type type) { Control control; _cache.TryGetValue(type, out control); if (control == null) { Func<Control> createInstance; _factory.TryGetValue(type, out createInstance); control = createInstance?.Invoke(); if (control != null) { _cache[type] = control; } } return control; } public void SetContent(object value) { Control control = null; if (value != null) { control = GetControl(value.GetType()); } this.Content = control; } } }
mit
C#
8c9024321cd2cd50afc5cc292f2c8b29d6d82ab8
fix bug: if two app uses netsparkle on same PC, the second crashes
shawnliang/NetSparkle,shawnliang/NetSparkle
NetSparkle/NetSparkleMainWindows.cs
NetSparkle/NetSparkleMainWindows.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace AppLimit.NetSparkle { public partial class NetSparkleMainWindows : Form, IDisposable { private StreamWriter sw = null; public NetSparkleMainWindows() { // init ui InitializeComponent(); // init logfile var fs = File.Open(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "NetSparkle.log"), FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite); sw = new StreamWriter(fs); } public void Report(String message) { if (lstActions.InvokeRequired) lstActions.Invoke(new Action<String>(Report), message); else { // build the message DateTime c = DateTime.Now; String msg = "[" + c.ToLongTimeString() + "." + c.Millisecond + "] " + message; // report to file ReportToFile(msg); // report the message into ui lstActions.Items.Add(msg); } } private void ReportToFile(String msg) { try { // write sw.WriteLine(msg); // flush sw.Flush(); } catch(Exception) { } } #region IDisposable Members void IDisposable.Dispose() { // flush again sw.Flush(); // close the stream sw.Dispose(); // close the base base.Dispose(); } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace AppLimit.NetSparkle { public partial class NetSparkleMainWindows : Form, IDisposable { private StreamWriter sw = null; public NetSparkleMainWindows() { // init ui InitializeComponent(); // init logfile sw = File.CreateText(Path.Combine(Environment.ExpandEnvironmentVariables("%temp%"), "NetSparkle.log")); } public void Report(String message) { if (lstActions.InvokeRequired) lstActions.Invoke(new Action<String>(Report), message); else { // build the message DateTime c = DateTime.Now; String msg = "[" + c.ToLongTimeString() + "." + c.Millisecond + "] " + message; // report to file ReportToFile(msg); // report the message into ui lstActions.Items.Add(msg); } } private void ReportToFile(String msg) { try { // write sw.WriteLine(msg); // flush sw.Flush(); } catch(Exception) { } } #region IDisposable Members void IDisposable.Dispose() { // flush again sw.Flush(); // close the stream sw.Dispose(); // close the base base.Dispose(); } #endregion } }
mit
C#
47fc86768c7e7dc9ef2b527dc084229fcf6fb3e1
Bump to version 2.2.0.0
MeltWS/proshine,bobus15/proshine,Silv3rPRO/proshine
PROShine/Properties/AssemblyInfo.cs
PROShine/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using System.Windows; // 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("PROShine")] [assembly: AssemblyDescription("A free, open-source and advanced bot for Pokemon Revolution Online.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Silv3r")] [assembly: AssemblyProduct("PROShine")] [assembly: AssemblyCopyright("Copyright © Silv3r, 2016-2032")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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("2.2.0.0")] [assembly: AssemblyFileVersion("2.2.0.0")] [assembly: NeutralResourcesLanguage("en")]
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using System.Windows; // 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("PROShine")] [assembly: AssemblyDescription("A free, open-source and advanced bot for Pokemon Revolution Online.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Silv3r")] [assembly: AssemblyProduct("PROShine")] [assembly: AssemblyCopyright("Copyright © Silv3r, 2016-2032")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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("2.1.3.0")] [assembly: AssemblyFileVersion("2.1.3.0")] [assembly: NeutralResourcesLanguage("en")]
mit
C#
23ab92b85d8b8eea18405094fbf9415e62a4f153
update contact
lderache/LeTruck,lderache/LeTruck,lderache/LeTruck
src/mvc5/TheTruck.Web/Views/Home/Contact.cshtml
src/mvc5/TheTruck.Web/Views/Home/Contact.cshtml
@{ ViewBag.Title = "Contact"; } <h2>@ViewBag.Title.</h2> <p> We would love to hear your feedback about products and suggestions. </p> <address> <strong>Support:</strong> <a href="mailto:[email protected]">[email protected]</a><br /> </address>
@{ ViewBag.Title = "Contact"; } <h2>@ViewBag.Title.</h2> <h3>@ViewBag.Message</h3> <address> One Microsoft Way<br /> Redmond, WA 98052-6399<br /> <abbr title="Phone">P:</abbr> 425.555.0100 </address> <address> <strong>Support:</strong> <a href="mailto:[email protected]">[email protected]</a><br /> <strong>Marketing:</strong> <a href="mailto:[email protected]">[email protected]</a> </address>
mit
C#
87e9fb37990b34369f235f0fbce7383a63e9b858
Fix build
gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer
Server/Message/FlagSyncMsgReader.cs
Server/Message/FlagSyncMsgReader.cs
using LunaCommon.Message.Data.Flag; using LunaCommon.Message.Interface; using LunaCommon.Message.Types; using Server.Client; using Server.Message.Base; using Server.System; namespace Server.Message { public class FlagSyncMsgReader : ReaderBase { public override void HandleMessage(ClientStructure client, IClientMessageBase message) { var data = (FlagBaseMsgData)message.Data; switch (data.FlagMessageType) { case FlagMessageType.ListRequest: FlagSystem.HandleFlagListRequestMessage(client); //We don't use this message anymore so we can recycle it message.Recycle(); break; case FlagMessageType.FlagData: FlagSystem.HandleFlagDataMessage(client, (FlagDataMsgData)data); break; } } } }
using LunaCommon.Message.Data.Flag; using LunaCommon.Message.Interface; using LunaCommon.Message.Types; using Server.Client; using Server.Message.Base; using Server.System; namespace Server.Message { public class FlagSyncMsgReader : ReaderBase { public override void HandleMessage(ClientStructure client, IClientMessageBase message) { var data = (FlagBaseMsgData)message.Data; switch (data.FlagMessageType) { case FlagMessageType.ListRequest: FlagSyncMsgSender.HandleFlagListRequestMessage(client); //We don't use this message anymore so we can recycle it message.Recycle(); break; case FlagMessageType.FlagData: FlagSyncMsgSender.HandleFlagDataMessage(client, (FlagDataMsgData)data); break; } } } }
mit
C#
803c1e8b65f1ac0957f65dd80d6ae535257fa326
Bump v1.0.6
karronoli/tiny-sato
TinySato/Properties/AssemblyInfo.cs
TinySato/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("TinySato")] [assembly: AssemblyDescription("You can construct and send SBPL packet to Sato printer. Sato printer is needed to recognized by windows driver.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TinySato")] [assembly: AssemblyCopyright("Copyright 2016 karronoli")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("f56213db-fa1f-42da-b930-b642a56ee840")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: [assembly: AssemblyVersion("1.0.6.*")] [assembly: AssemblyFileVersion("1.0.6")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("TinySato")] [assembly: AssemblyDescription("You can construct and send SBPL packet to Sato printer. Sato printer is needed to recognized by windows driver.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TinySato")] [assembly: AssemblyCopyright("Copyright 2016 karronoli")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("f56213db-fa1f-42da-b930-b642a56ee840")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: [assembly: AssemblyVersion("1.0.5.*")] [assembly: AssemblyFileVersion("1.0.5")]
apache-2.0
C#
cef001ef6ccc06144169c66d48cb8c332320df4d
Fix file name in license boilerplace
roman-yagodin/R7.Epsilon,roman-yagodin/R7.Epsilon,roman-yagodin/R7.Epsilon
R7.Epsilon.Tests/CustomPortalConfigTests.cs
R7.Epsilon.Tests/CustomPortalConfigTests.cs
// // CustomPortalConfigTests.cs // // Author: // Roman M. Yagodin <[email protected]> // // Copyright (c) 2016 Roman M. Yagodin // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using R7.Epsilon.Components; using Xunit; using System.IO; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization; namespace R7.Epsilon.Tests { public class CustomPortalConfigTests { [Theory] [InlineData (0)] [InlineData (2)] [InlineData (3)] public void PortalConfigDeserializationTest (int portalNumber) { var configFile = Path.Combine ("..", "..", "..", "R7.Epsilon", "Customizations", "volgau.com", "Portals", portalNumber.ToString (), "R7.Epsilon.yml"); using (var configReader = new StringReader (File.ReadAllText (configFile))) { var deserializer = new Deserializer (namingConvention: new HyphenatedNamingConvention ()); Assert.NotNull (deserializer.Deserialize<EpsilonPortalConfig> (configReader)); } } } }
// // DefaultPortalConfigTests.cs // // Author: // Roman M. Yagodin <[email protected]> // // Copyright (c) 2016 Roman M. Yagodin // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using R7.Epsilon.Components; using Xunit; using System.IO; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization; namespace R7.Epsilon.Tests { public class CustomPortalConfigTests { [Theory] [InlineData (0)] [InlineData (2)] [InlineData (3)] public void PortalConfigDeserializationTest (int portalNumber) { var configFile = Path.Combine ("..", "..", "..", "R7.Epsilon", "Customizations", "volgau.com", "Portals", portalNumber.ToString (), "R7.Epsilon.yml"); using (var configReader = new StringReader (File.ReadAllText (configFile))) { var deserializer = new Deserializer (namingConvention: new HyphenatedNamingConvention ()); Assert.NotNull (deserializer.Deserialize<EpsilonPortalConfig> (configReader)); } } } }
agpl-3.0
C#
459905cfca9ef25f32dbabc953cdbe97ea29e6d7
Fix warning on net5.0
jherby2k/AudioWorks
AudioWorks/tests/AudioWorks.TestUtilities/HashUtility.cs
AudioWorks/tests/AudioWorks.TestUtilities/HashUtility.cs
/* Copyright © 2018 Jeremy Herbison This file is part of AudioWorks. AudioWorks is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. AudioWorks is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with AudioWorks. If not, see <https://www.gnu.org/licenses/>. */ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security.Cryptography; namespace AudioWorks.TestUtilities { public static class HashUtility { [SuppressMessage("Microsoft.Security", "CA5351:Do not use insecure cryptographic algorithm MD5.", Justification = "This method is not security critical")] public static string CalculateHash(string filePath) { using (var md5 = MD5.Create()) using (var fileStream = File.OpenRead(filePath)) #if NETSTANDARD2_0 return BitConverter.ToString(md5.ComputeHash(fileStream)).Replace("-", string.Empty); #else return BitConverter.ToString(md5.ComputeHash(fileStream)) .Replace("-", string.Empty, StringComparison.Ordinal); #endif } [SuppressMessage("Microsoft.Security", "CA5351:Do not use insecure cryptographic algorithm MD5.", Justification = "This method is not security critical")] public static string CalculateHash(byte[]? data) { if (data == null) return string.Empty; using (var md5 = MD5.Create()) #if NETSTANDARD2_0 return BitConverter.ToString(md5.ComputeHash(data)).Replace("-", string.Empty); #else return BitConverter.ToString(md5.ComputeHash(data)) .Replace("-", string.Empty, StringComparison.OrdinalIgnoreCase); #endif } } }
/* Copyright © 2018 Jeremy Herbison This file is part of AudioWorks. AudioWorks is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. AudioWorks is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with AudioWorks. If not, see <https://www.gnu.org/licenses/>. */ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security.Cryptography; namespace AudioWorks.TestUtilities { public static class HashUtility { [SuppressMessage("Microsoft.Security", "CA5351:Do not use insecure cryptographic algorithm MD5.", Justification = "This method is not security critical")] public static string CalculateHash(string filePath) { using (var md5 = MD5.Create()) using (var fileStream = File.OpenRead(filePath)) return BitConverter.ToString(md5.ComputeHash(fileStream)) .Replace("-", string.Empty); } [SuppressMessage("Microsoft.Security", "CA5351:Do not use insecure cryptographic algorithm MD5.", Justification = "This method is not security critical")] public static string CalculateHash(byte[]? data) { if (data == null) return string.Empty; using (var md5 = MD5.Create()) return BitConverter.ToString(md5.ComputeHash(data)) .Replace("-", string.Empty); } } }
agpl-3.0
C#
2d319f6358c2e8152cae82c535e0aa2cffa44ca9
scale default to 1:1
ruarai/Trigrad,ruarai/Trigrad
Trigrad/DataTypes/TrigradOptions.cs
Trigrad/DataTypes/TrigradOptions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Trigrad.DataTypes { /// <summary> Options for the usage of the TrigradCompressor. </summary> public class TrigradOptions { /// <summary> Constructs a TrigradOptions with a random seed. </summary> public TrigradOptions() { Random = new Random(); } /// <summary> Constructs a TrigradOptions with a specified seed. </summary> public TrigradOptions(int seed) { Random = new Random(seed); } /// <summary> The radius of sampled colours around a point, with 0 forming only 1 sample. </summary> public int SampleRadius = 1; /// <summary> The goal number of samples to be achieved. </summary> public int SampleCount = 1000; /// <summary> The frequency table providing the TrigradCompressor values regarding the chance a pixel will be sampled. </summary> public FrequencyTable FrequencyTable = null; /// <summary> The random number generator to be used by the TrigradCompressor. </summary> public Random Random; /// <summary> The factor to upscale the bitmap during compression. </summary> public int ScaleFactor = 1; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Trigrad.DataTypes { /// <summary> Options for the usage of the TrigradCompressor. </summary> public class TrigradOptions { /// <summary> Constructs a TrigradOptions with a random seed. </summary> public TrigradOptions() { Random = new Random(); } /// <summary> Constructs a TrigradOptions with a specified seed. </summary> public TrigradOptions(int seed) { Random = new Random(seed); } /// <summary> The radius of sampled colours around a point, with 0 forming only 1 sample. </summary> public int SampleRadius = 1; /// <summary> The goal number of samples to be achieved. </summary> public int SampleCount = 1000; /// <summary> The frequency table providing the TrigradCompressor values regarding the chance a pixel will be sampled. </summary> public FrequencyTable FrequencyTable = null; /// <summary> The random number generator to be used by the TrigradCompressor. </summary> public Random Random; /// <summary> The factor to upscale the bitmap during compression. </summary> public int ScaleFactor; } }
mit
C#
f6fd7efeb3036f5288459ae7910938e94b741994
Add UVs to newly created geom meshes
deepmind/mujoco,deepmind/mujoco,deepmind/mujoco,deepmind/mujoco,deepmind/mujoco
unity/Runtime/Components/Shapes/MjMeshFilter.cs
unity/Runtime/Components/Shapes/MjMeshFilter.cs
// Copyright 2019 DeepMind Technologies Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Mujoco { [RequireComponent(typeof(MjShapeComponent))] [RequireComponent(typeof(MeshFilter))] [ExecuteInEditMode] public class MjMeshFilter : MonoBehaviour { private MjShapeComponent _geom; private Vector4 _shapeChangeStamp; private MeshFilter _meshFilter; protected void Awake() { _geom = GetComponent<MjShapeComponent>(); _shapeChangeStamp = new Vector4(0, 0, 0, -1); _meshFilter = GetComponent<MeshFilter>(); } protected void Update() { var currentChangeStamp = _geom.GetChangeStamp(); if ((_shapeChangeStamp - currentChangeStamp).magnitude <= 1e-3f) { return; } _shapeChangeStamp = currentChangeStamp; Tuple<Vector3[], int[]> meshData = _geom.BuildMesh(); if (meshData == null) { throw new ArgumentException("Unsupported geom shape detected"); } DisposeCurrentMesh(); var mesh = new Mesh(); // Name this mesh to easily track resources in Unity analysis tools. mesh.name = $"Mujoco mesh for {gameObject.name}, id:{mesh.GetInstanceID()}"; _meshFilter.sharedMesh = mesh; mesh.vertices = meshData.Item1; mesh.triangles = meshData.Item2; Vector2[] uvs = new Vector2[mesh.vertices.Length]; for (int i = 0; i < uvs.Length; i++){ uvs[i] = new Vector2(mesh.vertices[i].x, mesh.vertices[i].z); } mesh.uv = uvs; mesh.RecalculateNormals(); mesh.RecalculateTangents(); } protected void OnDestroy() { DisposeCurrentMesh(); } // Dynamically created meshes with no references are only disposed automatically on scene changes. // This prevents resource leaks in case the host environment doesn't reload scenes. private void DisposeCurrentMesh() { if (_meshFilter.sharedMesh != null) { #if UNITY_EDITOR DestroyImmediate(_meshFilter.sharedMesh); #else Destroy(_meshFilter.sharedMesh); #endif } } } }
// Copyright 2019 DeepMind Technologies Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Mujoco { [RequireComponent(typeof(MjShapeComponent))] [RequireComponent(typeof(MeshFilter))] [ExecuteInEditMode] public class MjMeshFilter : MonoBehaviour { private MjShapeComponent _geom; private Vector4 _shapeChangeStamp; private MeshFilter _meshFilter; protected void Awake() { _geom = GetComponent<MjShapeComponent>(); _shapeChangeStamp = new Vector4(0, 0, 0, -1); _meshFilter = GetComponent<MeshFilter>(); } protected void Update() { var currentChangeStamp = _geom.GetChangeStamp(); if ((_shapeChangeStamp - currentChangeStamp).magnitude <= 1e-3f) { return; } _shapeChangeStamp = currentChangeStamp; Tuple<Vector3[], int[]> meshData = _geom.BuildMesh(); if (meshData == null) { throw new ArgumentException("Unsupported geom shape detected"); } DisposeCurrentMesh(); var mesh = new Mesh(); // Name this mesh to easily track resources in Unity analysis tools. mesh.name = $"Mujoco mesh for {gameObject.name}, id:{mesh.GetInstanceID()}"; _meshFilter.sharedMesh = mesh; mesh.vertices = meshData.Item1; mesh.triangles = meshData.Item2; mesh.RecalculateNormals(); mesh.RecalculateTangents(); } protected void OnDestroy() { DisposeCurrentMesh(); } // Dynamically created meshes with no references are only disposed automatically on scene changes. // This prevents resource leaks in case the host environment doesn't reload scenes. private void DisposeCurrentMesh() { if (_meshFilter.sharedMesh != null) { #if UNITY_EDITOR DestroyImmediate(_meshFilter.sharedMesh); #else Destroy(_meshFilter.sharedMesh); #endif } } } }
apache-2.0
C#
a6cc9183406129457d84f713fdc78ae5bef5e1de
Package Update #CHANGE: Pushed AdamsLair.WinForms 1.1.6
AdamsLair/winforms
WinForms/Properties/AssemblyInfo.cs
WinForms/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("AdamsLair.WinForms")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AdamsLair.WinForms")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("735ee5dc-8c18-4a06-8e64-2f172ddd01cc")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.6")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("AdamsLair.WinForms")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AdamsLair.WinForms")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("735ee5dc-8c18-4a06-8e64-2f172ddd01cc")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.5")]
mit
C#
087257e210733ac153e3b35502da5efc02b4445f
Make MediaManager a static property
mike-rowley/XamarinMediaManager,mike-rowley/XamarinMediaManager,martijn00/XamarinMediaManager,martijn00/XamarinMediaManager
MediaManager/Platforms/Ios/Video/PlayerViewController.cs
MediaManager/Platforms/Ios/Video/PlayerViewController.cs
using AVKit; namespace MediaManager.Platforms.Ios.Video { public class PlayerViewController : AVPlayerViewController { protected static MediaManagerImplementation MediaManager => CrossMediaManager.Apple; public override void ViewWillDisappear(bool animated) { base.ViewWillDisappear(animated); if (MediaManager.MediaPlayer.VideoView == View.Superview) { MediaManager.MediaPlayer.VideoView = null; } Player = null; } } }
using AVKit; namespace MediaManager.Platforms.Ios.Video { public class PlayerViewController : AVPlayerViewController { protected MediaManagerImplementation MediaManager => CrossMediaManager.Apple; public override void ViewWillDisappear(bool animated) { base.ViewWillDisappear(animated); if (MediaManager.MediaPlayer.VideoView == View.Superview) { MediaManager.MediaPlayer.VideoView = null; } Player = null; } } }
mit
C#
92fa4b71facddae2fca8abf774f9ff7475d855fe
add tests for all methods
Pondidum/NuCache,Pondidum/NuCache,Pondidum/NuCache
NuCache.Tests/PackageSources/RemotePackageSourceTests.cs
NuCache.Tests/PackageSources/RemotePackageSourceTests.cs
using System; using NSubstitute; using NuCache.Infrastructure; using NuCache.PackageSources; namespace NuCache.Tests.PackageSources { public class RemotePackageSourceTests { private void Test(Action<RemotePackageSource, Uri> method) { var client = Substitute.For<WebClient>(); var transformer = new UriHostTransformer(new Uri("http://localhost.fiddler:42174")); var source = new RemotePackageSource(client, transformer); method(source, new Uri("http://example.com/api/v2")); client.Received().GetResponseAsync(new Uri("http://localhost.fiddler:42174/api/v2")); } public void When_calling_get() { Test((s,u) => s.Get(u)); } public void When_calling_metadata() { Test((s,u) => s.Metadata(u)); } public void When_calling_list() { Test((s,u) => s.List(u)); } public void When_calling_search() { Test((s,u) => s.Search(u)); } public void When_calling_findPackagesByID() { Test((s,u) => s.FindPackagesByID(u)); } public void When_calling_getPackageByID() { Test((s, u) => s.GetPackageByID(u)); } } }
using System; using NSubstitute; using NuCache.Infrastructure; using NuCache.PackageSources; namespace NuCache.Tests.PackageSources { public class RemotePackageSourceTests { public void When_calling_get() { var client = Substitute.For<WebClient>(); var transformer = new UriHostTransformer(new Uri("http://localhost.fiddler:42174")); var source = new RemotePackageSource(client, transformer); source.Get(new Uri("http://example.com/api/v2")); client.Received().GetResponseAsync(new Uri("http://localhost.fiddler:42174/api/v2")); } } }
lgpl-2.1
C#
11214bedb9d42ee93c09e25740a57bd354731abf
Decrease the interval
gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer
Server/Settings/Definition/IntervalSettingsDefinition.cs
Server/Settings/Definition/IntervalSettingsDefinition.cs
using LunaCommon.Xml; using System; namespace Server.Settings.Definition { [Serializable] public class IntervalSettingsDefinition { [XmlComment(Value = "Interval in ms at which the client will send POSITION updates of his vessel when other players are NEARBY. " + "Decrease it if your clients have good network connection and you plan to do dogfights, although in that case consider using interpolation aswell")] public int VesselPositionUpdatesMsInterval { get; set; } = 50; [XmlComment(Value = "Interval in ms at which the client will send POSITION updates for vessels that are uncontrolled and nearby him. " + "This interval is also applied used to send position updates of HIS OWN vessel when NOBODY is around")] public int SecondaryVesselPositionUpdatesMsInterval { get; set; } = 150; [XmlComment(Value = "Interval in ms at which users will check the controlled and close uncontrolled vessel and sync the parts that have changes " + "(ladders that extend or shields that open) to the server. " + "Caution! Puting a very low value could make clients with slow computers to lag a lot!")] public int VesselPartsSyncMsInterval { get; set; } = 500; [XmlComment(Value = "Send/Receive tick clock. Keep this value low but at least above 2ms to avoid extreme CPU usage.")] public int SendReceiveThreadTickMs { get; set; } = 5; [XmlComment(Value = "Main thread polling in ms. Keep this value low but at least above 2ms to avoid extreme CPU usage.")] public int MainTimeTick { get; set; } = 5; [XmlComment(Value = "Interval in ms at which internal LMP structures (Subspaces, Vessels, Scenario files, ...) will be backed up to a file")] public int BackupIntervalMs { get; set; } = 30000; } }
using LunaCommon.Xml; using System; namespace Server.Settings.Definition { [Serializable] public class IntervalSettingsDefinition { [XmlComment(Value = "Interval in ms at which the client will send POSITION updates of his vessel when other players are NEARBY. " + "Decrease it if your clients have good network connection and you plan to do dogfights, although in that case consider using interpolation aswell")] public int VesselPositionUpdatesMsInterval { get; set; } = 50; [XmlComment(Value = "Interval in ms at which the client will send POSITION updates for vessels that are uncontrolled and nearby him. " + "This interval is also applied used to send position updates of HIS OWN vessel when NOBODY is around")] public int SecondaryVesselPositionUpdatesMsInterval { get; set; } = 500; [XmlComment(Value = "Interval in ms at which users will check the controlled and close uncontrolled vessel and sync the parts that have changes " + "(ladders that extend or shields that open) to the server. " + "Caution! Puting a very low value could make clients with slow computers to lag a lot!")] public int VesselPartsSyncMsInterval { get; set; } = 500; [XmlComment(Value = "Send/Receive tick clock. Keep this value low but at least above 2ms to avoid extreme CPU usage.")] public int SendReceiveThreadTickMs { get; set; } = 5; [XmlComment(Value = "Main thread polling in ms. Keep this value low but at least above 2ms to avoid extreme CPU usage.")] public int MainTimeTick { get; set; } = 5; [XmlComment(Value = "Interval in ms at which internal LMP structures (Subspaces, Vessels, Scenario files, ...) will be backed up to a file")] public int BackupIntervalMs { get; set; } = 30000; } }
mit
C#
0ac346f8d122f00b829a657248fe18882589bb39
Fix NoShrineRoom logic if shrine is null
MoyTW/MTW_AncestorSpirits
Source/MTW_AncestorSpirits/ThoughtWorker_NoShrineRoom.cs
Source/MTW_AncestorSpirits/ThoughtWorker_NoShrineRoom.cs
using RimWorld; using Verse; namespace MTW_AncestorSpirits { class ThoughtWorker_NoShrineRoom : ThoughtWorker { private static RoomRoleDef shrineRoomDef = DefDatabase<RoomRoleDef>.GetNamed("MTW_ShrineRoom"); protected override ThoughtState CurrentStateInternal(Pawn p) { // TODO: There's gotta be a better way of doin' this! if (!AncestorUtils.IsAncestor(p)) { return ThoughtState.Inactive; } var shrine = Find.Map.GetComponent<MapComponent_AncestorTicker>().CurrentSpawner; if (shrine == null) { return ThoughtState.ActiveAtStage(1); } // HACK ALERT! Change Shrines to have an Interaction cell, and use that instead of a random one! var room = RoomQuery.RoomAtFast(shrine.RandomAdjacentCellCardinal()); if (room == null) { return ThoughtState.ActiveAtStage(1); } else if (room.Role != shrineRoomDef) { return ThoughtState.ActiveAtStage(1); } else { return ThoughtState.Inactive; } } } }
using RimWorld; using Verse; namespace MTW_AncestorSpirits { class ThoughtWorker_NoShrineRoom : ThoughtWorker { private static RoomRoleDef shrineRoomDef = DefDatabase<RoomRoleDef>.GetNamed("MTW_ShrineRoom"); protected override ThoughtState CurrentStateInternal(Pawn p) { // TODO: There's gotta be a better way of doin' this! if (!AncestorUtils.IsAncestor(p)) { return ThoughtState.Inactive; } var shrine = Find.Map.GetComponent<MapComponent_AncestorTicker>().CurrentSpawner; if (shrine == null) { return ThoughtState.Inactive; } // HACK ALERT! Change Shrines to have an Interaction cell, and use that instead of a random one! var room = RoomQuery.RoomAtFast(shrine.RandomAdjacentCellCardinal()); if (room == null) { return ThoughtState.ActiveAtStage(1); } else if (room.Role != shrineRoomDef) { return ThoughtState.ActiveAtStage(1); } else { return ThoughtState.Inactive; } } } }
mit
C#
16ef6c2748675dd20255649f443523fff06aaf14
Improve comments on the interface.
gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT
LINQToTTree/LINQToTTreeLib/ExecutionCommon/IQueryExectuor.cs
LINQToTTree/LINQToTTreeLib/ExecutionCommon/IQueryExectuor.cs
 using System.Collections.Generic; using System.IO; namespace LINQToTTreeLib.ExecutionCommon { /// <summary> /// Runs an execution request /// </summary> interface IQueryExectuor { /// <summary> /// Run request, and return the results /// </summary> /// <param name="queryDirectory"></param> /// <param name="templateFile">Path to the main runner file</param> /// <param name="varsToTransfer">A list of variables that are used as input to the routine.</param> /// <returns>A list of objects and names pulled from the output root file</returns> IDictionary<string, ROOTNET.Interface.NTObject> Execute( FileInfo templateFile, DirectoryInfo queryDirectory, IEnumerable<KeyValuePair<string, object>> varsToTransfer); /// <summary> /// Set the execution envrionment. Must be done before the call, should not /// change after the first setting. /// </summary> ExecutionEnvironment Environment { set; } } }
 using System.Collections.Generic; using System.IO; namespace LINQToTTreeLib.ExecutionCommon { /// <summary> /// Runs an execution request /// </summary> interface IQueryExectuor { /// <summary> /// Run request, and return the results /// </summary> /// <param name="remotePacket"></param> /// <returns></returns> IDictionary<string, ROOTNET.Interface.NTObject> Execute( FileInfo templateFile, DirectoryInfo queryDirectory, IEnumerable<KeyValuePair<string, object>> varsToTransfer); /// <summary> /// Set the execution envrionment. Must be done before the call, should not /// change after the first setting. /// </summary> ExecutionEnvironment Environment { set; } } }
lgpl-2.1
C#
3f8adc48a81c644c5b879715fa88e66b626618cc
Add exceptions messages
RockstarLabs/OwinOAuthProviders,NewBoCo/OwinOAuthProviders,qanuj/OwinOAuthProviders,CrustyJew/OwinOAuthProviders,nbelyh/OwinOAuthProviders,TerribleDev/OwinOAuthProviders,TerribleDev/OwinOAuthProviders,RockstarLabs/OwinOAuthProviders,qanuj/OwinOAuthProviders,NewBoCo/OwinOAuthProviders,yfann/OwinOAuthProviders,TerribleDev/OwinOAuthProviders,Lorac/OwinOAuthProviders,nbelyh/OwinOAuthProviders,CrustyJew/OwinOAuthProviders,yonglehou/OwinOAuthProviders,jmloeffler/OwinOAuthProviders,tparnell8/OwinOAuthProviders,NewBoCo/OwinOAuthProviders,qanuj/OwinOAuthProviders,tparnell8/OwinOAuthProviders,jmloeffler/OwinOAuthProviders,jmloeffler/OwinOAuthProviders,CrustyJew/OwinOAuthProviders,yonglehou/OwinOAuthProviders,yfann/OwinOAuthProviders,Lorac/OwinOAuthProviders,yonglehou/OwinOAuthProviders,yfann/OwinOAuthProviders,tparnell8/OwinOAuthProviders,TerribleDev/OwinOAuthProviders,RockstarLabs/OwinOAuthProviders,Lorac/OwinOAuthProviders,NewBoCo/OwinOAuthProviders,qanuj/OwinOAuthProviders,nbelyh/OwinOAuthProviders
Owin.Security.Providers/Imgur/ImgurAuthenticationDefaults.cs
Owin.Security.Providers/Imgur/ImgurAuthenticationDefaults.cs
namespace Owin.Security.Providers.Imgur { internal static class ImgurAuthenticationDefaults { internal const string AccessDeniedErrorMessage = "access_denied"; internal const string AccessTokenPropertyName = "access_token"; internal const string AccountIdPropertyName = "account_id"; internal const string AccountUsernamePropertyName = "account_username"; internal const string AuthenticationType = "Imgur"; internal const string AuthorizationCodeGrantType = "authorization_code"; internal const string AuthorizationUri = "https://api.imgur.com/oauth2/authorize"; internal const string CallbackPath = "/signin-imgur"; internal const string ClientIdParameter = "client_id"; internal const string ClientSecretParameter = "client_secret"; internal const string CodeParameter = "code"; internal const string CodeResponseType = "code"; internal const string CommunicationFailureMessage = "An error occurred while talking with imgur's server."; internal const string DeserializationFailureMessage = "The deserialization of the imgur's response failed. Perhaps imgur changed the response format?"; internal const string ErrorParameter = "error"; internal const string ExpiresInPropertyName = "expires_in"; internal const string GrantTypeParameter = "grant_type"; internal const string Int32Format = "D"; internal const string InvalidAuthenticationTicketMessage = "Invalid authentication ticket."; internal const string RefreshInPropertyName = "refresh_token"; internal const string ResponseTypeParameter = "response_type"; internal const string ScopePropertyName = "scope"; internal const string StateParameter = "state"; internal const string TokenTypePropertyName = "token_type"; internal const string TokenUri = "https://api.imgur.com/oauth2/token"; internal const string Version = "v1"; internal const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string"; } }
namespace Owin.Security.Providers.Imgur { internal static class ImgurAuthenticationDefaults { internal const string AccessDeniedErrorMessage = "access_denied"; internal const string AccessTokenPropertyName = "access_token"; internal const string AccountIdPropertyName = "account_id"; internal const string AccountUsernamePropertyName = "account_username"; internal const string AuthenticationType = "Imgur"; internal const string AuthorizationCodeGrantType = "authorization_code"; internal const string AuthorizationUri = "https://api.imgur.com/oauth2/authorize"; internal const string CallbackPath = "/signin-imgur"; internal const string ClientIdParameter = "client_id"; internal const string ClientSecretParameter = "client_secret"; internal const string CodeParameter = "code"; internal const string CodeResponseType = "code"; internal const string CommunicationFailureMessage = ""; // TODO internal const string DeserializationFailureMessage = ""; // TODO internal const string ErrorParameter = "error"; internal const string ExpiresInPropertyName = "expires_in"; internal const string GrantTypeParameter = "grant_type"; internal const string Int32Format = "D"; internal const string InvalidAuthenticationTicketMessage = ""; // TODO internal const string RefreshInPropertyName = "refresh_token"; internal const string ResponseTypeParameter = "response_type"; internal const string ScopePropertyName = "scope"; internal const string StateParameter = "state"; internal const string TokenTypePropertyName = "token_type"; internal const string TokenUri = "https://api.imgur.com/oauth2/token"; internal const string Version = "v1"; internal const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string"; } }
mit
C#
1230a68e8dfa3aae8c8904234e1597352a6ade29
Remove PublishConfiguration.QueueName (#1051)
micdenny/EasyNetQ,EasyNetQ/EasyNetQ
Source/EasyNetQ/FluentConfiguration/IPublishConfiguration.cs
Source/EasyNetQ/FluentConfiguration/IPublishConfiguration.cs
namespace EasyNetQ.FluentConfiguration { /// <summary> /// Allows publish configuration to be fluently extended without adding overloads to IBus /// /// e.g. /// x => x.WithTopic("*.brighton").WithPriority(2) /// </summary> public interface IPublishConfiguration { /// <summary> /// Sets a priority of the message /// </summary> /// <param name="priority">The priority to set</param> /// <returns>IPublishConfiguration</returns> IPublishConfiguration WithPriority(byte priority); /// <summary> /// Sets a topic for the message /// </summary> /// <param name="topic">The topic to set</param> /// <returns>IPublishConfiguration</returns> IPublishConfiguration WithTopic(string topic); /// <summary> /// Sets a TTL for the message /// </summary> /// <param name="expires">The TTL to set in milliseconds</param> /// <returns>IPublishConfiguration</returns> IPublishConfiguration WithExpires(int expires); } public class PublishConfiguration : IPublishConfiguration { private readonly string defaultTopic; public PublishConfiguration(string defaultTopic) { Preconditions.CheckNotNull(defaultTopic, "defaultTopic"); this.defaultTopic = defaultTopic; } public IPublishConfiguration WithPriority(byte priority) { Priority = priority; return this; } public IPublishConfiguration WithTopic(string topic) { Topic = topic; return this; } public IPublishConfiguration WithExpires(int expires) { Expires = expires; return this; } public byte? Priority { get; private set; } private string topic; public string Topic { get { return topic ?? defaultTopic; } private set { topic = value; } } public int? Expires { get; private set; } } }
namespace EasyNetQ.FluentConfiguration { /// <summary> /// Allows publish configuration to be fluently extended without adding overloads to IBus /// /// e.g. /// x => x.WithTopic("*.brighton").WithPriority(2) /// </summary> public interface IPublishConfiguration { /// <summary> /// Sets a priority of the message /// </summary> /// <param name="priority">The priority to set</param> /// <returns>IPublishConfiguration</returns> IPublishConfiguration WithPriority(byte priority); /// <summary> /// Sets a topic for the message /// </summary> /// <param name="topic">The topic to set</param> /// <returns>IPublishConfiguration</returns> IPublishConfiguration WithTopic(string topic); /// <summary> /// Sets a TTL for the message /// </summary> /// <param name="expires">The TTL to set in milliseconds</param> /// <returns>IPublishConfiguration</returns> IPublishConfiguration WithExpires(int expires); /// <summary> /// Sets the queue name to publish to /// </summary> /// <param name="queueName">The queue name</param> /// <returns>IPublishConfiguration</returns> IPublishConfiguration WithQueueName(string queueName); } public class PublishConfiguration : IPublishConfiguration { private readonly string defaultTopic; public PublishConfiguration(string defaultTopic) { Preconditions.CheckNotNull(defaultTopic, "defaultTopic"); this.defaultTopic = defaultTopic; } public IPublishConfiguration WithPriority(byte priority) { Priority = priority; return this; } public IPublishConfiguration WithTopic(string topic) { Topic = topic; return this; } public IPublishConfiguration WithExpires(int expires) { Expires = expires; return this; } public IPublishConfiguration WithQueueName(string queueName) { QueueName = queueName; return this; } public byte? Priority { get; private set; } private string topic; public string Topic { get { return topic ?? defaultTopic; } private set { topic = value; } } public int? Expires { get; private set; } public string QueueName { get; private set; } } }
mit
C#
af1aa725a3a5686e0202b87e9d7ac5b37f5c21b7
Add a few more tests
aarondandy/we-cant-spell
WeCantSpell.Tests/Integration/CSharp/CommentSpellingTests.cs
WeCantSpell.Tests/Integration/CSharp/CommentSpellingTests.cs
using System.Collections.Generic; using System.Threading.Tasks; using FluentAssertions; using WeCantSpell.Tests.Utilities; using Xunit; namespace WeCantSpell.Tests.Integration.CSharp { public class CommentSpellingTests : CSharpTestBase { public static IEnumerable<object[]> can_find_mistakes_in_comments_data { get { yield return new object[] { "aardvark", 660 }; yield return new object[] { "simple", 1186 }; yield return new object[] { "under", 1235 }; yield return new object[] { "inline", 111 }; yield return new object[] { "tag", 320 }; yield return new object[] { "Here", 898 }; yield return new object[] { "Just", 1130 }; } } [Theory, MemberData(nameof(can_find_mistakes_in_comments_data))] public async Task can_find_mistakes_in_comments(string expectedWord, int expectedStart) { var expectedEnd = expectedStart + expectedWord.Length; var analyzer = new SpellingAnalyzerCSharp(new WrongWordChecker(expectedWord)); var project = await ReadCodeFileAsProjectAsync("XmlDoc.SimpleExamples.cs"); var diagnostics = await GetDiagnosticsAsync(project, analyzer); diagnostics.Should().ContainSingle() .Subject.Should() .HaveId("SP3112") .And.HaveLocation(expectedStart, expectedEnd, "XmlDoc.SimpleExamples.cs") .And.HaveMessageContaining(expectedWord); } } }
using System.Collections.Generic; using System.Threading.Tasks; using FluentAssertions; using WeCantSpell.Tests.Utilities; using Xunit; namespace WeCantSpell.Tests.Integration.CSharp { public class CommentSpellingTests : CSharpTestBase { public static IEnumerable<object[]> can_find_mistakes_in_comments_data { get { yield return new object[] { "aardvark", 660 }; yield return new object[] { "simple", 1186 }; yield return new object[] { "under", 1235 }; } } [Theory, MemberData(nameof(can_find_mistakes_in_comments_data))] public async Task can_find_mistakes_in_comments(string expectedWord, int expectedStart) { var expectedEnd = expectedStart + expectedWord.Length; var analyzer = new SpellingAnalyzerCSharp(new WrongWordChecker(expectedWord)); var project = await ReadCodeFileAsProjectAsync("XmlDoc.SimpleExamples.cs"); var diagnostics = await GetDiagnosticsAsync(project, analyzer); diagnostics.Should().ContainSingle() .Subject.Should() .HaveId("SP3112") .And.HaveLocation(expectedStart, expectedEnd, "XmlDoc.SimpleExamples.cs") .And.HaveMessageContaining(expectedWord); } } }
mit
C#
16fd7f5a287cf921445f51ae7a587b6ccebe1327
Simplify slightly redundant assertions
peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu
osu.Game.Tests/Database/RulesetStoreTests.cs
osu.Game.Tests/Database/RulesetStoreTests.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Game.Models; using osu.Game.Stores; namespace osu.Game.Tests.Database { public class RulesetStoreTests : RealmTest { [Test] public void TestCreateStore() { RunTestWithRealm((realmFactory, storage) => { var rulesets = new RealmRulesetStore(realmFactory, storage); Assert.AreEqual(4, rulesets.AvailableRulesets.Count()); Assert.AreEqual(4, realmFactory.Context.All<RealmRuleset>().Count()); }); } [Test] public void TestCreateStoreTwiceDoesntAddRulesetsAgain() { RunTestWithRealm((realmFactory, storage) => { var rulesets = new RealmRulesetStore(realmFactory, storage); var rulesets2 = new RealmRulesetStore(realmFactory, storage); Assert.AreEqual(4, rulesets.AvailableRulesets.Count()); Assert.AreEqual(4, rulesets2.AvailableRulesets.Count()); Assert.AreEqual(rulesets.AvailableRulesets.First(), rulesets2.AvailableRulesets.First()); Assert.AreEqual(4, realmFactory.Context.All<RealmRuleset>().Count()); }); } [Test] public void TestRetrievedRulesetsAreDetached() { RunTestWithRealm((realmFactory, storage) => { var rulesets = new RealmRulesetStore(realmFactory, storage); Assert.IsFalse(rulesets.AvailableRulesets.First().IsManaged); Assert.IsFalse(rulesets.GetRuleset(0)?.IsManaged); Assert.IsFalse(rulesets.GetRuleset("mania")?.IsManaged); }); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Game.Models; using osu.Game.Stores; namespace osu.Game.Tests.Database { public class RulesetStoreTests : RealmTest { [Test] public void TestCreateStore() { RunTestWithRealm((realmFactory, storage) => { var rulesets = new RealmRulesetStore(realmFactory, storage); Assert.AreEqual(4, rulesets.AvailableRulesets.Count()); Assert.AreEqual(4, realmFactory.Context.All<RealmRuleset>().Count()); }); } [Test] public void TestCreateStoreTwiceDoesntAddRulesetsAgain() { RunTestWithRealm((realmFactory, storage) => { var rulesets = new RealmRulesetStore(realmFactory, storage); var rulesets2 = new RealmRulesetStore(realmFactory, storage); Assert.AreEqual(4, rulesets.AvailableRulesets.Count()); Assert.AreEqual(4, rulesets2.AvailableRulesets.Count()); Assert.AreEqual(rulesets.AvailableRulesets.First(), rulesets2.AvailableRulesets.First()); Assert.AreEqual(4, realmFactory.Context.All<RealmRuleset>().Count()); }); } [Test] public void TestRetrievedRulesetsAreDetached() { RunTestWithRealm((realmFactory, storage) => { var rulesets = new RealmRulesetStore(realmFactory, storage); Assert.IsTrue(rulesets.AvailableRulesets.First().IsManaged == false); Assert.IsTrue(rulesets.GetRuleset(0)?.IsManaged == false); Assert.IsTrue(rulesets.GetRuleset("mania")?.IsManaged == false); }); } } }
mit
C#
8117d3220157b71ebdb3beaf84fc274efaba16e9
add notes about Repository interface structure and direction
EdVinyard/DddSandbox
Domain/Aggregate/Auction/IReverseAuctionRepository.cs
Domain/Aggregate/Auction/IReverseAuctionRepository.cs
using DDD; using System; using System.Collections.Generic; namespace Domain.Aggregate.Auction { // TODO: This Repository interface doesn't conform to either // of the recommended designs, in particular, the Update() method. // // Collection-Oriented: the "traditional DDD approach because it adheres to // the basic ideas presented in the original DDD pattern. These very // closely mimic a collection, simulating at least some of its standard // interface. Here you design a Repository interface that does not hint // in any way that there is an underlying persistence mechanism, avoiding // any notion of saving or persisting data to a store." // - IDDD, Vernor, Chapter: Repositories // // Persistence-Oriented: you "must explicitly put() both new and changed // objects into the store, effectively replacing any value previously // associated with the given key. Using these kinds of data stores // greatly simplifies the basic writes and reads of Aggregates." // - IDDD, Vernor, Chapter: Repositories // // These offer the advantage that they are more amenable to changes in // persistence mechanism, for example from a relational database to a // Object- or Document-oriented data store. public interface IReverseAuctionRepository : IRepository { // TODO: To preserve the illusion of an in-memory Set as the // Repository, should this method be named "Add"? ReverseAuctionAggregate Save(ReverseAuctionAggregate ra); // TODO: In a Collection-Oriented repository, mimicking a Set, this // could simply be the indexer-getter (i.e., `repository[id]`), but // this is OK as is. ReverseAuctionAggregate Get(int id); // TODO: Is this method needed? If NHibernate is tracking dirty // (changed) instances, and the FlushMode is set correctly, I think // this method is unneccessary. ReverseAuctionAggregate Update(ReverseAuctionAggregate ra); // TODO: Convert the following method into an example of a "use-case // optimal query" that cuts across Aggregate boundaries and returns // a collection of Value Types. In this case, return a Value Type // "projection" that cuts across the ReverseAuction and Bid Aggregates, // including information that would normally be accessible only by // navigation from each root, separately. A direct query is // optimization, but it's OK! We'll NEVER use the returned Value // Types to mutate the Domain directly, but often the end-user will // direct some mutation based on the identifiers returned in the // Value Type projection. // "This is where you specify a complex query against the persistence // mechanism, dynamically placing the results into a Value Object(6) // specifically designed to address the needs of the use case. // // It should not seem strange for a Repository to in some cases answer // a Value Object rather than an Aggregate instance.A Repository that // provides a size() method answers a very simple Value in the form // of an integer count of the total Aggregate instances it holds. A // use case optimal query is just extending this notion a bit to // provide a somewhat more complex Value, one that addresses more // complex client demands." // // - IDDD, Vernor, Chapter: Repositories /// <summary> /// Find all auctions that are "live" (i.e., currently accepting bids) /// and return them one page at a time. /// </summary> IReadOnlyList<ReverseAuction> GetLive( DateTimeOffset dt, int pageSize, int pageIndex); // "If you find that you must create many finder methods supporting // use case optimal queries on multiple Repositories, it’s probably // a code smell.First of all, this situation could be an indication // that you’ve misjudged Aggregate boundaries and overlooked the // opportunity to design one or more Aggregates of different types. // The code smell here might be called Repository masks Aggregate // mis-design. // // However, what if you encounter this situation and your analysis // indicates that your Aggregate boundaries are well designed? This // could point to the need to consider using CQRS (4)." // // - IDDD, Vernor, Chapter: Repositories } }
using DDD; using System; using System.Collections.Generic; namespace Domain.Aggregate.Auction { public interface IReverseAuctionRepository : IRepository { ReverseAuctionAggregate Save(ReverseAuctionAggregate ra); ReverseAuctionAggregate Get(int id); ReverseAuctionAggregate Update(ReverseAuctionAggregate ra); IReadOnlyList<ReverseAuction> GetLive( DateTimeOffset dt, int pageSize, int pageIndex); } }
mit
C#
50f0bf53e1c24ffbb7fdc90caf7551920ba14d23
Add resources
Vultour/music-tracker
MusicTracker/MusicTracker/GUI/MainWindowController.cs
MusicTracker/MusicTracker/GUI/MainWindowController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using MusicTracker.Core; namespace MusicTracker.GUI { class MainWindowController { private MusicList musicList; public MainWindow View { get; private set; } public MainWindowController() { this.musicList = new MusicList(); this.View = new MainWindow(); } private void loadPrevious() { if (!Directory.Exists(Properties.Resources.SAVE_FILE_PATH)) { Directory.CreateDirectory(Properties.Resources.SAVE_FILE_PATH); } if (!File.Exists(String.Format("{0}\\{1}", Properties.Resources.SAVE_FILE_PATH, Properties.Resources.SAVE_FILE_NAME))) { this.musicList } } // TODO: Add event handlers } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MusicTracker.GUI { class MainWindowController { public MainWindow View { get; private set; } public MainWindowController() { this.View = new MainWindow(); } // TODO: Add event handlers } }
apache-2.0
C#
ffeb4867b720707c2ecc4343e9a7d9e273cafa96
Improve TruncateMilliseconds test helper
libgit2/libgit2sharp,PKRoma/libgit2sharp
LibGit2Sharp.Tests/TestHelpers/DateTimeOffsetExtensions.cs
LibGit2Sharp.Tests/TestHelpers/DateTimeOffsetExtensions.cs
using System; namespace LibGit2Sharp.Tests.TestHelpers { public static class DateTimeOffsetExtensions { public static DateTimeOffset TruncateMilliseconds(this DateTimeOffset dto) => new DateTimeOffset(dto.Year, dto.Month, dto.Day, dto.Hour, dto.Minute, dto.Second, dto.Offset); } }
using System; namespace LibGit2Sharp.Tests.TestHelpers { public static class DateTimeOffsetExtensions { public static DateTimeOffset TruncateMilliseconds(this DateTimeOffset dto) { // From http://stackoverflow.com/a/1005222/335418 return dto.AddTicks( - (dto.Ticks % TimeSpan.TicksPerSecond)); } } }
mit
C#
6d3b4b089fc2ce8eb35c13eb733a0841b0aa5735
Update ServicesManager.cs
odaibert/Service-Fabric-Self-Scale-Service
SaaSManagerService/ServicesManager/ServicesManager.cs
SaaSManagerService/ServicesManager/ServicesManager.cs
using System; using System.Collections.Generic; using System.Fabric; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceFabric.Services.Communication.Runtime; using Microsoft.ServiceFabric.Services.Runtime; namespace ServicesManager { /// <summary> /// The FabricRuntime creates an instance of this class for each service type instance. /// In some point, need to change to Stateful Service? /// </summary> internal sealed class ServicesManager : StatelessService // In some point, change to stateful service { public ServicesManager(StatelessServiceContext context) : base(context) { } /// <summary> /// Optional override to create listeners (like tcp, http) for this service instance. /// </summary> /// <returns>The collection of listeners.</returns> protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners() { return new ServiceInstanceListener[] { new ServiceInstanceListener(serviceContext => new OwinCommunicationListener(Startup.ConfigureApp, serviceContext, ServiceEventSource.Current, "ServiceEndpoint")) }; } } }
using System; using System.Collections.Generic; using System.Fabric; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceFabric.Services.Communication.Runtime; using Microsoft.ServiceFabric.Services.Runtime; namespace ServicesManager { /// <summary> /// The FabricRuntime creates an instance of this class for each service type instance. /// In some point, need to change to Stateful Service? /// </summary> internal sealed class ServicesManager : StatelessService { public ServicesManager(StatelessServiceContext context) : base(context) { } /// <summary> /// Optional override to create listeners (like tcp, http) for this service instance. /// </summary> /// <returns>The collection of listeners.</returns> protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners() { return new ServiceInstanceListener[] { new ServiceInstanceListener(serviceContext => new OwinCommunicationListener(Startup.ConfigureApp, serviceContext, ServiceEventSource.Current, "ServiceEndpoint")) }; } } }
mit
C#
afeb230d1ed4137014355f4e58fe7cb408267610
update Orchard.RewriteRules to address unthemed 404 and 500 pages
andrewconnell/aci-orchardcms,andrewconnell/aci-orchardcms,andrewconnell/aci-orchardcms,andrewconnell/aci-orchardcms
Modules/Contrib.RewriteRules/Controllers/HomeController.cs
Modules/Contrib.RewriteRules/Controllers/HomeController.cs
using Orchard.Themes; using System.Web.Mvc; namespace Contrib.RewriteRules.Controllers { [Themed] public class HomeController : Controller { public ActionResult Rewrite(string path) { return new HttpNotFoundResult(); } } }
using System.Web.Mvc; namespace Contrib.RewriteRules.Controllers { public class HomeController : Controller { public ActionResult Rewrite(string path) { return new HttpNotFoundResult(); } } }
bsd-3-clause
C#
4e9f638f255e9e8f2196fd0a7c03bd436fe2b4d8
revert change
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/ViewModels/NavBarItemViewModel.cs
WalletWasabi.Fluent/ViewModels/NavBarItemViewModel.cs
using ReactiveUI; using System; namespace WalletWasabi.Fluent.ViewModels { public abstract class NavBarItemViewModel : ViewModelBase, IRoutableViewModel { private bool _isSelected; private bool _isExpanded; private string _title; public NavBarItemViewModel(IScreen screen) { HostScreen = screen; } public string UrlPathSegment { get; } = Guid.NewGuid().ToString().Substring(0, 5); public IScreen HostScreen { get; } public bool IsExpanded { get => _isExpanded; set => this.RaiseAndSetIfChanged(ref _isExpanded, value); } public string Title { get => _title; set => this.RaiseAndSetIfChanged(ref _title, value); } public bool IsSelected { get => _isSelected; set => this.RaiseAndSetIfChanged(ref _isSelected, value); } } }
using ReactiveUI; using System; namespace WalletWasabi.Fluent.ViewModels { public abstract class NavBarItemViewModel : ViewModelBase, IRoutableViewModel { private bool _isSelected; private bool _isExpanded; private string _title; public NavBarItemViewModel(IScreen screen) { HostScreen = screen; } public string UrlPathSegment => Guid.NewGuid().ToString().Substring(0, 5); public IScreen HostScreen { get; } public bool IsExpanded { get => _isExpanded; set => this.RaiseAndSetIfChanged(ref _isExpanded, value); } public string Title { get => _title; set => this.RaiseAndSetIfChanged(ref _title, value); } public bool IsSelected { get => _isSelected; set => this.RaiseAndSetIfChanged(ref _isSelected, value); } } }
mit
C#
06229ad7b2c39c17bc332ca8ff1ca5e90ba4577f
Fix a typo in const name
LibertyLocked/RestRPC,LibertyLocked/RestRPC,LibertyLocked/RestRPC,LibertyLocked/RestRPC
WebScriptHook.Framework/Messages/Outputs/ChannelRequest.cs
WebScriptHook.Framework/Messages/Outputs/ChannelRequest.cs
namespace WebScriptHook.Framework.Messages.Outputs { /// <summary> /// Sent by the component to request a channel for itself on the server. /// This tells the server the name of this component, as well as the maximum number of requests /// the component can handle per tick. /// Once the server receives this message, a channel will be created, registered under this component's name. /// Inputs sent by web clients will then be delivered to this component. /// </summary> class ChannelRequest : WebOutput { const char HEADER_CHANNEL = 'n'; public ChannelRequest(string ComponentName, int InputQueueLimit) : base(HEADER_CHANNEL, new object[] { ComponentName, InputQueueLimit }, null) { } } }
namespace WebScriptHook.Framework.Messages.Outputs { /// <summary> /// Sent by the component to request a channel for itself on the server. /// This tells the server the name of this component, as well as the maximum number of requests /// the component can handle per tick. /// Once the server receives this message, a channel will be created, registered under this component's name. /// Inputs sent by web clients will then be delivered to this component. /// </summary> class ChannelRequest : WebOutput { const char HEADER_CACHE = 'n'; public ChannelRequest(string ComponentName, int InputQueueLimit) : base(HEADER_CACHE, new object[] { ComponentName, InputQueueLimit }, null) { } } }
mit
C#
d745e5a2e7ae034635cc372f2d942af36df85c53
Make sure previous changes about Android project namespace update is properly taken into account.
Noxalus/Xmas-Hell
Xmas-Hell/Xmas-Hell-Android/Resources/Resource.Designer.cs
Xmas-Hell/Xmas-Hell-Android/Resources/Resource.Designer.cs
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <auto-generated> // Ce code a été généré par un outil. // Version du runtime :4.0.30319.42000 // // Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si // le code est régénéré. // </auto-generated> //------------------------------------------------------------------------------ [assembly: global::Android.Runtime.ResourceDesignerAttribute("XmasHellAndroid.Resource", IsApplication=true)] namespace XmasHellAndroid { [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")] public partial class Resource { static Resource() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } public static void UpdateIdValues() { } public partial class Attribute { static Attribute() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Attribute() { } } public partial class Drawable { // aapt resource value: 0x7f020000 public const int Icon = 2130837504; // aapt resource value: 0x7f020001 public const int Splash = 2130837505; static Drawable() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Drawable() { } } public partial class String { // aapt resource value: 0x7f030000 public const int ApplicationName = 2130903040; static String() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private String() { } } public partial class Style { // aapt resource value: 0x7f040000 public const int Theme_Splash = 2130968576; static Style() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Style() { } } } } #pragma warning restore 1591
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <auto-generated> // Ce code a été généré par un outil. // Version du runtime :4.0.30319.42000 // // Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si // le code est régénéré. // </auto-generated> //------------------------------------------------------------------------------ [assembly: global::Android.Runtime.ResourceDesignerAttribute("Xmas_Hell_Android.Resource", IsApplication=true)] namespace Xmas_Hell_Android { [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")] public partial class Resource { static Resource() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } public static void UpdateIdValues() { } public partial class Attribute { static Attribute() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Attribute() { } } public partial class Drawable { // aapt resource value: 0x7f020000 public const int Icon = 2130837504; // aapt resource value: 0x7f020001 public const int Splash = 2130837505; static Drawable() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Drawable() { } } public partial class String { // aapt resource value: 0x7f030000 public const int ApplicationName = 2130903040; static String() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private String() { } } public partial class Style { // aapt resource value: 0x7f040000 public const int Theme_Splash = 2130968576; static Style() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Style() { } } } } #pragma warning restore 1591
mit
C#
e212305f1a48d5e41ef8414a4a19a0eb4241b715
add tumble function
GRGSIBERIA/maya-camera
MayaCamera.cs
MayaCamera.cs
using UnityEngine; using System.Collections; public class MayaCamera : MonoBehaviour { Vector3 lookAtPosition; public float dollySpeed = 1f; public float tumbleSpeed = 1f; public float trackSpeed = 1f; Vector3 prevMousePosition; Vector3 prevMouseSpeed; public Vector3 mouseSpeed; public Vector3 mouseAccel; // Use this for initialization void Start () { lookAtPosition = Vector3.zero; prevMousePosition = Input.mousePosition; mouseSpeed = Vector3.zero; mouseAccel = Vector3.zero; Camera.main.transform.LookAt(lookAtPosition); } // Update is called once per frame void Update () { CalculateMousePhisics(); Tumble(); Dolly(); Track(); } void Tumble() { if (Input.GetKey(KeyCode.LeftAlt) && Input.GetMouseButton(0)) { // NbN, tumble Vector3 inverse_vector = Camera.main.transform.position - lookAtPosition; float length = inverse_vector.magnitude; inverse_vector.Normalize(); Vector3 rotated_vector = Quaternion.Euler( mouseSpeed.x * tumbleSpeed, mouseSpeed.y * tumbleSpeed, 0) * inverse_vector; Camera.main.transform.position = rotated_vector + lookAtPosition; Camera.main.transform.LookAt(lookAtPosition); } } void Dolly() { if (Input.GetKey(KeyCode.LeftAlt) && Input.GetMouseButton(1)) { // ENbN, dolly var dollied_local = Camera.main.transform.localPosition; dollied_local.z -= mouseSpeed.y * dollySpeed; Camera.main.transform.localPosition = dollied_local; } } void Track() { if (Input.GetKey(KeyCode.LeftAlt) && Input.GetMouseButton(2)) { // NbN, track Camera.main.transform.localPosition -= mouseSpeed; lookAtPosition -= mouseSpeed; } } void CalculateMousePhisics() { // }EX̑xxvZ mouseSpeed = Input.mousePosition - prevMousePosition; mouseAccel = mouseSpeed - prevMouseSpeed; prevMouseSpeed = mouseSpeed; prevMousePosition = Input.mousePosition; } }
using UnityEngine; using System.Collections; public class MayaCamera : MonoBehaviour { public float dollySpeed = 1f; public float tumbleSpeed = 1f; public float trackSpeed = 1f; Vector3 prevMousePosition; Vector3 prevMouseSpeed; public Vector3 mouseSpeed; public Vector3 mouseAccel; // Use this for initialization void Start () { prevMousePosition = Input.mousePosition; mouseSpeed = Vector3.zero; mouseAccel = Vector3.zero; } // Update is called once per frame void Update () { CalculateMousePhisics(); Tumble(); Dolly(); Track(); } void Tumble() { if (Input.GetKey(KeyCode.LeftAlt) && Input.GetMouseButton(0)) { // NbN, tumble } } void Dolly() { if (Input.GetKey(KeyCode.LeftAlt) && Input.GetMouseButton(1)) { // ENbN, dolly var dollied_local = Camera.main.transform.localPosition; dollied_local.z -= mouseSpeed.y * dollySpeed; Camera.main.transform.localPosition = dollied_local; } } void Track() { if (Input.GetKey(KeyCode.LeftAlt) && Input.GetMouseButton(2)) { // NbN, track Camera.main.transform.localPosition -= mouseSpeed; } } void CalculateMousePhisics() { // }EX̑xxvZ mouseSpeed = Input.mousePosition - prevMousePosition; mouseAccel = mouseSpeed - prevMouseSpeed; prevMouseSpeed = mouseSpeed; prevMousePosition = Input.mousePosition; } }
bsd-3-clause
C#
0367c147c035cbda191b65f874b9cc24e676ffce
Fix non-variant default name for tests-weekly (#1435)
tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools
tools/pipeline-generator/Azure.Sdk.Tools.PipelineGenerator/Conventions/WeeklyIntegrationTestingPipelineConvention.cs
tools/pipeline-generator/Azure.Sdk.Tools.PipelineGenerator/Conventions/WeeklyIntegrationTestingPipelineConvention.cs
using Microsoft.Extensions.Logging; using Microsoft.TeamFoundation.Build.WebApi; namespace PipelineGenerator.Conventions { public class WeeklyIntegrationTestingPipelineConvention : IntegrationTestingPipelineConvention { public WeeklyIntegrationTestingPipelineConvention(ILogger logger, PipelineGenerationContext context) : base(logger, context) { } protected override string GetDefinitionName(SdkComponent component) { var definitionName = $"{Context.Prefix} - {component.Name} - tests-weekly"; if (component.Variant != null) { definitionName += $".{component.Variant}"; } return definitionName; } protected override Schedule CreateScheduleFromDefinition(BuildDefinition definition) { var bucket = definition.Id % TotalBuckets; var startHours = bucket / BucketsPerHour; var startMinutes = bucket % BucketsPerHour; var schedule = new Schedule { DaysToBuild = ScheduleDays.Saturday | ScheduleDays.Sunday, ScheduleOnlyWithChanges = true, StartHours = FirstSchedulingHour + startHours, StartMinutes = startMinutes * BucketSizeInMinutes, TimeZoneId = "Pacific Standard Time", }; schedule.BranchFilters.Add("+master"); return schedule; } } }
using Microsoft.Extensions.Logging; using Microsoft.TeamFoundation.Build.WebApi; namespace PipelineGenerator.Conventions { public class WeeklyIntegrationTestingPipelineConvention : IntegrationTestingPipelineConvention { public WeeklyIntegrationTestingPipelineConvention(ILogger logger, PipelineGenerationContext context) : base(logger, context) { } protected override string GetDefinitionName(SdkComponent component) { return component.Variant == null ? $"{Context.Prefix} - {component.Name} - tests" : $"{Context.Prefix} - {component.Name} - tests-weekly.{component.Variant}"; } protected override Schedule CreateScheduleFromDefinition(BuildDefinition definition) { var bucket = definition.Id % TotalBuckets; var startHours = bucket / BucketsPerHour; var startMinutes = bucket % BucketsPerHour; var schedule = new Schedule { DaysToBuild = ScheduleDays.Saturday | ScheduleDays.Sunday, ScheduleOnlyWithChanges = true, StartHours = FirstSchedulingHour + startHours, StartMinutes = startMinutes * BucketSizeInMinutes, TimeZoneId = "Pacific Standard Time", }; schedule.BranchFilters.Add("+master"); return schedule; } } }
mit
C#
4e10d191756c505d48a56bcaa499954c17f7f0f1
Update default Max Body Size
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.AspNetCore.ResponseCaching/ResponseCacheOptions.cs
src/Microsoft.AspNetCore.ResponseCaching/ResponseCacheOptions.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. using System.ComponentModel; using Microsoft.AspNetCore.ResponseCaching.Internal; namespace Microsoft.AspNetCore.Builder { public class ResponseCacheOptions { /// <summary> /// The largest cacheable size for the response body in bytes. The default is set to 64 MB. /// </summary> public long MaximumBodySize { get; set; } = 64 * 1024 * 1024; /// <summary> /// <c>true</c> if request paths are case-sensitive; otherwise <c>false</c>. The default is to treat paths as case-insensitive. /// </summary> public bool UseCaseSensitivePaths { get; set; } = false; /// <summary> /// For testing purposes only. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] internal ISystemClock SystemClock { get; set; } = new SystemClock(); } }
// 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.ComponentModel; using Microsoft.AspNetCore.ResponseCaching.Internal; namespace Microsoft.AspNetCore.Builder { public class ResponseCacheOptions { /// <summary> /// The largest cacheable size for the response body in bytes. The default is set to 1 MB. /// </summary> public long MaximumBodySize { get; set; } = 1024 * 1024; /// <summary> /// <c>true</c> if request paths are case-sensitive; otherwise <c>false</c>. The default is to treat paths as case-insensitive. /// </summary> public bool UseCaseSensitivePaths { get; set; } = false; /// <summary> /// For testing purposes only. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] internal ISystemClock SystemClock { get; set; } = new SystemClock(); } }
apache-2.0
C#