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
6b4c227a63315a34f5d450980399882cceeac22f
change inner routine of TrExtension
TakeAsh/cs-WpfUtility
WpfUtility/TrExtension.cs
WpfUtility/TrExtension.cs
using System; using System.Resources; using System.Windows.Markup; using System.Xaml; namespace WpfUtility { /// <summary> /// Translation Extension for XAML Markup /// </summary> /// <remarks> /// <list type="bullet"> /// <item>[XAML のマークアップ拡張を使った WPF での国際化 | プログラマーズ雑記帳](http://yohshiy.blog.fc2.com/blog-entry-242.html)</item> /// <item>[Internationalization in .NET and WPF - Lorenz Cuno Klopfenstein - Klopfenstein.net](http://www.klopfenstein.net/lorenz.aspx/internationalization-in-net-and-wpf-presentation-foundation)</item> /// <item>[Accessing "current class" from WPF custom MarkupExtension - Stack Overflow](http://stackoverflow.com/questions/3047448)</item> /// </list> /// </remarks> [MarkupExtensionReturnType(typeof(string))] public class TrExtension : MarkupExtension { const string NotFoundError = "#NotFound#"; string _key; public TrExtension(string key) { _key = key; } public override object ProvideValue(IServiceProvider serviceProvider) { if (String.IsNullOrEmpty(_key)) { return NotFoundError; } ResourceManager resourceManager; var rootObjectProvider = GetService<IRootObjectProvider>(serviceProvider); if (rootObjectProvider != null && (resourceManager = ResourceHelper.GetResourceManager(rootObjectProvider.RootObject)) != null) { return resourceManager.GetString(_key) ?? _key; } return _key; } private static T GetService<T>(IServiceProvider serviceProvider) where T : class { return serviceProvider.GetService(typeof(T)) as T; } } }
using System; using System.Resources; using System.Windows.Markup; using System.Xaml; namespace WpfUtility { /// <summary> /// Translation Extension for XAML Markup /// </summary> /// <remarks> /// <list type="bullet"> /// <item>[XAML のマークアップ拡張を使った WPF での国際化 | プログラマーズ雑記帳](http://yohshiy.blog.fc2.com/blog-entry-242.html)</item> /// <item>[Internationalization in .NET and WPF - Lorenz Cuno Klopfenstein - Klopfenstein.net](http://www.klopfenstein.net/lorenz.aspx/internationalization-in-net-and-wpf-presentation-foundation)</item> /// <item>[Accessing "current class" from WPF custom MarkupExtension - Stack Overflow](http://stackoverflow.com/questions/3047448)</item> /// </list> /// </remarks> [MarkupExtensionReturnType(typeof(string))] public class TrExtension : MarkupExtension { const string NotFoundError = "#NotFound#"; string _key; public TrExtension(string key) { _key = key; } public override object ProvideValue(IServiceProvider serviceProvider) { if (String.IsNullOrEmpty(_key)) { return NotFoundError; } var rootObjectProvider = serviceProvider.GetService(typeof(IRootObjectProvider)) as IRootObjectProvider; ResourceManager resourceManager; if (rootObjectProvider == null || (resourceManager = ResourceHelper.GetResourceManager(rootObjectProvider.RootObject)) == null) { return _key; } return resourceManager.GetString(_key) ?? _key; } } }
mit
C#
f0cc56860b2225a264e1b4a36825f7c0e44d7fe6
Remove uneccessary enum parse
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerAccounts.Web/Mappings/AgreementInfoConverter.cs
src/SFA.DAS.EmployerAccounts.Web/Mappings/AgreementInfoConverter.cs
using System; using AutoMapper; using SFA.DAS.EAS.Account.Api.Types; using SFA.DAS.EmployerAccounts.Web.ViewModels; namespace SFA.DAS.EmployerAccounts.Web.Mappings { public class AgreementInfoConverter : ITypeConverter<AccountDetailViewModel, AgreementInfoViewModel> { public AgreementInfoViewModel Convert(AccountDetailViewModel source, AgreementInfoViewModel destination, ResolutionContext context) { var newAgreementInfo = new AgreementInfoViewModel { Type = source.AccountAgreementType }; return newAgreementInfo; } } }
using System; using AutoMapper; using SFA.DAS.EAS.Account.Api.Types; using SFA.DAS.EmployerAccounts.Web.ViewModels; namespace SFA.DAS.EmployerAccounts.Web.Mappings { public class AgreementInfoConverter : ITypeConverter<AccountDetailViewModel, AgreementInfoViewModel> { public AgreementInfoViewModel Convert(AccountDetailViewModel source, AgreementInfoViewModel destination, ResolutionContext context) { var newAgreementInfo = new AgreementInfoViewModel { Type = (AccountAgreementType)Enum.Parse(typeof(AccountAgreementType), source.AccountAgreementType.ToString(), true) }; return newAgreementInfo; } } }
mit
C#
a648be0c86295a632df7f7708c5e0e258d4c5ae7
Add a menu topper image
Morphan1/Voxalia,Morphan1/Voxalia,Morphan1/Voxalia
Voxalia/ClientGame/ClientMainSystem/MainMenuScreen.cs
Voxalia/ClientGame/ClientMainSystem/MainMenuScreen.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL4; using Voxalia.ClientGame.GraphicsSystems; using Voxalia.ClientGame.UISystem; using Voxalia.ClientGame.UISystem.MenuSystem; namespace Voxalia.ClientGame.ClientMainSystem { public class MainMenuScreen: Screen { public UIMenu Menus; public Texture Mouse; public Texture Topper; public override void Init() { Menus = new UIMenu(TheClient); Menus.Add(new UIMenuButton("ui/menus/buttons/basic", "Singleplayer", () => { UIConsole.WriteLine("SP!"); }, 10, 300, 350, 70, TheClient.FontSets.SlightlyBigger)); Menus.Add(new UIMenuButton("ui/menus/buttons/basic", "Multiplayer", () => { UIConsole.WriteLine("MP!"); }, 10, 400, 350, 70, TheClient.FontSets.SlightlyBigger)); Mouse = TheClient.Textures.GetTexture("ui/mouse_cursor"); Topper = TheClient.Textures.GetTexture("ui/menus/voxalia_topper"); } public override void Tick() { Menus.TickAll(); } public override void SwitchTo() { MouseHandler.ReleaseMouse(); } public override void Render() { TheClient.Establish2D(); GL.ClearBuffer(ClearBuffer.Color, 0, new float[] { 0, 0.5f, 0.5f, 1 }); GL.ClearBuffer(ClearBuffer.Depth, 0, new float[] { 1 }); Topper.Bind(); TheClient.Rendering.RenderRectangle(0, 0, TheClient.Window.Width, TheClient.Window.Width / 2); Menus.RenderAll(TheClient.gDelta); Mouse.Bind(); TheClient.Rendering.RenderRectangle(MouseHandler.MouseX(), MouseHandler.MouseY(), MouseHandler.MouseX() + 16, MouseHandler.MouseY() + 16); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL4; using Voxalia.ClientGame.GraphicsSystems; using Voxalia.ClientGame.UISystem; using Voxalia.ClientGame.UISystem.MenuSystem; namespace Voxalia.ClientGame.ClientMainSystem { public class MainMenuScreen: Screen { public UIMenu Menus; public Texture Mouse; public override void Init() { Menus = new UIMenu(TheClient); Menus.Add(new UIMenuButton("ui/menus/buttons/basic", "Singleplayer", () => { UIConsole.WriteLine("SP!"); }, 10, 100, 350, 70, TheClient.FontSets.SlightlyBigger)); Menus.Add(new UIMenuButton("ui/menus/buttons/basic", "Multiplayer", () => { UIConsole.WriteLine("MP!"); }, 10, 200, 350, 70, TheClient.FontSets.SlightlyBigger)); Mouse = TheClient.Textures.GetTexture("ui/mouse_cursor"); } public override void Tick() { Menus.TickAll(); } public override void SwitchTo() { MouseHandler.ReleaseMouse(); } public override void Render() { TheClient.Establish2D(); GL.ClearBuffer(ClearBuffer.Color, 0, new float[] { 0, 0.5f, 0.5f, 1 }); GL.ClearBuffer(ClearBuffer.Depth, 0, new float[] { 1 }); Menus.RenderAll(TheClient.gDelta); Mouse.Bind(); TheClient.Rendering.RenderRectangle(MouseHandler.MouseX(), MouseHandler.MouseY(), MouseHandler.MouseX() + 16, MouseHandler.MouseY() + 16); } } }
mit
C#
2ed4af9eb522773f974baff5d8da7e66277734c6
change version to 3.0.3
rpmoore/ds3_net_sdk,RachelTucker/ds3_net_sdk,shabtaisharon/ds3_net_sdk,SpectraLogic/ds3_net_sdk,rpmoore/ds3_net_sdk,RachelTucker/ds3_net_sdk,RachelTucker/ds3_net_sdk,rpmoore/ds3_net_sdk,shabtaisharon/ds3_net_sdk,SpectraLogic/ds3_net_sdk,shabtaisharon/ds3_net_sdk,SpectraLogic/ds3_net_sdk
VersionInfo.cs
VersionInfo.cs
/* * ****************************************************************************** * Copyright 2014 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file 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.Reflection; // 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("3.0.3.0")] [assembly: AssemblyFileVersion("3.0.3.0")]
/* * ****************************************************************************** * Copyright 2014 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file 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.Reflection; // 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("3.0.2.0")] [assembly: AssemblyFileVersion("3.0.2.0")]
apache-2.0
C#
e9645edc9e9df90b74bf4e7e8ebea4bb0f505133
Add identifying tag to MassTransit health checks.
phatboyg/MassTransit,MassTransit/MassTransit,MassTransit/MassTransit,phatboyg/MassTransit
src/Containers/MassTransit.AspNetCoreIntegration/HostedServiceConfigurationExtensions.cs
src/Containers/MassTransit.AspNetCoreIntegration/HostedServiceConfigurationExtensions.cs
namespace MassTransit { using AspNetCoreIntegration; using AspNetCoreIntegration.HealthChecks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using Monitoring.Health; /// <summary> /// These are the updated extensions compatible with the container registration code. They should be used, for real. /// </summary> public static class HostedServiceConfigurationExtensions { /// <summary> /// Adds the MassTransit <see cref="IHostedService" />, which includes a bus and endpoint health check. /// Use it together with UseHealthCheck to get more detailed diagnostics. /// </summary> /// <param name="services"></param> public static IServiceCollection AddMassTransitHostedService(this IServiceCollection services) { AddHealthChecks(services); return services.AddSingleton<IHostedService, MassTransitHostedService>(); } public static IServiceCollection AddMassTransitHostedService(this IServiceCollection services, IBusControl bus) { AddHealthChecks(services); return services.AddSingleton<IHostedService>(p => new BusHostedService(bus)); } static void AddHealthChecks(IServiceCollection services) { services.AddOptions(); services.AddHealthChecks(); services.AddSingleton<IConfigureOptions<HealthCheckServiceOptions>>(provider => new ConfigureBusHealthCheckServiceOptions(provider.GetServices<IBusHealth>(), new[] {"ready", "masstransit"})); } } }
namespace MassTransit { using AspNetCoreIntegration; using AspNetCoreIntegration.HealthChecks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using Monitoring.Health; /// <summary> /// These are the updated extensions compatible with the container registration code. They should be used, for real. /// </summary> public static class HostedServiceConfigurationExtensions { /// <summary> /// Adds the MassTransit <see cref="IHostedService" />, which includes a bus and endpoint health check. /// Use it together with UseHealthCheck to get more detailed diagnostics. /// </summary> /// <param name="services"></param> public static IServiceCollection AddMassTransitHostedService(this IServiceCollection services) { AddHealthChecks(services); return services.AddSingleton<IHostedService, MassTransitHostedService>(); } public static IServiceCollection AddMassTransitHostedService(this IServiceCollection services, IBusControl bus) { AddHealthChecks(services); return services.AddSingleton<IHostedService>(p => new BusHostedService(bus)); } static void AddHealthChecks(IServiceCollection services) { services.AddOptions(); services.AddHealthChecks(); services.AddSingleton<IConfigureOptions<HealthCheckServiceOptions>>(provider => new ConfigureBusHealthCheckServiceOptions(provider.GetServices<IBusHealth>(), new[] {"ready"})); } } }
apache-2.0
C#
8b5356f3ffd767b87d420163ef3301465cbd35e3
Update StopRepository
nycmobiledev/transit-app-experiments
gtfs/GTFSApi/Infrastructure.GTFS.Static.Subway.FileSystem/StopRepository.cs
gtfs/GTFSApi/Infrastructure.GTFS.Static.Subway.FileSystem/StopRepository.cs
using System; using System.Collections.Generic; using System.IO; using CsvHelper; using NYCMobileDev.TransitApp.Domain.GTFS.Static.Subway.Entities; using NYCMobileDev.TransitApp.Domain.GTFS.Static.Subway.Interfaces; namespace NYCMobileDev.TransitApp.Infrastructure.GTFS.Static.Subway.FileSystem { public class StopRepository : IStopRepository { private readonly string _stopFilePath; public StopRepository(string stopFilePath) { _stopFilePath = stopFilePath; } public IEnumerable<Stop> GetAllStops() { var csv = new CsvReader(File.OpenText(_stopFilePath)); var records = csv.GetRecords<Stop>(); } } }
using System; using System.Collections.Generic; using System.IO; using CsvHelper; using NYCMobileDev.TransitApp.Domain.GTFS.Static.Subway.Entities; using NYCMobileDev.TransitApp.Domain.GTFS.Static.Subway.Interfaces; namespace NYCMobileDev.TransitApp.Infrastructure.GTFS.Static.Subway.FileSystem { public class StopRepository : IStopRepository { private readonly string _stopFilePath; public StopRepository(string stopFilePath) { _stopFilePath = stopFilePath; } public IEnumerable<Stop> GetAllStops() { var csv = new CsvReader(File.Op) } } }
mit
C#
5afb57bbb05bc3db5be6d7e9aa7feb1cb7c34a62
Remove explicit offloading in TaskExtensionHelper (#6545)
markcowl/azure-sdk-for-net,hyonholee/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,hyonholee/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,hyonholee/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,stankovski/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,hyonholee/azure-sdk-for-net,stankovski/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,hyonholee/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net
sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TaskExtensionHelper.cs
sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TaskExtensionHelper.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.ServiceBus.Primitives { using System; using System.Threading.Tasks; static class TaskExtensionHelper { public static void Schedule(Func<Task> func) { _ = ScheduleInternal(func); } static async Task ScheduleInternal(Func<Task> func) { try { await func().ConfigureAwait(false); } catch (Exception ex) { MessagingEventSource.Log.ScheduleTaskFailed(func, ex); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.ServiceBus.Primitives { using System; using System.Threading.Tasks; static class TaskExtensionHelper { public static void Schedule(Func<Task> func) { Task.Run(async () => { try { await func().ConfigureAwait(false); } catch (Exception ex) { MessagingEventSource.Log.ScheduleTaskFailed(func, ex); } }); } } }
mit
C#
c35818bbd73b2b2e437aae8068d95d588268907e
Add constructor to Player class
allyjweir/battleships
Battleships/Player.cs
Battleships/Player.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Battleships { public class Player { #region Properties public string Name { get; } public Board GameBoard { get; } #endregion #region Constructors public Player(string name) { Name = name; GameBoard = new Board(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Battleships { public class Player { #region Properties #endregion } }
mit
C#
1d39a20a5403fbbaa9aa010cdc5f2f79ea4fcbf5
make specs building again
appccelerate/statemachine
source/Appccelerate.StateMachine.Specs/Sync/CurrentStateExtension.cs
source/Appccelerate.StateMachine.Specs/Sync/CurrentStateExtension.cs
//------------------------------------------------------------------------------- // <copyright file="CurrentStateExtension.cs" company="Appccelerate"> // Copyright (c) 2008-2017 Appccelerate // // 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. // </copyright> //------------------------------------------------------------------------------- namespace Appccelerate.StateMachine.Sync { using Appccelerate.StateMachine.Extensions; public class CurrentStateExtension : ExtensionBase<int, int> { public int CurrentState { get; private set; } public override void SwitchedState(IStateMachineInformation<int, int> stateMachine, int oldState, int newState) { this.CurrentState = newState; } } }
//------------------------------------------------------------------------------- // <copyright file="CurrentStateExtension.cs" company="Appccelerate"> // Copyright (c) 2008-2017 Appccelerate // // 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. // </copyright> //------------------------------------------------------------------------------- namespace Appccelerate.StateMachine.Sync { using Appccelerate.StateMachine.Extensions; using Appccelerate.StateMachine.Machine; public class CurrentStateExtension : ExtensionBase<int, int> { public int CurrentState { get; private set; } public override void SwitchedState(IStateMachineInformation<int, int> stateMachine, IState<int, int> oldState, IState<int, int> newState) { this.CurrentState = newState.Id; } } }
apache-2.0
C#
28ba0dd3b72d9f16ec77012314a054467f2d29fe
debug code
SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments
src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api/Controllers/BulkUploadController.cs
src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api/Controllers/BulkUploadController.cs
using MediatR; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using SFA.DAS.Authorization.Mvc.Attributes; using SFA.DAS.CommitmentsV2.Api.Types.Requests; using SFA.DAS.CommitmentsV2.Application.Commands.BulkUploadAddDraftApprenticeships; using SFA.DAS.CommitmentsV2.Features; using SFA.DAS.CommitmentsV2.Shared.Interfaces; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace SFA.DAS.CommitmentsV2.Api.Controllers { [ApiController] [DasAuthorize(Feature.BulkUploadV2)] [Route("api/{providerId}/bulkupload")] public class BulkUploadController : ControllerBase { private readonly IMediator _mediator; private readonly IModelMapper _modelMapper; private readonly ILogger<BulkUploadController> _logger; public BulkUploadController(IMediator mediator, IModelMapper modelMapper, ILogger<BulkUploadController> logger) { _mediator = mediator; _modelMapper = modelMapper; _logger = logger; } [HttpPost] [Route("")] public async Task<IActionResult> AddDraftApprenticeships(BulkUploadAddDraftApprenticeshipsRequest request, CancellationToken cancellationToken = default) { foreach (var df in request.BulkUploadDraftApprenticeships) { _logger.LogInformation($"Received Bulk upload request for ULN : {df.Uln} with start date : {df.StartDate.Value.ToString("dd/MM/yyyy")}"); } _logger.LogInformation($"Received Bulk upload request for Provider : {request.ProviderId} with number of apprentices : {request.BulkUploadDraftApprenticeships?.Count() ?? 0}"); var command = await _modelMapper.Map<BulkUploadAddDraftApprenticeshipsCommand>(request); var result = await _mediator.Send(command, cancellationToken); return Ok(result); } } }
using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using SFA.DAS.Authorization.Mvc.Attributes; using SFA.DAS.CommitmentsV2.Api.Types.Requests; using SFA.DAS.CommitmentsV2.Application.Commands.BulkUploadAddDraftApprenticeships; using SFA.DAS.CommitmentsV2.Features; using SFA.DAS.CommitmentsV2.Shared.Interfaces; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace SFA.DAS.CommitmentsV2.Api.Controllers { [ApiController] [DasAuthorize(Feature.BulkUploadV2)] [Route("api/{providerId}/bulkupload")] public class BulkUploadController : ControllerBase { private readonly IMediator _mediator; private readonly IModelMapper _modelMapper; private readonly ILogger<BulkUploadController> _logger; public BulkUploadController(IMediator mediator, IModelMapper modelMapper, ILogger<BulkUploadController> logger) { _mediator = mediator; _modelMapper = modelMapper; _logger = logger; } [HttpPost] [Route("")] public async Task<IActionResult> AddDraftApprenticeships(BulkUploadAddDraftApprenticeshipsRequest request, CancellationToken cancellationToken = default) { _logger.LogInformation($"Received Bulk upload request for Provider : {request.ProviderId} with number of apprentices : {request.BulkUploadDraftApprenticeships?.Count() ?? 0}"); var command = await _modelMapper.Map<BulkUploadAddDraftApprenticeshipsCommand>(request); var result = await _mediator.Send(command, cancellationToken); return Ok(result); } } }
mit
C#
f09c6a4e81f0ed9b6a0c0a8e4eb1ec8353a8029d
Update to link
SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice
src/SFA.DAS.ProviderApprenticeshipsService.Web/Views/CreateCohort/Create.cshtml
src/SFA.DAS.ProviderApprenticeshipsService.Web/Views/CreateCohort/Create.cshtml
@model SFA.DAS.ProviderApprenticeshipsService.Web.Models.CreateCohort.CreateCohortViewModel @{ ViewBag.Title = "Create Cohort"; } <div class="grid-row"> <div class="column-two-thirds"> <h1 class="heading-xlarge">Choose an employer</h1> <p>Choose an employer you want to create a new cohort on behalf of.</p> <p>@Model.LegalEntities.Count() result@(Model.LegalEntities.Count() != 0 ? "s" : null) found.</p> <table class="table"> <thead> <tr> <th scope="col">Employer</th> <th scope="col">Account name</th> <th scope="col">Agreement ID</th> <th scope="col"><span class="vh">Action</span></th> </tr> </thead> <tbody> @foreach (var legalEntity in Model.LegalEntities) { <tr> <td>@legalEntity.EmployerAccountLegalEntityName</td> <td>@legalEntity.EmployerName</td> <td>@legalEntity.EmployerAccountLegalEntityPublicHashedId</td> <td class="link-right"><a href="@Url.Action("Confirm")">Select <span class="vh">@legalEntity.EmployerAccountLegalEntityName</span></a></td> </tr> } </tbody> </table> </div> </div> @section breadcrumb { <div class="breadcrumbs"> <a href="@Url.Action("Index", "Account")" aria-label="Back to account home" class="back-link">Back</a> </div> }
@model SFA.DAS.ProviderApprenticeshipsService.Web.Models.CreateCohort.CreateCohortViewModel @{ ViewBag.Title = "Create Cohort"; } <div class="grid-row"> <div class="column-two-thirds"> <h1 class="heading-xlarge">Choose an employer</h1> <p>Choose an employer you want to create a new cohort on behalf of.</p> <p>@Model.LegalEntities.Count() result@(Model.LegalEntities.Count() != 0 ? "s" : null) found.</p> <table class="table"> <thead> <tr> <th scope="col">Employer</th> <th scope="col">Account name</th> <th scope="col">Agreement ID</th> <th scope="col"><span class="vh">Action</span></th> </tr> </thead> <tbody> @foreach (var legalEntity in Model.LegalEntities) { <tr> <td>@legalEntity.EmployerAccountLegalEntityName</td> <td>@legalEntity.EmployerName</td> <td>@legalEntity.EmployerAccountLegalEntityPublicHashedId</td> <td class="link-right"><a href="">Select <span class="vh">@legalEntity.EmployerAccountLegalEntityName</span></a></td> </tr> } </tbody> </table> </div> </div> @section breadcrumb { <div class="breadcrumbs"> <a href="@Url.Action("Index", "Account")" aria-label="Back to account home" class="back-link">Back</a> </div> }
mit
C#
71ede1ac2842084b002707e79e9e7d15be918c38
Bump version
HelloFax/hellosign-dotnet-sdk
HelloSign/Properties/AssemblyInfo.cs
HelloSign/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("HelloSign")] [assembly: AssemblyDescription("Client library for using the HelloSign API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HelloSign")] [assembly: AssemblyProduct("HelloSign")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("HelloSign")] [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("c36ca08c-9b2a-4b52-a8ae-03d364d69267")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // [assembly: AssemblyVersion("1.0.*")] // [assembly: AssemblyVersion("0.0.0.0")] // NOTE: This gets reported in the user-agent string for HTTP requests made. [assembly: AssemblyFileVersion("0.5.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("HelloSign")] [assembly: AssemblyDescription("Client library for using the HelloSign API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HelloSign")] [assembly: AssemblyProduct("HelloSign")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("HelloSign")] [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("c36ca08c-9b2a-4b52-a8ae-03d364d69267")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // [assembly: AssemblyVersion("1.0.*")] // [assembly: AssemblyVersion("0.0.0.0")] // NOTE: This gets reported in the user-agent string for HTTP requests made. [assembly: AssemblyFileVersion("0.4.0.0")]
mit
C#
6c2ec96ef8e1d6cee3994ac5d81ddf8d3a157f9c
Remove unintended code
peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework
osu.Framework/Graphics/Audio/DrawableSample.cs
osu.Framework/Graphics/Audio/DrawableSample.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Audio.Sample; namespace osu.Framework.Graphics.Audio { /// <summary> /// A <see cref="SampleChannel"/> wrapper to allow insertion in the draw hierarchy to allow transforms, lifetime management etc. /// </summary> public class DrawableSample : DrawableAudioWrapper, ISample { private readonly Sample sample; /// <summary> /// Construct a new drawable sample instance. /// </summary> /// <param name="sample">The audio sample to wrap.</param> /// <param name="disposeSampleOnDisposal">Whether the sample should be automatically disposed on drawable disposal/expiry.</param> public DrawableSample(Sample sample, bool disposeSampleOnDisposal = true) : base(sample, disposeSampleOnDisposal) { this.sample = sample; } public SampleChannel Play() => sample.Play(); public double Length => sample.Length; public int PlaybackConcurrency { get => sample.PlaybackConcurrency; set => sample.PlaybackConcurrency = value; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Audio.Sample; namespace osu.Framework.Graphics.Audio { /// <summary> /// A <see cref="SampleChannel"/> wrapper to allow insertion in the draw hierarchy to allow transforms, lifetime management etc. /// </summary> public class DrawableSample : DrawableAudioWrapper, ISample { private readonly Sample sample; /// <summary> /// Construct a new drawable sample instance. /// </summary> /// <param name="sample">The audio sample to wrap.</param> /// <param name="disposeSampleOnDisposal">Whether the sample should be automatically disposed on drawable disposal/expiry.</param> public DrawableSample(Sample sample, bool disposeSampleOnDisposal = true) : base(sample, disposeSampleOnDisposal) { this.sample = sample; sample.Volume.Value = 0.5; } public SampleChannel Play() => sample.Play(); public double Length => sample.Length; public int PlaybackConcurrency { get => sample.PlaybackConcurrency; set => sample.PlaybackConcurrency = value; } } }
mit
C#
98410dbb6d3276d674bba5e5f77bdffd1e598b40
Reduce shake transform count by one for more aesthetic behaviour
johnneijzen/osu,ppy/osu,UselessToucan/osu,DrabWeb/osu,smoogipoo/osu,naoey/osu,DrabWeb/osu,ppy/osu,ppy/osu,2yangk23/osu,2yangk23/osu,peppy/osu-new,ZLima12/osu,smoogipoo/osu,ZLima12/osu,naoey/osu,peppy/osu,peppy/osu,EVAST9919/osu,DrabWeb/osu,johnneijzen/osu,NeoAdonis/osu,EVAST9919/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,smoogipooo/osu,UselessToucan/osu,smoogipoo/osu,naoey/osu,peppy/osu
osu.Game/Graphics/Containers/ShakeContainer.cs
osu.Game/Graphics/Containers/ShakeContainer.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Graphics.Containers { /// <summary> /// A container that adds the ability to shake its contents. /// </summary> public class ShakeContainer : Container { /// <summary> /// Shake the contents of this container. /// </summary> public void Shake() { const float shake_amount = 8; const float shake_duration = 30; this.MoveToX(shake_amount, shake_duration / 2, Easing.OutSine).Then() .MoveToX(-shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(-shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(0, shake_duration / 2, Easing.InSine); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Graphics.Containers { /// <summary> /// A container that adds the ability to shake its contents. /// </summary> public class ShakeContainer : Container { /// <summary> /// Shake the contents of this container. /// </summary> public void Shake() { const float shake_amount = 8; const float shake_duration = 30; this.MoveToX(shake_amount, shake_duration / 2, Easing.OutSine).Then() .MoveToX(-shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(-shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(0, shake_duration / 2, Easing.InSine); } } }
mit
C#
03e13105b33a3c2972301abfc7aa587c787ba353
Add test
sakapon/KLibrary.Linq
KLibrary4/UnitTest/Linq/ArrayTest.cs
KLibrary4/UnitTest/Linq/ArrayTest.cs
using System; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using static KLibrary.Linq.Array2; namespace UnitTest.Linq { [TestClass] public class ArrayTest { [TestMethod] public void Chain() { Range(1, 15, 2) .Filter(i => i % 3 != 0) .Map(i => i * i) .Sort(i => Convert.ToString(i)) .ForEach(Console.WriteLine); } [TestMethod] public void Sort_1() { Assert.IsTrue(Enumerable.Range(0, 10).Reverse().SequenceEqual(Range(0, 10).Sort((x, y) => -x.CompareTo(y)))); Assert.IsTrue(Enumerable.Range(0, 10).Reverse().SequenceEqual(Range(0, 10).Sort(x => (double)x, (x, y) => -x.CompareTo(y)))); } [TestMethod] public void Reverse_1() { Assert.IsTrue(Enumerable.Range(3, 10).Reverse().SequenceEqual(Range(3, 10).Reverse())); } [TestMethod] public void Range_1() { Assert.IsTrue(Enumerable.Range(0, 10).SequenceEqual(Range(0, 10))); Assert.IsTrue(Enumerable.Range(3, 10).SequenceEqual(Range(3, 10))); Assert.IsTrue(Enumerable.Empty<int>().SequenceEqual(Range(3, 0))); Assert.IsTrue(Enumerable.Range(0, 10).Select(i => 2 * i + 3).SequenceEqual(Range(3, 10, 2))); Assert.IsTrue(Enumerable.Range(-6, 10).Reverse().SequenceEqual(Range(3, 10, -1))); } [TestMethod] public void Subarray_1() { Assert.IsTrue(Enumerable.Range(0, 5).SequenceEqual(Range(0, 10).Subarray(0, 5))); Assert.IsTrue(Enumerable.Range(3, 5).SequenceEqual(Range(0, 10).Subarray(3, 5))); Assert.IsTrue(Enumerable.Range(5, 5).SequenceEqual(Range(0, 10).Subarray(5, 5))); } [TestMethod] public void ArrayEqual_1() { Assert.AreEqual(true, Array.Empty<int>().ArrayEqual(Array.Empty<int>())); Assert.AreEqual(true, Range(0, 10).ArrayEqual(Range(0, 10))); Assert.AreEqual(false, Range(0, 10).ArrayEqual(Range(1, 10))); Assert.AreEqual(true, new[] { 1.23, 2, -3 }.ArrayEqual(new[] { "1.23", "2", "-3" }, (d, s) => d.ToString() == s)); Assert.AreEqual(false, new[] { 1.23, 2, -3, 4 }.ArrayEqual(new[] { "1.23", "2", "-3" }, (d, s) => d.ToString() == s)); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using static KLibrary.Linq.Array2; namespace UnitTest.Linq { [TestClass] public class ArrayTest { [TestMethod] public void Chain() { var result = Range(1, 15, 2) .Filter(i => i % 3 != 0) .Map(i => i * i) .Sort(i => Convert.ToString(i)); Console.WriteLine(string.Join(", ", result)); } [TestMethod] public void Sort_1() { Assert.IsTrue(Enumerable.Range(0, 10).Reverse().SequenceEqual(Range(0, 10).Sort((x, y) => -x.CompareTo(y)))); Assert.IsTrue(Enumerable.Range(0, 10).Reverse().SequenceEqual(Range(0, 10).Sort(x => (double)x, (x, y) => -x.CompareTo(y)))); } [TestMethod] public void Range_1() { Assert.IsTrue(Enumerable.Range(0, 10).SequenceEqual(Range(0, 10))); Assert.IsTrue(Enumerable.Range(3, 10).SequenceEqual(Range(3, 10))); Assert.IsTrue(Enumerable.Empty<int>().SequenceEqual(Range(3, 0))); Assert.IsTrue(Enumerable.Range(0, 10).Select(i => 2 * i + 3).SequenceEqual(Range(3, 10, 2))); Assert.IsTrue(Enumerable.Range(-6, 10).Reverse().SequenceEqual(Range(3, 10, -1))); } } }
mit
C#
8ba17dddb324a591d4832c0dd3403f20607f5699
Change to version 1.0.1
t3knoid/KeepAwake
KeepAwake/Properties/AssemblyInfo.cs
KeepAwake/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("KeepAwake")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Frank Refol")] [assembly: AssemblyProduct("KeepAwake")] [assembly: AssemblyCopyright("Copyright © Frank Refol 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("6bc385f1-6f77-4584-97ca-3f0f56b6bb5f")] // 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.1.*")]
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("KeepAwake")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Frank Refol")] [assembly: AssemblyProduct("KeepAwake")] [assembly: AssemblyCopyright("Copyright © Frank Refol 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("6bc385f1-6f77-4584-97ca-3f0f56b6bb5f")] // 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.*")]
mit
C#
b6f80521d15218c0d5fa08d6f18662ca1cf71f2d
Update JsonHelper.cs
qapquiz/UnityUtilities
Assets/Scripts/JsonHelper.cs
Assets/Scripts/JsonHelper.cs
// From https://forum.unity3d.com/threads/how-to-load-an-array-with-jsonutility.375735/ // Author: ffleurey using System.Collections; using System.Collections.Generic; using System.Text; using UnityEngine; public class JsonHelper : MonoBehaviour { [System.Serializable] public struct Wrapper<T> { public T[] array; } public static T[] FromJsonArray<T>(string json) { string newJson = new StringBuilder().Append("{\"array\": ").Append(json).Append("}").ToString(); Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>> (newJson); return wrapper.array; } }
// From https://forum.unity3d.com/threads/how-to-load-an-array-with-jsonutility.375735/ // Author: ffleurey using System.Collections; using System.Collections.Generic; using System.Text; using UnityEngine; public class JsonHelper : MonoBehaviour { public static T[] FromJsonArray<T>(string json) { string newJson = new StringBuilder().Append("{\"array\": ").Append(json).Append("}").ToString(); Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>> (newJson); return wrapper.array; } [System.Serializable] public class Wrapper<T> { public T[] array; } }
mit
C#
318c00b2bef1644f0e4a660b3bce287069ddbe01
Remove call to Application.Current.Dispatcher.CheckAccess() - seems there's a null point happening on a rare instance when Application.Current.Dispatcher is null Rely on parent calling code to execute on the correct thread (which it was already executing on the UI Thread)
windygu/CefSharp,rover886/CefSharp,Haraguroicha/CefSharp,yoder/CefSharp,haozhouxu/CefSharp,VioletLife/CefSharp,Octopus-ITSM/CefSharp,Haraguroicha/CefSharp,wangzheng888520/CefSharp,ruisebastiao/CefSharp,Livit/CefSharp,joshvera/CefSharp,rlmcneary2/CefSharp,joshvera/CefSharp,haozhouxu/CefSharp,battewr/CefSharp,zhangjingpu/CefSharp,Octopus-ITSM/CefSharp,joshvera/CefSharp,ITGlobal/CefSharp,jamespearce2006/CefSharp,NumbersInternational/CefSharp,illfang/CefSharp,ruisebastiao/CefSharp,wangzheng888520/CefSharp,zhangjingpu/CefSharp,yoder/CefSharp,twxstar/CefSharp,twxstar/CefSharp,ITGlobal/CefSharp,dga711/CefSharp,yoder/CefSharp,jamespearce2006/CefSharp,VioletLife/CefSharp,AJDev77/CefSharp,Octopus-ITSM/CefSharp,gregmartinhtc/CefSharp,haozhouxu/CefSharp,Haraguroicha/CefSharp,rover886/CefSharp,joshvera/CefSharp,windygu/CefSharp,zhangjingpu/CefSharp,yoder/CefSharp,wangzheng888520/CefSharp,jamespearce2006/CefSharp,rover886/CefSharp,jamespearce2006/CefSharp,Octopus-ITSM/CefSharp,wangzheng888520/CefSharp,battewr/CefSharp,windygu/CefSharp,gregmartinhtc/CefSharp,gregmartinhtc/CefSharp,NumbersInternational/CefSharp,haozhouxu/CefSharp,windygu/CefSharp,dga711/CefSharp,Livit/CefSharp,jamespearce2006/CefSharp,AJDev77/CefSharp,VioletLife/CefSharp,illfang/CefSharp,rover886/CefSharp,NumbersInternational/CefSharp,twxstar/CefSharp,rlmcneary2/CefSharp,Haraguroicha/CefSharp,AJDev77/CefSharp,NumbersInternational/CefSharp,ruisebastiao/CefSharp,battewr/CefSharp,dga711/CefSharp,rover886/CefSharp,ITGlobal/CefSharp,rlmcneary2/CefSharp,ITGlobal/CefSharp,VioletLife/CefSharp,zhangjingpu/CefSharp,illfang/CefSharp,rlmcneary2/CefSharp,gregmartinhtc/CefSharp,Livit/CefSharp,twxstar/CefSharp,Livit/CefSharp,dga711/CefSharp,ruisebastiao/CefSharp,Haraguroicha/CefSharp,battewr/CefSharp,illfang/CefSharp,AJDev77/CefSharp
CefSharp.Wpf/DelegateCommand.cs
CefSharp.Wpf/DelegateCommand.cs
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.Windows.Input; namespace CefSharp.Wpf { internal class DelegateCommand : ICommand { private readonly Action commandHandler; private readonly Func<bool> canExecuteHandler; public event EventHandler CanExecuteChanged; public DelegateCommand(Action commandHandler, Func<bool> canExecuteHandler = null) { this.commandHandler = commandHandler; this.canExecuteHandler = canExecuteHandler; } public void Execute(object parameter) { commandHandler(); } public bool CanExecute(object parameter) { return canExecuteHandler == null || canExecuteHandler(); } public void RaiseCanExecuteChanged() { if (CanExecuteChanged != null) { CanExecuteChanged(this, new EventArgs()); } } } }
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.Windows; using System.Windows.Input; namespace CefSharp.Wpf { internal class DelegateCommand : ICommand { private readonly Action commandHandler; private readonly Func<bool> canExecuteHandler; public event EventHandler CanExecuteChanged; public DelegateCommand(Action commandHandler, Func<bool> canExecuteHandler = null) { this.commandHandler = commandHandler; this.canExecuteHandler = canExecuteHandler; } public void Execute(object parameter) { commandHandler(); } public bool CanExecute(object parameter) { return canExecuteHandler == null || canExecuteHandler(); } public void RaiseCanExecuteChanged() { if (!Application.Current.Dispatcher.CheckAccess()) { Application.Current.Dispatcher.BeginInvoke((Action) RaiseCanExecuteChanged); return; } if (CanExecuteChanged != null) { CanExecuteChanged(this, new EventArgs()); } } } }
bsd-3-clause
C#
00216c75fde7a7cb7d338c9040dbab98114f92ac
Comment for validation error rendering
kjac/FormEditor,kjac/FormEditor,kjac/FormEditor
Source/Umbraco/Views/Partials/FormEditor/FieldsNoScript/core.utils.validationerror.cshtml
Source/Umbraco/Views/Partials/FormEditor/FieldsNoScript/core.utils.validationerror.cshtml
@inherits Umbraco.Web.Mvc.UmbracoViewPage<FormEditor.Fields.IFieldWithValidation> @* for the NoScript rendering, this is solely rendered server side *@ @if (Model.Invalid) { <div class="text-danger validation-error"> @Model.ErrorMessage </div> }
@inherits Umbraco.Web.Mvc.UmbracoViewPage<FormEditor.Fields.IFieldWithValidation> @if (Model.Invalid) { <div class="text-danger validation-error"> @Model.ErrorMessage </div> }
mit
C#
bad7862e0f231623dd0df9b12b2473a1dbe9005b
add heloloe
toannvqo/dnn_publish
Components/ProductController.cs
Components/ProductController.cs
using DotNetNuke.Data; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Christoc.Modules.DNNModule1.Components { public class ProductController { public Product GetProduct(int productId) { Product p; using (IDataContext ctx = DataContext.Instance()) { Console.WriteLine("hello world"); var rep = ctx.GetRepository<Product>(); p = rep.GetById(productId); } return p; } public IEnumerable<Product> getAll() { IEnumerable<Product> p; using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); p = rep.Get(); } return p; } public void CreateProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Insert(p); } } public void DeleteProduct(int productId) { var p = GetProduct(productId); DeleteProduct(p); } public void DeleteProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Delete(p); } } public void UpdateProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Update(p); } } } }
using DotNetNuke.Data; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Christoc.Modules.DNNModule1.Components { public class ProductController { public Product GetProduct(int productId) { Product p; using (IDataContext ctx = DataContext.Instance()) { Console.WriteLine("hello"); var rep = ctx.GetRepository<Product>(); p = rep.GetById(productId); } return p; } public IEnumerable<Product> getAll() { IEnumerable<Product> p; using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); p = rep.Get(); } return p; } public void CreateProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Insert(p); } } public void DeleteProduct(int productId) { var p = GetProduct(productId); DeleteProduct(p); } public void DeleteProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Delete(p); } } public void UpdateProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Update(p); } } } }
mit
C#
e7b279be23561f9f24d7e9f020e23c0d9bb2d5a7
Test something fails
hartmannr76/EasyIoC,hartmannr76/EasyIoC
EasyIoC/AssemblyFinder.cs
EasyIoC/AssemblyFinder.cs
using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection; using Microsoft.Extensions.DependencyModel; namespace EasyIoC { public class AssemblyFinder { private readonly HashSet<string> _defaultIgnoredAssemblies = new HashSet<string>() { "Microsoft.", "System." }; public ImmutableList<Assembly> FindAssemblies(HashSet<string> ignoredAssemblies) { var ctx = DependencyContext.Default; ignoredAssemblies = ignoredAssemblies ?? _defaultIgnoredAssemblies; var assemblyNames = from li in ctx.RuntimeLibraries from assemblyName in lib.GetDefaultAssemblyNames(ctx) where ignoredAssemblies.Any(x => assemblyName.Name.StartsWith(x)) select assemblyName; var lookup = assemblyNames.ToLookup(x => x.Name).Select(x => x.First()); var asList = lookup.Select(Assembly.Load).ToImmutableList(); return asList; } } }
using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection; using Microsoft.Extensions.DependencyModel; namespace EasyIoC { public class AssemblyFinder { private readonly HashSet<string> _defaultIgnoredAssemblies = new HashSet<string>() { "Microsoft.", "System." }; public ImmutableList<Assembly> FindAssemblies(HashSet<string> ignoredAssemblies) { var ctx = DependencyContext.Default; ignoredAssemblies = ignoredAssemblies ?? _defaultIgnoredAssemblies; var assemblyNames = from lib in ctx.RuntimeLibraries from assemblyName in lib.GetDefaultAssemblyNames(ctx) where ignoredAssemblies.Any(x => assemblyName.Name.StartsWith(x)) select assemblyName; var lookup = assemblyNames.ToLookup(x => x.Name).Select(x => x.First()); var asList = lookup.Select(Assembly.Load).ToImmutableList(); return asList; } } }
mit
C#
54790a94c442745f32f7b67b93eb3ff99e0f6c8b
Remove return xml comments, not valid anymore
Livit/CefSharp,battewr/CefSharp,haozhouxu/CefSharp,NumbersInternational/CefSharp,Haraguroicha/CefSharp,NumbersInternational/CefSharp,wangzheng888520/CefSharp,jamespearce2006/CefSharp,VioletLife/CefSharp,NumbersInternational/CefSharp,yoder/CefSharp,jamespearce2006/CefSharp,AJDev77/CefSharp,twxstar/CefSharp,windygu/CefSharp,Haraguroicha/CefSharp,gregmartinhtc/CefSharp,wangzheng888520/CefSharp,AJDev77/CefSharp,joshvera/CefSharp,VioletLife/CefSharp,yoder/CefSharp,zhangjingpu/CefSharp,dga711/CefSharp,ITGlobal/CefSharp,joshvera/CefSharp,battewr/CefSharp,VioletLife/CefSharp,rlmcneary2/CefSharp,battewr/CefSharp,ruisebastiao/CefSharp,illfang/CefSharp,illfang/CefSharp,haozhouxu/CefSharp,wangzheng888520/CefSharp,twxstar/CefSharp,dga711/CefSharp,dga711/CefSharp,wangzheng888520/CefSharp,twxstar/CefSharp,jamespearce2006/CefSharp,haozhouxu/CefSharp,rlmcneary2/CefSharp,zhangjingpu/CefSharp,Haraguroicha/CefSharp,yoder/CefSharp,Haraguroicha/CefSharp,jamespearce2006/CefSharp,joshvera/CefSharp,NumbersInternational/CefSharp,AJDev77/CefSharp,ITGlobal/CefSharp,ITGlobal/CefSharp,jamespearce2006/CefSharp,windygu/CefSharp,ruisebastiao/CefSharp,dga711/CefSharp,joshvera/CefSharp,rlmcneary2/CefSharp,Livit/CefSharp,zhangjingpu/CefSharp,rlmcneary2/CefSharp,ruisebastiao/CefSharp,AJDev77/CefSharp,ruisebastiao/CefSharp,gregmartinhtc/CefSharp,zhangjingpu/CefSharp,illfang/CefSharp,gregmartinhtc/CefSharp,Livit/CefSharp,gregmartinhtc/CefSharp,windygu/CefSharp,yoder/CefSharp,haozhouxu/CefSharp,windygu/CefSharp,VioletLife/CefSharp,Haraguroicha/CefSharp,illfang/CefSharp,twxstar/CefSharp,ITGlobal/CefSharp,battewr/CefSharp,Livit/CefSharp
CefSharp/IDownloadHandler.cs
CefSharp/IDownloadHandler.cs
// Copyright © 2010-2015 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. namespace CefSharp { public interface IDownloadHandler { /// <summary> /// Called before a download begins. /// </summary> /// <param name="browser">The browser instance</param> /// <param name="downloadItem">Represents the file being downloaded.</param> /// <param name="callback">Callback interface used to asynchronously continue a download.</param> void OnBeforeDownload(IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback); /// <summary> /// Called when a download's status or progress information has been updated. This may be called multiple times before and after <see cref="OnBeforeDownload"/>. /// </summary> /// <param name="browser">The browser instance</param> /// <param name="downloadItem">Represents the file being downloaded.</param> /// <param name="callback">The callback used to Cancel/Pause/Resume the process</param> void OnDownloadUpdated(IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback); } }
// Copyright © 2010-2015 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. namespace CefSharp { public interface IDownloadHandler { /// <summary> /// Called before a download begins. /// </summary> /// <param name="browser">The browser instance</param> /// <param name="downloadItem">Represents the file being downloaded.</param> /// <param name="callback">Callback interface used to asynchronously continue a download.</param> /// <returns>Return True to continue the download otherwise return False to cancel the download</returns> void OnBeforeDownload(IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback); /// <summary> /// Called when a download's status or progress information has been updated. This may be called multiple times before and after <see cref="OnBeforeDownload"/>. /// </summary> /// <param name="browser">The browser instance</param> /// <param name="downloadItem">Represents the file being downloaded.</param> /// <param name="callback">The callback used to Cancel/Pause/Resume the process</param> /// <returns>Return True to cancel, otherwise False to allow the download to continue.</returns> void OnDownloadUpdated(IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback); } }
bsd-3-clause
C#
d42eb56fee4b3aeff9e336553db1dcf1c70f23f2
Fix content root for non-windows xunit tests with no app domains
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
test/Microsoft.AspNetCore.StaticFiles.Tests/StaticFilesTestServer.cs
test/Microsoft.AspNetCore.StaticFiles.Tests/StaticFilesTestServer.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; using System.Collections.Generic; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.PlatformAbstractions; namespace Microsoft.AspNetCore.StaticFiles { public static class StaticFilesTestServer { public static TestServer Create(Action<IApplicationBuilder> configureApp, Action<IServiceCollection> configureServices = null) { var contentRootNet451 = PlatformServices.Default.Runtime.OperatingSystemPlatform == Platform.Windows ? "." : "../../../../test/Microsoft.AspNetCore.StaticFiles.Tests"; Action<IServiceCollection> defaultConfigureServices = services => { }; var configuration = new ConfigurationBuilder() .AddInMemoryCollection(new [] { new KeyValuePair<string, string>("webroot", ".") }) .Build(); var builder = new WebHostBuilder() #if NET451 .UseContentRoot(contentRootNet451) #endif .UseConfiguration(configuration) .Configure(configureApp) .ConfigureServices(configureServices ?? defaultConfigureServices); return new TestServer(builder); } } }
// 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; using System.Collections.Generic; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.StaticFiles { public static class StaticFilesTestServer { public static TestServer Create(Action<IApplicationBuilder> configureApp, Action<IServiceCollection> configureServices = null) { Action<IServiceCollection> defaultConfigureServices = services => { }; var configuration = new ConfigurationBuilder() .AddInMemoryCollection(new [] { new KeyValuePair<string, string>("webroot", ".") }) .Build(); var builder = new WebHostBuilder() .UseConfiguration(configuration) .Configure(configureApp) .ConfigureServices(configureServices ?? defaultConfigureServices); return new TestServer(builder); } } }
apache-2.0
C#
a88ce555e39700c6827af6194ac55dea9833170f
fix logging mistake
sebastian-heinz/SvrKit,sebastian-heinz/Arrowgene.Services,sebastian-heinz/MarrySocket
MarrySocket/MServer/PacketManager.cs
MarrySocket/MServer/PacketManager.cs
/* * Copyright 2015 Sebastian Heinz <sebastian.heinz.gt@googlemail.com> * * 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. * */ namespace MarrySocket.MServer { using MarrySocket.MExtra.Logging; using MarrySocket.MExtra.Packet; using MarrySocket.MExtra.Serialization; internal class PacketManager { private Logger logger; private ServerConfig serverConfig; private ISerialization serializer; internal PacketManager(ServerConfig serverConfig) { this.serverConfig = serverConfig; this.logger = this.serverConfig.Logger; this.serializer = this.serverConfig.Serializer; } internal void Handle(ClientSocket clientSocket, ReadPacket packet) { object myClass = this.serializer.Deserialize(packet.SerializedClass, this.logger); if (myClass != null) { clientSocket.InTraffic += packet.PacketHeader.PacketSize; this.serverConfig.OnReceivedPacket(packet.PacketHeader.PacketId, clientSocket, myClass); this.logger.Write("Client[{0}]: Handled Packet: {1}", clientSocket.Id, packet.PacketHeader.PacketId, LogType.PACKET); } else { this.logger.Write("Client[{0}]: Could not handled packet: {1}", clientSocket.Id, packet.PacketHeader.PacketId, LogType.PACKET); } } } }
/* * Copyright 2015 Sebastian Heinz <sebastian.heinz.gt@googlemail.com> * * 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. * */ namespace MarrySocket.MServer { using MarrySocket.MExtra.Logging; using MarrySocket.MExtra.Packet; using MarrySocket.MExtra.Serialization; internal class PacketManager { private Logger logger; private ServerConfig serverConfig; private ISerialization serializer; internal PacketManager(ServerConfig serverConfig) { this.serverConfig = serverConfig; this.logger = this.serverConfig.Logger; this.serializer = this.serverConfig.Serializer; } internal void Handle(ClientSocket clientSocket, ReadPacket packet) { object myClass = this.serializer.Deserialize(packet.SerializedClass, this.logger); if (myClass != null) { clientSocket.InTraffic += packet.PacketHeader.PacketSize; this.serverConfig.OnReceivedPacket(packet.PacketHeader.PacketId, clientSocket, myClass); this.logger.Write("Client[{0}]: Handled Packet: {0}", clientSocket.Id, packet.PacketHeader.PacketId, LogType.PACKET); } else { this.logger.Write("Client[{0}]: Could not handled packet: {0}", clientSocket.Id, packet.PacketHeader.PacketId, LogType.PACKET); } } } }
unknown
C#
a2ebcb1b25cae2ce0e79f934f4be6d6f6a8672f8
Update Program.cs
sunhyung/JCompareCS
JCompareCS/Program.cs
JCompareCS/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace JCompareCS { class Program { static void Main(string[] args) { JCompareCore core = new JCompareCore(); string srcFile = "Sample Source File Path"; string dstFile = "Sample Destination File Path"; StreamReader srSource = new StreamReader(srcFile); while (srSource.Peek() >= 0) { core.AddSourceLine(srSource.ReadLine()); } srSource.Close(); StreamReader srDest = new StreamReader(dstFile); while (srDest.Peek() >= 0) { core.AddDestinationLine(srDest.ReadLine()); } srDest.Close(); core.DoCompare(); for (int i = 0; i < core.GetResultCount(); i++) { CompareElement item = core.GetResultItem(i); Console.WriteLine("Source line : {0}, Destination line : {1}, Line count of same contents : {2}", item.srcStartIndex, item.dstStartIndex, item.lineCountOfSameContext); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace JCompareCS { class Program { static void Main(string[] args) { JCompareCore core = new JCompareCore(); string srcFile = "C:\\Users\\Lee SunHyung\\Documents\\Visual Studio 2012\\Projects\\AlgorithmsPractice\\Algorithm1\\Algorithm1.cpp"; string dstFile = "C:\\Users\\Lee SunHyung\\Documents\\Visual Studio 2012\\Projects\\AlgorithmsPractice\\Algorithm2\\Algorithm2.cpp"; StreamReader srSource = new StreamReader(srcFile); while (srSource.Peek() >= 0) { core.AddSourceLine(srSource.ReadLine()); } srSource.Close(); StreamReader srDest = new StreamReader(dstFile); while (srDest.Peek() >= 0) { core.AddDestinationLine(srDest.ReadLine()); } srDest.Close(); core.DoCompare(); for (int i = 0; i < core.GetResultCount(); i++) { CompareElement item = core.GetResultItem(i); Console.WriteLine("Source line : {0}, Destination line : {1}, Line count of same contents : {2}", item.srcStartIndex, item.dstStartIndex, item.lineCountOfSameContext); } } } }
mit
C#
a4072fceeb530b6bfc7aac32bfe8cf8ba4647958
add skip upload link
MacsDickinson/HackManchester2014,MacsDickinson/HackManchester2014,MacsDickinson/HackManchester2014
HackManchester2014/HackManchester2014/Donation/Views/Register4.cshtml
HackManchester2014/HackManchester2014/Donation/Views/Register4.cshtml
@{ Layout = "Shared/_Layout.cshtml"; } @inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic> <article class="register main-content"> <section class="layout-constrained layout-constrained--narrow"> <div class="layout-constrained layout-constrained--narrow"> <div class="page-intro"> <h1>Upload Your Picture</h1> <p> Great work for making your donation, you can now upload your proof for completing the challenge. </p> </div> <div class="form-panel"> <h2 class="progress-step"><span class="progress-step__indicator">3</span>Upload picture</h2> <fieldset> <legend class="form-step__intro">Prove you have done the challenge</legend> <div class="form-group"> <form id="upload-form" method="POST" enctype="multipart/form-data"> <label for="proof-file" class="btn btn--primary"> Upload your image <input type="file" id="proof-file" name="file" onchange="$('#upload-form').submit();" /> </label> </form> <a href="./nominate" class="btn--secondary">Or just nominate</a> </div> </fieldset> </div> </div> </section> </article>
@{ Layout = "Shared/_Layout.cshtml"; } @inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic> <article class="register main-content"> <section class="layout-constrained layout-constrained--narrow"> <div class="layout-constrained layout-constrained--narrow"> <div class="page-intro"> <h1>Upload Your Picture</h1> <p> Great work for making your donation, you can now upload your proof for completing the challenge. </p> </div> <div class="form-panel"> <h2 class="progress-step"><span class="progress-step__indicator">3</span>Upload picture</h2> <fieldset> <legend class="form-step__intro">Prove you have done the challenge</legend> <div class="form-group"> <form id="upload-form" method="POST" enctype="multipart/form-data"> <label for="proof-file" class="btn btn--primary"> Upload your image <input type="file" id="proof-file" name="file" onchange="$('#upload-form').submit();" /> </label> </form> </div> </fieldset> </div> </div> </section> </article>
mit
C#
8e5ba71122d91a8fcdfcaef30422580793971910
Add the "expired" value to the RecipientStatus enum
messagebird/csharp-rest-api
MessageBird/Objects/Recipient.cs
MessageBird/Objects/Recipient.cs
using System; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace MessageBird.Objects { public class Recipient { public enum RecipientStatus { // Message status [EnumMember(Value = "scheduled")] Scheduled, [EnumMember(Value = "sent")] Sent, [EnumMember(Value = "buffered")] Buffered, [EnumMember(Value = "delivered")] Delivered, [EnumMember(Value = "delivery_failed")] DeliveryFailed, [EnumMember(Value = "expired")] Expired // Voice message status [EnumMember(Value = "calling")] Calling, [EnumMember(Value = "answered")] Answered, [EnumMember(Value = "failed")] Failed, // reserved for future use [EnumMember(Value = "busy")] Busy, [EnumMember(Value = "machine")] Machine }; [JsonProperty("recipient")] public long Msisdn { get; set; } [JsonProperty("status")] [JsonConverter(typeof(StringEnumConverter))] public RecipientStatus? Status { get; set; } [JsonProperty("statusDatetime")] public DateTime? StatusDatetime { get; set; } public Recipient(long msisdn) { Msisdn = msisdn; } public override string ToString() { return JsonConvert.SerializeObject(this, Formatting.Indented); } } }
using System; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace MessageBird.Objects { public class Recipient { public enum RecipientStatus { // Message status [EnumMember(Value = "scheduled")] Scheduled, [EnumMember(Value = "sent")] Sent, [EnumMember(Value = "buffered")] Buffered, [EnumMember(Value = "delivered")] Delivered, [EnumMember(Value = "delivery_failed")] DeliveryFailed, // Voice message status [EnumMember(Value = "calling")] Calling, [EnumMember(Value = "answered")] Answered, [EnumMember(Value = "failed")] Failed, // reserved for future use [EnumMember(Value = "busy")] Busy, [EnumMember(Value = "machine")] Machine }; [JsonProperty("recipient")] public long Msisdn { get; set; } [JsonProperty("status")] [JsonConverter(typeof(StringEnumConverter))] public RecipientStatus? Status { get; set; } [JsonProperty("statusDatetime")] public DateTime? StatusDatetime { get; set; } public Recipient(long msisdn) { Msisdn = msisdn; } public override string ToString() { return JsonConvert.SerializeObject(this, Formatting.Indented); } } }
isc
C#
e6c840cad73a10e73d8e1e5af1a7bf416b8d497f
Implement more complete dispose pattern
TurnerSoftware/MongoFramework
MongoFramework/MongoDbContext.cs
MongoFramework/MongoDbContext.cs
using System; using System.Collections.Generic; using MongoDB.Driver; using System.Reflection; using MongoFramework.Infrastructure; using System.Linq; namespace MongoFramework { public class MongoDbContext : IMongoDbContext, IDisposable { protected IMongoDatabase database { get; set; } private IList<IMongoDbSet> dbSets { get; set; } public MongoDbContext(string connectionName) { var mongoUrl = MongoDbUtility.GetMongoUrlFromConfig(connectionName); if (mongoUrl == null) { throw new MongoConfigurationException("No connection string found with the name \'" + connectionName + "\'"); } database = MongoDbUtility.GetDatabase(mongoUrl); InitialiseDbSets(); } public MongoDbContext(string connectionString, string databaseName) { database = MongoDbUtility.GetDatabase(connectionString, databaseName); InitialiseDbSets(); } internal MongoDbContext(IMongoDatabase database) { this.database = database; InitialiseDbSets(); } public static MongoDbContext CreateWithDatabase(IMongoDatabase database) { return new MongoDbContext(database); } private void InitialiseDbSets() { dbSets = new List<IMongoDbSet>(); //Construct the MongoDbSet properties var properties = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); var mongoDbSetType = typeof(IMongoDbSet); foreach (var property in properties) { var propertyType = property.PropertyType; if (propertyType.IsGenericType && mongoDbSetType.IsAssignableFrom(propertyType)) { var dbSet = Activator.CreateInstance(propertyType) as IMongoDbSet; dbSet.SetDatabase(database); dbSets.Add(dbSet); property.SetValue(this, dbSet); } } } public virtual void SaveChanges() { foreach (var dbSet in dbSets) { dbSet.SaveChanges(); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { database = null; dbSets = null; } } ~MongoDbContext() { Dispose(false); } } }
using System; using System.Collections.Generic; using MongoDB.Driver; using System.Reflection; using MongoFramework.Infrastructure; using System.Linq; namespace MongoFramework { public class MongoDbContext : IMongoDbContext, IDisposable { protected IMongoDatabase database { get; set; } private IList<IMongoDbSet> dbSets { get; set; } public MongoDbContext(string connectionName) { var mongoUrl = MongoDbUtility.GetMongoUrlFromConfig(connectionName); if (mongoUrl == null) { throw new MongoConfigurationException("No connection string found with the name \'" + connectionName + "\'"); } database = MongoDbUtility.GetDatabase(mongoUrl); InitialiseDbSets(); } public MongoDbContext(string connectionString, string databaseName) { database = MongoDbUtility.GetDatabase(connectionString, databaseName); InitialiseDbSets(); } internal MongoDbContext(IMongoDatabase database) { this.database = database; InitialiseDbSets(); } public static MongoDbContext CreateWithDatabase(IMongoDatabase database) { return new MongoDbContext(database); } private void InitialiseDbSets() { dbSets = new List<IMongoDbSet>(); //Construct the MongoDbSet properties var properties = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); var mongoDbSetType = typeof(IMongoDbSet); foreach (var property in properties) { var propertyType = property.PropertyType; if (propertyType.IsGenericType && mongoDbSetType.IsAssignableFrom(propertyType)) { var dbSet = Activator.CreateInstance(propertyType) as IMongoDbSet; dbSet.SetDatabase(database); dbSets.Add(dbSet); property.SetValue(this, dbSet); } } } public virtual void SaveChanges() { foreach (var dbSet in dbSets) { dbSet.SaveChanges(); } } public void Dispose() { if (database != null) { database = null; dbSets = null; } } } }
mit
C#
c542089cd98f7d50fec0b8c702808c0d49c6c24f
Fix service bus scenario test to use new name and assert for errors early
akromm/azure-sdk-tools,DinoV/azure-sdk-tools,Madhukarc/azure-sdk-tools,Madhukarc/azure-sdk-tools,akromm/azure-sdk-tools,markcowl/azure-sdk-tools,markcowl/azure-sdk-tools,Madhukarc/azure-sdk-tools,akromm/azure-sdk-tools,johnkors/azure-sdk-tools,akromm/azure-sdk-tools,Madhukarc/azure-sdk-tools,akromm/azure-sdk-tools,antonba/azure-sdk-tools,antonba/azure-sdk-tools,johnkors/azure-sdk-tools,markcowl/azure-sdk-tools,Madhukarc/azure-sdk-tools,DinoV/azure-sdk-tools,DinoV/azure-sdk-tools,markcowl/azure-sdk-tools,DinoV/azure-sdk-tools,antonba/azure-sdk-tools,antonba/azure-sdk-tools,johnkors/azure-sdk-tools,johnkors/azure-sdk-tools,antonba/azure-sdk-tools,markcowl/azure-sdk-tools,johnkors/azure-sdk-tools,DinoV/azure-sdk-tools
WindowsAzurePowershell/src/Management.ServiceBus.Test/ScenarioTest.cs
WindowsAzurePowershell/src/Management.ServiceBus.Test/ScenarioTest.cs
// ---------------------------------------------------------------------------------- // // Copyright 2011 Microsoft Corporation // 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. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.CloudService.Test.Tests { using System.Collections.ObjectModel; using System.Management.Automation; using Microsoft.WindowsAzure.Management.CloudService.Model; using VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Management.CloudService.Test.Utilities; using Microsoft.WindowsAzure.Management.ServiceBus.Properties; [TestClass] public class ScenarioTest : PowerShellTest { public ScenarioTest() : base("Microsoft.WindowsAzure.Management.ServiceBus.dll", "Microsoft.WindowsAzure.Management.CloudService.dll" ) { } [TestCategory("Scenario"), TestMethod] public void CreateAndGetServiceBusNamespace() { string serviceBusNamespaceName = "AzureSDKCreateAndGetServiceBusNamespaceTest"; int locationIndex = 5; // North Central US string expectedRemoveVerbose = string.Format(Resources.RemovingNamespaceMessage, serviceBusNamespaceName); powershell.Runspace.SessionStateProxy.SetVariable("name", serviceBusNamespaceName); powershell.Runspace.SessionStateProxy.SetVariable("index", locationIndex); AddScenarioScript("CreateAndGetServiceBusNamespace.ps1"); Collection<PSObject> result = powershell.Invoke(); Assert.IsTrue(powershell.Streams.Error.Count.Equals(0)); Assert.AreEqual<string>(serviceBusNamespaceName, Testing.GetPSVariableValue<string>(result[0], "Name")); Assert.AreEqual<string>(expectedRemoveVerbose, powershell.Streams.Verbose[0].Message); } } }
// ---------------------------------------------------------------------------------- // // Copyright 2011 Microsoft Corporation // 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. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.CloudService.Test.Tests { using System.Collections.ObjectModel; using System.Management.Automation; using Microsoft.WindowsAzure.Management.CloudService.Model; using VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Management.CloudService.Test.Utilities; using Microsoft.WindowsAzure.Management.ServiceBus.Properties; [TestClass] public class ScenarioTest : PowerShellTest { public ScenarioTest() : base("Microsoft.WindowsAzure.Management.ServiceBus.dll", "Microsoft.WindowsAzure.Management.CloudService.dll" ) { } [TestCategory("Scenario"), TestMethod] public void CreateAndGetServiceBusNamespace() { string serviceBusNamespaceName = "OneSDKCreateAndGetServiceBusNamespace"; int locationIndex = 5; // North Central US string expectedRemoveVerbose = string.Format(Resources.RemovingNamespaceMessage, serviceBusNamespaceName); powershell.Runspace.SessionStateProxy.SetVariable("name", serviceBusNamespaceName); powershell.Runspace.SessionStateProxy.SetVariable("index", locationIndex); AddScenarioScript("CreateAndGetServiceBusNamespace.ps1"); Collection<PSObject> result = powershell.Invoke(); Assert.AreEqual<string>(serviceBusNamespaceName, Testing.GetPSVariableValue<string>(result[0], "Name")); Assert.AreEqual<string>(expectedRemoveVerbose, powershell.Streams.Verbose[0].Message); Assert.IsTrue(powershell.Streams.Error.Count.Equals(0)); } } }
apache-2.0
C#
a2ee21c202dc330d2c08f01e86a2930f801f3ff8
Bump version
kamil-mrzyglod/Oxygenize
Oxygenize/Properties/AssemblyInfo.cs
Oxygenize/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("Oxygenize")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Codenova.pl")] [assembly: AssemblyProduct("Oxygenize")] [assembly: AssemblyCopyright("Copyright © Codenova.pl 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("4edf4eea-cc6f-4d91-a2bf-c5315abf240c")] // 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.0.1.0")] [assembly: AssemblyFileVersion("2.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("Oxygenize")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Codenova.pl")] [assembly: AssemblyProduct("Oxygenize")] [assembly: AssemblyCopyright("Copyright © Codenova.pl 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("4edf4eea-cc6f-4d91-a2bf-c5315abf240c")] // 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.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")]
mit
C#
67ed290df1038e4be4aefc4bbb415c57fbf3f81e
write log messages to the debug console
pauldendulk/Mapsui,charlenni/Mapsui,charlenni/Mapsui
Samples/Mapsui.Samples.Forms/Mapsui.Samples.Forms.Shared/App.xaml.cs
Samples/Mapsui.Samples.Forms/Mapsui.Samples.Forms.Shared/App.xaml.cs
using System; using System.Diagnostics; using Mapsui.Logging; using Xamarin.Forms; namespace Mapsui.Samples.Forms { public partial class App : Application { public App() { InitializeComponent(); Logger.LogDelegate += LogMethod; if (Device.Idiom == TargetIdiom.Phone) MainPage = new NavigationPage(new Mapsui.Samples.Forms.MainPage()); else MainPage = new Mapsui.Samples.Forms.MainPageLarge(); } 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 } private void LogMethod(LogLevel logLevel, string message, Exception exception) { Debug.WriteLine($"{logLevel}: {message}, {exception}"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xamarin.Forms; namespace Mapsui.Samples.Forms { public partial class App : Application { public App() { InitializeComponent(); if (Device.Idiom == TargetIdiom.Phone) MainPage = new NavigationPage(new Mapsui.Samples.Forms.MainPage()); else MainPage = new Mapsui.Samples.Forms.MainPageLarge(); } 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#
18eb6fc55bfe76d5d2569187440fd5595be2ba04
Correct typo in docs
lambdacasserole/shaver
Shaver/CopyButton.cs
Shaver/CopyButton.cs
using System.Drawing; using System.Windows.Forms; namespace Shaver { /// <summary> /// A copy keyboard button. /// </summary> class CopyButton : KeyboardButton { private int iconSize; /// <summary> /// Gets or sets the icon size on the button. /// </summary> public int IconSize { get { return iconSize; } set { iconSize = value; Refresh(); } } /// <summary> /// Initializes a new instance of a copy keyboard button. /// </summary> public CopyButton() : base() { // Initialize icon size to 15. iconSize = 15; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); // Draw two pages copy symbol. int height = iconSize; int width = (height / 3) * 2; e.Graphics.DrawRectangle(new Pen(TextColor), (int)(Width / 2) - (int)(width / 1.5), (int)(Height / 2) - (int)(height / 1.5), width, height); e.Graphics.FillRectangle(new SolidBrush(TextColor), (int)(Width / 2) - (int)(width / 4), (int)(Height / 2) - (int)(height / 4), width, height); } } }
using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace Shaver { /// <summary> /// A copy keyboard button. /// </summary> class CopyButton : KeyboardButton { private int iconSize; /// <summary> /// Gets or sets the icon size on the button. /// </summary> public int IconSize { get { return iconSize; } set { iconSize = value; Refresh(); } } /// <summary> /// Initializes a new instance of a shift button. /// </summary> public CopyButton() : base() { iconSize = 15; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); // Draw two pages copy symbol. int height = iconSize; int width = (height / 3) * 2; e.Graphics.DrawRectangle(new Pen(TextColor), (int)(Width / 2) - (int)(width / 1.5), (int)(Height / 2) - (int)(height / 1.5), width, height); e.Graphics.FillRectangle(new SolidBrush(TextColor), (int)(Width / 2) - (int)(width / 4), (int)(Height / 2) - (int)(height / 4), width, height); } } }
mit
C#
358fe8f4719d555513eaa7b65a69ede46c27165c
Clean up comments.
DimensionDataCBUSydney/jab
jab/jab/Test/ServiceTests.cs
jab/jab/Test/ServiceTests.cs
using NSwag; using Xunit; namespace jab.tests { public partial class ApiBestPracticeTestBase { /// <summary> /// Require HTTPS support. /// </summary> /// <param name="service"> /// The <see cref="SwaggerService"/> to test. /// </param> [Theory, ParameterisedClassData(typeof(ApiServices), testDefinition)] public void RequireHttps(SwaggerService service) { Assert.True(service.Schemes.Contains(SwaggerSchema.Https), $"{service.BaseUrl} does not support HTTPS"); } } }
using NSwag; using Xunit; namespace jab.tests { public partial class ApiBestPracticeTestBase { /// <summary> /// Require HTTPS support. /// </summary> /// <param name="service"></param> /// <param name="path"></param> /// <param name="method"></param> /// <param name="operation"></param> [Theory, ParameterisedClassData(typeof(ApiServices), testDefinition)] public void RequireHttps( SwaggerService service ) { Assert.True(service.Schemes.Contains(SwaggerSchema.Https), $"{service.BaseUrl} does not support HTTPS"); } } }
apache-2.0
C#
1b8876319e1da1076d8fb6f35bee39c7aa566915
Update XGroup.cs
Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D
Test/Core/XGroup.cs
Test/Core/XGroup.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 System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Test.Core { public class XGroup : XShape { public string _name; public IList<XShape> _shapes; public string Name { get { return _name; } set { if (value != _name) { _name = value; Notify("Name"); } } } public IList<XShape> Shapes { get { return _shapes; } set { if (value != _shapes) { _shapes = value; Notify("Shapes"); } } } public override void Draw(object dc, IRenderer renderer, double dx, double dy) { foreach (var shape in Shapes) { shape.Draw(dc, renderer, dx, dy); } } public static XGroup Create(string name) { return new XGroup() { Name = name, Shapes = new ObservableCollection<XShape>() }; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Test.Core { public class XGroup : XShape { public string _name; public IList<XShape> _shapes; public string Name { get { return _name; } set { if (value != _name) { _name = value; Notify("Name"); } } } public IList<XShape> Shapes { get { return _shapes; } set { if (value != _shapes) { _shapes = value; Notify("Shapes"); } } } public override void Draw(object dc, IRenderer renderer, double dx, double dy) { foreach (var shape in Shapes) { shape.Draw(dc, renderer, dx, dy); } } public static XGroup Create(string name) { return new XGroup() { Name = name, Shapes = new ObservableCollection<XShape>() }; } } }
mit
C#
750fa775c9061915c273c74ec49f08d662c747ed
Fix typo
maxmind/GeoIP2-dotnet
MaxMind.GeoIP2/Model/MaxMind.cs
MaxMind.GeoIP2/Model/MaxMind.cs
#region using MaxMind.Db; using Newtonsoft.Json; #endregion namespace MaxMind.GeoIP2.Model { /// <summary> /// Contains data related to your MaxMind account. /// </summary> public class MaxMind { /// <summary> /// Constructor /// </summary> public MaxMind() { } /// <summary> /// Constructor /// </summary> [Constructor] public MaxMind([Parameter("queries_remaining")] int? queriesRemaining = null) { QueriesRemaining = queriesRemaining; } /// <summary> /// The number of remaining queries in your account for the web /// service end point. This will be null when using a local /// database. /// </summary> [JsonProperty("queries_remaining")] public int? QueriesRemaining { get; internal set; } /// <summary> /// Returns a <see cref="string" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="string" /> that represents this instance. /// </returns> public override string ToString() { return $"MaxMind [ QueriesRemaining={QueriesRemaining} ]"; } } }
#region using MaxMind.Db; using Newtonsoft.Json; #endregion namespace MaxMind.GeoIP2.Model { /// <summary> /// Contains data related to your MaxMind account. /// </summary> public class MaxMind { /// <summary> /// Constructor /// </summary> public MaxMind() { } /// <summary> /// Constructor /// </summary> [Constructor] public MaxMind([Parameter("queries_remaining")] int? queriesRemaining = null) { QueriesRemaining = queriesRemaining; } /// <summary> /// The number of remaining queried in your account for the web /// service end point. This will be null when using a local /// database. /// </summary> [JsonProperty("queries_remaining")] public int? QueriesRemaining { get; internal set; } /// <summary> /// Returns a <see cref="string" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="string" /> that represents this instance. /// </returns> public override string ToString() { return $"MaxMind [ QueriesRemaining={QueriesRemaining} ]"; } } }
apache-2.0
C#
a1cc27d0efccf47fb576b12b427a58d2d8f89a48
Change obsolete signature for method Error
alexvictoor/BrowserLog,alexvictoor/BrowserLog,alexvictoor/BrowserLog
BrowserLog.NLog.Demo/Program.cs
BrowserLog.NLog.Demo/Program.cs
using System; using System.Threading; using NLog; using NLogConfig = NLog.Config; namespace BrowserLog.NLog.Demo { class Program { static void Main(string[] args) { LogManager.Configuration = new NLogConfig.XmlLoggingConfiguration("NLog.config", true); var logger = LogManager.GetLogger("*", typeof(Program)); logger.Info("Hello!"); Thread.Sleep(1000); for (int i = 0; i < 100000; i++) { logger.Info("Hello this is a log from a server-side process!"); Thread.Sleep(100); logger.Warn("Hello this is a warning from a server-side process!"); logger.Debug("... and here is another log again ({0})", i); Thread.Sleep(200); try { ThrowExceptionWithStackTrace(4); } catch (Exception ex) { logger.Error(ex, "An error has occured, really?"); } Thread.Sleep(1000); } } static void ThrowExceptionWithStackTrace(int depth) { if (depth == 0) { throw new Exception("A fake exception to show an example"); } ThrowExceptionWithStackTrace(--depth); } } }
using System; using System.Threading; using NLog; using NLogConfig = NLog.Config; namespace BrowserLog.NLog.Demo { class Program { static void Main(string[] args) { LogManager.Configuration = new NLogConfig.XmlLoggingConfiguration("NLog.config", true); var logger = LogManager.GetLogger("*", typeof(Program)); logger.Info("Hello!"); Thread.Sleep(1000); for (int i = 0; i < 100000; i++) { logger.Info("Hello this is a log from a server-side process!"); Thread.Sleep(100); logger.Warn("Hello this is a warning from a server-side process!"); logger.Debug("... and here is another log again ({0})", i); Thread.Sleep(200); try { ThrowExceptionWithStackTrace(4); } catch (Exception ex) { logger.Error("An error has occured, really?", ex); } Thread.Sleep(1000); } } static void ThrowExceptionWithStackTrace(int depth) { if (depth == 0) { throw new Exception("A fake exception to show an example"); } ThrowExceptionWithStackTrace(--depth); } } }
apache-2.0
C#
2888ecdd99ccad316f0f3bd39cb2eba055aea45e
Update assemblyinfo
PKTINOS/SpongeGame
Code/Properties/AssemblyInfo.cs
Code/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("SpongeGame")] [assembly: AssemblyDescription("A game featuring Sponge, the character created by the Vinesauce community.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("PKTINOS")] [assembly: AssemblyProduct("OpenTKPlatformerExample")] [assembly: AssemblyCopyright("")] [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("4ddde25f-8dc9-4d00-b6ff-5bee608286c4")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SpongeGame")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("SpongeGame")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("OpenTKPlatformerExample")] [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("4ddde25f-8dc9-4d00-b6ff-5bee608286c4")] // 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#
b3f4ec2469b13ec5d9c2cd0aa7aae7b8bc9bb18e
Improve tab fragment
jbatonnet/shared
Android/Layout/TabFragment.cs
Android/Layout/TabFragment.cs
using System; using System.Collections.Generic; using System.Linq; using Android.App; using Android.Content; using Android.Content.PM; using Android.Database; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Support.Design.Widget; using Android.Support.V4.Widget; using Android.Support.V4.View; using Android.Support.V7.App; using Android.Support.V7.Widget; using Android.Utilities; using Android.Views; using Android.Widget; using Java.Lang; using Fragment = Android.Support.V4.App.Fragment; using Toolbar = Android.Support.V7.Widget.Toolbar; using SearchView = Android.Support.V7.Widget.SearchView; namespace Android.Utilities { public abstract class TabFragment : Fragment { public abstract string Title { get; } protected virtual void OnGotFocus() { } protected virtual void OnLostFocus() { } public virtual void Refresh() { } public override void SetMenuVisibility(bool visible) { base.SetMenuVisibility(visible); if (visible) OnGotFocus(); else OnLostFocus(); } } }
using System; using System.Collections.Generic; using System.Linq; using Android.App; using Android.Content; using Android.Content.PM; using Android.Database; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Support.Design.Widget; using Android.Support.V4.Widget; using Android.Support.V4.View; using Android.Support.V7.App; using Android.Support.V7.Widget; using Android.Utilities; using Android.Views; using Android.Widget; using Java.Lang; using Fragment = Android.Support.V4.App.Fragment; using Toolbar = Android.Support.V7.Widget.Toolbar; using SearchView = Android.Support.V7.Widget.SearchView; namespace Android.Utilities { public abstract class TabFragment : Fragment { public abstract string Title { get; } public virtual void Refresh() { } } }
mit
C#
6d2a8c5794d98c89b84d97edfaa1c5bd2551660e
Fix side-effect of renaming
emazzotta/unity-tower-defense
Assets/Scripts/MetallKefer.cs
Assets/Scripts/MetallKefer.cs
using UnityEngine; using System.Collections; public class MetallKefer : MonoBehaviour { private GameController game; private GameObject[] baseBuildable; private GameObject nextWaypiont; private int health; private int currentWaypointIndex = 0; private int movementSpeed = 2; void Start () { this.health = 100; this.game = GameObject.FindObjectOfType<GameController>(); this.nextWaypiont = this.game.getWaypoints () [this.currentWaypointIndex]; this.setInitialPosition (); } void Update() { this.moveToNextWaypoint (); if (this.transform.position.Equals( this.nextWaypiont.transform.position )) { this.SetNextWaypoint (); } } void SetNextWaypoint() { if (this.currentWaypointIndex < this.game.getWaypoints ().Length - 1) { this.currentWaypointIndex += 1; this.nextWaypiont = this.game.getWaypoints () [this.currentWaypointIndex]; this.nextWaypiont.GetComponent<Renderer> ().material.color = Utils.getRandomColor(); } } private void setInitialPosition() { this.transform.position = this.nextWaypiont.transform.position; } private void moveToNextWaypoint() { float step = movementSpeed * Time.deltaTime; Vector3 lookRotation = this.nextWaypiont.transform.position - transform.position; if (lookRotation != Vector3.zero) { var targetRotation = Quaternion.LookRotation(lookRotation); transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 5 * Time.deltaTime); this.transform.position = Vector3.MoveTowards(transform.position, this.nextWaypiont.transform.position, step); } } public void TakeDamage(int damage) { health -= damage; if (this.gameObject && health <= 0) { Destroy (this.gameObject); } } public int GetHealth() { return this.health; } }
using UnityEngine; using System.Collections; public class MetallKefer : MonoBehaviour { private Game game; private GameObject[] baseBuildable; private GameObject nextWaypiont; private int health; private int currentWaypointIndex = 0; private int movementSpeed = 2; void Start () { this.health = 100; this.game = GameObject.FindObjectOfType<Game>(); this.nextWaypiont = this.game.getWaypoints () [this.currentWaypointIndex]; this.setInitialPosition (); } void Update() { this.moveToNextWaypoint (); if (this.transform.position.Equals( this.nextWaypiont.transform.position )) { this.SetNextWaypoint (); } } void SetNextWaypoint() { if (this.currentWaypointIndex < this.game.getWaypoints ().Length - 1) { this.currentWaypointIndex += 1; this.nextWaypiont = this.game.getWaypoints () [this.currentWaypointIndex]; this.nextWaypiont.GetComponent<Renderer> ().material.color = Utils.getRandomColor(); } } private void setInitialPosition() { this.transform.position = this.nextWaypiont.transform.position; } private void moveToNextWaypoint() { float step = movementSpeed * Time.deltaTime; Vector3 lookRotation = this.nextWaypiont.transform.position - transform.position; if (lookRotation != Vector3.zero) { var targetRotation = Quaternion.LookRotation(lookRotation); transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 5 * Time.deltaTime); this.transform.position = Vector3.MoveTowards(transform.position, this.nextWaypiont.transform.position, step); } } public void TakeDamage(int damage) { health -= damage; if (this.gameObject && health <= 0) { Destroy (this.gameObject); } } public int GetHealth() { return this.health; } }
mit
C#
f81ffa636dc1770284c3d88c9f9514bdc4a30f22
Use BindTo instead of taking the game's beatmap bindable.
peppy/osu-new,DrabWeb/osu,DrabWeb/osu,tacchinotacchi/osu,ZLima12/osu,UselessToucan/osu,DrabWeb/osu,UselessToucan/osu,smoogipoo/osu,2yangk23/osu,Nabile-Rahmani/osu,naoey/osu,2yangk23/osu,smoogipooo/osu,Drezi126/osu,smoogipoo/osu,naoey/osu,EVAST9919/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,ppy/osu,ZLima12/osu,ppy/osu,johnneijzen/osu,smoogipoo/osu,NeoAdonis/osu,Damnae/osu,ppy/osu,johnneijzen/osu,peppy/osu,Frontear/osuKyzer,peppy/osu,NeoAdonis/osu,naoey/osu,EVAST9919/osu,osu-RP/osu-RP
osu.Game/Graphics/Containers/BeatSyncedContainer.cs
osu.Game/Graphics/Containers/BeatSyncedContainer.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Configuration; using osu.Framework.Graphics.Containers; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Timing; namespace osu.Game.Graphics.Containers { public class BeatSyncedContainer : Container { private Bindable<WorkingBeatmap> beatmap = new Bindable<WorkingBeatmap>(); private int lastBeat; private double lastTimingPointStart; //This is to avoid sending new beats when not at the very start of the beat private const int seek_tolerance = 20; private const double min_beat_length = 1E-100; protected override void Update() { if (beatmap.Value?.Track == null) return; double trackCurrentTime = beatmap.Value.Track.CurrentTime; ControlPoint overridePoint; ControlPoint controlPoint = beatmap.Value.Beatmap.TimingInfo.TimingPointAt(trackCurrentTime, out overridePoint); if (controlPoint == null) return; bool kiai = (overridePoint ?? controlPoint).KiaiMode; double beatLength = controlPoint.BeatLength; double timingPointStart = controlPoint.Time; int beat = beatLength > min_beat_length ? (int)((trackCurrentTime - timingPointStart) / beatLength) : 0; //The beats before the start of the first control point are off by 1, this should do the trick if (trackCurrentTime < timingPointStart) beat--; if ((timingPointStart != lastTimingPointStart || beat != lastBeat) && (int)((trackCurrentTime - timingPointStart) % beatLength) <= seek_tolerance) OnNewBeat(beat, beatLength, controlPoint.TimeSignature, kiai); lastBeat = beat; lastTimingPointStart = timingPointStart; } protected virtual void OnNewBeat(int newBeat, double beatLength, TimeSignatures timeSignature, bool kiai) { } [BackgroundDependencyLoader] private void load(OsuGameBase game) { beatmap.BindTo(game.Beatmap); } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Configuration; using osu.Framework.Graphics.Containers; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Timing; namespace osu.Game.Graphics.Containers { public class BeatSyncedContainer : Container { private Bindable<WorkingBeatmap> beatmap; private int lastBeat; private double lastTimingPointStart; //This is to avoid sending new beats when not at the very start of the beat private const int seek_tolerance = 20; private const double min_beat_length = 1E-100; protected override void Update() { if (beatmap.Value == null) return; double trackCurrentTime = beatmap.Value.Track.CurrentTime; ControlPoint overridePoint; ControlPoint controlPoint = beatmap.Value.Beatmap.TimingInfo.TimingPointAt(trackCurrentTime, out overridePoint); if (controlPoint == null) return; bool kiai = (overridePoint ?? controlPoint).KiaiMode; double beatLength = controlPoint.BeatLength; double timingPointStart = controlPoint.Time; int beat = beatLength > min_beat_length ? (int)((trackCurrentTime - timingPointStart) / beatLength) : 0; //The beats before the start of the first control point are off by 1, this should do the trick if (trackCurrentTime < timingPointStart) beat--; if ((timingPointStart != lastTimingPointStart || beat != lastBeat) && (int)((trackCurrentTime - timingPointStart) % beatLength) <= seek_tolerance) OnNewBeat(beat, beatLength, controlPoint.TimeSignature, kiai); lastBeat = beat; lastTimingPointStart = timingPointStart; } protected virtual void OnNewBeat(int newBeat, double beatLength, TimeSignatures timeSignature, bool kiai) { } [BackgroundDependencyLoader] private void load(OsuGameBase game) { beatmap = game.Beatmap; } } }
mit
C#
f84d14d043d06ba4c021336f1e657298f4ee7e72
work on ChartColors web
avifatal/framework,AlejandroCano/framework,avifatal/framework,signumsoftware/framework,signumsoftware/framework,AlejandroCano/framework
Signum.Entities/Basics/Color.cs
Signum.Entities/Basics/Color.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; using System.Drawing; namespace Signum.Entities.Basics { [Serializable] public class ColorDN : EmbeddedEntity { public ColorDN() { } public static ColorDN FromARGB(byte a, byte r, byte g, byte b) { return new ColorDN { Argb = a << 0x18 | r << 0x10 | g << 0x8 | b }; } public static ColorDN FromARGB(byte a, int rgb) { return new ColorDN { Argb = a << 0x18 | rgb }; } public static ColorDN FromARGB(int argb) { return new ColorDN { Argb = argb }; } int argb; public int Argb { get { return argb; } set { SetToStr(ref argb, value, () => Argb); } } [HiddenProperty] public byte A { get { return (byte)((argb >> 0x18) & 0xff); } } [HiddenProperty] public byte R { get { return (byte)((argb >> 0x10) & 0xff); } } [HiddenProperty] public byte G { get { return (byte)((argb >> 0x8) & 0xff); } } [HiddenProperty] public byte B { get { return (byte)(argb & 0xff); } } public Color ToColor() { return Color.FromArgb(argb); } public override string ToString() { return ToColor().ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; using System.Drawing; namespace Signum.Entities.Basics { [Serializable] public class ColorDN : EmbeddedEntity { public ColorDN() { } public ColorDN(byte a, byte r, byte g, byte b) { argb = a << 0x18 | r << 0x10 | g << 0x8 | b; } int argb; public int Argb { get { return argb; } set { SetToStr(ref argb, value, () => Argb); } } [HiddenProperty] public byte A { get { return (byte)((argb >> 0x18) & 0xff); } } [HiddenProperty] public byte R { get { return (byte)((argb >> 0x10) & 0xff); } } [HiddenProperty] public byte G { get { return (byte)((argb >> 0x8) & 0xff); } } [HiddenProperty] public byte B { get { return (byte)(argb & 0xff); } } public Color ToColor() { return Color.FromArgb(argb); } public override string ToString() { return ToColor().ToString(); } } }
mit
C#
4477e2d9e6d002109ee4ceeea0fe562bac8d3c84
add connect by username and password
Xarlot/NGitLab
NGitLab/NGitLab/GitLabClient.cs
NGitLab/NGitLab/GitLabClient.cs
using NGitLab.Impl; using NGitLab.Models; namespace NGitLab { public class GitLabClient { readonly Api api; public readonly INamespaceClient Groups; public readonly IIssueClient Issues; public readonly IProjectClient Projects; public readonly IUserClient Users; GitLabClient(string hostUrl, string apiToken) { api = new Api(hostUrl, apiToken); Users = new UserClient(api); Projects = new ProjectClient(api); Issues = new IssueClient(api); Groups = new NamespaceClient(api); } public static GitLabClient Connect(string hostUrl, string username, string password) { var api = new Api(hostUrl, ""); var session = api.Post().To<Session>($"/session?login={username}&password={password}"); return Connect(hostUrl, session.PrivateToken); } public static GitLabClient Connect(string hostUrl, string apiToken) { return new GitLabClient(hostUrl, apiToken); } public IRepositoryClient GetRepository(int projectId) { return new RepositoryClient(api, projectId); } public IMergeRequestClient GetMergeRequest(int projectId) { return new MergeRequestClient(api, projectId); } } }
using NGitLab.Impl; namespace NGitLab { public class GitLabClient { readonly Api api; public readonly INamespaceClient Groups; public readonly IIssueClient Issues; public readonly IProjectClient Projects; public readonly IUserClient Users; GitLabClient(string hostUrl, string apiToken) { api = new Api(hostUrl, apiToken); Users = new UserClient(api); Projects = new ProjectClient(api); Issues = new IssueClient(api); Groups = new NamespaceClient(api); } public static GitLabClient Connect(string hostUrl, string apiToken) { return new GitLabClient(hostUrl, apiToken); } public IRepositoryClient GetRepository(int projectId) { return new RepositoryClient(api, projectId); } public IMergeRequestClient GetMergeRequest(int projectId) { return new MergeRequestClient(api, projectId); } } }
mit
C#
bc888bb7a7625d623305785bfe2bc12e62ceac24
Add ColumnSpecification documentation (part of #34)
felipebz/ndapi
Ndapi/ColumnSpecification.cs
Ndapi/ColumnSpecification.cs
using Ndapi.Core.Handles; using Ndapi.Enums; namespace Ndapi { /// <summary> /// Represents a record group column. /// </summary> public class ColumnSpecification : NdapiObject { /// <summary> /// Creates a record group column. /// </summary> /// <param name="module"></param> /// <param name="name"></param> public ColumnSpecification(RecordGroup module, string name) { Create(name, ObjectType.ColumnSpecification, module); } internal ColumnSpecification(ObjectSafeHandle handle) : base(handle) { } /// <summary> /// Gets or sets the column data type. /// </summary> public ColumnSpecificationDataType DataType { get { return GetNumberProperty<ColumnSpecificationDataType>(NdapiConstants.D2FP_COL_DAT_TYP); } set { SetNumberProperty(NdapiConstants.D2FP_COL_DAT_TYP, value); } } /// <summary> /// Gets or sets the maximum length. /// </summary> public int MaximumLength { get { return GetNumberProperty(NdapiConstants.D2FP_MAX_LEN); } set { SetNumberProperty(NdapiConstants.D2FP_MAX_LEN, value); } } /// <summary> /// Gets the number of values. /// </summary> public int ValueCount => GetNumberProperty(NdapiConstants.D2FP_COL_VALS_COUNT); } }
using Ndapi.Core.Handles; using Ndapi.Enums; namespace Ndapi { public class ColumnSpecification : NdapiObject { public ColumnSpecification(FormModule module, string name) { Create(name, ObjectType.ColumnSpecification, module); } internal ColumnSpecification(ObjectSafeHandle handle) : base(handle) { } public ColumnSpecificationDataType DataType { get { return GetNumberProperty<ColumnSpecificationDataType>(NdapiConstants.D2FP_COL_DAT_TYP); } set { SetNumberProperty(NdapiConstants.D2FP_COL_DAT_TYP, value); } } public int MaximumLength { get { return GetNumberProperty(NdapiConstants.D2FP_MAX_LEN); } set { SetNumberProperty(NdapiConstants.D2FP_MAX_LEN, value); } } public int ValueCount => GetNumberProperty(NdapiConstants.D2FP_COL_VALS_COUNT); } }
mit
C#
784024ea7a1909acd5bba6563bedd9029cefc46f
Change List data type to IEnumerable
lukecahill/NutritionTracker
food_tracker/DAL/WholeDay.cs
food_tracker/DAL/WholeDay.cs
using System; using System.ComponentModel.DataAnnotations; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace food_tracker.DAL { public class WholeDay { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public string WholeDayId { get; set; } public DateTime dateTime { get; set; } public double dailyTotal { get; set; } public virtual IEnumerable<NutritionItem> foodsDuringDay { get; set; } [Obsolete("Only needed for serialization and materialization", true)] public WholeDay() { } public WholeDay(string dayId) { this.WholeDayId = dayId; this.dateTime = DateTime.UtcNow; this.dailyTotal = 0; } } }
using System; using System.ComponentModel.DataAnnotations; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace food_tracker.DAL { public class WholeDay { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public string WholeDayId { get; set; } public DateTime dateTime { get; set; } public double dailyTotal { get; set; } public virtual List<NutritionItem> foodsDuringDay { get; set; } [Obsolete("Only needed for serialization and materialization", true)] public WholeDay() { } public WholeDay(string dayId) { this.WholeDayId = dayId; this.dateTime = DateTime.UtcNow; this.dailyTotal = 0; } } }
mit
C#
69e3911b9b5964105c13c935383e52775111e302
Update ValuesController.cs
cayodonatti/TopGearApi
TopGearApi/Controllers/ValuesController.cs
TopGearApi/Controllers/ValuesController.cs
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Mvc; namespace TopGearApi.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 public string Get(int id) { return "value"; } // POST api/values public void Post([FromBody]string value) { } // PUT api/values/5 public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 public void Delete(int id) { } [System.Web.Http.HttpGet] [Route("Test")] public IHttpActionResult Obter() { /*var content = JsonConvert.SerializeObject(new { ab = "teste1", cd = "teste2 " }); return base.Json(content);*/ // Then I return the list return new JsonResult { Data = new { ab = "teste1", cd = "teste2 " } }; } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Mvc; namespace TopGearApi.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 public string Get(int id) { return "value"; } // POST api/values public void Post([FromBody]string value) { } // PUT api/values/5 public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 public void Delete(int id) { } [HttpGet] [Route("Test")] public IHttpActionResult Obter() { /*var content = JsonConvert.SerializeObject(new { ab = "teste1", cd = "teste2 " }); return base.Json(content);*/ // Then I return the list return new JsonResult { Data = new { ab = "teste1", cd = "teste2 " } }; } } }
mit
C#
5e5943cf29b242e3d729f7fe32ddcbeebe99705c
Add escaping to query string parsing
mattolenik/winston,mattolenik/winston,mattolenik/winston
Winston/Net/Extensions.cs
Winston/Net/Extensions.cs
using System; using System.Collections.Specialized; using System.Text.RegularExpressions; namespace Winston.Net { static class Extensions { public static NameValueCollection ParseQueryString(this Uri uri) { var result = new NameValueCollection(); var query = uri.Query; // remove anything other than query string from url if (query.Contains("?")) { query = query.Substring(query.IndexOf('?') + 1); } foreach (string vp in Regex.Split(query, "&")) { var singlePair = Regex.Split(vp, "="); if (singlePair.Length == 2) { result.Add(Uri.UnescapeDataString(singlePair[0]), Uri.UnescapeDataString(singlePair[1])); } else { // only one key with no value specified in query string result.Add(Uri.UnescapeDataString(singlePair[0]), string.Empty); } } return result; } } }
using System; using System.Collections.Specialized; using System.Text.RegularExpressions; namespace Winston.Net { static class Extensions { public static NameValueCollection ParseQueryString(this Uri uri) { var result = new NameValueCollection(); var query = uri.Query; // remove anything other than query string from url if (query.Contains("?")) { query = query.Substring(query.IndexOf('?') + 1); } foreach (string vp in Regex.Split(query, "&")) { var singlePair = Regex.Split(vp, "="); if (singlePair.Length == 2) { result.Add(singlePair[0], singlePair[1]); } else { // only one key with no value specified in query string result.Add(singlePair[0], string.Empty); } } return result; } } }
mit
C#
60926ca60a0ed5743ced99ce288d748f5892603b
Change year in footer to 2021
DominikStiller/Vertretungsplan,DominikStiller/Vertretungsplan,DominikStiller/Vertretungsplan,DominikStiller/Vertretungsplan
Web/Views/Shared/_Layout.cshtml
Web/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <title>@ViewData["Title"]</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="robots" content="none"> <meta name="description" content="Vertretungsplan des Gymnasium Unterrieden Sindelfingen"> <meta name="theme-color" content="#eee"> <link rel="icon" type="image/png" href="/images/icon.png"> <link rel="apple-touch-icon" href="/images/icon_apple.png"> <link rel="stylesheet" href="/main.min.css" asp-append-version="true"> @RenderSection("LightweightScripts", false) <script src="https://use.typekit.net/hii3spj.js"></script> <script>try { Typekit.load({ async: true }); } catch (e) { }</script> @if (!ViewData.ContainsKey("Lightweight")) { @RenderSection("Scripts", false) <script src="/main.min.js" asp-append-version="true"></script> <environment names="Production"> <script> (function (i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-99091816-1', 'auto'); ga('set', 'anonymizeIp', true); ga('send', 'pageview'); </script> </environment> } </head> <body> @if (Context.User.Identity.IsAuthenticated) { @await Html.PartialAsync("_MenuBar") } <main> @RenderBody() </main> @if (!ViewData.ContainsKey("HideFooter")) { <footer> <a href="#" id="jumptotop">&#9650; Nach oben</a> <span id="copyright">&copy;2021 <a href="https://dominikstiller.com/" target="_blank">Dominik Stiller</a> &middot; <a href="/datenschutz">Datenschutz</a></span> </footer> } </body> </html>
<!DOCTYPE html> <html> <head> <title>@ViewData["Title"]</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="robots" content="none"> <meta name="description" content="Vertretungsplan des Gymnasium Unterrieden Sindelfingen"> <meta name="theme-color" content="#eee"> <link rel="icon" type="image/png" href="/images/icon.png"> <link rel="apple-touch-icon" href="/images/icon_apple.png"> <link rel="stylesheet" href="/main.min.css" asp-append-version="true"> @RenderSection("LightweightScripts", false) <script src="https://use.typekit.net/hii3spj.js"></script> <script>try { Typekit.load({ async: true }); } catch (e) { }</script> @if (!ViewData.ContainsKey("Lightweight")) { @RenderSection("Scripts", false) <script src="/main.min.js" asp-append-version="true"></script> <environment names="Production"> <script> (function (i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-99091816-1', 'auto'); ga('set', 'anonymizeIp', true); ga('send', 'pageview'); </script> </environment> } </head> <body> @if (Context.User.Identity.IsAuthenticated) { @await Html.PartialAsync("_MenuBar") } <main> @RenderBody() </main> @if (!ViewData.ContainsKey("HideFooter")) { <footer> <a href="#" id="jumptotop">&#9650; Nach oben</a> <span id="copyright">&copy;2020 <a href="http://dominikstiller.de/" target="_blank">Dominik Stiller</a> &middot; <a href="/datenschutz">Datenschutz</a></span> </footer> } </body> </html>
mit
C#
a700aa2cd30c2f3c018445a937ba6fbd857fee4e
Handle cases where a namespace declaration isn't found in the ancestors of a type declaration
brettfo/roslyn,diryboy/roslyn,davkean/roslyn,tmat/roslyn,shyamnamboodiripad/roslyn,swaroop-sridhar/roslyn,gafter/roslyn,aelij/roslyn,nguerrera/roslyn,mgoertz-msft/roslyn,abock/roslyn,abock/roslyn,AmadeusW/roslyn,KevinRansom/roslyn,heejaechang/roslyn,weltkante/roslyn,dotnet/roslyn,sharwell/roslyn,ErikSchierboom/roslyn,bartdesmet/roslyn,heejaechang/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,brettfo/roslyn,agocke/roslyn,davkean/roslyn,stephentoub/roslyn,wvdd007/roslyn,tmat/roslyn,gafter/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,tannergooding/roslyn,reaction1989/roslyn,wvdd007/roslyn,jmarolf/roslyn,nguerrera/roslyn,KirillOsenkov/roslyn,dotnet/roslyn,stephentoub/roslyn,gafter/roslyn,jmarolf/roslyn,weltkante/roslyn,abock/roslyn,reaction1989/roslyn,KevinRansom/roslyn,mgoertz-msft/roslyn,panopticoncentral/roslyn,reaction1989/roslyn,shyamnamboodiripad/roslyn,KirillOsenkov/roslyn,panopticoncentral/roslyn,eriawan/roslyn,physhi/roslyn,agocke/roslyn,eriawan/roslyn,genlu/roslyn,tmat/roslyn,eriawan/roslyn,diryboy/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,AlekseyTs/roslyn,swaroop-sridhar/roslyn,jmarolf/roslyn,brettfo/roslyn,sharwell/roslyn,agocke/roslyn,swaroop-sridhar/roslyn,davkean/roslyn,physhi/roslyn,wvdd007/roslyn,AmadeusW/roslyn,genlu/roslyn,diryboy/roslyn,mavasani/roslyn,aelij/roslyn,AlekseyTs/roslyn,ErikSchierboom/roslyn,jasonmalinowski/roslyn,KirillOsenkov/roslyn,AlekseyTs/roslyn,CyrusNajmabadi/roslyn,mgoertz-msft/roslyn,nguerrera/roslyn,jasonmalinowski/roslyn,tannergooding/roslyn,CyrusNajmabadi/roslyn,heejaechang/roslyn,panopticoncentral/roslyn,genlu/roslyn,physhi/roslyn,stephentoub/roslyn,aelij/roslyn,bartdesmet/roslyn,weltkante/roslyn,mavasani/roslyn,dotnet/roslyn,tannergooding/roslyn,sharwell/roslyn,KevinRansom/roslyn
src/Features/CSharp/Portable/MoveToNamespace/CSharpMoveToNamespaceService.cs
src/Features/CSharp/Portable/MoveToNamespace/CSharpMoveToNamespaceService.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Composition; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MoveToNamespace; namespace Microsoft.CodeAnalysis.CSharp.MoveToNamespace { [ExportLanguageService(typeof(AbstractMoveToNamespaceService), LanguageNames.CSharp), Shared] internal class CSharpMoveToNamespaceService : AbstractMoveToNamespaceService<CompilationUnitSyntax, NamespaceDeclarationSyntax, TypeDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpMoveToNamespaceService( [Import(AllowDefault = true)] IMoveToNamespaceOptionsService moveToNamespaceOptionsService) : base(moveToNamespaceOptionsService) { } protected override string GetNamespaceName(NamespaceDeclarationSyntax syntax) => syntax.Name.ToString(); protected override string GetNamespaceName(TypeDeclarationSyntax syntax) { var namespaceDecl = syntax.FirstAncestorOrSelf<NamespaceDeclarationSyntax>(); if (namespaceDecl == null) { return string.Empty; } return GetNamespaceName(namespaceDecl); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Composition; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MoveToNamespace; namespace Microsoft.CodeAnalysis.CSharp.MoveToNamespace { [ExportLanguageService(typeof(AbstractMoveToNamespaceService), LanguageNames.CSharp), Shared] internal class CSharpMoveToNamespaceService : AbstractMoveToNamespaceService<CompilationUnitSyntax, NamespaceDeclarationSyntax, TypeDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpMoveToNamespaceService( [Import(AllowDefault = true)] IMoveToNamespaceOptionsService moveToNamespaceOptionsService) : base(moveToNamespaceOptionsService) { } protected override string GetNamespaceName(NamespaceDeclarationSyntax syntax) => syntax.Name.ToString(); protected override string GetNamespaceName(TypeDeclarationSyntax syntax) => GetNamespaceName(syntax.FirstAncestorOrSelf<NamespaceDeclarationSyntax>()); } }
mit
C#
ae376c50a4b921947bef8ec81658573e9bf9e995
Update copyright year
activescott/lessmsi,activescott/lessmsi,activescott/lessmsi
src/CommonAssemblyInfo.cs
src/CommonAssemblyInfo.cs
// 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. // // Copyright (c) 2004-2013 Scott Willeke (http://scott.willeke.com) // // Authors: // Scott Willeke (scott@willeke.com) // using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion("1.0.10.*")] [assembly: AssemblyCopyright("Copyright Scott Willeke © 2004-2021")] // 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)]
// 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. // // Copyright (c) 2004-2013 Scott Willeke (http://scott.willeke.com) // // Authors: // Scott Willeke (scott@willeke.com) // using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion("1.0.10.*")] [assembly: AssemblyCopyright("Copyright Scott Willeke © 2004-2015")] // 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)]
mit
C#
af20fa2cef0cd6e91cb12af0b4bd17743a6dc226
Enable underscore in middle of long name.
nemec/clipr
clipr/Core/ArgumentValidation.cs
clipr/Core/ArgumentValidation.cs
using System; using System.Text.RegularExpressions; namespace clipr.Core { internal static class ArgumentValidation { public static bool IsAllowedShortName(char c) { return Char.IsLetter(c); } internal const string IsAllowedShortNameExplanation = "Short arguments must be letters."; public static bool IsAllowedLongName(string name) { return name != null && Regex.IsMatch(name, @"^[a-zA-Z][a-zA-Z0-9\-_]*[a-zA-Z0-9]$"); } internal const string IsAllowedLongNameExplanation = "Long arguments must begin with a letter, contain a letter, " + "digit, underscore, or hyphen, and end with a letter or a digit."; } }
using System; using System.Text.RegularExpressions; namespace clipr.Core { internal static class ArgumentValidation { public static bool IsAllowedShortName(char c) { return Char.IsLetter(c); } internal const string IsAllowedShortNameExplanation = "Short arguments must be letters."; public static bool IsAllowedLongName(string name) { return name != null && Regex.IsMatch(name, @"^[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9]$"); } internal const string IsAllowedLongNameExplanation = "Long arguments must begin with a letter, contain a letter, " + "digit, or hyphen, and end with a letter or a digit."; } }
mit
C#
7c1a235aecc9ad0963c23ca6478a3b516b9672bc
Add `LocalisableString.Interpolate` method.
ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework
osu.Framework/Localisation/LocalisableString.cs
osu.Framework/Localisation/LocalisableString.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; #nullable enable namespace osu.Framework.Localisation { /// <summary> /// A descriptor representing text that can be localised and formatted. /// </summary> public readonly struct LocalisableString : IEquatable<LocalisableString> { /// <summary> /// The underlying data. /// </summary> internal readonly object? Data; /// <summary> /// Creates a new <see cref="LocalisableString"/> with underlying string data. /// </summary> public LocalisableString(string data) { Data = data; } /// <summary> /// Creates a new <see cref="LocalisableString"/> with underlying localisable string data. /// </summary> public LocalisableString(ILocalisableStringData data) { Data = data; } /// <summary> /// Replaces one or more format items in a specified string with a localised string representation of a corresponding object in <paramref name="args"/>. /// </summary> /// <param name="format">The format string.</param> /// <param name="args">The objects to format.</param> public static LocalisableString Format(string format, params object?[] args) => new LocalisableFormattableString(format, args); /// <summary> /// Creates a <see cref="LocalisableString"/> representation of the specified interpolated string. /// </summary> /// <param name="interpolation">The interpolated string containing format and arguments.</param> public static LocalisableString Interpolate(FormattableString interpolation) => new LocalisableFormattableString(interpolation); // it's somehow common to call default(LocalisableString), and we should return empty string then. public override string ToString() => Data?.ToString() ?? string.Empty; public bool Equals(LocalisableString other) => LocalisableStringEqualityComparer.Default.Equals(this, other); public override bool Equals(object? obj) => obj is LocalisableString other && Equals(other); public override int GetHashCode() => LocalisableStringEqualityComparer.Default.GetHashCode(this); public static bool operator ==(LocalisableString left, LocalisableString right) => left.Equals(right); public static bool operator !=(LocalisableString left, LocalisableString right) => !left.Equals(right); public static implicit operator LocalisableString(string text) => new LocalisableString(text); public static implicit operator LocalisableString(TranslatableString translatable) => new LocalisableString(translatable); public static implicit operator LocalisableString(RomanisableString romanisable) => new LocalisableString(romanisable); public static implicit operator LocalisableString(LocalisableFormattableString formattable) => new LocalisableString(formattable); public static implicit operator LocalisableString(CaseTransformableString transformable) => new LocalisableString(transformable); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; #nullable enable namespace osu.Framework.Localisation { /// <summary> /// A descriptor representing text that can be localised and formatted. /// </summary> public readonly struct LocalisableString : IEquatable<LocalisableString> { /// <summary> /// The underlying data. /// </summary> internal readonly object? Data; /// <summary> /// Creates a new <see cref="LocalisableString"/> with underlying string data. /// </summary> public LocalisableString(string data) { Data = data; } /// <summary> /// Creates a new <see cref="LocalisableString"/> with underlying localisable string data. /// </summary> public LocalisableString(ILocalisableStringData data) { Data = data; } /// <summary> /// Replaces one or more format items in a specified string with a localised string representation of a corresponding object in <paramref name="args"/>. /// </summary> /// <param name="format">The format string.</param> /// <param name="args">The objects to format.</param> public static LocalisableString Format(string format, params object?[] args) => new LocalisableFormattableString(format, args); // it's somehow common to call default(LocalisableString), and we should return empty string then. public override string ToString() => Data?.ToString() ?? string.Empty; public bool Equals(LocalisableString other) => LocalisableStringEqualityComparer.Default.Equals(this, other); public override bool Equals(object? obj) => obj is LocalisableString other && Equals(other); public override int GetHashCode() => LocalisableStringEqualityComparer.Default.GetHashCode(this); public static bool operator ==(LocalisableString left, LocalisableString right) => left.Equals(right); public static bool operator !=(LocalisableString left, LocalisableString right) => !left.Equals(right); public static implicit operator LocalisableString(string text) => new LocalisableString(text); public static implicit operator LocalisableString(TranslatableString translatable) => new LocalisableString(translatable); public static implicit operator LocalisableString(RomanisableString romanisable) => new LocalisableString(romanisable); public static implicit operator LocalisableString(LocalisableFormattableString formattable) => new LocalisableString(formattable); public static implicit operator LocalisableString(CaseTransformableString transformable) => new LocalisableString(transformable); } }
mit
C#
5ec1f4deb3d9e5b4b1b7837e394acbc664b8aeae
Prepare Release
dfensgmbh/biz.dfch.CS.Appclusive.Scheduler
src/AssemblyVersion.cs
src/AssemblyVersion.cs
using System.Reflection; // 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("3.4.0.*")]
using System.Reflection; // 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("3.3.0.*")]
apache-2.0
C#
82c18c2ba4d3b3475830fe0a65de0aa38533c758
add interface to controller [#136036659]
revaturelabs/revashare-svc-webapi
revashare-svc-webapi/revashare-svc-webapi.Client/Controllers/DriverController.cs
revashare-svc-webapi/revashare-svc-webapi.Client/Controllers/DriverController.cs
using revashare_svc_webapi.Logic.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace revashare_svc_webapi.Client.Controllers { [RoutePrefix("rider")] public class DriverController : ApiController { private readonly IDriverRepository repo; public DriverController(IDriverRepository repo) { this.repo = repo; } // GET: api/Driver public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET: api/Driver/5 public string Get(int id) { return "value"; } // POST: api/Driver public void Post([FromBody]string value) { } // PUT: api/Driver/5 public void Put(int id, [FromBody]string value) { } // DELETE: api/Driver/5 public void Delete(int id) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace revashare_svc_webapi.Client.Controllers { public class DriverController : ApiController { // GET: api/Driver public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET: api/Driver/5 public string Get(int id) { return "value"; } // POST: api/Driver public void Post([FromBody]string value) { } // PUT: api/Driver/5 public void Put(int id, [FromBody]string value) { } // DELETE: api/Driver/5 public void Delete(int id) { } } }
mit
C#
2cb217e06c04d63de4bc4151c7631b9abc448062
Fix editor legacy beatmap skins not receiving transformer
NeoAdonis/osu,peppy/osu,ppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu
osu.Game/Screens/Edit/EditorSkinProvidingContainer.cs
osu.Game/Screens/Edit/EditorSkinProvidingContainer.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Skinning; #nullable enable namespace osu.Game.Screens.Edit { /// <summary> /// A <see cref="SkinProvidingContainer"/> that fires <see cref="ISkinSource.SourceChanged"/> when users have made a change to the beatmap skin /// of the map being edited. /// </summary> public class EditorSkinProvidingContainer : RulesetSkinProvidingContainer { private readonly EditorBeatmapSkin? beatmapSkin; public EditorSkinProvidingContainer(EditorBeatmap editorBeatmap) : base(editorBeatmap.PlayableBeatmap.BeatmapInfo.Ruleset.CreateInstance(), editorBeatmap.PlayableBeatmap, editorBeatmap.BeatmapSkin?.Skin) { beatmapSkin = editorBeatmap.BeatmapSkin; } protected override void LoadComplete() { base.LoadComplete(); if (beatmapSkin != null) beatmapSkin.BeatmapSkinChanged += TriggerSourceChanged; } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (beatmapSkin != null) beatmapSkin.BeatmapSkinChanged -= TriggerSourceChanged; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Skinning; #nullable enable namespace osu.Game.Screens.Edit { /// <summary> /// A <see cref="SkinProvidingContainer"/> that fires <see cref="ISkinSource.SourceChanged"/> when users have made a change to the beatmap skin /// of the map being edited. /// </summary> public class EditorSkinProvidingContainer : RulesetSkinProvidingContainer { private readonly EditorBeatmapSkin? beatmapSkin; public EditorSkinProvidingContainer(EditorBeatmap editorBeatmap) : base(editorBeatmap.PlayableBeatmap.BeatmapInfo.Ruleset.CreateInstance(), editorBeatmap.PlayableBeatmap, editorBeatmap.BeatmapSkin) { beatmapSkin = editorBeatmap.BeatmapSkin; } protected override void LoadComplete() { base.LoadComplete(); if (beatmapSkin != null) beatmapSkin.BeatmapSkinChanged += TriggerSourceChanged; } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (beatmapSkin != null) beatmapSkin.BeatmapSkinChanged -= TriggerSourceChanged; } } }
mit
C#
1ad239b802fc120cdd474e358318f2c51a7bd706
Add the new managers to the root context.
Mitsugaru/game-off-2016
Assets/Scripts/RootContext.cs
Assets/Scripts/RootContext.cs
using UnityEngine; using System.Collections; using strange.extensions.context.impl; using strange.extensions.context.api; public class RootContext : MVCSContext, IRootContext { public RootContext(MonoBehaviour view) : base(view) { } public RootContext(MonoBehaviour view, ContextStartupFlags flags) : base(view, flags) { } protected override void mapBindings() { base.mapBindings(); GameObject managers = GameObject.Find("Managers"); injectionBinder.Bind<IRootContext>().ToValue(this).ToSingleton().CrossContext(); EventManager eventManager = managers.GetComponent<EventManager>(); injectionBinder.Bind<IEventManager>().ToValue(eventManager).ToSingleton().CrossContext(); ICameraLayerManager cameraManager = managers.GetComponent<ICameraLayerManager>(); injectionBinder.Bind<ICameraLayerManager>().ToValue(cameraManager).ToSingleton().CrossContext(); IGameLayerManager gameManager = managers.GetComponent<IGameLayerManager>(); injectionBinder.Bind<IGameLayerManager>().ToValue(gameManager).ToSingleton().CrossContext(); } public void Inject(Object o) { injectionBinder.injector.Inject(o); } }
using UnityEngine; using System.Collections; using strange.extensions.context.impl; using strange.extensions.context.api; public class RootContext : MVCSContext, IRootContext { public RootContext(MonoBehaviour view) : base(view) { } public RootContext(MonoBehaviour view, ContextStartupFlags flags) : base(view, flags) { } protected override void mapBindings() { base.mapBindings(); GameObject managers = GameObject.Find("Managers"); injectionBinder.Bind<IRootContext>().ToValue(this).ToSingleton().CrossContext(); EventManager eventManager = managers.GetComponent<EventManager>(); injectionBinder.Bind<IEventManager>().ToValue(eventManager).ToSingleton().CrossContext(); } public void Inject(Object o) { injectionBinder.injector.Inject(o); } }
mit
C#
4f3d55444e0a646ba2f50622313a5fc96dc17630
Set anti-forgery token unique claim type
antonburger/SimplestMvc5Auth
SimplestMvc5Auth/Global.asax.cs
SimplestMvc5Auth/Global.asax.cs
using System; using System.Security.Claims; using System.Web.Helpers; using System.Web.Mvc; using System.Web.Routing; namespace SimplestMvc5Auth { public class Global : System.Web.HttpApplication { private static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapMvcAttributeRoutes(); } protected void Application_Start(object sender, EventArgs e) { RegisterRoutes(RouteTable.Routes); AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name; } protected void Session_Start(object sender, EventArgs e) { } protected void Application_BeginRequest(object sender, EventArgs e) { } protected void Application_AuthenticateRequest(object sender, EventArgs e) { } protected void Application_Error(object sender, EventArgs e) { } protected void Session_End(object sender, EventArgs e) { } protected void Application_End(object sender, EventArgs e) { } } }
using System; using System.Web.Mvc; using System.Web.Routing; namespace SimplestMvc5Auth { public class Global : System.Web.HttpApplication { private static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapMvcAttributeRoutes(); } protected void Application_Start(object sender, EventArgs e) { RegisterRoutes(RouteTable.Routes); } protected void Session_Start(object sender, EventArgs e) { } protected void Application_BeginRequest(object sender, EventArgs e) { } protected void Application_AuthenticateRequest(object sender, EventArgs e) { } protected void Application_Error(object sender, EventArgs e) { } protected void Session_End(object sender, EventArgs e) { } protected void Application_End(object sender, EventArgs e) { } } }
mit
C#
092e604dee5aa890c4519302691c41c84d1db5ce
Fix snippet to make it work with the latest version of C# library
TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets
video/rest/rooms/create-group-room-with-h264/create-group-room.5.x.cs
video/rest/rooms/create-group-room-with-h264/create-group-room.5.x.cs
// Download the twilio-csharp library from twilio.com/docs/libraries/csharp using System; using System.Collections.Generic; using Twilio; using Twilio.Rest.Video.V1; class Example { static void Main (string[] args) { // Find your Account SID and Auth Token at twilio.com/console const string apiKeySid = "SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; const string apiKeySecret = "your_api_key_secret"; TwilioClient.Init(apiKeySid, apiKeySecret); var room = RoomResource.Create( uniqueName: "DailyStandupWithH264Codec", type: RoomResource.RoomTypeEnum.Group, videoCodecs: new List<RoomResource.VideoCodecEnum> { RoomResource.VideoCodecEnum.H264 }, statusCallback: new Uri("http://example.org")); Console.WriteLine(room.Sid); } }
// Download the twilio-csharp library from twilio.com/docs/libraries/csharp using System; using Twilio; using Twilio.Rest.Video.V1; class Example { static void Main (string[] args) { // Find your Account SID and Auth Token at twilio.com/console const string apiKeySid = "SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; const string apiKeySecret = "your_api_key_secret"; TwilioClient.Init(apiKeySid, apiKeySecret); var room = RoomResource.Create( uniqueName: "DailyStandupWithH264Codec", type: RoomResource.RoomTypeEnum.Group, videoCodecs: RoomResource.VideoCodecEnum.H264, statusCallback: new Uri("http://example.org")); Console.WriteLine(room.Sid); } }
mit
C#
8599cec7e6b4ced80b4eabecdafe4e6695e66673
add overload for AddAlert
ceee/UptimeSharp
UptimeSharp/Components/Alert.cs
UptimeSharp/Components/Alert.cs
using RestSharp; using System.Collections.Generic; using UptimeSharp.Models; namespace UptimeSharp { /// <summary> /// UptimeClient /// </summary> public partial class UptimeClient { /// <summary> /// Retrieves alerts from UptimeRobot /// </summary> /// <param name="IDs">Retrieve specified alert contacts by supplying IDs for them.</param> /// <returns></returns> public List<Alert> RetrieveAlerts(int[] alertIDs = null) { return Get<AlertResponse>("getAlertContacts").Items; } /// <summary> /// Adds an alert. /// mobile/SMS alert contacts are not supported yet, see: http://www.uptimerobot.com/api.asp#methods /// </summary> /// <param name="type">The type.</param> /// <param name="value">The value.</param> /// <returns></returns> public bool AddAlert(AlertType type, string value) { List<Parameter> parameters = new List<Parameter>() { Utilities.CreateParam("alertContactType", (int)type), Utilities.CreateParam("alertContactValue", value) }; return Get<DefaultResponse>("newAlertContact", parameters).Status; } /// <summary> /// Adds an alert. /// mobile/SMS alert contacts are not supported yet, see: http://www.uptimerobot.com/api.asp#methods /// </summary> /// <param name="alert">The alert.</param> /// <returns></returns> public bool AddAlert(Alert alert) { List<Parameter> parameters = new List<Parameter>() { Utilities.CreateParam("alertContactType", (int)alert.Type), Utilities.CreateParam("alertContactValue", alert.Value) }; return Get<DefaultResponse>("newAlertContact", parameters).Status; } /// <summary> /// Removes an alert. /// </summary> /// <param name="type">The type.</param> /// <param name="value">The value.</param> /// <returns></returns> public bool DeleteAlert(int alertID) { List<Parameter> parameters = new List<Parameter>() { Utilities.CreateParam("alertContactID", alertID) }; return Get<DefaultResponse>("deleteAlertContact", parameters).Status; } /// <summary> /// Removes an alert. /// </summary> /// <param name="alert">The alert.</param> /// <returns></returns> public bool DeleteAlert(Alert alert) { return DeleteAlert((int)alert.ID); } } }
using RestSharp; using System.Collections.Generic; using UptimeSharp.Models; namespace UptimeSharp { /// <summary> /// UptimeClient /// </summary> public partial class UptimeClient { /// <summary> /// Retrieves alerts from UptimeRobot /// </summary> /// <param name="IDs">Retrieve specified alert contacts by supplying IDs for them.</param> /// <returns></returns> public List<Alert> RetrieveAlerts(int[] alertIDs = null) { return Get<AlertResponse>("getAlertContacts").Items; } /// <summary> /// Adds an alert. /// mobile/SMS alert contacts are not supported yet, see: http://www.uptimerobot.com/api.asp#methods /// </summary> /// <param name="type">The type.</param> /// <param name="value">The value.</param> /// <returns></returns> public bool AddAlert(AlertType type, string value) { List<Parameter> parameters = new List<Parameter>() { Utilities.CreateParam("alertContactType", (int)type), Utilities.CreateParam("alertContactValue", value) }; return Get<DefaultResponse>("newAlertContact", parameters).Status; } /// <summary> /// Removes an alert. /// </summary> /// <param name="type">The type.</param> /// <param name="value">The value.</param> /// <returns></returns> public bool DeleteAlert(int alertID) { List<Parameter> parameters = new List<Parameter>() { Utilities.CreateParam("alertContactID", alertID) }; return Get<DefaultResponse>("deleteAlertContact", parameters).Status; } /// <summary> /// Removes an alert. /// </summary> /// <param name="alert">The alert.</param> /// <returns></returns> public bool DeleteAlert(Alert alert) { return DeleteAlert((int)alert.ID); } } }
mit
C#
11d47a2379bd22ad5ec386ebbd3d305e09f01563
update SonarLint ignore file
AndreyShpilevoy/DemProject,AndreyShpilevoy/DemProject,AndreyShpilevoy/DemProject
DEM_MVC/GlobalSuppressions.cs
DEM_MVC/GlobalSuppressions.cs
 // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "S1118:Utility classes should not have public constructors", Justification = "<Pending>", Scope = "type", Target = "~T:DEM_MVC.RouteConfig")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "S1118:Utility classes should not have public constructors", Justification = "<Pending>", Scope = "type", Target = "~T:DEM_MVC.FilterConfig")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "S1118:Utility classes should not have public constructors", Justification = "<Pending>", Scope = "type", Target = "~T:DEM_MVC.BundleConfig")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Maintainability", "S1067:Expressions should not be too complex", Justification = "<Pending>", Scope = "member", Target = "~M:DEM_MVC.Controllers.ManageController.Index(System.Nullable{DEM_MVC.Controllers.ManageController.ManageMessageId})~System.Threading.Tasks.Task{System.Web.Mvc.ActionResult}")]
 // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "S1118:Utility classes should not have public constructors", Justification = "<Pending>", Scope = "type", Target = "~T:DEM_MVC.RouteConfig")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "S1118:Utility classes should not have public constructors", Justification = "<Pending>", Scope = "type", Target = "~T:DEM_MVC.FilterConfig")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "S1118:Utility classes should not have public constructors", Justification = "<Pending>", Scope = "type", Target = "~T:DEM_MVC.BundleConfig")]
mit
C#
2cabea326978eabe4e04549a05a913128d505273
test push
karamalie/ddac-assignment,karamalie/ddac-assignment,karamalie/ddac-assignment
DdacAssignment/Global.asax.cs
DdacAssignment/Global.asax.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace DdacAssignment { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace DdacAssignment { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // env test } } }
mit
C#
cfefb1003c22cdf831f7eb372a248b0a22a586fc
Fix name issue in SendAnswerFactory.
fhict-Intellicloud/nl.fhict.intellicloud.backend,fhict-Intellicloud/nl.fhict.intellicloud.backend
IntelliCloud/IntelliCloud.Business/Plugins/Loader/SendAnswerFactory.cs
IntelliCloud/IntelliCloud.Business/Plugins/Loader/SendAnswerFactory.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using nl.fhict.IntelliCloud.Common.DataTransfer; namespace nl.fhict.IntelliCloud.Business.Plugins.Loader { /// <summary> /// A factory that loads the correct send answer plugin according to the given <see cref="SourceDefinition"/>. /// A send answer plugin can send an answer using a specific service, like mail, Facebook or Twitter. /// </summary> internal class SendAnswerFactory { /// <summary> /// Loads the send answer plugin for the given <see cref="SourceDefinition"/>. /// </summary> /// <param name="sourceDefinition">The source definition for which the plugin needs to be loaded.</param> /// <returns>Returns the loaded send answer plugin.</returns> public ISendAnswerPlugin LoadPlugin(SourceDefinition sourceDefinition) { switch (sourceDefinition.Name) { case "Mail": // TODO uncomment // return new MailSendAnswerPlugin(); case "Facebook": // TODO uncomment // return new FacebookSendAnswerPlugin(); case "Twitter": // TODO uncomment // return new TwitterSendAnswerPlugin(); default: throw new NotImplementedException("The provided source is not supported, so the answer couldn't be send."); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using nl.fhict.IntelliCloud.Common.DataTransfer; namespace nl.fhict.IntelliCloud.Business.Plugins.Loader { /// <summary> /// A factory that loads the correct send answer plugin according to the given <see cref="SourceDefinition"/>. /// A send answer plugin can send an answer using a specific service, like mail, Facebook or Twitter. /// </summary> internal class SendAnswerFactory { /// <summary> /// Loads the send answer plugin for the given <see cref="SourceDefinition"/>. /// </summary> /// <param name="sourceDefinition">The source definition for which the plugin needs to be loaded.</param> /// <returns>Returns the loaded send answer plugin.</returns> public ISendAnswerPlugin LoadPlugin(SourceDefinition sourceDefinition) { switch (sourceDefinition.Name) { case "Mail": // TODO uncomment // return new MailSendAnswerPlugin(); case "Facebook": // TODO uncomment // return new FacebookSendAnswerPlugin(); case "Twitter": // TODO uncomment // return new FacebookSendAnswerPlugin(); default: throw new NotImplementedException("The provided source is not supported, so the answer couldn't be send."); } } } }
apache-2.0
C#
b7958935429487f04e28b729d3214ddebc36a0eb
Remove rogue using
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.AspNetCore.Authentication.Google/GoogleAppBuilderExtensions.cs
src/Microsoft.AspNetCore.Authentication.Google/GoogleAppBuilderExtensions.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; using Microsoft.AspNetCore.Authentication.Google; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.Builder { /// <summary> /// Extension methods to add Google authentication capabilities to an HTTP application pipeline. /// </summary> public static class GoogleAppBuilderExtensions { /// <summary> /// Obsolete, see https://go.microsoft.com/fwlink/?linkid=845470 /// </summary> /// <param name="app">The <see cref="IApplicationBuilder"/> to add the handler to.</param> /// <returns>A reference to this instance after the operation has completed.</returns> public static IApplicationBuilder UseGoogleAuthentication(this IApplicationBuilder app) { throw new NotSupportedException("This method is no longer supported, see https://go.microsoft.com/fwlink/?linkid=845470"); } /// <summary> /// Obsolete, see https://go.microsoft.com/fwlink/?linkid=845470 /// </summary> /// <param name="app">The <see cref="IApplicationBuilder"/> to add the handler to.</param> /// <param name="options">A <see cref="GoogleOptions"/> that specifies options for the handler.</param> /// <returns>A reference to this instance after the operation has completed.</returns> public static IApplicationBuilder UseGoogleAuthentication(this IApplicationBuilder app, GoogleOptions options) { throw new NotSupportedException("This method is no longer supported, see https://go.microsoft.com/fwlink/?linkid=845470"); } } }
// 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; using Microsoft.AspNetCore.Authentication.Google; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.Builder { /// <summary> /// Extension methods to add Google authentication capabilities to an HTTP application pipeline. /// </summary> public static class GoogleAppBuilderExtensions { /// <summary> /// Obsolete, see https://go.microsoft.com/fwlink/?linkid=845470 /// </summary> /// <param name="app">The <see cref="IApplicationBuilder"/> to add the handler to.</param> /// <returns>A reference to this instance after the operation has completed.</returns> public static IApplicationBuilder UseGoogleAuthentication(this IApplicationBuilder app) { throw new NotSupportedException("This method is no longer supported, see https://go.microsoft.com/fwlink/?linkid=845470"); } /// <summary> /// Obsolete, see https://go.microsoft.com/fwlink/?linkid=845470 /// </summary> /// <param name="app">The <see cref="IApplicationBuilder"/> to add the handler to.</param> /// <param name="options">A <see cref="GoogleOptions"/> that specifies options for the handler.</param> /// <returns>A reference to this instance after the operation has completed.</returns> public static IApplicationBuilder UseGoogleAuthentication(this IApplicationBuilder app, GoogleOptions options) { throw new NotSupportedException("This method is no longer supported, see https://go.microsoft.com/fwlink/?linkid=845470"); } } }
apache-2.0
C#
f576ccde8360d276c6718fd3a04adbdc35cf8604
remove nameof
MystFan/Heroically-Recipes,MystFan/Heroically-Recipes
Source/HeroicallyRecipes/Data/HeroicallyRecipes.Data/Repositories/DbRepository.cs
Source/HeroicallyRecipes/Data/HeroicallyRecipes.Data/Repositories/DbRepository.cs
namespace HeroicallyRecipes.Data.Repositories { using System; using System.Data.Entity; using System.Linq; using Models; // TODO: Why BaseModel<int> instead BaseModel<TKey>? public class DbRepository<T> : IDbRepository<T> where T : BaseModel<int> { public DbRepository(DbContext context) { if (context == null) { throw new ArgumentException("An instance of DbContext is required to use this repository."); } this.Context = context; this.DbSet = this.Context.Set<T>(); } private IDbSet<T> DbSet { get; set; } private DbContext Context { get; set; } public IQueryable<T> All() { return this.DbSet.Where(x => !x.IsDeleted); } public IQueryable<T> AllWithDeleted() { return this.DbSet; } public T GetById(int id) { return this.All().FirstOrDefault(x => x.Id == id); } public void Add(T entity) { this.DbSet.Add(entity); } public void Delete(T entity) { entity.IsDeleted = true; entity.DeletedOn = DateTime.Now; } public void HardDelete(T entity) { this.DbSet.Remove(entity); } public void SaveChanges() { this.Context.SaveChanges(); } } }
namespace HeroicallyRecipes.Data.Repositories { using System; using System.Data.Entity; using System.Linq; using Models; // TODO: Why BaseModel<int> instead BaseModel<TKey>? public class DbRepository<T> : IDbRepository<T> where T : BaseModel<int> { public DbRepository(DbContext context) { if (context == null) { throw new ArgumentException("An instance of DbContext is required to use this repository.", nameof(context)); } this.Context = context; this.DbSet = this.Context.Set<T>(); } private IDbSet<T> DbSet { get; set; } private DbContext Context { get; set; } public IQueryable<T> All() { return this.DbSet.Where(x => !x.IsDeleted); } public IQueryable<T> AllWithDeleted() { return this.DbSet; } public T GetById(int id) { return this.All().FirstOrDefault(x => x.Id == id); } public void Add(T entity) { this.DbSet.Add(entity); } public void Delete(T entity) { entity.IsDeleted = true; entity.DeletedOn = DateTime.Now; } public void HardDelete(T entity) { this.DbSet.Remove(entity); } public void SaveChanges() { this.Context.SaveChanges(); } } }
mit
C#
4c6791dffd1635767f7add5b3e290ca92bc243d0
Update ObservableExtensions.cs
keith-hall/Extensions,keith-hall/Extensions
src/ObservableExtensions.cs
src/ObservableExtensions.cs
using System; using System.Reactive.Linq; namespace HallLibrary.Extensions { /// <summary> /// Contains extension methods for working with observables. /// </summary> public static class ObservableExtensions { public static IObservable<TOutput> WithPrevious<TSource, TOutput>(this IObservable<TSource> source, Func<TSource, TSource, TOutput> projection) { return source.Scan(Tuple.Create(default(TSource), default(TSource)), (previous, current) => Tuple.Create(previous.Item2, current)) .Select(t => projection(t.Item1, t.Item2)); } } }
using System; using System.Reactive.Linq; namespace HallLibrary.Extensions { public static class ObservableExtensions { public static IObservable<TOutput> WithPrevious<TSource, TOutput>(this IObservable<TSource> source, Func<TSource, TSource, TOutput> projection) { return source.Scan(Tuple.Create(default(TSource), default(TSource)), (previous, current) => Tuple.Create(previous.Item2, current)) .Select(t => projection(t.Item1, t.Item2)); } } }
apache-2.0
C#
0e68df7ca1d38c61b025d4302e6c90a67e78ade4
Improve benchmarks
ppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,peppy/osu-framework
osu.Framework.Benchmarks/BenchmarkWeakList.cs
osu.Framework.Benchmarks/BenchmarkWeakList.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using BenchmarkDotNet.Attributes; using osu.Framework.Lists; namespace osu.Framework.Benchmarks { public class BenchmarkWeakList : BenchmarkTest { [Params(1, 10, 100, 1000)] public int ItemCount { get; set; } private readonly object[] objects = new object[1000]; private WeakList<object> weakList; public override void SetUp() { for (int i = 0; i < ItemCount; i++) objects[i] = new object(); } [Benchmark(Baseline = true)] public void Add() => init(); [Benchmark] public void RemoveOne() { init(); weakList.Remove(objects[objects.Length - 1]); } [Benchmark] public void RemoveAllIteratively() { init(); for (int i = 0; i < ItemCount; i++) weakList.Remove(objects[i]); } [Benchmark] public void Clear() { init(); weakList.Clear(); } [Benchmark] public bool Contains() { init(); return weakList.Contains(objects[objects.Length - 1]); } [Benchmark] public object[] AddAndEnumerate() { init(); return weakList.ToArray(); } [Benchmark] public object[] ClearAndEnumerate() { init(); weakList.Clear(); return weakList.ToArray(); } private void init() { weakList = new WeakList<object>(); for (int i = 0; i < ItemCount; i++) weakList.Add(objects[i]); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using BenchmarkDotNet.Attributes; using NUnit.Framework; using osu.Framework.Lists; namespace osu.Framework.Benchmarks { public class BenchmarkWeakList : BenchmarkTest { private readonly object[] objects = new object[1000]; private WeakList<object> weakList; public override void SetUp() { for (int i = 0; i < 1000; i++) objects[i] = new object(); } [IterationSetup] [SetUp] public void IterationSetup() { weakList = new WeakList<object>(); foreach (var obj in objects) weakList.Add(obj); } [Benchmark] public void Add() => weakList.Add(new object()); [Benchmark] public void Remove() => weakList.Remove(objects[0]); [Benchmark] public void RemoveEach() { foreach (var obj in objects) weakList.Remove(obj); } [Benchmark] public void Clear() => weakList.Clear(); [Benchmark] public bool Contains() => weakList.Contains(objects[0]); [Benchmark] public object[] Enumerate() => weakList.ToArray(); [Benchmark] public object[] ClearAndEnumerate() { weakList.Clear(); return weakList.ToArray(); } } }
mit
C#
d55324585d678603435adcaed815d3d85186037b
Change RoomSubmittingPlayer's request implementation to return null on RoomID missing, rather than silently succeeding
UselessToucan/osu,peppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu-new,peppy/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,smoogipooo/osu
osu.Game/Screens/Play/RoomSubmittingPlayer.cs
osu.Game/Screens/Play/RoomSubmittingPlayer.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Online.API; using osu.Game.Online.Rooms; using osu.Game.Scoring; namespace osu.Game.Screens.Play { /// <summary> /// A player instance which submits to a room backing. This is generally used by playlists and multiplayer. /// </summary> public abstract class RoomSubmittingPlayer : SubmittingPlayer { [Resolved(typeof(Room), nameof(Room.RoomID))] protected Bindable<long?> RoomId { get; private set; } protected readonly PlaylistItem PlaylistItem; protected RoomSubmittingPlayer(PlaylistItem playlistItem, PlayerConfiguration configuration = null) : base(configuration) { PlaylistItem = playlistItem; } protected override APIRequest<APIScoreToken> CreateTokenRequest() { if (!(RoomId.Value is long roomId)) return null; return new CreateRoomScoreRequest(roomId, PlaylistItem.ID, Game.VersionHash); } protected override APIRequest<MultiplayerScore> CreateSubmissionRequest(Score score, long token) => new SubmitRoomScoreRequest(token, RoomId.Value ?? 0, PlaylistItem.ID, score.ScoreInfo); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Online.API; using osu.Game.Online.Rooms; using osu.Game.Scoring; namespace osu.Game.Screens.Play { /// <summary> /// A player instance which submits to a room backing. This is generally used by playlists and multiplayer. /// </summary> public abstract class RoomSubmittingPlayer : SubmittingPlayer { [Resolved(typeof(Room), nameof(Room.RoomID))] protected Bindable<long?> RoomId { get; private set; } protected readonly PlaylistItem PlaylistItem; protected RoomSubmittingPlayer(PlaylistItem playlistItem, PlayerConfiguration configuration = null) : base(configuration) { PlaylistItem = playlistItem; } protected override APIRequest<APIScoreToken> CreateTokenRequest() => new CreateRoomScoreRequest(RoomId.Value ?? 0, PlaylistItem.ID, Game.VersionHash); protected override APIRequest<MultiplayerScore> CreateSubmissionRequest(Score score, long token) => new SubmitRoomScoreRequest(token, RoomId.Value ?? 0, PlaylistItem.ID, score.ScoreInfo); } }
mit
C#
a0f8079f76bd42f7f065fd01f283cdea3a1fc643
Use 'long' datatype for IDs in sample applications to avoid warnings.
azabluda/InfoCarrier.Core
sample/Datamodel.cs
sample/Datamodel.cs
// Copyright (c) on/off it-solutions gmbh. All rights reserved. // Licensed under the MIT license. See license.txt file in the project root for license information. #pragma warning disable SA1402 // FileMayOnlyContainASingleType #pragma warning disable SA1649 // FileNameMustMatchTypeName namespace InfoCarrierSample { using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore; public class Blog { public long Id { get; set; } public long AuthorId { get; set; } public Author Author { get; set; } public IList<Post> Posts { get; set; } } public class Post { public long Id { get; set; } public long BlogId { get; set; } public DateTime CreationDate { get; set; } public string Title { get; set; } public Blog Blog { get; set; } } public class Author { public long Id { get; set; } public string Name { get; set; } } public class BloggingContext : DbContext { public BloggingContext(DbContextOptions options) : base(options) { } public DbSet<Blog> Blogs { get; set; } public DbSet<Author> Authors { get; set; } } }
// Copyright (c) on/off it-solutions gmbh. All rights reserved. // Licensed under the MIT license. See license.txt file in the project root for license information. #pragma warning disable SA1402 // FileMayOnlyContainASingleType #pragma warning disable SA1649 // FileNameMustMatchTypeName namespace InfoCarrierSample { using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore; public class Blog { public decimal Id { get; set; } public decimal AuthorId { get; set; } public Author Author { get; set; } public IList<Post> Posts { get; set; } } public class Post { public decimal Id { get; set; } public decimal BlogId { get; set; } public DateTime CreationDate { get; set; } public string Title { get; set; } public Blog Blog { get; set; } } public class Author { public decimal Id { get; set; } public string Name { get; set; } } public class BloggingContext : DbContext { public BloggingContext(DbContextOptions options) : base(options) { } public DbSet<Blog> Blogs { get; set; } public DbSet<Author> Authors { get; set; } } }
mit
C#
4fccadac87b055ea94ba8428433f47f54b006a04
remove abstract ,unused class TextBreaker
LayoutFarm/PixelFarm
src/PixelFarm/Typography/Typography.TextBreak/Typography.TextBreak/BreakEngine.cs
src/PixelFarm/Typography/Typography.TextBreak/Typography.TextBreak/BreakEngine.cs
//MIT, 2016-2017, WinterDev //some code from ICU project with BSD license namespace Typography.TextBreak { public delegate void OnBreak(BreakBounds breakBounds); public class BreakBounds { public int startIndex; public int length; public bool stopNext; public WorkKind kind; } public enum WorkKind { Whitespace, NewLine, Text, Number, Punc } public struct SplitBound { public readonly int startIndex; public readonly int length; public SplitBound(int startIndex, int length) { this.startIndex = startIndex; this.length = length; } #if DEBUG public override string ToString() { return startIndex + ":" + length; } #endif } }
//MIT, 2016-2017, WinterDev //some code from ICU project with BSD license namespace Typography.TextBreak { public enum TextBreakKind { Word, Sentence, } public delegate void OnBreak(BreakBounds breakBounds); public class BreakBounds { public int startIndex; public int length; public bool stopNext; public WorkKind kind; } public enum WorkKind { Whitespace, NewLine, Text, Number, Punc } public abstract class TextBreaker { public abstract void DoBreak(char[] input, int start, int len, OnBreak onbreak); public TextBreakKind BreakKind { get; set; } public void DoBreak(char[] charBuff, OnBreak onbreak) { IsCanceled = false;//reset //to end DoBreak(charBuff, 0, charBuff.Length, onbreak); } protected bool IsCanceled { get; set; } /// <summary> /// cancel current breaking task /// </summary> public void Cancel() { IsCanceled = true; } } public struct SplitBound { public readonly int startIndex; public readonly int length; public SplitBound(int startIndex, int length) { this.startIndex = startIndex; this.length = length; } #if DEBUG public override string ToString() { return startIndex + ":" + length; } #endif } }
bsd-2-clause
C#
e222547e735008b19474dee07028533016cb80ca
Fix the test
fredericDelaporte/nhibernate-core,gliljas/nhibernate-core,livioc/nhibernate-core,alobakov/nhibernate-core,ngbrown/nhibernate-core,hazzik/nhibernate-core,gliljas/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,ngbrown/nhibernate-core,ManufacturingIntelligence/nhibernate-core,fredericDelaporte/nhibernate-core,nhibernate/nhibernate-core,nkreipke/nhibernate-core,alobakov/nhibernate-core,livioc/nhibernate-core,hazzik/nhibernate-core,nkreipke/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nhibernate/nhibernate-core,ngbrown/nhibernate-core,alobakov/nhibernate-core,hazzik/nhibernate-core,nkreipke/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core,RogerKratz/nhibernate-core,nhibernate/nhibernate-core,livioc/nhibernate-core,gliljas/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core,fredericDelaporte/nhibernate-core,fredericDelaporte/nhibernate-core,lnu/nhibernate-core,ManufacturingIntelligence/nhibernate-core,RogerKratz/nhibernate-core,hazzik/nhibernate-core
src/NHibernate.Test/NHSpecificTest/NH739/Fixture.cs
src/NHibernate.Test/NHSpecificTest/NH739/Fixture.cs
using System; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH739 { [TestFixture] public class Fixture : BugTestCase { [Test] public void Bug() { int catId; using (ISession sess = OpenSession()) { Cat c = new Cat(); sess.Save(c); catId = c.Id; sess.Flush(); } using (ISession sess = OpenSession()) { Cat c = (Cat) sess.Get(typeof(Cat), catId); Cat kitten = new Cat(); c.Children.Add(kitten); kitten.Mother = c; sess.Save(kitten); Assert.AreEqual(1, c.Children.Count); //Test will fail here, the c.Children.Count is 2 here sess.Delete(c); sess.Delete(kitten); sess.Flush(); } } } }
using System; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH739 { [TestFixture] public class Fixture : BugTestCase { [Test] public void Bug() { using (ISession sess = OpenSession()) { Cat c = new Cat(); sess.Save(c); sess.Clear(); c = (Cat) sess.Get(typeof(Cat), c.Id); Cat kitten = new Cat(); c.Children.Add(kitten); kitten.Mother = c; sess.Save(kitten); Assert.AreEqual(1, c.Children.Count); //Test will fail here, the c.Children.Count is 2 here sess.Delete(c); sess.Delete(kitten); sess.Flush(); } } } }
lgpl-2.1
C#
03bfef60316b8e0e6d02848f4f6185ea81f070a6
Make hft-server runtime options not based on HFTArgsDirect
greggman/hft-unity3d,greggman/hft-unity3d,greggman/hft-unity3d,greggman/hft-unity3d
hft-server/hft-server/HFTRuntimeOptions.cs
hft-server/hft-server/HFTRuntimeOptions.cs
using System; namespace HappyFunTimes { public class HFTRuntimeOptions { public string dataPath = ""; public string url = ""; public string id = ""; public string name = ""; public string gameId = "HFTUnity"; // this is kind of left over from when one server supported mutiple games public string controllerFilename = ""; public bool disconnectPlayersIfGameDisconnects = true; public bool installationMode = false; public bool master = false; public bool showInList = true; public bool showMessages; public bool debug; public bool startServer; public bool dns; public bool captivePortal; public string serverPort = ""; public string rendezvousUrl; public string args; } }
using System; namespace HappyFunTimes { public class HFTRuntimeOptions : HFTArgsDirect { public HFTRuntimeOptions(string prefix) : base(prefix) { } public string dataPath = ""; public string url = ""; public string id = ""; public string name = ""; public string gameId = "HFTUnity"; // this is kind of left over from when one server supported mutiple games public string controllerFilename = ""; public bool disconnectPlayersIfGameDisconnects = true; public bool installationMode = false; public bool master = false; public bool showInList = true; public bool showMessages; public bool debug; public bool startServer; public bool dns; public bool captivePortal; public string serverPort = ""; public string rendezvousUrl; } }
bsd-3-clause
C#
eebfcb7ff40ce6240008c22a07eca33eecc88bb5
Remove superfluous construction of ReadOnlySpan<byte> from byte[ ]. An implicit cast is available in this context, so the same method overload is in fact called, and the implementation of the implicit cast performs the same construction for us.
fixie/fixie
src/Fixie/Internal/Serialization.cs
src/Fixie/Internal/Serialization.cs
namespace Fixie.Internal { using System.Text; using System.Text.Json; static class Serialization { public static string Serialize<TMessage>(TMessage message) => Encoding.UTF8.GetString(JsonSerializer.SerializeToUtf8Bytes(message)); public static TMessage Deserialize<TMessage>(string message) => JsonSerializer.Deserialize<TMessage>(Encoding.UTF8.GetBytes(message))!; } }
namespace Fixie.Internal { using System; using System.Text; using System.Text.Json; static class Serialization { public static string Serialize<TMessage>(TMessage message) => Encoding.UTF8.GetString(JsonSerializer.SerializeToUtf8Bytes(message)); public static TMessage Deserialize<TMessage>(string message) => JsonSerializer.Deserialize<TMessage>(new ReadOnlySpan<byte>(Encoding.UTF8.GetBytes(message)))!; } }
mit
C#
f3acaafd4539d2bef08e47ee047b77be56c27b1c
Add missing permission registration in OC.ReverseProxy module (#11542)
stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2
src/OrchardCore.Modules/OrchardCore.ReverseProxy/Startup.cs
src/OrchardCore.Modules/OrchardCore.ReverseProxy/Startup.cs
using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using OrchardCore.DisplayManagement.Handlers; using OrchardCore.Modules; using OrchardCore.Navigation; using OrchardCore.ReverseProxy.Drivers; using OrchardCore.ReverseProxy.Services; using OrchardCore.ReverseProxy.Settings; using OrchardCore.Security.Permissions; using OrchardCore.Settings; using OrchardCore.Settings.Deployment; namespace OrchardCore.ReverseProxy { public class Startup : StartupBase { // we need this to start before other security related initialization logic public override int Order => -1; public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { app.UseForwardedHeaders(); } public override void ConfigureServices(IServiceCollection services) { services.AddScoped<INavigationProvider, AdminMenu>(); services.AddScoped<IPermissionProvider, Permissions>(); services.AddScoped<IDisplayDriver<ISite>, ReverseProxySettingsDisplayDriver>(); services.AddSingleton<ReverseProxyService>(); services.TryAddEnumerable(ServiceDescriptor .Transient<IConfigureOptions<ForwardedHeadersOptions>, ForwardedHeadersOptionsConfiguration>()); } } [RequireFeatures("OrchardCore.Deployment")] public class DeploymentStartup : StartupBase { public override void ConfigureServices(IServiceCollection services) { services.AddSiteSettingsPropertyDeploymentStep<ReverseProxySettings, DeploymentStartup>(S => S["Reverse Proxy settings"], S => S["Exports the Reverse Proxy settings."]); } } }
using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using OrchardCore.DisplayManagement.Handlers; using OrchardCore.Modules; using OrchardCore.Navigation; using OrchardCore.ReverseProxy.Drivers; using OrchardCore.ReverseProxy.Services; using OrchardCore.ReverseProxy.Settings; using OrchardCore.Settings; using OrchardCore.Settings.Deployment; namespace OrchardCore.ReverseProxy { public class Startup : StartupBase { // we need this to start before other security related initialization logic public override int Order => -1; public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { app.UseForwardedHeaders(); } public override void ConfigureServices(IServiceCollection services) { services.AddScoped<INavigationProvider, AdminMenu>(); services.AddScoped<IDisplayDriver<ISite>, ReverseProxySettingsDisplayDriver>(); services.AddSingleton<ReverseProxyService>(); services.TryAddEnumerable(ServiceDescriptor .Transient<IConfigureOptions<ForwardedHeadersOptions>, ForwardedHeadersOptionsConfiguration>()); } } [RequireFeatures("OrchardCore.Deployment")] public class DeploymentStartup : StartupBase { public override void ConfigureServices(IServiceCollection services) { services.AddSiteSettingsPropertyDeploymentStep<ReverseProxySettings, DeploymentStartup>(S => S["Reverse Proxy settings"], S => S["Exports the Reverse Proxy settings."]); } } }
bsd-3-clause
C#
3f8379b86f77a1f3b67658a3cf3f5c17df57fb72
Fix log message.
aluxnimm/outlookcaldavsynchronizer
CalDavSynchronizer/Implementation/GoogleContacts/GoogleApiOperationExecutor.cs
CalDavSynchronizer/Implementation/GoogleContacts/GoogleApiOperationExecutor.cs
// This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/) // Copyright (c) 2015 Gerhard Zehetbauer // Copyright (c) 2015 Alexander Nimmervoll // // This program 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. // // This program 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 this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using Google.Contacts; using Google.GData.Client; using log4net; namespace CalDavSynchronizer.Implementation.GoogleContacts { class GoogleApiOperationExecutor : IGoogleApiOperationExecutor { private static readonly ILog s_logger = LogManager.GetLogger (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); readonly ContactsRequest _contactFacade; const int c_exponentialBackoffBaseMilliseconds = 100; const int c_exponentialBackoffMaxRetries = 6; private readonly Random _exponentialBackoffRandom = new Random(); public GoogleApiOperationExecutor (ContactsRequest contactFacade) { if (contactFacade == null) throw new ArgumentNullException (nameof (contactFacade)); _contactFacade = contactFacade; } public T Execute<T> (Func<ContactsRequest, T> operation) { for (int retryCount = 0;; retryCount++) { try { return operation (_contactFacade); } catch (GDataRequestException x) when ((((x.InnerException as WebException) ?.Response as HttpWebResponse) ?.StatusCode == HttpStatusCode.ServiceUnavailable) && retryCount < c_exponentialBackoffMaxRetries) { var sleepMilliseconds = (int) Math.Pow (2, retryCount) * c_exponentialBackoffBaseMilliseconds + _exponentialBackoffRandom.Next (c_exponentialBackoffBaseMilliseconds); s_logger.Warn ($"Retrying operation in {sleepMilliseconds}ms."); Thread.Sleep (sleepMilliseconds); } } } public void Execute (Action<ContactsRequest> operation) { Execute (f => { operation (f); return 0; }); } } }
// This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/) // Copyright (c) 2015 Gerhard Zehetbauer // Copyright (c) 2015 Alexander Nimmervoll // // This program 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. // // This program 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 this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using Google.Contacts; using Google.GData.Client; using log4net; namespace CalDavSynchronizer.Implementation.GoogleContacts { class GoogleApiOperationExecutor : IGoogleApiOperationExecutor { private static readonly ILog s_logger = LogManager.GetLogger (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); readonly ContactsRequest _contactFacade; const int c_exponentialBackoffBaseMilliseconds = 100; const int c_exponentialBackoffMaxRetries = 6; private readonly Random _exponentialBackoffRandom = new Random(); public GoogleApiOperationExecutor (ContactsRequest contactFacade) { if (contactFacade == null) throw new ArgumentNullException (nameof (contactFacade)); _contactFacade = contactFacade; } public T Execute<T> (Func<ContactsRequest, T> operation) { for (int retryCount = 0;; retryCount++) { try { return operation (_contactFacade); } catch (GDataRequestException x) when ((((x.InnerException as WebException) ?.Response as HttpWebResponse) ?.StatusCode == HttpStatusCode.ServiceUnavailable) && retryCount < c_exponentialBackoffMaxRetries) { var sleepMilliseconds = (int) Math.Pow (2, retryCount) * c_exponentialBackoffBaseMilliseconds + _exponentialBackoffRandom.Next (c_exponentialBackoffBaseMilliseconds); s_logger.Warn ($"Retrying operation in ${sleepMilliseconds}ms."); Thread.Sleep (sleepMilliseconds); } } } public void Execute (Action<ContactsRequest> operation) { Execute (f => { operation (f); return 0; }); } } }
agpl-3.0
C#
be6b731ab49460384d0c26832ceb66db3bf83291
Support Xamarin.Mac assemblies in MonoMacMainLoopIntegration
mono/guiunit
src/framework/GuiUnit/MonoMacMainLoopIntegration.cs
src/framework/GuiUnit/MonoMacMainLoopIntegration.cs
using System; using System.Linq; namespace GuiUnit { public class MonoMacMainLoopIntegration : IMainLoopIntegration { Type Application { get; set; } object SharedApplication { get; set; } public MonoMacMainLoopIntegration () { Application = Type.GetType ("MonoMac.AppKit.NSApplication, MonoMac"); if (Application == null) Application = Type.GetType ("AppKit.NSApplication, Xamarin.Mac"); if (Application == null) throw new NotSupportedException (); } public void InitializeToolkit () { var initMethod = Application.GetMethod ("Init", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); initMethod.Invoke (null, null); var sharedAppProperty = Application.GetProperty ("SharedApplication", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); SharedApplication = sharedAppProperty.GetValue (null, null); } public void InvokeOnMainLoop (InvokerHelper helper) { var potentialMethods = Application.GetMethods (System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); var invokeOnMainThreadMethod = potentialMethods.First (m => m.Name == "InvokeOnMainThread" && m.GetParameters ().Length == 1); var invoker = Delegate.CreateDelegate (invokeOnMainThreadMethod.GetParameters () [0].ParameterType, helper, "Invoke"); invokeOnMainThreadMethod.Invoke (SharedApplication, new [] { invoker }); } public void RunMainLoop () { Application.GetMethod ("Run").Invoke (SharedApplication, null); } public void Shutdown () { Application.GetMethod ("Terminate").Invoke (SharedApplication, new [] { SharedApplication }); } } }
using System; using System.Linq; namespace GuiUnit { public class MonoMacMainLoopIntegration : IMainLoopIntegration { Type Application { get; set; } object SharedApplication { get; set; } public MonoMacMainLoopIntegration () { Application = Type.GetType ("MonoMac.AppKit.NSApplication, MonoMac"); if (Application == null) throw new NotSupportedException (); } public void InitializeToolkit () { var initMethod = Application.GetMethod ("Init", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); initMethod.Invoke (null, null); var sharedAppProperty = Application.GetProperty ("SharedApplication", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); SharedApplication = sharedAppProperty.GetValue (null, null); } public void InvokeOnMainLoop (InvokerHelper helper) { var potentialMethods = Application.GetMethods (System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); var invokeOnMainThreadMethod = potentialMethods.First (m => m.Name == "InvokeOnMainThread" && m.GetParameters ().Length == 1); var invoker = Delegate.CreateDelegate (invokeOnMainThreadMethod.GetParameters () [0].ParameterType, helper, "Invoke"); invokeOnMainThreadMethod.Invoke (SharedApplication, new [] { invoker }); } public void RunMainLoop () { Application.GetMethod ("Run").Invoke (SharedApplication, null); } public void Shutdown () { Application.GetMethod ("Terminate").Invoke (SharedApplication, new [] { SharedApplication }); } } }
mit
C#
64014f7f5a3e8b061a6f3d671dda18633ce78184
use uribuilder
Teleopti/Stardust
Manager/Manager/JobManager.cs
Manager/Manager/JobManager.cs
using System; using System.Collections.Generic; using Stardust.Manager.Constants; using Stardust.Manager.Helpers; using Stardust.Manager.Interfaces; using Stardust.Manager.Models; namespace Stardust.Manager { public class JobManager { private readonly IJobRepository _jobRepository; private readonly IWorkerNodeRepository _nodeRepository; private readonly IHttpSender _httpSender; public JobManager(IJobRepository jobRepository, IWorkerNodeRepository nodeRepository, IHttpSender httpSender) { _jobRepository = jobRepository; _nodeRepository = nodeRepository; _httpSender = httpSender; } public async void CheckAndAssignNextJob() { var availableNodes = _nodeRepository.LoadAllFreeNodes(); var upNodes = new List<WorkerNode>(); foreach (var availableNode in availableNodes) { var nodeUriBuilder = new NodeUriBuilderHelper(availableNode.Url); Uri postUri=nodeUriBuilder.GetIsAliveTemplateUri(); var response = await _httpSender.PostAsync(postUri.ToString(), null); if (response != null && response.IsSuccessStatusCode) upNodes.Add(availableNode); } _jobRepository.CheckAndAssignNextJob(upNodes, _httpSender); } public void Add(JobDefinition job) { _jobRepository.Add(job); CheckAndAssignNextJob(); } public void CancelThisJob(Guid id) { _jobRepository.CancelThisJob(id, _httpSender); } public void SetEndResultOnJobAndRemoveIt(Guid jobId, string result) { _jobRepository.SetEndResultOnJob(jobId, result); _jobRepository.DeleteJob(jobId); } public void ReportProgress(JobProgressModel model) { _jobRepository.ReportProgress(model.JobId, model.ProgressDetail); } public JobHistory GetJobHistory(Guid jobId) { return _jobRepository.History(jobId); } } }
using System; using System.Collections.Generic; using Stardust.Manager.Constants; using Stardust.Manager.Interfaces; using Stardust.Manager.Models; namespace Stardust.Manager { public class JobManager { private readonly IJobRepository _jobRepository; private readonly IWorkerNodeRepository _nodeRepository; private readonly IHttpSender _httpSender; public JobManager(IJobRepository jobRepository, IWorkerNodeRepository nodeRepository, IHttpSender httpSender) { _jobRepository = jobRepository; _nodeRepository = nodeRepository; _httpSender = httpSender; } public async void CheckAndAssignNextJob() { var availableNodes = _nodeRepository.LoadAllFreeNodes(); var upNodes = new List<WorkerNode>(); foreach (var availableNode in availableNodes) { var response = await _httpSender.PostAsync(availableNode.Url + NodeRouteConstants.IsAlive, ""); if (response != null && response.IsSuccessStatusCode) upNodes.Add(availableNode); } _jobRepository.CheckAndAssignNextJob(upNodes, _httpSender); } public void Add(JobDefinition job) { _jobRepository.Add(job); CheckAndAssignNextJob(); } public void CancelThisJob(Guid id) { _jobRepository.CancelThisJob(id, _httpSender); } public void SetEndResultOnJobAndRemoveIt(Guid jobId, string result) { _jobRepository.SetEndResultOnJob(jobId, result); _jobRepository.DeleteJob(jobId); } public void ReportProgress(JobProgressModel model) { _jobRepository.ReportProgress(model.JobId, model.ProgressDetail); } public JobHistory GetJobHistory(Guid jobId) { return _jobRepository.History(jobId); } } }
mit
C#
fb3622debd2adf8b107ab79f3a9dffbf8d127baf
Update Index.cshtml
dncuug/dot-net.in.ua,dncuug/dot-net.in.ua,dncuug/dot-net.in.ua
src/WebSite/Views/Home/Index.cshtml
src/WebSite/Views/Home/Index.cshtml
@using X.PagedList; @using X.PagedList.Mvc.Core; @model IPagedList<Core.ViewModels.PublicationViewModel> @{ ViewData["Title"] = "Welcome!"; } @section head { <meta property="og:title" content="@Core.Settings.Current.WebSiteTitle" /> <meta property="og:type" content="website" /> <meta property="og:url" content="@Core.Settings.Current.WebSiteUrl" /> <meta property="og:image" content="@Core.Settings.Current.FacebookImage" /> <meta property="og:description" content="@Core.Settings.Current.DefaultDescription" /> <meta name="keywords" content="@Core.Settings.Current.DefaultKeywords" /> <meta name="description" content="@Core.Settings.Current.DefaultDescription" /> } @section top { <!-- Main jumbotron for a primary marketing message or call to action --> <div class="jumbotron"> <div class="container"> <h1>Welcome to the daily developers digest!</h1> <h3 style="color: #FFF">All news and events will be here!</h3> <span style="color: #FFF"> Project supported by .NET Core Ukrainian User Group, Microsoft Azure Ukraine User Group and Xamarin Ukraine User Group! </span> </div> </div> } @for (var i=0; i<Model.Count(); i++) { @Html.Partial("_Publication", Model[i]) if (i == 2) { @Html.Partial("_InFeedAd") } } @Html.PagedListPager(Model, page => $"/page/{page}")
@using X.PagedList; @using X.PagedList.Mvc.Core; @model IPagedList<Core.ViewModels.PublicationViewModel> @{ ViewData["Title"] = "Welcome!"; } @section head { <meta property="og:title" content="@Core.Settings.Current.WebSiteTitle" /> <meta property="og:type" content="website" /> <meta property="og:url" content="@Core.Settings.Current.WebSiteUrl" /> <meta property="og:image" content="@Core.Settings.Current.FacebookImage" /> <meta property="og:description" content="@Core.Settings.Current.DefaultDescription" /> <meta name="keywords" content="@Core.Settings.Current.DefaultKeywords" /> <meta name="description" content="@Core.Settings.Current.DefaultDescription" /> } @section top { <!-- Main jumbotron for a primary marketing message or call to action --> <div class="jumbotron"> <div class="container"> <h1>Welcome to the daily developers digest!</h1> <h3 style="color: #FFF">All news and events will be here!</h3> <span style="color: #FFF"> Project supported by .NET Core Ukrainian User Group, Microsoft Azure Ukraine User Group and Xamarin Ukraine User Group ! </span> </div> </div> } @for (var i=0; i<Model.Count(); i++) { @Html.Partial("_Publication", Model[i]) if (i == 2) { @Html.Partial("_InFeedAd") } } @Html.PagedListPager(Model, page => $"/page/{page}")
mit
C#
b35e979ce200e8d5bf5e9bd0e83fd102602410fd
create constructor with validation methods
passenger-stack/Passenger,passenger-stack/Passenger
Passenger.Core/Domain/Node.cs
Passenger.Core/Domain/Node.cs
using System; using System.Text.RegularExpressions; namespace Passenger.Core.Domain { public class Node { private static readonly Regex NameRegex = new Regex("^(?![_.-])(?!.*[_.-]{2})[a-zA-Z0-9._.-]+(?<![_.-])$"); public string Address { get; protected set; } public double Longitude { get; protected set; } public double Latitude { get; protected set; } public DateTime UpdatedAt { get; protected set; } protected Node() { } protected Node(string address, double longitude, double latitude) { SetAdress(address); SetLongitude(longitude); SetLatitude(latitude); } public void SetAdress(string address) { if(!NameRegex.IsMatch(address)) { throw new Exception("Adress is invalid."); } Address = address; UpdatedAt = DateTime.UtcNow; } public void SetLongitude(double longitude) { if (double.IsNaN(longitude)) { throw new Exception("Longitude must be a number."); } if (Longitude == longitude) { return; } Longitude = longitude; UpdatedAt = DateTime.UtcNow; } public void SetLatitude(double latitude) { if (double.IsNaN(Latitude)) { throw new Exception("Latitude must be a number."); } if (Latitude == latitude) { return; } Latitude = latitude; UpdatedAt = DateTime.UtcNow; } public static Node Create(string address, double longitude, double latitude) => new Node(address, longitude, latitude); } }
namespace Passenger.Core.Domain { public class Node { public string Address { get; protected set; } public double Longitude { get; protected set; } public double Latitude { get; protected set; } } }
mit
C#
6a22a0470fe5cd57aafb018e72fef7cb720afdb5
Comment on next steps.
mcollier/ServiceFabricPubSub,flyingoverclouds/ServiceFabricPubSub,brentstineman/ServiceFabricPubSub,digimaun/ServiceFabricPubSub
src/ServiceFabricPubSub/RequestRouter/RequestAuthorizationAttribute.cs
src/ServiceFabricPubSub/RequestRouter/RequestAuthorizationAttribute.cs
using System; using System.Linq; using System.Net.Http; using System.Web.Http; using System.Web.Http.Controllers; namespace RequestRouterService { public class RequestAuthorizationAttribute : AuthorizeAttribute { public override void OnAuthorization(HttpActionContext actionContext) { if (Authorize(actionContext)) { return; } HandleUnauthorizedRequest(actionContext); } private bool Authorize(HttpActionContext actionContext) { bool isAuthorized = false; try { var requestKeyHeaderValue = actionContext.Request.Headers.GetValues("x-request-key").FirstOrDefault(); // TODO: Parse the request URL to get the tenant name. Use the tenant name to call the tenant specific // application's admin service to get the key(s). // Validate the admin key(s) against the ones from the service. if (!string.IsNullOrEmpty(requestKeyHeaderValue)) { // TODO: perform validation HttpServiceUriBuilder builder = new HttpServiceUriBuilder { ServiceName = "TenantApplication/AdminService" }; Uri serviceUri = builder.Build(); using (HttpClient httpClient = new HttpClient()) { var response = httpClient.GetAsync(serviceUri).Result; } } isAuthorized = true; } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); // TODO: Log this someplace better. isAuthorized = false; } return isAuthorized; } } }
using System; using System.Linq; using System.Net.Http; using System.Web.Http; using System.Web.Http.Controllers; namespace RequestRouterService { public class RequestAuthorizationAttribute : AuthorizeAttribute { public override void OnAuthorization(HttpActionContext actionContext) { if (Authorize(actionContext)) { return; } HandleUnauthorizedRequest(actionContext); } private bool Authorize(HttpActionContext actionContext) { bool isAuthorized = false; try { var requestKeyHeaderValue = actionContext.Request.Headers.GetValues("x-request-key").FirstOrDefault(); if (!string.IsNullOrEmpty(requestKeyHeaderValue)) { // TODO: perform validation HttpServiceUriBuilder builder = new HttpServiceUriBuilder { ServiceName = "TenantApplication/AdminService" }; Uri serviceUri = builder.Build(); using (HttpClient httpClient = new HttpClient()) { var response = httpClient.GetAsync(serviceUri).Result; } } isAuthorized = true; } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); // TODO: Log this someplace better. isAuthorized = false; } return isAuthorized; } } }
mit
C#
28e967fbdb240a8e8c16e487b8d4e0e2b48bc2e3
add null check on tcpClient
Piotrekol/StreamCompanion,Piotrekol/StreamCompanion
osu!StreamCompanion/Code/Modules/MapDataGetters/TcpSocket/TcpSocketManager.cs
osu!StreamCompanion/Code/Modules/MapDataGetters/TcpSocket/TcpSocketManager.cs
using System; using System.IO; using System.Net; using System.Net.Sockets; namespace osu_StreamCompanion.Code.Modules.MapDataGetters.TcpSocket { public class TcpSocketManager : IDisposable { private TcpClient _tcpClient; BinaryWriter _writer = null; public int ServerPort = 7839; public string ServerIp = "127.0.0.1"; public bool AutoReconnect = false; public bool Connect() { if (_writer != null) return true; _tcpClient = new TcpClient(); try { _tcpClient.Connect(IPAddress.Parse(ServerIp), ServerPort); _writer = new BinaryWriter(_tcpClient.GetStream()); } catch (SocketException) { //No server avaliable, or it is busy/full. return false; } return true; } public void Write(string data) { bool written = false; try { if (_tcpClient?.Connected ?? false) { _writer?.Write(data); written = true; } } catch (IOException) { //connection most likely closed _writer?.Dispose(); _writer = null; ((IDisposable)_tcpClient)?.Dispose(); } if (!written && AutoReconnect) { Connect(); } } public void Dispose() { ((IDisposable)_tcpClient)?.Dispose(); _writer?.Dispose(); } } }
using System; using System.IO; using System.Net; using System.Net.Sockets; namespace osu_StreamCompanion.Code.Modules.MapDataGetters.TcpSocket { public class TcpSocketManager : IDisposable { private TcpClient _tcpClient; BinaryWriter _writer = null; public int ServerPort = 7839; public string ServerIp = "127.0.0.1"; public bool AutoReconnect = false; public bool Connect() { if (_writer != null) return true; _tcpClient = new TcpClient(); try { _tcpClient.Connect(IPAddress.Parse(ServerIp), ServerPort); _writer = new BinaryWriter(_tcpClient.GetStream()); } catch (SocketException) { //No server avaliable, or it is busy/full. return false; } return true; } public void Write(string data) { bool written = false; try { if (_tcpClient.Connected) { _writer?.Write(data); written = true; } } catch (IOException) { //connection most likely closed _writer?.Dispose(); _writer = null; ((IDisposable)_tcpClient)?.Dispose(); } if (!written && AutoReconnect) { Connect(); } } public void Dispose() { ((IDisposable)_tcpClient)?.Dispose(); _writer?.Dispose(); } } }
mit
C#
f6b50e5fde80dd0fb172f07e958dd4739975be0e
Use StyledWindow services
AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia
tests/Avalonia.Markup.Xaml.UnitTests/SetterTests.cs
tests/Avalonia.Markup.Xaml.UnitTests/SetterTests.cs
using System.Linq; using Avalonia.Data; using Avalonia.Styling; using Avalonia.UnitTests; using Xunit; namespace Avalonia.Markup.Xaml.UnitTests { public class SetterTests : XamlTestBase { [Fact] public void Setter_Should_Work_Outside_Of_Style_With_SetterTargetType_Attribute() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var xaml = @" <Animation xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' x:SetterTargetType='Avalonia.Controls.Button'> <KeyFrame> <Setter Property='Content' Value='{Binding}'/> </KeyFrame> </Animation>"; var animation = (Animation.Animation)AvaloniaRuntimeXamlLoader.Load(xaml); var setter = (Setter)animation.Children[0].Setters[0]; Assert.IsType<Binding>(setter.Value); } } } }
using System.Linq; using Avalonia.Data; using Avalonia.Styling; using Avalonia.UnitTests; using Xunit; namespace Avalonia.Markup.Xaml.UnitTests { public class SetterTests : XamlTestBase { [Fact] public void Setter_Should_Work_Outside_Of_Style_With_SetterTargetType_Attribute() { using (UnitTestApplication.Start(TestServices.MockPlatformWrapper)) { var xaml = @" <Animation xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' x:SetterTargetType='Avalonia.Controls.Button'> <KeyFrame> <Setter Property='Content' Value='{Binding}'/> </KeyFrame> </Animation>"; var animation = (Animation.Animation)AvaloniaRuntimeXamlLoader.Load(xaml); var setter = (Setter)animation.Children[0].Setters[0]; Assert.IsType<Binding>(setter.Value); } } } }
mit
C#
4c42d4031440623a7ac1d62a7b2201691df0c6bb
Correct the comment from explosion to object
smoogipoo/osu,ppy/osu,NeoAdonis/osu,naoey/osu,NeoAdonis/osu,naoey/osu,peppy/osu,peppy/osu,UselessToucan/osu,2yangk23/osu,johnneijzen/osu,ZLima12/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,DrabWeb/osu,NeoAdonis/osu,smoogipooo/osu,naoey/osu,ZLima12/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,EVAST9919/osu,DrabWeb/osu,2yangk23/osu,ppy/osu,peppy/osu-new,DrabWeb/osu,EVAST9919/osu,johnneijzen/osu
osu.Game.Rulesets.Osu/Mods/OsuModTransform.cs
osu.Game.Rulesets.Osu/Mods/OsuModTransform.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using osu.Framework.Graphics; using osu.Game.Graphics; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects; using OpenTK; namespace osu.Game.Rulesets.Osu.Mods { internal class OsuModTransform : Mod, IApplicableToDrawableHitObjects { public override string Name => "Transform"; public override string ShortenedName => "TR"; public override FontAwesome Icon => FontAwesome.fa_arrows; public override ModType Type => ModType.Fun; public override string Description => "Everything rotates. EVERYTHING."; public override double ScoreMultiplier => 1; private float theta; public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables) { foreach (var drawable in drawables) { var hitObject = (OsuHitObject) drawable.HitObject; float appearDistance = (float)(hitObject.TimePreempt - hitObject.TimeFadeIn) / 2; Vector2 originalPosition = drawable.Position; Vector2 appearOffset = new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)) * appearDistance; //the - 1 and + 1 prevents the hit objects to appear in the wrong position. double appearTime = hitObject.StartTime - hitObject.TimePreempt - 1; double moveDuration = hitObject.TimePreempt + 1; using (drawable.BeginAbsoluteSequence(appearTime, true)) { drawable .MoveToOffset(appearOffset) .MoveTo(originalPosition, moveDuration, Easing.InOutSine); } theta += (float) hitObject.TimeFadeIn / 1000; } } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using osu.Framework.Graphics; using osu.Game.Graphics; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects; using OpenTK; namespace osu.Game.Rulesets.Osu.Mods { internal class OsuModTransform : Mod, IApplicableToDrawableHitObjects { public override string Name => "Transform"; public override string ShortenedName => "TR"; public override FontAwesome Icon => FontAwesome.fa_arrows; public override ModType Type => ModType.Fun; public override string Description => "Everything rotates. EVERYTHING."; public override double ScoreMultiplier => 1; private float theta; public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables) { foreach (var drawable in drawables) { var hitObject = (OsuHitObject) drawable.HitObject; float appearDistance = (float)(hitObject.TimePreempt - hitObject.TimeFadeIn) / 2; Vector2 originalPosition = drawable.Position; Vector2 appearOffset = new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)) * appearDistance; //the - 1 and + 1 prevents the hit explosion to appear in the wrong position. double appearTime = hitObject.StartTime - hitObject.TimePreempt - 1; double moveDuration = hitObject.TimePreempt + 1; using (drawable.BeginAbsoluteSequence(appearTime, true)) { drawable .MoveToOffset(appearOffset) .MoveTo(originalPosition, moveDuration, Easing.InOutSine); } theta += (float) hitObject.TimeFadeIn / 1000; } } } }
mit
C#
e6d66f8b579e82e05d0ac2863b1e079a74e2df38
Fix the demo with the last changes
proyecto26/RestClient
demo/Assets/MainScript.cs
demo/Assets/MainScript.cs
using UnityEngine; using UnityEditor; using Models; using Proyecto26; using System.Collections.Generic; public class MainScript : MonoBehaviour { private readonly string basePath = "https://jsonplaceholder.typicode.com"; public void Get(){ // We can add default request headers for all requests RestClient.DefaultRequestHeaders["Authorization"] = "Bearer ..."; RequestHelper requestOptions = null; RestClient.GetArray<Post>(basePath + "/posts").Then(res => { EditorUtility.DisplayDialog ("Posts", JsonHelper.ArrayToJsonString<Post>(res, true), "Ok"); return RestClient.GetArray<Todo>(basePath + "/todos"); }).Then(res => { EditorUtility.DisplayDialog ("Todos", JsonHelper.ArrayToJsonString<Todo>(res, true), "Ok"); return RestClient.GetArray<User>(basePath + "/users"); }).Then(res => { EditorUtility.DisplayDialog ("Users", JsonHelper.ArrayToJsonString<User>(res, true), "Ok"); // We can add specific options and override default headers for a request requestOptions = new RequestHelper { Uri = basePath + "/photos", Headers = new Dictionary<string, string> { { "Authorization", "Other token..." } } }; return RestClient.GetArray<Photo>(requestOptions); }).Then(res => { EditorUtility.DisplayDialog("Header", requestOptions.GetHeader("Authorization"), "Ok"); // And later we can clean the default headers for all requests RestClient.CleanDefaultHeaders(); }).Catch(err => EditorUtility.DisplayDialog ("Error", err.Message, "Ok")); } public void Post(){ RestClient.Post<Post>(basePath + "/posts", new Post { title = "My first title", body = "My first message", userId = 26 }) .Then(res => EditorUtility.DisplayDialog ("Success", JsonUtility.ToJson(res, true), "Ok")) .Catch(err => EditorUtility.DisplayDialog ("Error", err.Message, "Ok")); } public void Put(){ RestClient.Put<Post>(basePath + "/posts/1", new Post { title = "My new title", body = "My new message", userId = 26 }, (err, res, body) => { if(err != null){ EditorUtility.DisplayDialog ("Error", err.Message, "Ok"); } else{ EditorUtility.DisplayDialog ("Success", JsonUtility.ToJson(body, true), "Ok"); } }); } public void Delete(){ RestClient.Delete(basePath + "/posts/1", (err, res) => { if(err != null){ EditorUtility.DisplayDialog ("Error", err.Message, "Ok"); } else{ EditorUtility.DisplayDialog ("Success", "Status: " + res.StatusCode.ToString(), "Ok"); } }); } }
using UnityEngine; using UnityEditor; using Models; using Proyecto26; using System.Collections.Generic; public class MainScript : MonoBehaviour { private readonly string basePath = "https://jsonplaceholder.typicode.com"; public void Get(){ // We can add default request headers for all requests RestClient.DefaultRequestHeaders["Authorization"] = "Bearer ..."; RequestHelper requestOptions = null; RestClient.GetArray<Post>(basePath + "/posts").Then(res => { EditorUtility.DisplayDialog ("Posts", JsonHelper.ArrayToJsonString<Post>(res, true), "Ok"); return RestClient.GetArray<Todo>(basePath + "/todos"); }).Then(res => { EditorUtility.DisplayDialog ("Todos", JsonHelper.ArrayToJsonString<Todo>(res, true), "Ok"); return RestClient.GetArray<User>(basePath + "/users"); }).Then(res => { EditorUtility.DisplayDialog ("Users", JsonHelper.ArrayToJsonString<User>(res, true), "Ok"); // We can add specific options and override default headers for a request requestOptions = new RequestHelper { url = basePath + "/photos", headers = new Dictionary<string, string> { { "Authorization", "Other token..." } } }; return RestClient.GetArray<Photo>(requestOptions); }).Then(res => { EditorUtility.DisplayDialog("Header", requestOptions.GetHeader("Authorization"), "Ok"); // And later we can clean the default headers for all requests RestClient.CleanDefaultHeaders(); }).Catch(err => EditorUtility.DisplayDialog ("Error", err.Message, "Ok")); } public void Post(){ RestClient.Post<Models.Post>(basePath + "/posts", new Models.Post { title = "My first title", body = "My first message", userId = 26 }) .Then(res => EditorUtility.DisplayDialog ("Success", JsonUtility.ToJson(res, true), "Ok")) .Catch(err => EditorUtility.DisplayDialog ("Error", err.Message, "Ok")); } public void Put(){ RestClient.Put<Post>(basePath + "/posts/1", new Models.Post { title = "My new title", body = "My new message", userId = 26 }, (err, res, body) => { if(err != null){ EditorUtility.DisplayDialog ("Error", err.Message, "Ok"); } else{ EditorUtility.DisplayDialog ("Success", JsonUtility.ToJson(body, true), "Ok"); } }); } public void Delete(){ RestClient.Delete(basePath + "/posts/1", (err, res) => { if(err != null){ EditorUtility.DisplayDialog ("Error", err.Message, "Ok"); } else{ EditorUtility.DisplayDialog ("Success", "Status: " + res.statusCode.ToString(), "Ok"); } }); } }
mit
C#
6c4fb61841271d32baa0096b02533d026c0c7b8f
Add equivalence key to fixer's code actions
natidea/roslyn-analyzers,bkoelman/roslyn-analyzers,Anniepoh/roslyn-analyzers,qinxgit/roslyn-analyzers,pakdev/roslyn-analyzers,jasonmalinowski/roslyn-analyzers,dotnet/roslyn-analyzers,mavasani/roslyn-analyzers,genlu/roslyn-analyzers,mavasani/roslyn-analyzers,pakdev/roslyn-analyzers,srivatsn/roslyn-analyzers,heejaechang/roslyn-analyzers,dotnet/roslyn-analyzers
src/Microsoft.ApiDesignGuidelines.Analyzers/Core/ExceptionsShouldBePublic.Fixer.cs
src/Microsoft.ApiDesignGuidelines.Analyzers/Core/ExceptionsShouldBePublic.Fixer.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.CodeActions; namespace Microsoft.ApiDesignGuidelines.Analyzers { /// <summary> /// CA1064: Exceptions should be public /// </summary> [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic), Shared] public sealed class ExceptionsShouldBePublicFixer : CodeFixProvider { public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(ExceptionsShouldBePublicAnalyzer.RuleId); public sealed override FixAllProvider GetFixAllProvider() { // See https://github.com/dotnet/roslyn/blob/master/docs/analyzers/FixAllProvider.md for more information on Fix All Providers return WellKnownFixAllProviders.BatchFixer; } public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var node = root.FindNode(context.Span); var diagnostic = context.Diagnostics.Single(); // create one equivalence key value for all actions produced by this fixer // i.e. Fix All fixes every occurrence of this diagnostic var equivalenceKey = nameof(ExceptionsShouldBePublicFixer); var action = CodeAction.Create( MicrosoftApiDesignGuidelinesAnalyzersResources.MakeExceptionPublic, c => MakePublic(context.Document, node, context.CancellationToken), equivalenceKey); context.RegisterCodeFix(action, diagnostic); } private async Task<Document> MakePublic(Document document, SyntaxNode classDecl, CancellationToken cancellationToken) { DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); editor.SetAccessibility(classDecl, Accessibility.Public); return editor.GetChangedDocument(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.CodeActions; namespace Microsoft.ApiDesignGuidelines.Analyzers { /// <summary> /// CA1064: Exceptions should be public /// </summary> [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic), Shared] public sealed class ExceptionsShouldBePublicFixer : CodeFixProvider { public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(ExceptionsShouldBePublicAnalyzer.RuleId); public sealed override FixAllProvider GetFixAllProvider() { // See https://github.com/dotnet/roslyn/blob/master/docs/analyzers/FixAllProvider.md for more information on Fix All Providers return WellKnownFixAllProviders.BatchFixer; } public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var node = root.FindNode(context.Span); var diagnostic = context.Diagnostics.Single(); var action = CodeAction.Create(MicrosoftApiDesignGuidelinesAnalyzersResources.MakeExceptionPublic, c => MakePublic(context.Document, node, context.CancellationToken)); context.RegisterCodeFix(action, diagnostic); } private async Task<Document> MakePublic(Document document, SyntaxNode classDecl, CancellationToken cancellationToken) { DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); editor.SetAccessibility(classDecl, Accessibility.Public); return editor.GetChangedDocument(); } } }
mit
C#
2a4185186b406a08b1e400c6703c60156f17bfd7
Update DonationChing.cs
Barleytree/NitoriWare,uulltt/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare,plrusek/NitoriWare,NitorInc/NitoriWare
Assets/Resources/Microgames/_Finished/Donation/Scripts/DonationChing.cs
Assets/Resources/Microgames/_Finished/Donation/Scripts/DonationChing.cs
using UnityEngine; using System.Collections; public class DonationChing : MonoBehaviour { public ObjectPool pool; new public AudioSource audio; public float initialScale, growSpeed, maxScale, fadeStartTime, fadeSpeed, ySpeed; public Vector2 xBounds, yBounds; private float scale, time, alpha; private TextMesh mesh; void Start () { mesh = GetComponent<TextMesh>(); } public void reset(Vector3 position) { position += new Vector3(Random.Range(xBounds.x, xBounds.y), Random.Range(yBounds.x, yBounds.y), pool.prefab.transform.position.z); transform.position = position; //audio.pitch = Time.timeScale; //audio.Play(); time = 0f; alpha = 1f; scale = initialScale; transform.position = new Vector3(transform.position.x, transform.position.y, -5f); } void Update () { time += Time.deltaTime; if (scale < maxScale) { scale += growSpeed * Time.deltaTime; } scale = Mathf.Min(scale, maxScale); if (time >= fadeStartTime) { alpha -= fadeSpeed * Time.deltaTime; if (alpha <= 0f) { pool.poolObject(gameObject); } } updateAppearance(); transform.position += new Vector3(0f, ySpeed , .05f) * Time.deltaTime; } void updateAppearance() { transform.localScale = new Vector3(scale, scale, transform.localScale.z); Color color = mesh.color; color.a = alpha; mesh.color = color; } }
using UnityEngine; using System.Collections; public class DonationChing : MonoBehaviour { public ObjectPool pool; new public AudioSource audio; public float initialScale, growSpeed, maxScale, fadeStartTime, fadeSpeed, ySpeed; public Vector2 xBounds, yBounds; private float scale, time, alpha; private TextMesh mesh; void Start () { mesh = GetComponent<TextMesh>(); } public void reset(Vector3 position) { position += new Vector3(Random.Range(xBounds.x, xBounds.y), Random.Range(yBounds.x, yBounds.y), pool.prefab.transform.position.z); transform.position = position; //audio.pitch = Time.timeScale; //audio.Play(); time = 0f; alpha = 1f; scale = initialScale; transform.position = new Vector3(transform.position.x, transform.position.y, -5f); } void Update () { time += Time.deltaTime; if (scale < maxScale) { scale += growSpeed * Time.deltaTime; } scale = Mathf.Min(scale, maxScale); if (time >= fadeStartTime) { alpha -= fadeSpeed * Time.deltaTime; if (alpha <= 0f) { pool.poolObject(gameObject); } } updateAppearance(); transform.position += new Vector3(0f, ySpeed * Time.deltaTime, .05f * Time.deltaTime); } void updateAppearance() { transform.localScale = new Vector3(scale, scale, transform.localScale.z); Color color = mesh.color; color.a = alpha; mesh.color = color; } }
mit
C#
de6ffbc95816b636dcb4d81ec310a04e0d940893
Update EntityFrameworkConvertToDbGeography.cs
GeoJSON-Net/GeoJSON.Net.Contrib
src/GeoJSON.Net.Contrib.EntityFramework/EntityFrameworkConvertToDbGeography.cs
src/GeoJSON.Net.Contrib.EntityFramework/EntityFrameworkConvertToDbGeography.cs
using System.Data.Entity.Spatial; using GeoJSON.Net.Geometry; using GeoJSON.Net.Contrib.Wkb.Conversions; namespace GeoJSON.Net.Contrib.EntityFramework { public static partial class EntityFrameworkConvert { [Obsolete("This method will be removed in future releases, consider migrating now to the newest signature.", false)] public static DbGeography ToDbGeography(this IGeometryObject geometryObject) { return geometryObject.ToDbGeography(4326); } public static DbGeography ToDbGeography(this IGeometryObject geometryObject, int coordinateSystemId = 4326) { return DbGeography.FromBinary(WkbEncode.Encode(geometryObject), coordinateSystemId); } } }
using System.Data.Entity.Spatial; using GeoJSON.Net.Geometry; using GeoJSON.Net.Contrib.Wkb.Conversions; namespace GeoJSON.Net.Contrib.EntityFramework { public static partial class EntityFrameworkConvert { public static DbGeography ToDbGeography(this IGeometryObject geometryObject, int coordinateSystemId = 4326) { return DbGeography.FromBinary(WkbEncode.Encode(geometryObject), coordinateSystemId); } } }
mit
C#
90f38c4cf2de2c0d31e142970298ede915421ebd
Bump version of Amazon.Lambda.APIGatewayEvents
thedevopsmachine/aws-lambda-dotnet,thedevopsmachine/aws-lambda-dotnet,thedevopsmachine/aws-lambda-dotnet,thedevopsmachine/aws-lambda-dotnet
Libraries/src/Amazon.Lambda.APIGatewayEvents/Properties/AssemblyInfo.cs
Libraries/src/Amazon.Lambda.APIGatewayEvents/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Amazon.Lambda.APIGatewayEvents")] [assembly: AssemblyDescription("Lambda event interfaces for API Gateway event source.")] [assembly: AssemblyProduct("Amazon Web Services Lambda Interface for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: ComVisible(false)] [assembly: System.CLSCompliant(true)] [assembly: AssemblyVersion("1.0")] [assembly: AssemblyFileVersion("1.2.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Amazon.Lambda.APIGatewayEvents")] [assembly: AssemblyDescription("Lambda event interfaces for API Gateway event source.")] [assembly: AssemblyProduct("Amazon Web Services Lambda Interface for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: ComVisible(false)] [assembly: System.CLSCompliant(true)] [assembly: AssemblyVersion("1.0")] [assembly: AssemblyFileVersion("1.1.3.0")]
apache-2.0
C#
8c9ff703dcb1954e5abf00de6c68ece6f3b3fa81
update block text in markdown. (#1450)
superyyrrzz/docfx,928PJY/docfx,DuncanmaMSFT/docfx,pascalberger/docfx,928PJY/docfx,pascalberger/docfx,hellosnow/docfx,superyyrrzz/docfx,hellosnow/docfx,dotnet/docfx,DuncanmaMSFT/docfx,928PJY/docfx,superyyrrzz/docfx,dotnet/docfx,dotnet/docfx,hellosnow/docfx,pascalberger/docfx
src/Microsoft.DocAsCode.MarkdownLite/Basic/BlockRules/MarkdownTextBlockRule.cs
src/Microsoft.DocAsCode.MarkdownLite/Basic/BlockRules/MarkdownTextBlockRule.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.MarkdownLite { using System; using System.Text.RegularExpressions; using Microsoft.DocAsCode.MarkdownLite.Matchers; public class MarkdownTextBlockRule : IMarkdownRule { // @"^[^\n]+\n?" private static readonly Matcher _TextMatcher = Matcher.AnyStringInSingleLine + Matcher.NewLine.Maybe(); public virtual string Name => "Text"; [Obsolete("Please use LHeadingMatcher.")] public virtual Regex Text => Regexes.Block.Text; public virtual Matcher TextMatcher => _TextMatcher; public virtual IMarkdownToken TryMatch(IMarkdownParser parser, IMarkdownParsingContext context) { if (Text != Regexes.Block.Text) { return TryMatchOld(parser, context); } var match = context.Match(TextMatcher); if (match?.Length > 0) { var sourceInfo = context.Consume(match.Length); return new MarkdownTextToken(this, parser.Context, sourceInfo.Markdown, sourceInfo); } return null; } public virtual IMarkdownToken TryMatchOld(IMarkdownParser parser, IMarkdownParsingContext context) { var match = Text.Match(context.CurrentMarkdown); if (match.Length == 0) { return null; } var sourceInfo = context.Consume(match.Length); return new MarkdownTextToken(this, parser.Context, match.Value, sourceInfo); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.MarkdownLite { using System.Text.RegularExpressions; public class MarkdownTextBlockRule : IMarkdownRule { public virtual string Name => "Text"; public virtual Regex Text => Regexes.Block.Text; public virtual IMarkdownToken TryMatch(IMarkdownParser parser, IMarkdownParsingContext context) { var match = Text.Match(context.CurrentMarkdown); if (match.Length == 0) { return null; } var sourceInfo = context.Consume(match.Length); return new MarkdownTextToken(this, parser.Context, match.Value, sourceInfo); } } }
mit
C#
edd0d166b1c774cf102cc83208c52c56d6ab8df4
Add text transforms to OsuSpriteText
Drezi126/osu,DrabWeb/osu,naoey/osu,EVAST9919/osu,peppy/osu,Frontear/osuKyzer,2yangk23/osu,smoogipoo/osu,NeoAdonis/osu,naoey/osu,UselessToucan/osu,johnneijzen/osu,EVAST9919/osu,DrabWeb/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,DrabWeb/osu,ZLima12/osu,ppy/osu,ZLima12/osu,smoogipoo/osu,peppy/osu-new,smoogipooo/osu,johnneijzen/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,2yangk23/osu,peppy/osu,Nabile-Rahmani/osu,naoey/osu
osu.Game/Graphics/Sprites/OsuSpriteText.cs
osu.Game/Graphics/Sprites/OsuSpriteText.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.MathUtils; using OpenTK; using OpenTK.Graphics; using osu.Framework.Graphics.Transforms; namespace osu.Game.Graphics.Sprites { public class OsuSpriteText : SpriteText { public const float FONT_SIZE = 16; public OsuSpriteText() { Shadow = true; TextSize = FONT_SIZE; } protected override Drawable CreateFallbackCharacterDrawable() { var tex = GetTextureForCharacter('?'); if (tex != null) { float adjust = (RNG.NextSingle() - 0.5f) * 2; return new Sprite { Texture = tex, Origin = Anchor.Centre, Anchor = Anchor.Centre, Scale = new Vector2(1 + adjust * 0.2f), Rotation = adjust * 15, Colour = Color4.White, }; } return base.CreateFallbackCharacterDrawable(); } } public static class OsuSpriteTextTransformExtensions { /// <summary> /// Sets <see cref="OsuSpriteText.Text"/> to a new value after a duration. /// </summary> /// <returns>A <see cref="TransformSequence{T}"/> to which further transforms can be added.</returns> public static TransformSequence<T> TransformTextTo<T>(this T spriteText, string newText, double duration = 0, Easing easing = Easing.None) where T : OsuSpriteText => spriteText.TransformTo(nameof(OsuSpriteText.Text), newText, duration, easing); /// <summary> /// Sets <see cref="OsuSpriteText.Text"/> to a new value after a duration. /// </summary> /// <returns>A <see cref="TransformSequence{T}"/> to which further transforms can be added.</returns> public static TransformSequence<T> TransformTextTo<T>(this TransformSequence<T> t, string newText, double duration = 0, Easing easing = Easing.None) where T : OsuSpriteText => t.Append(o => o.TransformTextTo(newText, duration, easing)); } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.MathUtils; using OpenTK; using OpenTK.Graphics; namespace osu.Game.Graphics.Sprites { public class OsuSpriteText : SpriteText { public const float FONT_SIZE = 16; public OsuSpriteText() { Shadow = true; TextSize = FONT_SIZE; } protected override Drawable CreateFallbackCharacterDrawable() { var tex = GetTextureForCharacter('?'); if (tex != null) { float adjust = (RNG.NextSingle() - 0.5f) * 2; return new Sprite { Texture = tex, Origin = Anchor.Centre, Anchor = Anchor.Centre, Scale = new Vector2(1 + adjust * 0.2f), Rotation = adjust * 15, Colour = Color4.White, }; } return base.CreateFallbackCharacterDrawable(); } } }
mit
C#
78f03ec6db73f57fe94969d2e6b65cbde59e4da0
Add missing await
taddison/blog-oms-to-slack
GenericFunctionExternalConfig/OMSToSlack/OMSMetricToSlack.cs
GenericFunctionExternalConfig/OMSToSlack/OMSMetricToSlack.cs
using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Host; using OMSToSlack; using OMSToSlack.Models; using OMSToSlack.Models.OMS; using System; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; public class OMSMetricToSlack { private static AlertProcessor __processor; [FunctionName("OMSMetricToSlack")] public static async Task<object> Run([HttpTrigger(WebHookType = "genericJson")]HttpRequestMessage req, TraceWriter log, ExecutionContext context) { if(__processor == null) { __processor = new AlertProcessor(context); } var data = await req.Content.ReadAsAsync<OMSPayload>(); var metrics = data.SearchResults.Tables[0].Rows.Select(r => { return new MetricValue(DateTime.Parse(r[0].ToString()), Double.Parse(r[2].ToString())); }); // Server1|E: var computerName = data.SearchResults.Tables[0].Rows[0][1].ToString(); string instanceName = null; if(computerName.Contains('|')) { var split = computerName.Split('|'); computerName = split[0]; instanceName = split[1]; } var alert = new Alert(data.MetricName, computerName, instanceName, metrics); await __processor.ProcessAlert(alert); return req.CreateResponse(HttpStatusCode.OK); } }
using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Host; using OMSToSlack; using OMSToSlack.Models; using OMSToSlack.Models.OMS; using System; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; public class OMSMetricToSlack { private static AlertProcessor __processor; [FunctionName("OMSMetricToSlack")] public static async Task<object> Run([HttpTrigger(WebHookType = "genericJson")]HttpRequestMessage req, TraceWriter log, ExecutionContext context) { if(__processor == null) { __processor = new AlertProcessor(context); } var data = await req.Content.ReadAsAsync<OMSPayload>(); var metrics = data.SearchResults.Tables[0].Rows.Select(r => { return new MetricValue(DateTime.Parse(r[0].ToString()), Double.Parse(r[2].ToString())); }); // Server1|E: var computerName = data.SearchResults.Tables[0].Rows[0][1].ToString(); string instanceName = null; if(computerName.Contains('|')) { var split = computerName.Split('|'); computerName = split[0]; instanceName = split[1]; } var alert = new Alert(data.MetricName, computerName, instanceName, metrics); __processor.ProcessAlert(alert); return req.CreateResponse(HttpStatusCode.OK); } }
mit
C#
3a3bc84865012be90bfd91b7bce382d3c4b6a82a
Undo eicon status fix because it broke things
WreckedAvent/slimCat
slimCat/Utilities/Converters/BbCodeConverter.cs
slimCat/Utilities/Converters/BbCodeConverter.cs
#region Copyright // <copyright file="BbCodeConverter.cs"> // Copyright (c) 2013-2015, Justin Kadrovach, All rights reserved. // // This source is subject to the Simplified BSD License. // Please see the License.txt file for more information. // All other rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // </copyright> #endregion namespace slimCat.Utilities { #region Usings using System; using System.Collections.Generic; using System.Globalization; using System.Web; using System.Windows.Data; using System.Windows.Documents; using Models; using Services; #endregion /// <summary> /// Converts history messages into document inlines. /// </summary> public sealed class BbCodeConverter : BbCodeBaseConverter, IValueConverter { #region Constructors public BbCodeConverter(IChatState chatState, IThemeLocator locator) : base(chatState, locator) { } public BbCodeConverter() { } #endregion #region Explicit Interface Methods object IValueConverter.Convert(object value, Type type, object parameter, CultureInfo cultureInfo) { if (value == null) return null; var text = value as string ?? value.ToString(); text = HttpUtility.HtmlDecode(text); IList<Inline> toReturn = new List<Inline>(); toReturn.Add(Parse(text)); return toReturn; } object IValueConverter.ConvertBack(object value, Type type, object parameter, CultureInfo cultureInfo) { throw new NotImplementedException(); } #endregion } }
#region Copyright // <copyright file="BbCodeConverter.cs"> // Copyright (c) 2013-2015, Justin Kadrovach, All rights reserved. // // This source is subject to the Simplified BSD License. // Please see the License.txt file for more information. // All other rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // </copyright> #endregion namespace slimCat.Utilities { #region Usings using System; using System.Collections.Generic; using System.Globalization; using System.Web; using System.Windows.Data; using System.Windows.Documents; using Models; using Services; #endregion /// <summary> /// Converts history messages into document inlines. /// </summary> public sealed class BbCodeConverter : BbCodeBaseConverter, IValueConverter { #region Constructors public BbCodeConverter(IChatState chatState, IThemeLocator locator) : base(chatState, locator) { } public BbCodeConverter() { } #endregion #region Explicit Interface Methods IList<Inline> toReturn = new List<Inline>(); //reusing the same variable instead of making new ones each call, //because it risks crashing from using too much memory otherwise object IValueConverter.Convert(object value, Type type, object parameter, CultureInfo cultureInfo) { if (value == null) return null; var text = value as string ?? value.ToString(); text = HttpUtility.HtmlDecode(text); toReturn.Clear(); toReturn.Add(Parse(text)); return toReturn; } object IValueConverter.ConvertBack(object value, Type type, object parameter, CultureInfo cultureInfo) { throw new NotImplementedException(); } #endregion } }
bsd-2-clause
C#
2f0c85f1f8307c95e53a6f2a364bca13c22d814c
fix match-matchbox interaction (#8715)
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/Light/EntitySystems/MatchboxSystem.cs
Content.Server/Light/EntitySystems/MatchboxSystem.cs
using Content.Server.Light.Components; using Content.Server.Storage.EntitySystems; using Content.Shared.Interaction; using Content.Shared.Smoking; namespace Content.Server.Light.EntitySystems { public sealed class MatchboxSystem : EntitySystem { [Dependency] private readonly MatchstickSystem _stickSystem = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<MatchboxComponent, InteractUsingEvent>(OnInteractUsing, before: new[] { typeof(StorageSystem) }); } private void OnInteractUsing(EntityUid uid, MatchboxComponent component, InteractUsingEvent args) { if (!args.Handled && EntityManager.TryGetComponent<MatchstickComponent?>(args.Used, out var matchstick) && matchstick.CurrentState == SmokableState.Unlit) { _stickSystem.Ignite(matchstick, args.User); args.Handled = true; } } } }
using Content.Server.Light.Components; using Content.Shared.Interaction; using Content.Shared.Smoking; namespace Content.Server.Light.EntitySystems { public sealed class MatchboxSystem : EntitySystem { public override void Initialize() { base.Initialize(); SubscribeLocalEvent<MatchboxComponent, InteractUsingEvent>(OnInteractUsing); } private void OnInteractUsing(EntityUid uid, MatchboxComponent component, InteractUsingEvent args) { if (!args.Handled && EntityManager.TryGetComponent<MatchstickComponent?>(args.Used, out var matchstick) && matchstick.CurrentState == SmokableState.Unlit) { Get<MatchstickSystem>().Ignite(matchstick, args.User); args.Handled = true; } } } }
mit
C#
2de404e877edbe4fcbe8c67cee0a7f213da82be3
Update GameBinariesHandler
lucasdavid/Gamedalf,lucasdavid/Gamedalf
Gamedalf/Infrastructure/Games/GameBinariesHandler.cs
Gamedalf/Infrastructure/Games/GameBinariesHandler.cs
using Gamedalf.Infrastructure.Exceptions; using System; using System.IO; using System.Web; namespace Gamedalf.Infrastructure.Games { public class GameBinariesHandler : GameFilesHandler { private const string BasePath = "~/GamesBinaries"; private HttpPostedFileBase _binary; public GameBinariesHandler(int id, HttpPostedFileBase binary) : this(id, binary, false) { } public GameBinariesHandler(int id, HttpPostedFileBase binary, bool @override) : base(id, BasePath, @override) { if (binary == null || binary.ContentLength == 0) { throw new ArgumentException("Cannot construct GameBinariesHandler with given arguments: binary = " + binary); } _binary = binary; } public virtual GameBinariesHandler Save() { var file = Path.Combine(_directory, "installer" + Path.GetExtension(_binary.FileName)); if (File.Exists(file) && !_override) { throw new FileOverrideException(); } using (var fs = new FileStream(file, FileMode.Create)) { var buffer = new byte[_binary.InputStream.Length]; _binary.InputStream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, buffer.Length); } return this; } public virtual GameBinariesHandler SaveAll() { SaveDirectory(); return Save(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; namespace Gamedalf.Infrastructure.Games { public class GameBinariesHandler : GameFilesHandler { private const string BasePath = "~/GamesBinaries"; private HttpPostedFile _binary; public GameBinariesHandler(int id, HttpPostedFile binary) : this(id, binary, false) { } public GameBinariesHandler(int id, HttpPostedFile binary, bool @override) : base(id, BasePath, @override) { if (binary == null || binary.ContentLength == 0) { throw new ArgumentException("Cannot construct GameBinariesHandler with given arguments: binary = " + binary); } _binary = binary; } public virtual GameBinariesHandler Save() { var file = Path.Combine(_directory, "installer" + Path.GetExtension(_binary.FileName)); _binary.SaveAs(file); return this; } public virtual GameBinariesHandler SaveAll() { SaveDirectory(); return Save(); } } }
mit
C#
ff5e5c4e273c126f88b9eea715fc05d2b27d8b64
Improve _ToolbarButton template.
jtm789/CMS,andyshao/CMS,techwareone/Kooboo-CMS,techwareone/Kooboo-CMS,lingxyd/CMS,Kooboo/CMS,lingxyd/CMS,jtm789/CMS,Kooboo/CMS,lingxyd/CMS,andyshao/CMS,andyshao/CMS,techwareone/Kooboo-CMS,Kooboo/CMS,jtm789/CMS
Kooboo.CMS/Kooboo.CMS.Web/Views/Shared/_ToolbarButton.cshtml
Kooboo.CMS/Kooboo.CMS.Web/Views/Shared/_ToolbarButton.cshtml
@model Kooboo.CMS.Sites.Extension.UI.TopToolbar.ToolbarButton @{ var routeValues = ViewContext.RequestContext.AllRouteValues().Merge("return", ViewContext.HttpContext.Request.RawUrl); IDictionary<string, object> htmlAttributes = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); if (Model.CommandTarget!=null) { if (!string.IsNullOrEmpty(Model.CommandTarget.Area)) { routeValues = routeValues.Merge("area", Model.CommandTarget.Area); } if (!string.IsNullOrEmpty(Model.CommandTarget.Controller)) { routeValues = routeValues.Merge("controller", Model.CommandTarget.Controller); } if (Model.CommandTarget.RouteValues != null) { routeValues = routeValues.Merge(new RouteValueDictionary(Model.CommandTarget.RouteValues)); } htmlAttributes["href"] = Url.Action(Model.CommandTarget.Action, routeValues); } if (Model.HtmlAttributes != null) { htmlAttributes = htmlAttributes.Merge(Model.HtmlAttributes);// Html.GenerateHtmlAttributes(Model.HtmlAttributes); } } <li> <a @Html.GenerateHtmlAttributes(htmlAttributes)> @if (!string.IsNullOrEmpty(Model.IconClass)) { @Html.IconImage(Model.IconClass) } @(Model.CommandText.Localize()) </a> </li>
@model Kooboo.CMS.Sites.Extension.UI.TopToolbar.ToolbarButton @{ var routeValues = ViewContext.RequestContext.AllRouteValues().Merge("return", ViewContext.HttpContext.Request.RawUrl); if (!string.IsNullOrEmpty(Model.CommandTarget.Area)) { routeValues = routeValues.Merge("area", Model.CommandTarget.Area); } if (!string.IsNullOrEmpty(Model.CommandTarget.Controller)) { routeValues = routeValues.Merge("controller", Model.CommandTarget.Controller); } if (Model.CommandTarget.RouteValues != null) { routeValues = routeValues.Merge(new RouteValueDictionary(Model.CommandTarget.RouteValues)); } IHtmlString htmlAttributes = null; if (Model.HtmlAttributes != null) { htmlAttributes = Html.GenerateHtmlAttributes(Model.HtmlAttributes); } } <li> <a href="@Url.Action(Model.CommandTarget.Action, routeValues)" @htmlAttributes> @if (!string.IsNullOrEmpty(Model.IconClass)) { @Html.IconImage(Model.IconClass) } @(Model.CommandText.Localize()) </a> </li>
bsd-3-clause
C#
1b6746955b8db59ce34791c0f726bee42a4eddf6
Fix wrong padding value used to calc Descent
prime31/Nez,prime31/Nez,ericmbernier/Nez,prime31/Nez,Blucky87/Nez
Nez.PipelineImporter/BitmapFonts/BitmapFontWriter.cs
Nez.PipelineImporter/BitmapFonts/BitmapFontWriter.cs
using Microsoft.Xna.Framework.Content.Pipeline; using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Compiler; using System.Collections.Generic; using Microsoft.Xna.Framework.Content.Pipeline.Graphics; using System; using Nez.PipelineImporter; namespace Nez.BitmapFontImporter { [ContentTypeWriter] public class BitmapFontWriter : ContentTypeWriter<BitmapFontProcessorResult> { protected override void Write( ContentWriter writer, BitmapFontProcessorResult result ) { writer.Write( result.packTexturesIntoXnb ); // write our textures if we should else write the texture names if( result.packTexturesIntoXnb ) { writer.Write( result.textures.Count ); foreach( var tex in result.textures ) writer.WriteObject( tex ); } else { writer.Write( result.textureNames.Count ); for( var i = 0; i < result.textureNames.Count; i++ ) { writer.Write( result.textureNames[i] ); writer.Write( result.textureOrigins[i] ); } } // write the font data var fontFile = result.fontFile; writer.Write( fontFile.common.lineHeight ); var padding = fontFile.info.padding.Split( new char[] { ',' } ); if( padding.Length != 4 ) throw new PipelineException( "font padding is invalid! It should contain 4 values" ); writer.Write( int.Parse( padding[0] ) ); // top writer.Write( int.Parse( padding[1] ) ); // left writer.Write( int.Parse( padding[2] ) ); // bottom writer.Write( int.Parse( padding[3] ) ); // right writer.Write( getDescent( fontFile, int.Parse( padding[2] ) ) ); writer.Write( fontFile.chars.Count ); foreach( var c in fontFile.chars ) { writer.Write( c.id ); writer.Write( c.page ); writer.Write( c.x ); writer.Write( c.y ); writer.Write( c.width ); writer.Write( c.height ); writer.Write( c.xOffset ); writer.Write( c.yOffset ); writer.Write( c.xAdvance ); } } int getDescent( BitmapFontFile fontFile, int padBottom ) { var descent = 0; foreach( var c in fontFile.chars ) { if( c.width > 0 && c.height > 0 ) descent = Math.Min( fontFile.common.base_ + c.yOffset, descent ); } return descent + padBottom; } public override string GetRuntimeType( TargetPlatform targetPlatform ) { return typeof( Nez.BitmapFonts.BitmapFont ).AssemblyQualifiedName; } public override string GetRuntimeReader( TargetPlatform targetPlatform ) { return typeof( Nez.BitmapFonts.BitmapFontReader ).AssemblyQualifiedName; } } }
using Microsoft.Xna.Framework.Content.Pipeline; using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Compiler; using System.Collections.Generic; using Microsoft.Xna.Framework.Content.Pipeline.Graphics; using System; using Nez.PipelineImporter; namespace Nez.BitmapFontImporter { [ContentTypeWriter] public class BitmapFontWriter : ContentTypeWriter<BitmapFontProcessorResult> { protected override void Write( ContentWriter writer, BitmapFontProcessorResult result ) { writer.Write( result.packTexturesIntoXnb ); // write our textures if we should else write the texture names if( result.packTexturesIntoXnb ) { writer.Write( result.textures.Count ); foreach( var tex in result.textures ) writer.WriteObject( tex ); } else { writer.Write( result.textureNames.Count ); for( var i = 0; i < result.textureNames.Count; i++ ) { writer.Write( result.textureNames[i] ); writer.Write( result.textureOrigins[i] ); } } // write the font data var fontFile = result.fontFile; writer.Write( fontFile.common.lineHeight ); var padding = fontFile.info.padding.Split( new char[] { ',' } ); if( padding.Length != 4 ) throw new PipelineException( "font padding is invalid! It should contain 4 values" ); writer.Write( int.Parse( padding[0] ) ); // top writer.Write( int.Parse( padding[1] ) ); // left writer.Write( int.Parse( padding[2] ) ); // bottom writer.Write( int.Parse( padding[3] ) ); // right writer.Write( getDescent( fontFile, int.Parse( padding[3] ) ) ); writer.Write( fontFile.chars.Count ); foreach( var c in fontFile.chars ) { writer.Write( c.id ); writer.Write( c.page ); writer.Write( c.x ); writer.Write( c.y ); writer.Write( c.width ); writer.Write( c.height ); writer.Write( c.xOffset ); writer.Write( c.yOffset ); writer.Write( c.xAdvance ); } } int getDescent( BitmapFontFile fontFile, int padBottom ) { var descent = 0; foreach( var c in fontFile.chars ) { if( c.width > 0 && c.height > 0 ) descent = Math.Min( fontFile.common.base_ + c.yOffset, descent ); } return descent + padBottom; } public override string GetRuntimeType( TargetPlatform targetPlatform ) { return typeof( Nez.BitmapFonts.BitmapFont ).AssemblyQualifiedName; } public override string GetRuntimeReader( TargetPlatform targetPlatform ) { return typeof( Nez.BitmapFonts.BitmapFontReader ).AssemblyQualifiedName; } } }
mit
C#
b7d40e795959426c74b9c4ced3ee4e10bd329db5
Add tests
oledb/PiforatioAlpha
Piforatio.Core/Pifaratio.Test/Core/PTaskModelTest.cs
Piforatio.Core/Pifaratio.Test/Core/PTaskModelTest.cs
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Moq; using Piforatio.Core.ObjectsAbstract; using Piforatio.Core.DataModel; using static Piforatio.Test.Core.FakesFabrica; namespace Piforatio.Test.Core { [TestFixture] public class PTaskModelTest { [Test] public void CreateAndSavePTask_Failed() { //Arrange IDataContextFactory factory = CreateDataContextFabricaStub(); PTaskModel model = new PTaskModel(factory, null); //Act //Assert throw new NotImplementedException(); } [Test] public void CreateAndSavePTask() { //Arrange IDataContextFactory factory = CreateDataContextFabricaStub(); IProject project = CreateProject("Test Project", new DateTime(2017, 1, 20), 34); PTaskModel model = new PTaskModel(factory, null); //Act //Assert throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Moq; using Piforatio.Core.ObjectsAbstract; using Piforatio.Core.DataModel; using static Piforatio.Test.Core.FakesFabrica; namespace Piforatio.Test.Core { [TestFixture] public class PTaskModelTest { [Test] public void CreateAndSavePTask() { throw new NotImplementedException(); } } }
mit
C#
49fba553fd6a4ddd203e536b48e0dfab79023c99
Write to isLatLong property
Esri/coordinate-tool-addin-dotnet
source/CoordinateConversion/CoordinateConversionLibrary/Views/AmbiguousCoordsView.xaml.cs
source/CoordinateConversion/CoordinateConversionLibrary/Views/AmbiguousCoordsView.xaml.cs
using CoordinateConversionLibrary.Models; using System.Windows; namespace CoordinateConversionLibrary.Views { /// <summary> /// Interaction logic for AmbiguousCoordsView.xaml /// </summary> public partial class AmbiguousCoordsView : Window { public bool CheckedLatLon { get { return _checkedLatLon; } set { _checkedLatLon = value; _checkedLonLat = !_checkedLatLon; } } bool _checkedLatLon; public bool CheckedLonLat { get { return _checkedLonLat; } set { _checkedLonLat = value; _checkedLatLon = !_checkedLonLat; } } bool _checkedLonLat; public AmbiguousCoordsView() { InitializeComponent(); this.DataContext = this; CheckedLatLon = true; } private void OkButton_Click(object sender, RoutedEventArgs e) { this.Visibility = System.Windows.Visibility.Hidden; CoordinateConversionLibraryConfig.AddInConfig.isLatLong = CheckedLatLon; } private void OnDontShowAgainClick(object sender, RoutedEventArgs e) { CoordinateConversionLibraryConfig.AddInConfig.DisplayAmbiguousCoordsDlg = !cbDontShowAgain.IsChecked.Value; } } }
using CoordinateConversionLibrary.Models; using System.Windows; namespace CoordinateConversionLibrary.Views { /// <summary> /// Interaction logic for AmbiguousCoordsView.xaml /// </summary> public partial class AmbiguousCoordsView : Window { public bool CheckedLatLon { get { return _checkedLatLon; } set { _checkedLatLon = value; _checkedLonLat = !_checkedLatLon; } } bool _checkedLatLon; public bool CheckedLonLat { get { return _checkedLonLat; } set { _checkedLonLat = value; _checkedLatLon = !_checkedLonLat; } } bool _checkedLonLat; public AmbiguousCoordsView() { InitializeComponent(); this.DataContext = this; CheckedLatLon = true; } private void OkButton_Click(object sender, RoutedEventArgs e) { this.Visibility = System.Windows.Visibility.Hidden; } private void OnDontShowAgainClick(object sender, RoutedEventArgs e) { CoordinateConversionLibraryConfig.AddInConfig.DisplayAmbiguousCoordsDlg = !cbDontShowAgain.IsChecked.Value; } } }
apache-2.0
C#
0e4065cc1f2dc7cda7a0e6ae30c67729cf4f02c0
Reorder InMemoryCache.TryGet()
superkarn/RatanaLibrary
src/RatanaLibrary.Common/Cache/InMemoryCache.cs
src/RatanaLibrary.Common/Cache/InMemoryCache.cs
using System; using System.Runtime.Caching; namespace RatanaLibrary.Common.Cache { /// <summary> /// An in-memory implementation of the ICache interface. /// </summary> public class InMemoryCache : ICache { private static Object Lock = new Object(); public InMemoryCache() { } T ICache.GetOrAdd<T>(String key, Func<T> orAdd) { return ((ICache)this).GetOrAdd(key, orAdd, TimeSpan.FromDays(1)); } T ICache.GetOrAdd<T>(String key, Func<T> orAdd, TimeSpan expiration) { T value = default(T); // Try to get the item // If the item is not found, lock and try again. // If it's not found this time, add it to the cache. if (!this.TryGet(key, out value)) { lock(InMemoryCache.Lock) { if (!this.TryGet(key, out value)) { value = orAdd(); MemoryCache.Default.Add(key, value, DateTime.Now.Add(expiration)); } } } return value; } void ICache.Remove(String key) { MemoryCache.Default.Remove(key); } /// <summary> /// Look for the item in the cache. /// If the item is found, set the value and return true, /// else set the value to default and return false. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> private Boolean TryGet<T>(String key, out T value) { if (!MemoryCache.Default.Contains(key)) { value = default(T); return false; } value = (T)MemoryCache.Default.Get(key); return true; } } }
using System; using System.Runtime.Caching; namespace RatanaLibrary.Common.Cache { /// <summary> /// An in-memory implementation of the ICache interface. /// </summary> public class InMemoryCache : ICache { private static Object Lock = new Object(); public InMemoryCache() { } T ICache.GetOrAdd<T>(String key, Func<T> orAdd) { return ((ICache)this).GetOrAdd(key, orAdd, TimeSpan.FromDays(1)); } T ICache.GetOrAdd<T>(String key, Func<T> orAdd, TimeSpan expiration) { T value = default(T); // Try to get the item // If the item is not found, lock and try again. // If it's not found this time, add it to the cache. if (!this.TryGet(key, out value)) { lock(InMemoryCache.Lock) { if (!this.TryGet(key, out value)) { value = orAdd(); MemoryCache.Default.Add(key, value, DateTime.Now.Add(expiration)); } } } return value; } void ICache.Remove(String key) { MemoryCache.Default.Remove(key); } /// <summary> /// Look for the item in the cache. /// If the item is found, set the value and return true, /// else set the value to default and return false. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> private Boolean TryGet<T>(String key, out T value) { value = default(T); if (!MemoryCache.Default.Contains(key)) { return false; } value = (T)MemoryCache.Default.Get(key); return true; } } }
apache-2.0
C#
11d90471237ce57bc677ce52ddd567bec3dccdba
Update Option.ToString
copygirl/EntitySystem
src/Utility/Option.cs
src/Utility/Option.cs
using System; using System.Collections.Generic; namespace EntitySystem.Utility { public struct Option<T> : IEquatable<Option<T>> { readonly T _value; public bool HasValue { get; private set; } public T Value => Expect(() => new InvalidOperationException($"Option has no value")); public Option(T value, bool hasValue = true) { _value = value; HasValue = hasValue; } public static Option<T> None { get; } = new Option<T>(); public static Option<T> Some(T value) => new Option<T>(value); public T Expect(Func<Exception> func) { if (HasValue) return _value; else throw func(); } public void ExpectNone(Func<Exception> func) { if (!HasValue) throw func(); } public T Or(T @default) => (HasValue ? Value : @default); public T Or(Func<T> func) => (HasValue ? Value : func()); public Option<T> Or(Func<Option<T>> func) => (HasValue ? this : func()); public T OrDefault() => Or(default(T)); public Option<TResult> Map<TResult>(Func<T, TResult> func) => (HasValue ? Option<TResult>.Some(func(_value)) : Option<TResult>.None); public Option<TResult> Map<TResult>(Func<T, Option<TResult>> func) => (HasValue ? func(_value) : Option<TResult>.None); public Option<TResult> Cast<TResult>() => (HasValue ? (TResult)(object)_value : Option<TResult>.None); public static implicit operator Option<T>(T value) { if (value == null) throw new ArgumentNullException( "Implicit conversion to Option requires value to be non-null"); return Option<T>.Some(value); } public static explicit operator T(Option<T> option) => option.Value; public override bool Equals(object obj) => ((obj is Option<T>) && Equals((Option<T>)obj)); public bool Equals(Option<T> other) => Equals(other, EqualityComparer<T>.Default); public bool Equals(Option<T> other, IEqualityComparer<T> comparer) => ((HasValue == other.HasValue) && (!HasValue || comparer.Equals(_value, other.Value))); public static bool operator ==(Option<T> left, Option<T> right) => left.Equals(right); public static bool operator !=(Option<T> left, Option<T> right) => !left.Equals(right); public override int GetHashCode() => (HasValue ? (_value?.GetHashCode() ?? 0) : 0); public override string ToString() => $"{ GetType().GetFriendlyName() }.{ Map((value) => $"Some( { value.ToString()} )").Or("None") }"; } }
using System; using System.Collections.Generic; namespace EntitySystem.Utility { public struct Option<T> : IEquatable<Option<T>> { readonly T _value; public bool HasValue { get; private set; } public T Value => Expect(() => new InvalidOperationException($"Option has no value")); public Option(T value, bool hasValue = true) { _value = value; HasValue = hasValue; } public static Option<T> None { get; } = new Option<T>(); public static Option<T> Some(T value) => new Option<T>(value); public T Expect(Func<Exception> func) { if (HasValue) return _value; else throw func(); } public void ExpectNone(Func<Exception> func) { if (!HasValue) throw func(); } public T Or(T @default) => (HasValue ? Value : @default); public T Or(Func<T> func) => (HasValue ? Value : func()); public Option<T> Or(Func<Option<T>> func) => (HasValue ? this : func()); public T OrDefault() => Or(default(T)); public Option<TResult> Map<TResult>(Func<T, TResult> func) => (HasValue ? Option<TResult>.Some(func(_value)) : Option<TResult>.None); public Option<TResult> Map<TResult>(Func<T, Option<TResult>> func) => (HasValue ? func(_value) : Option<TResult>.None); public Option<TResult> Cast<TResult>() => (HasValue ? (TResult)(object)_value : Option<TResult>.None); public static implicit operator Option<T>(T value) { if (value == null) throw new ArgumentNullException( "Implicit conversion to Option requires value to be non-null"); return Option<T>.Some(value); } public static explicit operator T(Option<T> option) => option.Value; public override bool Equals(object obj) => ((obj is Option<T>) && Equals((Option<T>)obj)); public bool Equals(Option<T> other) => Equals(other, EqualityComparer<T>.Default); public bool Equals(Option<T> other, IEqualityComparer<T> comparer) => ((HasValue == other.HasValue) && (!HasValue || comparer.Equals(_value, other.Value))); public static bool operator ==(Option<T> left, Option<T> right) => left.Equals(right); public static bool operator !=(Option<T> left, Option<T> right) => !left.Equals(right); public override int GetHashCode() => (HasValue ? (_value?.GetHashCode() ?? 0) : 0); public override string ToString() => (typeof(Option<T>).Name + "." + (HasValue ? "Some" : "None")); } }
mit
C#
429c83d4874bda7f2d9cae4cb12047feaf31cd57
Remove the obsolete UseTypedRouting method
ivaylokenov/AspNet.Mvc.TypedRouting
src/AspNet.Mvc.TypedRouting/RouteBuilderExtensions.cs
src/AspNet.Mvc.TypedRouting/RouteBuilderExtensions.cs
namespace Microsoft.AspNetCore.Builder { using Routing; using System; public static class RouteBuilderExtensions { } }
namespace Microsoft.AspNetCore.Builder { using Routing; using System; public static class RouteBuilderExtensions { /// <summary> /// Allows using typed expression based link generation in ASP.NET Core MVC application. /// </summary> [Obsolete("UseTypedRouting is no longer needed and will be removed in the next version. Call 'AddMvc().AddTypedRouting()' instead.")] public static IRouteBuilder UseTypedRouting(this IRouteBuilder routeBuilder) { return routeBuilder; } } }
mit
C#
829475c87dd1e057bc89c19ac9535ac71e98082c
Reformat Main method.
kekekeks/PerspexVS,AvaloniaUI/PerspexVS
src/Templates/AvaloniaApplicationTemplate/App.xaml.cs
src/Templates/AvaloniaApplicationTemplate/App.xaml.cs
using System; using Avalonia; using Avalonia.Controls; using Avalonia.Diagnostics; using Avalonia.Themes.Default; using Avalonia.Markup.Xaml; namespace $safeprojectname$ { class App : Application { public override void Initialize() { AvaloniaXamlLoader.Load(this); base.Initialize(); } static void Main(string[] args) { AppBuilder.Configure<App>() .UseWin32() .UseDirect2D1() .Start<MainWindow>(); } public static void AttachDevTools(Window window) { #if DEBUG DevTools.Attach(window); #endif } } }
using System; using Avalonia; using Avalonia.Controls; using Avalonia.Diagnostics; using Avalonia.Themes.Default; using Avalonia.Markup.Xaml; namespace $safeprojectname$ { class App : Application { public override void Initialize() { AvaloniaXamlLoader.Load(this); base.Initialize(); } static void Main(string[] args) => AppBuilder.Configure<App>().UseWin32().UseDirect2D1().Start<MainWindow>(); public static void AttachDevTools(Window window) { #if DEBUG DevTools.Attach(window); #endif } } }
mit
C#