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
af7214c0c1b6c652d2a8da30c6a172a0ae1ee89a
Use AssemblyHelper for MainWindow title version
CalebChalmers/KAGTools
KAGTools/Windows/MainWindow.xaml.cs
KAGTools/Windows/MainWindow.xaml.cs
using GalaSoft.MvvmLight.Messaging; using KAGTools.Helpers; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace KAGTools.Windows { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { if (double.IsNaN(Properties.Settings.Default.Left) || double.IsNaN(Properties.Settings.Default.Top)) { WindowStartupLocation = WindowStartupLocation.CenterScreen; } InitializeComponent(); Title += string.Format(" v{0}", AssemblyHelper.Version); } private async void Window_Loaded(object sender, RoutedEventArgs e) { await UpdateHelper.UpdateApp(); } } }
using GalaSoft.MvvmLight.Messaging; using KAGTools.Helpers; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace KAGTools.Windows { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { if (double.IsNaN(Properties.Settings.Default.Left) || double.IsNaN(Properties.Settings.Default.Top)) { WindowStartupLocation = WindowStartupLocation.CenterScreen; } InitializeComponent(); Version version = Assembly.GetEntryAssembly().GetName().Version; Title += string.Format(" v{0}", version.ToString()); } private async void Window_Loaded(object sender, RoutedEventArgs e) { await UpdateHelper.UpdateApp(); } } }
mit
C#
703f64ac573843565f5ea744f65705cc5e8ad752
Fix test
tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools
src/dotnet/Azure.ClientSdk.Analyzers/Azure.ClientSdk.Analyzers.Tests/AzureAnalyzerTest.cs
src/dotnet/Azure.ClientSdk.Analyzers/Azure.ClientSdk.Analyzers.Tests/AzureAnalyzerTest.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Testing; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Testing; using Microsoft.CodeAnalysis.Testing.Verifiers; namespace Azure.ClientSdk.Analyzers.Tests { public class AzureAnalyzerTest<TAnalyzer> : CSharpAnalyzerTest<TAnalyzer, XUnitVerifier> where TAnalyzer : DiagnosticAnalyzer, new() { private static readonly ReferenceAssemblies DefaultReferenceAssemblies = ReferenceAssemblies.Default.AddPackages(ImmutableArray.Create( new PackageIdentity("Microsoft.Bcl.AsyncInterfaces", "1.1.0"), new PackageIdentity("System.Threading.Tasks.Extensions", "4.5.3"))); public AzureAnalyzerTest(LanguageVersion languageVersion = LanguageVersion.Latest) { SolutionTransforms.Add((solution, projectId) => { var project = solution.GetProject(projectId); var parseOptions = (CSharpParseOptions)project.ParseOptions; return solution.WithProjectParseOptions(projectId, parseOptions.WithLanguageVersion(languageVersion)); }); ReferenceAssemblies = DefaultReferenceAssemblies; } public string DescriptorName { get; set; } protected override DiagnosticDescriptor GetDefaultDiagnostic(DiagnosticAnalyzer[] analyzers) => string.IsNullOrWhiteSpace(DescriptorName) ? base.GetDefaultDiagnostic(analyzers) : analyzers.SelectMany(a => a.SupportedDiagnostics).FirstOrDefault(d => d.Id == DescriptorName) ?? base.GetDefaultDiagnostic(analyzers); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Testing; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Testing.Verifiers; namespace Azure.ClientSdk.Analyzers.Tests { public class AzureAnalyzerTest<TAnalyzer> : CSharpAnalyzerTest<TAnalyzer, XUnitVerifier> where TAnalyzer : DiagnosticAnalyzer, new() { public AzureAnalyzerTest(LanguageVersion languageVersion = LanguageVersion.Latest) { SolutionTransforms.Add((solution, projectId) => { var project = solution.GetProject(projectId); var parseOptions = (CSharpParseOptions)project.ParseOptions; return solution.WithProjectParseOptions(projectId, parseOptions.WithLanguageVersion(languageVersion)); }); TestState.AdditionalReferences.Add(typeof(ValueTask).Assembly); TestState.AdditionalReferences.Add(typeof(IAsyncDisposable).Assembly); } public string DescriptorName { get; set; } protected override DiagnosticDescriptor GetDefaultDiagnostic(DiagnosticAnalyzer[] analyzers) => string.IsNullOrWhiteSpace(DescriptorName) ? base.GetDefaultDiagnostic(analyzers) : analyzers.SelectMany(a => a.SupportedDiagnostics).FirstOrDefault(d => d.Id == DescriptorName) ?? base.GetDefaultDiagnostic(analyzers); } }
mit
C#
2bcfc5375d338a9e06ed422f0ada27f9f6c269fa
remove blank lines.
Aaron-Liu/enode,tangxuehua/enode
src/BankTransferSample/CommandHandlers/BankAccountCommandHandlers.cs
src/BankTransferSample/CommandHandlers/BankAccountCommandHandlers.cs
using System.Threading.Tasks; using BankTransferSample.ApplicationMessages; using BankTransferSample.Commands; using BankTransferSample.Domain; using ECommon.Components; using ENode.Commanding; using ENode.Infrastructure; namespace BankTransferSample.CommandHandlers { /// <summary>银行账户相关命令处理 /// </summary> [Component] public class BankAccountCommandHandlers : ICommandHandler<CreateAccountCommand>, //开户 ICommandAsyncHandler<ValidateAccountCommand>, //验证账户是否合法 ICommandHandler<AddTransactionPreparationCommand>, //添加预操作 ICommandHandler<CommitTransactionPreparationCommand> //提交预操作 { public void Handle(ICommandContext context, CreateAccountCommand command) { context.Add(new BankAccount(command.AggregateRootId, command.Owner)); } public Task<AsyncTaskResult<IApplicationMessage>> HandleAsync(ValidateAccountCommand command) { var applicationMessage = default(ApplicationMessage); //此处应该会调用外部接口验证账号是否合法,这里仅仅简单通过账号是否等于00003判断是否合法;根据账号的合法性,返回不同的应用层消息 if (command.AggregateRootId == "00003") { applicationMessage = new AccountValidateFailedMessage(command.AggregateRootId, command.TransactionId, "账户不可以是00003."); } else { applicationMessage = new AccountValidatePassedMessage(command.AggregateRootId, command.TransactionId); } return Task.FromResult(new AsyncTaskResult<IApplicationMessage>(AsyncTaskStatus.Success, applicationMessage)); } public void Handle(ICommandContext context, AddTransactionPreparationCommand command) { context.Get<BankAccount>(command.AggregateRootId).AddTransactionPreparation(command.TransactionId, command.TransactionType, command.PreparationType, command.Amount); } public void Handle(ICommandContext context, CommitTransactionPreparationCommand command) { context.Get<BankAccount>(command.AggregateRootId).CommitTransactionPreparation(command.TransactionId); } } }
using System.Threading.Tasks; using BankTransferSample.ApplicationMessages; using BankTransferSample.Commands; using BankTransferSample.Domain; using ECommon.Components; using ENode.Commanding; using ENode.Infrastructure; namespace BankTransferSample.CommandHandlers { /// <summary>银行账户相关命令处理 /// </summary> [Component] public class BankAccountCommandHandlers : ICommandHandler<CreateAccountCommand>, //开户 ICommandAsyncHandler<ValidateAccountCommand>, //验证账户是否合法 ICommandHandler<AddTransactionPreparationCommand>, //添加预操作 ICommandHandler<CommitTransactionPreparationCommand> //提交预操作 { public void Handle(ICommandContext context, CreateAccountCommand command) { context.Add(new BankAccount(command.AggregateRootId, command.Owner)); } public Task<AsyncTaskResult<IApplicationMessage>> HandleAsync(ValidateAccountCommand command) { var applicationMessage = default(ApplicationMessage); //此处应该会调用外部接口验证账号是否合法,这里仅仅简单通过账号是否等于00003判断是否合法;根据账号的合法性,返回不同的应用层消息 if (command.AggregateRootId == "00003") { applicationMessage = new AccountValidateFailedMessage(command.AggregateRootId, command.TransactionId, "账户不可以是00003."); } else { applicationMessage = new AccountValidatePassedMessage(command.AggregateRootId, command.TransactionId); } return Task.FromResult(new AsyncTaskResult<IApplicationMessage>(AsyncTaskStatus.Success, applicationMessage)); } public void Handle(ICommandContext context, AddTransactionPreparationCommand command) { context.Get<BankAccount>(command.AggregateRootId).AddTransactionPreparation(command.TransactionId, command.TransactionType, command.PreparationType, command.Amount); } public void Handle(ICommandContext context, CommitTransactionPreparationCommand command) { context.Get<BankAccount>(command.AggregateRootId).CommitTransactionPreparation(command.TransactionId); } } }
mit
C#
94bc774be5ee581d970a8c22f79181eb37d8748a
fix error in ShorContentHelper
csyntax/BlogSystem
src/BlogSystem.Web.Infrastructure/Helpers/Html/ShortContentHelper.cs
src/BlogSystem.Web.Infrastructure/Helpers/Html/ShortContentHelper.cs
namespace BlogSystem.Web.Infrastructure.Helpers.Html { using System.Web; using System.Web.Mvc; using AngleSharp.Parser.Html; public static class ShortContentHelper { public static IHtmlString Truncate(this HtmlHelper helper, string text) { var htmlParser = new HtmlParser(); var document = htmlParser.Parse(text); var p = document.QuerySelector("p"); if (p == null) { return helper.Raw(string.Empty); } return helper.Raw(p.InnerHtml); } } }
namespace BlogSystem.Web.Infrastructure.Helpers.Html { using System.Web; using System.Web.Mvc; using AngleSharp.Parser.Html; public static class ShortContentHelper { public static IHtmlString Truncate(this HtmlHelper helper, string text) { var htmlParser = new HtmlParser(); var document = htmlParser.Parse(text); var p = document.QuerySelector("p"); if (p is null) { return helper.Raw(string.Empty); } return helper.Raw(p.InnerHtml); } } }
mit
C#
181056b56ede7e784a9bd74cbcfd87726e97ec6e
Add ProfileMatches to CustomerRegistration response
TSEVOLLC/GIDX.SDK-csharp
src/GIDX.SDK/Models/CustomerIdentity/CustomerRegistrationResponse.cs
src/GIDX.SDK/Models/CustomerIdentity/CustomerRegistrationResponse.cs
using System; using System.Collections.Generic; namespace GIDX.SDK.Models.CustomerIdentity { public class CustomerRegistrationResponse : ResponseBase, IReasonCodes { public string MerchantCustomerID { get; set; } public decimal IdentityConfidenceScore { get; set; } public decimal FraudConfidenceScore { get; set; } public List<string> ReasonCodes { get; set; } public LocationDetail LocationDetail { get; set; } public ProfileMatch ProfileMatch { get; set; } public List<string> ProfileMatches { get; set; } public List<WatchCheck> WatchChecks { get; set; } } }
using System; using System.Collections.Generic; namespace GIDX.SDK.Models.CustomerIdentity { public class CustomerRegistrationResponse : ResponseBase, IReasonCodes { public string MerchantCustomerID { get; set; } public decimal IdentityConfidenceScore { get; set; } public decimal FraudConfidenceScore { get; set; } public List<string> ReasonCodes { get; set; } public LocationDetail LocationDetail { get; set; } public ProfileMatch ProfileMatch { get; set; } public List<WatchCheck> WatchChecks { get; set; } } }
mit
C#
8859210fbf28e8d95f7ecb8f30786dbd92886166
remove array
Appleseed/base,Appleseed/base
Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/SolrResponseItem.cs
Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/SolrResponseItem.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Appleseed.Base.Alerts.Model { class SolrResponseItem { public string id { get; set; } public string item_type { get; set; } public string address_1 { get; set; } public string city { get; set; } public string state { get; set; } public string classification { get; set; } public string country { get; set; } public string postal_code { get; set; } public string product_description { get; set; } public string product_quantity { get; set; } public string product_type { get; set; } public string code_info { get; set; } public string reason_for_recall { get; set; } public DateTime recall_initiation_date { get; set; } public string recall_number { get; set; } public string recalling_firm { get; set; } public string voluntary_mandated { get; set; } public DateTime report_date { get; set; } public string status { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Appleseed.Base.Alerts.Model { class SolrResponseItem { public string id { get; set; } public string item_type { get; set; } public string address_1 { get; set; } public string city { get; set; } public string state { get; set; } public string classification { get; set; } public string country { get; set; } public string postal_code { get; set; } public string product_description { get; set; } public string product_quantity { get; set; } public string product_type { get; set; } public string code_info { get; set; } public string reason_for_recall { get; set; } public DateTime recall_initiation_date { get; set; } public string recall_number { get; set; } public string recalling_firm { get; set; } public string[] voluntary_mandated { get; set; } public DateTime report_date { get; set; } public string[] status { get; set; } } }
apache-2.0
C#
033eefd955e2f2aeb1364fedb01ca26b9aaa65b4
Fix header names used in EmailMessageDecryptor
carbon/Amazon
src/Amazon.Ses.Extensions/EmailMessageDecryptor.cs
src/Amazon.Ses.Extensions/EmailMessageDecryptor.cs
using System.Security.Cryptography; using System.Text.Json; using Amazon.Kms; using Amazon.S3; namespace Amazon.Ses; public sealed class EmailMessageDecryptor { private readonly KmsClient _kms; public EmailMessageDecryptor(KmsClient kms) { _kms = kms; } public async Task<byte[]> DecryptAsync(S3Object encryptedBlob) { ArgumentNullException.ThrowIfNull(encryptedBlob); var cekAlg = encryptedBlob.Properties["x-amz-meta-x-amz-cek-alg"]; if (cekAlg is not "AES/GCM/NoPadding") { throw new Exception($"Expected AES/GCM/NoPadding. Was '{cekAlg}'"); } var encryptionContext = JsonSerializer.Deserialize<Dictionary<string, string>>(encryptedBlob.Properties["x-amz-meta-x-amz-matdesc"])!; byte[] envelopeKey = Convert.FromBase64String(encryptedBlob.Properties["x-amz-meta-x-amz-key-v2"]); byte[] envelopeIV = Convert.FromBase64String(encryptedBlob.Properties["x-amz-meta-x-amz-iv"]); long contentLength = long.Parse(encryptedBlob.Properties["x-amz-meta-x-amz-unencrypted-content-length"]); int tagLength = int.Parse(encryptedBlob.Properties["x-amz-meta-x-amz-tag-len"]); if (tagLength != 128) { throw new Exception($"x-amz-tag-len must be 128 bits. Was {tagLength}"); } if (contentLength > 10_000_000) { throw new Exception("> 10MB"); } string kmsCmkId = encryptionContext["kms_cmk_id"]; byte[] blobBytes = await encryptedBlob.ReadAsByteArrayAsync().ConfigureAwait(false); var tag = blobBytes[^16..]; var ciphertext = blobBytes[0..^16]; var decryptResult = await _kms.DecryptAsync(new DecryptRequest(kmsCmkId, envelopeKey, encryptionContext)); using var aes = new AesGcm(decryptResult.Plaintext); var message = new byte[contentLength]; aes.Decrypt(envelopeIV, ciphertext: ciphertext, tag: tag, plaintext: message); return message; } }
using System.Security.Cryptography; using System.Text.Json; using Amazon.Kms; using Amazon.S3; namespace Amazon.Ses; public sealed class EmailMessageDecryptor { private readonly KmsClient _kms; public EmailMessageDecryptor(KmsClient kms) { _kms = kms; } public async Task<byte[]> DecryptAsync(S3Object encryptedBlob) { ArgumentNullException.ThrowIfNull(encryptedBlob); var cekAlg = encryptedBlob.Properties["x-amz-cek-alg"]; if (cekAlg is not "AES/GCM/NoPadding") { throw new Exception($"Expected AES/GCM/NoPadding. Was '{cekAlg}'"); } var encryptionContext = JsonSerializer.Deserialize<Dictionary<string, string>>(encryptedBlob.Properties["x-amz-matdesc"])!; byte[] envelopeKey = Convert.FromBase64String(encryptedBlob.Properties["x-amz-key-v2"]); byte[] envelopeIV = Convert.FromBase64String(encryptedBlob.Properties["x-amz-iv"]); long contentLength = long.Parse(encryptedBlob.Properties["x-amz-unencrypted-content-length"]); int tagLength = int.Parse(encryptedBlob.Properties["x-amz-tag-len"]); if (tagLength != 128) { throw new Exception($"x-amz-tag-len must be 128 bits. Was {tagLength}"); } if (contentLength > 10_000_000) { throw new Exception("> 10MB"); } string kmsCmkId = encryptionContext["kms_cmk_id"]; byte[] blobBytes = await encryptedBlob.ReadAsByteArrayAsync().ConfigureAwait(false); var tag = blobBytes[^16..]; var ciphertext = blobBytes[0..^16]; var decryptResult = await _kms.DecryptAsync(new DecryptRequest(kmsCmkId, envelopeKey, encryptionContext)); using var aes = new AesGcm(decryptResult.Plaintext); var message = new byte[contentLength]; aes.Decrypt(envelopeIV, ciphertext: ciphertext, tag: tag, plaintext: message); return message; } }
mit
C#
63a959292990a287ab5aa336ce911386177db65b
Validate of MailConfiguration.
ZooPin/CK-Glouton,ZooPin/CK-Glouton,ZooPin/CK-Glouton,ZooPin/CK-Glouton
src/CK.Glouton.Server/Senders/MailConfiguration.cs
src/CK.Glouton.Server/Senders/MailConfiguration.cs
using CK.Glouton.Model.Server; using System; using System.Collections.Generic; using System.Text; namespace CK.Glouton.Server.Senders { public class MailConfiguration : IMailConfiguration { public string Name { get; set; } public string Email { get; set; } public string SmtpUsername { get; set; } public string SmtpPassword { get; set; } public string SmtpAdress { get; set; } public int SmptPort { get; set; } public bool Validate() { return !( string.IsNullOrEmpty(Name) || string.IsNullOrEmpty(Email) || string.IsNullOrEmpty(SmtpUsername) || string.IsNullOrEmpty(SmtpPassword) || string.IsNullOrEmpty(SmtpAdress) || SmptPort <= 0); } } }
using CK.Glouton.Model.Server; using System; using System.Collections.Generic; using System.Text; namespace CK.Glouton.Server.Senders { public class MailConfiguration : IMailConfiguration { public string Name { get; set; } public string Email { get; set; } public string SmtpUsername { get; set; } public string SmtpPassword { get; set; } public string SmtpAdress { get; set; } public int SmptPort { get; set; } public bool Validate() { return string.IsNullOrEmpty(Name) && string.IsNullOrEmpty(Email) && string.IsNullOrEmpty(SmtpUsername) && string.IsNullOrEmpty(SmtpPassword) && SmptPort != 0 && string.IsNullOrEmpty(SmtpAdress); } } }
mit
C#
44416fc4a4aec5535e5751bda5ec1a6fb010101b
improve logging in test user profile service
IdentityServer/IdentityServer4,chrisowhite/IdentityServer4,MienDev/IdentityServer4,chrisowhite/IdentityServer4,siyo-wang/IdentityServer4,jbijlsma/IdentityServer4,siyo-wang/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,MienDev/IdentityServer4,chrisowhite/IdentityServer4,siyo-wang/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,jbijlsma/IdentityServer4,jbijlsma/IdentityServer4,jbijlsma/IdentityServer4
src/IdentityServer4/Test/TestUserProfileService.cs
src/IdentityServer4/Test/TestUserProfileService.cs
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityServer4.Extensions; using IdentityServer4.Models; using IdentityServer4.Services; using Microsoft.Extensions.Logging; using System.Linq; using System.Threading.Tasks; namespace IdentityServer4.Test { public class TestUserProfileService : IProfileService { private readonly ILogger<TestUserProfileService> _logger; private readonly TestUserStore _users; public TestUserProfileService(TestUserStore users, ILogger<TestUserProfileService> logger) { _users = users; _logger = logger; } public Task GetProfileDataAsync(ProfileDataRequestContext context) { _logger.LogDebug("Get profile called for subject {subject} from client {client} with claim types{claimTypes} via {caller}", context.Subject.GetSubjectId(), context.Client.ClientName ?? context.Client.ClientId, context.RequestedClaimTypes, context.Caller); if (context.RequestedClaimTypes.Any()) { var user = _users.FindBySubjectId(context.Subject.GetSubjectId()); context.AddFilteredClaims(user.Claims); } return Task.FromResult(0); } public Task IsActiveAsync(IsActiveContext context) { context.IsActive = true; return Task.FromResult(0); } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityServer4.Extensions; using IdentityServer4.Models; using IdentityServer4.Services; using Microsoft.Extensions.Logging; using System.Linq; using System.Threading.Tasks; namespace IdentityServer4.Test { public class TestUserProfileService : IProfileService { private readonly ILogger<TestUserProfileService> _logger; private readonly TestUserStore _users; public TestUserProfileService(TestUserStore users, ILogger<TestUserProfileService> logger) { _users = users; _logger = logger; } public Task GetProfileDataAsync(ProfileDataRequestContext context) { _logger.LogDebug("Get profile called for {subject} from {client} with {claimTypes} because {caller}", context.Subject.GetSubjectId(), context.Client.ClientName, context.RequestedClaimTypes, context.Caller); if (context.RequestedClaimTypes.Any()) { var user = _users.FindBySubjectId(context.Subject.GetSubjectId()); context.AddFilteredClaims(user.Claims); } return Task.FromResult(0); } public Task IsActiveAsync(IsActiveContext context) { context.IsActive = true; return Task.FromResult(0); } } }
apache-2.0
C#
0a04f87b4b73dec646aea79f3b1726578cc71fae
Use IntPtr.Zero instead of new IntPtr(0)
vbfox/pinvoke,AArnott/pinvoke,jmelosegui/pinvoke
src/Kernel32.Desktop/Kernel32+SafeLibraryHandle.cs
src/Kernel32.Desktop/Kernel32+SafeLibraryHandle.cs
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace PInvoke { using System; using System.Runtime.InteropServices; /// <content> /// Contains the <see cref="SafeObjectHandle"/> nested type. /// </content> public static partial class Kernel32 { /// <summary> /// Represents a library handle that can be closed with <see cref="FreeLibrary"/>. /// </summary> public class SafeLibraryHandle : SafeHandle { public static readonly SafeLibraryHandle Null = new SafeLibraryHandle(IntPtr.Zero, false); /// <summary> /// Initializes a new instance of the <see cref="SafeLibraryHandle"/> class. /// </summary> public SafeLibraryHandle() : base(INVALID_HANDLE_VALUE, true) { } /// <summary> /// Initializes a new instance of the <see cref="SafeLibraryHandle"/> class. /// </summary> /// <param name="preexistingHandle">An object that represents the pre-existing handle to use.</param> /// <param name="ownsHandle"><see langword="true"/> to reliably release the handle during the finalization /// phase; <see langword="false"/> to prevent reliable release.</param> public SafeLibraryHandle(IntPtr preexistingHandle, bool ownsHandle) : base(INVALID_HANDLE_VALUE, ownsHandle) { this.SetHandle(preexistingHandle); } /// <inheritdoc /> public override bool IsInvalid => this.handle == INVALID_HANDLE_VALUE || this.handle == IntPtr.Zero; /// <inheritdoc /> protected override bool ReleaseHandle() => FreeLibrary(this.handle); } } }
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace PInvoke { using System; using System.Runtime.InteropServices; /// <content> /// Contains the <see cref="SafeObjectHandle"/> nested type. /// </content> public static partial class Kernel32 { /// <summary> /// Represents a library handle that can be closed with <see cref="FreeLibrary"/>. /// </summary> public class SafeLibraryHandle : SafeHandle { public static readonly SafeLibraryHandle Null = new SafeLibraryHandle(new IntPtr(0), false); /// <summary> /// Initializes a new instance of the <see cref="SafeLibraryHandle"/> class. /// </summary> public SafeLibraryHandle() : base(INVALID_HANDLE_VALUE, true) { } /// <summary> /// Initializes a new instance of the <see cref="SafeLibraryHandle"/> class. /// </summary> /// <param name="preexistingHandle">An object that represents the pre-existing handle to use.</param> /// <param name="ownsHandle"><see langword="true"/> to reliably release the handle during the finalization /// phase; <see langword="false"/> to prevent reliable release.</param> public SafeLibraryHandle(IntPtr preexistingHandle, bool ownsHandle) : base(INVALID_HANDLE_VALUE, ownsHandle) { this.SetHandle(preexistingHandle); } /// <inheritdoc /> public override bool IsInvalid => this.handle == INVALID_HANDLE_VALUE || this.handle == IntPtr.Zero; /// <inheritdoc /> protected override bool ReleaseHandle() => FreeLibrary(this.handle); } } }
mit
C#
c16b95fe9f1fd5a847e3919426982c053c3f48e4
Add new overload to DatabaseBuilder TryCreateDatabase method
Ackara/Daterpillar
src/Tests.Daterpillar/Utilities/DatabaseBuilder.cs
src/Tests.Daterpillar/Utilities/DatabaseBuilder.cs
using Gigobyte.Daterpillar.Transformation; using Gigobyte.Daterpillar.Transformation.Template; using System; using System.Data; namespace Tests.Daterpillar.Utilities { public static class DatabaseBuilder { public static bool TryResetDatabase(string connectionName, ITemplate template) { var settings = System.Configuration.ConfigurationManager.ConnectionStrings[connectionName]; var connection = (IDbConnection)Activator.CreateInstance(Type.GetType(settings.ProviderName)); var schema = Schema.Load(Test.Data.GetFile(Test.File.DataSoftXDDL).OpenRead()); return TryResetDatabase(connection, schema, template); } public static bool TryResetDatabase(IDbConnection connection, ITemplate template) { var schema = Schema.Load(Test.Data.GetFile(Test.File.DataSoftXDDL).OpenRead()); return TryResetDatabase(connection, schema, template); } public static bool TryResetDatabase(IDbConnection connection, Schema schema, ITemplate template) { try { TruncateDatabase(connection, schema); CreateSchema(connection, schema, template); return true; } catch (System.Data.Common.DbException ex) { System.Diagnostics.Debug.WriteLine($"ERROR: {ex.ErrorCode}"); System.Diagnostics.Debug.WriteLine(ex.Message); return false; } finally { connection?.Dispose(); } } internal static void TruncateDatabase(IDbConnection connection, Schema schema) { if (connection.State != ConnectionState.Open) connection.Open(); using (var commmand = connection.CreateCommand()) { for (int i = schema.Tables.Count - 1; i >= 0; i--) { commmand.CommandText = $"DROP TABLE {schema.Tables[i].Name};"; commmand.ExecuteNonQuery(); } } } internal static void CreateSchema(IDbConnection connection, Schema schema, ITemplate template) { if (connection.State != ConnectionState.Open) connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = template.Transform(schema); command.ExecuteNonQuery(); } } } }
using Gigobyte.Daterpillar.Transformation; using Gigobyte.Daterpillar.Transformation.Template; using System.Data; namespace Tests.Daterpillar.Utilities { public static class DatabaseBuilder { public static bool TryResetDatabase(IDbConnection connection, ITemplate template) { var schema = Schema.Load(Test.Data.GetFile(Test.File.DataSoftXDDL).OpenRead()); return TryResetDatabase(connection, schema, template); } public static bool TryResetDatabase(IDbConnection connection, Schema schema, ITemplate template) { try { TruncateDatabase(connection, schema); CreateSchema(connection, schema, template); return true; } catch (System.Data.Common.DbException ex) { System.Diagnostics.Debug.WriteLine($"ERROR: {ex.ErrorCode}"); System.Diagnostics.Debug.WriteLine(ex.Message); return false; } finally { connection?.Dispose(); } } internal static void TruncateDatabase(IDbConnection connection, Schema schema) { if (connection.State != ConnectionState.Open) connection.Open(); using (var commmand = connection.CreateCommand()) { for (int i = schema.Tables.Count - 1; i >= 0; i--) { commmand.CommandText = $"DROP TABLE {schema.Tables[i].Name};"; commmand.ExecuteNonQuery(); } } } internal static void CreateSchema(IDbConnection connection, Schema schema, ITemplate template) { if (connection.State != ConnectionState.Open) connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = template.Transform(schema); command.ExecuteNonQuery(); } } } }
mit
C#
fbb7de82c81bd23429b29c9f8d0135fb666671c3
Remove argument check.
kienct89/roslyn,dotnet/roslyn,jcouv/roslyn,3F/roslyn,srivatsn/roslyn,nguerrera/roslyn,bkoelman/roslyn,KevinH-MS/roslyn,devharis/roslyn,MihaMarkic/roslyn-prank,YOTOV-LIMITED/roslyn,wvdd007/roslyn,MattWindsor91/roslyn,CyrusNajmabadi/roslyn,jonatassaraiva/roslyn,orthoxerox/roslyn,GuilhermeSa/roslyn,MattWindsor91/roslyn,heejaechang/roslyn,Shiney/roslyn,Hosch250/roslyn,natgla/roslyn,huoxudong125/roslyn,a-ctor/roslyn,paulvanbrenk/roslyn,bartdesmet/roslyn,MichalStrehovsky/roslyn,kelltrick/roslyn,KiloBravoLima/roslyn,michalhosala/roslyn,nemec/roslyn,khyperia/roslyn,ahmedshuhel/roslyn,jonatassaraiva/roslyn,pjmagee/roslyn,nguerrera/roslyn,MichalStrehovsky/roslyn,khyperia/roslyn,krishnarajbb/roslyn,v-codeel/roslyn,brettfo/roslyn,MatthieuMEZIL/roslyn,akrisiun/roslyn,evilc0des/roslyn,amcasey/roslyn,poizan42/roslyn,jhendrixMSFT/roslyn,jonatassaraiva/roslyn,aelij/roslyn,VShangxiao/roslyn,KirillOsenkov/roslyn,zooba/roslyn,Hosch250/roslyn,SeriaWei/roslyn,basoundr/roslyn,Maxwe11/roslyn,nagyistoce/roslyn,oberxon/roslyn,jroggeman/roslyn,CaptainHayashi/roslyn,physhi/roslyn,amcasey/roslyn,balajikris/roslyn,jroggeman/roslyn,budcribar/roslyn,robinsedlaczek/roslyn,dovzhikova/roslyn,doconnell565/roslyn,SeriaWei/roslyn,Pvlerick/roslyn,zooba/roslyn,gafter/roslyn,bbarry/roslyn,jeffanders/roslyn,moozzyk/roslyn,zmaruo/roslyn,lisong521/roslyn,Hosch250/roslyn,tang7526/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,paulvanbrenk/roslyn,supriyantomaftuh/roslyn,xasx/roslyn,sharadagrawal/Roslyn,magicbing/roslyn,MatthieuMEZIL/roslyn,jeremymeng/roslyn,ericfe-ms/roslyn,enginekit/roslyn,VPashkov/roslyn,danielcweber/roslyn,abock/roslyn,tmat/roslyn,khellang/roslyn,khyperia/roslyn,jbhensley/roslyn,drognanar/roslyn,ljw1004/roslyn,sharwell/roslyn,jasonmalinowski/roslyn,mattscheffer/roslyn,ilyes14/roslyn,doconnell565/roslyn,stephentoub/roslyn,drognanar/roslyn,xoofx/roslyn,GuilhermeSa/roslyn,tannergooding/roslyn,KevinRansom/roslyn,mavasani/roslyn,stephentoub/roslyn,diryboy/roslyn,russpowers/roslyn,AnthonyDGreen/roslyn,natgla/roslyn,mattwar/roslyn,ericfe-ms/roslyn,MichalStrehovsky/roslyn,taylorjonl/roslyn,xoofx/roslyn,reaction1989/roslyn,balajikris/roslyn,lisong521/roslyn,MattWindsor91/roslyn,swaroop-sridhar/roslyn,wvdd007/roslyn,a-ctor/roslyn,MattWindsor91/roslyn,budcribar/roslyn,eriawan/roslyn,jasonmalinowski/roslyn,stebet/roslyn,thomaslevesque/roslyn,OmarTawfik/roslyn,jaredpar/roslyn,Giftednewt/roslyn,KevinRansom/roslyn,yeaicc/roslyn,zmaruo/roslyn,managed-commons/roslyn,HellBrick/roslyn,jamesqo/roslyn,CyrusNajmabadi/roslyn,antonssonj/roslyn,tmeschter/roslyn,VPashkov/roslyn,RipCurrent/roslyn,jroggeman/roslyn,MihaMarkic/roslyn-prank,dpoeschl/roslyn,RipCurrent/roslyn,jcouv/roslyn,mavasani/roslyn,jaredpar/roslyn,xasx/roslyn,tvand7093/roslyn,Pvlerick/roslyn,jaredpar/roslyn,panopticoncentral/roslyn,bbarry/roslyn,nagyistoce/roslyn,wvdd007/roslyn,aelij/roslyn,rgani/roslyn,jasonmalinowski/roslyn,magicbing/roslyn,moozzyk/roslyn,AlexisArce/roslyn,leppie/roslyn,bbarry/roslyn,grianggrai/roslyn,RipCurrent/roslyn,danielcweber/roslyn,VitalyTVA/roslyn,ilyes14/roslyn,vslsnap/roslyn,3F/roslyn,bartdesmet/roslyn,supriyantomaftuh/roslyn,kienct89/roslyn,nguerrera/roslyn,tvand7093/roslyn,jeffanders/roslyn,AArnott/roslyn,antiufo/roslyn,yjfxfjch/roslyn,pjmagee/roslyn,balajikris/roslyn,krishnarajbb/roslyn,michalhosala/roslyn,AlekseyTs/roslyn,ahmedshuhel/roslyn,huoxudong125/roslyn,natgla/roslyn,grianggrai/roslyn,FICTURE7/roslyn,mirhagk/roslyn,eriawan/roslyn,KirillOsenkov/roslyn,AnthonyDGreen/roslyn,mgoertz-msft/roslyn,pdelvo/roslyn,KirillOsenkov/roslyn,srivatsn/roslyn,VitalyTVA/roslyn,leppie/roslyn,mattwar/roslyn,evilc0des/roslyn,aelij/roslyn,oocx/roslyn,natidea/roslyn,3F/roslyn,dovzhikova/roslyn,paulvanbrenk/roslyn,michalhosala/roslyn,panopticoncentral/roslyn,FICTURE7/roslyn,gafter/roslyn,tmeschter/roslyn,robinsedlaczek/roslyn,tmat/roslyn,yjfxfjch/roslyn,mmitche/roslyn,EricArndt/roslyn,weltkante/roslyn,mmitche/roslyn,akrisiun/roslyn,aanshibudhiraja/Roslyn,dovzhikova/roslyn,EricArndt/roslyn,vcsjones/roslyn,pdelvo/roslyn,ErikSchierboom/roslyn,jeffanders/roslyn,shyamnamboodiripad/roslyn,jbhensley/roslyn,EricArndt/roslyn,Giftednewt/roslyn,AlekseyTs/roslyn,bkoelman/roslyn,OmarTawfik/roslyn,TyOverby/roslyn,basoundr/roslyn,zooba/roslyn,genlu/roslyn,jkotas/roslyn,AnthonyDGreen/roslyn,brettfo/roslyn,KamalRathnayake/roslyn,stephentoub/roslyn,mattscheffer/roslyn,sharwell/roslyn,budcribar/roslyn,rgani/roslyn,xoofx/roslyn,swaroop-sridhar/roslyn,cston/roslyn,ValentinRueda/roslyn,huoxudong125/roslyn,GuilhermeSa/roslyn,AArnott/roslyn,orthoxerox/roslyn,kelltrick/roslyn,managed-commons/roslyn,reaction1989/roslyn,ErikSchierboom/roslyn,magicbing/roslyn,jkotas/roslyn,CaptainHayashi/roslyn,KevinH-MS/roslyn,mseamari/Stuff,bkoelman/roslyn,jmarolf/roslyn,Inverness/roslyn,HellBrick/roslyn,reaction1989/roslyn,mseamari/Stuff,Giftednewt/roslyn,antonssonj/roslyn,CaptainHayashi/roslyn,physhi/roslyn,mgoertz-msft/roslyn,jeremymeng/roslyn,khellang/roslyn,TyOverby/roslyn,thomaslevesque/roslyn,dpoeschl/roslyn,davkean/roslyn,AmadeusW/roslyn,oberxon/roslyn,yjfxfjch/roslyn,leppie/roslyn,agocke/roslyn,thomaslevesque/roslyn,cston/roslyn,managed-commons/roslyn,akrisiun/roslyn,poizan42/roslyn,YOTOV-LIMITED/roslyn,tang7526/roslyn,vslsnap/roslyn,nemec/roslyn,oocx/roslyn,krishnarajbb/roslyn,VitalyTVA/roslyn,dpoeschl/roslyn,genlu/roslyn,natidea/roslyn,VSadov/roslyn,enginekit/roslyn,zmaruo/roslyn,weltkante/roslyn,robinsedlaczek/roslyn,tannergooding/roslyn,lorcanmooney/roslyn,ahmedshuhel/roslyn,ilyes14/roslyn,taylorjonl/roslyn,mirhagk/roslyn,DustinCampbell/roslyn,nagyistoce/roslyn,Pvlerick/roslyn,sharadagrawal/Roslyn,diryboy/roslyn,agocke/roslyn,enginekit/roslyn,mavasani/roslyn,FICTURE7/roslyn,taylorjonl/roslyn,AlexisArce/roslyn,orthoxerox/roslyn,mgoertz-msft/roslyn,devharis/roslyn,amcasey/roslyn,Shiney/roslyn,mirhagk/roslyn,mattwar/roslyn,cston/roslyn,dotnet/roslyn,tmat/roslyn,jamesqo/roslyn,OmarTawfik/roslyn,yeaicc/roslyn,lorcanmooney/roslyn,jcouv/roslyn,physhi/roslyn,sharadagrawal/Roslyn,KiloBravoLima/roslyn,tmeschter/roslyn,Inverness/roslyn,kelltrick/roslyn,yeaicc/roslyn,jhendrixMSFT/roslyn,drognanar/roslyn,ericfe-ms/roslyn,Maxwe11/roslyn,abock/roslyn,mseamari/Stuff,Shiney/roslyn,jbhensley/roslyn,oberxon/roslyn,basoundr/roslyn,antiufo/roslyn,davkean/roslyn,mattscheffer/roslyn,heejaechang/roslyn,VShangxiao/roslyn,xasx/roslyn,KamalRathnayake/roslyn,v-codeel/roslyn,oocx/roslyn,CyrusNajmabadi/roslyn,DustinCampbell/roslyn,HellBrick/roslyn,v-codeel/roslyn,lorcanmooney/roslyn,eriawan/roslyn,AArnott/roslyn,russpowers/roslyn,doconnell565/roslyn,genlu/roslyn,VSadov/roslyn,jkotas/roslyn,weltkante/roslyn,nemec/roslyn,AmadeusW/roslyn,jamesqo/roslyn,supriyantomaftuh/roslyn,stebet/roslyn,KiloBravoLima/roslyn,vslsnap/roslyn,danielcweber/roslyn,AlexisArce/roslyn,srivatsn/roslyn,VPashkov/roslyn,TyOverby/roslyn,agocke/roslyn,Maxwe11/roslyn,natidea/roslyn,brettfo/roslyn,abock/roslyn,devharis/roslyn,ljw1004/roslyn,KevinH-MS/roslyn,aanshibudhiraja/Roslyn,tvand7093/roslyn,antiufo/roslyn,jmarolf/roslyn,russpowers/roslyn,jhendrixMSFT/roslyn,moozzyk/roslyn,lisong521/roslyn,a-ctor/roslyn,kienct89/roslyn,mmitche/roslyn,KamalRathnayake/roslyn,jmarolf/roslyn,ljw1004/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,rgani/roslyn,AmadeusW/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,diryboy/roslyn,tang7526/roslyn,ValentinRueda/roslyn,KevinRansom/roslyn,MihaMarkic/roslyn-prank,ErikSchierboom/roslyn,SeriaWei/roslyn,pdelvo/roslyn,Inverness/roslyn,panopticoncentral/roslyn,stebet/roslyn,MatthieuMEZIL/roslyn,aanshibudhiraja/Roslyn,poizan42/roslyn,davkean/roslyn,evilc0des/roslyn,swaroop-sridhar/roslyn,dotnet/roslyn,AlekseyTs/roslyn,pjmagee/roslyn,sharwell/roslyn,ValentinRueda/roslyn,gafter/roslyn,grianggrai/roslyn,VShangxiao/roslyn,heejaechang/roslyn,vcsjones/roslyn,vcsjones/roslyn,jeremymeng/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,bartdesmet/roslyn,VSadov/roslyn,antonssonj/roslyn,shyamnamboodiripad/roslyn,DustinCampbell/roslyn,YOTOV-LIMITED/roslyn,khellang/roslyn
src/EditorFeatures/Core/Tagging/AsynchronousTaggerContext.cs
src/EditorFeatures/Core/Tagging/AsynchronousTaggerContext.cs
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Tagging { internal class AsynchronousTaggerContext<TTag, TState> where TTag : ITag { public TState State { get; set; } public IEnumerable<DocumentSnapshotSpan> SpansToTag { get; } public SnapshotPoint? CaretPosition { get; } public CancellationToken CancellationToken { get; } internal IEnumerable<DocumentSnapshotSpan> spansTagged; internal ImmutableArray<ITagSpan<TTag>>.Builder tagSpans = ImmutableArray.CreateBuilder<ITagSpan<TTag>>(); internal AsynchronousTaggerContext( TState state, IEnumerable<DocumentSnapshotSpan> spansToTag, SnapshotPoint? caretPosition, CancellationToken cancellationToken) { this.State = state; this.SpansToTag = spansToTag; this.CaretPosition = caretPosition; this.CancellationToken = cancellationToken; this.spansTagged = spansToTag; } public void AddTag(ITagSpan<TTag> tag) { tagSpans.Add(tag); } /// <summary> /// Used to allow taggers to indicate what spans were actually tagged. This is useful /// when the tagger decides to tag a different span than the entire file. If a sub-span /// of a document is tagged then the tagger infrastructure will keep previously computed /// tags from before and after the sub-span and merge them with the newly produced tags. /// </summary> public void SetSpansTagged(IEnumerable<DocumentSnapshotSpan> spansTagged) { this.spansTagged = spansTagged; } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Tagging { internal class AsynchronousTaggerContext<TTag, TState> where TTag : ITag { public TState State { get; set; } public IEnumerable<DocumentSnapshotSpan> SpansToTag { get; } public SnapshotPoint? CaretPosition { get; } public CancellationToken CancellationToken { get; } internal IEnumerable<DocumentSnapshotSpan> spansTagged; internal ImmutableArray<ITagSpan<TTag>>.Builder tagSpans = ImmutableArray.CreateBuilder<ITagSpan<TTag>>(); internal AsynchronousTaggerContext( TState state, IEnumerable<DocumentSnapshotSpan> spansToTag, SnapshotPoint? caretPosition, CancellationToken cancellationToken) { this.State = state; this.SpansToTag = spansToTag; this.CaretPosition = caretPosition; this.CancellationToken = cancellationToken; this.spansTagged = spansToTag; } public void AddTag(ITagSpan<TTag> tag) { tagSpans.Add(tag); } /// <summary> /// Used to allow taggers to indicate what spans were actually tagged. This is useful /// when the tagger decides to tag a different span than the entire file. If a sub-span /// of a document is tagged then the tagger infrastructure will keep previously computed /// tags from before and after the sub-span and merge them with the newly produced tags. /// </summary> public void SetSpansTagged(IEnumerable<DocumentSnapshotSpan> spansTagged) { if (spansTagged != null) { throw new InvalidOperationException("'spansTagged' has already been set."); } this.spansTagged = spansTagged; } } }
mit
C#
b2e82cbcfb1fbf31c2037aafc382b33d03f2d2d6
Reduce collision velocity from ship-to-asteroid
iridinite/shiftdrive
Client/Asteroid.cs
Client/Asteroid.cs
/* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using Microsoft.Xna.Framework; namespace ShiftDrive { /// <summary> /// A <seealso cref="GameObject"/> representing a single asteroid. /// </summary> internal sealed class Asteroid : GameObject { public Asteroid() { type = ObjectType.Asteroid; facing = Utils.RNG.Next(0, 360); spritename = "map/asteroid"; color = Color.White; bounding = 7f; } public override void Update(GameState world, float deltaTime) { base.Update(world, deltaTime); } protected override void OnCollision(GameObject other, float dist) { base.OnCollision(other, dist); // asteroids shouldn't move so much if ships bump into them, because // they should look heavy and sluggish if (other.type == ObjectType.AIShip || other.type == ObjectType.PlayerShip) this.velocity *= 0.5f; } public override bool IsTerrain() { return true; } } }
/* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using Microsoft.Xna.Framework; namespace ShiftDrive { /// <summary> /// A <seealso cref="GameObject"/> representing a single asteroid. /// </summary> internal sealed class Asteroid : GameObject { public Asteroid() { type = ObjectType.Asteroid; facing = Utils.RNG.Next(0, 360); spritename = "map/asteroid"; color = Color.White; bounding = 7f; } public override void Update(GameState world, float deltaTime) { base.Update(world, deltaTime); } public override bool IsTerrain() { return true; } } }
bsd-3-clause
C#
e5f81d2ca394a154082ae8290ab37379116a93ec
Revert "Changed contact email"
PoLaKoSz/CodeHub,aalok05/CodeHub
CodeHub/Views/Settings/AboutSettingsView.xaml.cs
CodeHub/Views/Settings/AboutSettingsView.xaml.cs
using CodeHub.ViewModels; using System; using Windows.ApplicationModel; using Windows.System; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace CodeHub.Views { public sealed partial class AboutSettingsView : SettingsDetailPageBase { private SettingsViewModel ViewModel; public AboutSettingsView() { this.InitializeComponent(); ViewModel = new SettingsViewModel(); this.DataContext = ViewModel; } private void OnCurrentStateChanged(object sender, VisualStateChangedEventArgs e) { if (e.NewState != null) TryNavigateBackForDesktopState(e.NewState.Name); } private async void RateButton_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e) { await Launcher.LaunchUriAsync( new Uri($"ms-windows-store://review/?PFN={Package.Current.Id.FamilyName}")); } private async void TwitterButton_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e) { await Launcher.LaunchUriAsync( new Uri("https://twitter.com/devaalok")); } private async void GithubButton_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e) { await GalaSoft.MvvmLight.Ioc.SimpleIoc.Default.GetInstance<Services.IAsyncNavigationService>().NavigateAsync(typeof(RepoDetailView), "Repository", "aalok05/CodeHub"); } private async void EmailButton_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e) { await Launcher.LaunchUriAsync( new Uri("mailto:contact@devnextdoor.com")); } } }
using CodeHub.ViewModels; using System; using Windows.ApplicationModel; using Windows.System; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace CodeHub.Views { public sealed partial class AboutSettingsView : SettingsDetailPageBase { private SettingsViewModel ViewModel; public AboutSettingsView() { this.InitializeComponent(); ViewModel = new SettingsViewModel(); this.DataContext = ViewModel; } private void OnCurrentStateChanged(object sender, VisualStateChangedEventArgs e) { if (e.NewState != null) TryNavigateBackForDesktopState(e.NewState.Name); } private async void RateButton_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e) { await Launcher.LaunchUriAsync( new Uri($"ms-windows-store://review/?PFN={Package.Current.Id.FamilyName}")); } private async void TwitterButton_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e) { await Launcher.LaunchUriAsync( new Uri("https://twitter.com/devaalok")); } private async void GithubButton_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e) { await GalaSoft.MvvmLight.Ioc.SimpleIoc.Default.GetInstance<Services.IAsyncNavigationService>().NavigateAsync(typeof(RepoDetailView), "Repository", "aalok05/CodeHub"); } private async void EmailButton_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e) { await Launcher.LaunchUriAsync( new Uri("mailto:aalok@devnextdoor.com")); } } }
mit
C#
553133b59b0079b8bcb84320316b9a56ea94e0cb
Fix is-type function typo
yeaicc/ConfuserEx,Desolath/ConfuserEx3,timnboys/ConfuserEx,engdata/ConfuserEx,Desolath/Confuserex
Confuser.Core/Project/Patterns/IsTypeFunction.cs
Confuser.Core/Project/Patterns/IsTypeFunction.cs
using System; using System.Text; using System.Text.RegularExpressions; using dnlib.DotNet; namespace Confuser.Core.Project.Patterns { /// <summary> /// A function that indicate the type of type(?). /// </summary> public class IsTypeFunction : PatternFunction { internal const string FnName = "is-type"; /// <inheritdoc /> public override string Name { get { return FnName; } } /// <inheritdoc /> public override int ArgumentCount { get { return 1; } } /// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { TypeDef type = definition as TypeDef; if (type == null && definition is IMemberDef) type = ((IMemberDef)definition).DeclaringType; if (type == null) return false; string typeRegex = Arguments[0].Evaluate(definition).ToString(); var typeType = new StringBuilder(); if (type.IsEnum) typeType.Append("enum "); if (type.IsInterface) typeType.Append("interface "); if (type.IsValueType) typeType.Append("valuetype "); if (type.IsDelegate()) typeType.Append("delegate "); if (type.IsAbstract) typeType.Append("abstract "); if (type.IsNested) typeType.Append("nested "); if (type.IsSerializable) typeType.Append("serializable "); return Regex.IsMatch(typeType.ToString(), typeRegex); } } }
using System; using System.Text; using System.Text.RegularExpressions; using dnlib.DotNet; namespace Confuser.Core.Project.Patterns { /// <summary> /// A function that indicate the type of type(?). /// </summary> public class IsTypeFunction : PatternFunction { internal const string FnName = "is-type"; /// <inheritdoc /> public override string Name { get { return FnName; } } /// <inheritdoc /> public override int ArgumentCount { get { return 1; } } /// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { TypeDef type = definition as TypeDef; if (type == null && definition is IMemberDef) type = ((IMemberDef)type).DeclaringType; if (type == null) return false; string typeRegex = Arguments[0].Evaluate(definition).ToString(); var typeType = new StringBuilder(); if (type.IsEnum) typeType.Append("enum "); if (type.IsInterface) typeType.Append("interface "); if (type.IsValueType) typeType.Append("valuetype "); if (type.IsDelegate()) typeType.Append("delegate "); if (type.IsAbstract) typeType.Append("abstract "); if (type.IsNested) typeType.Append("nested "); if (type.IsSerializable) typeType.Append("serializable "); return Regex.IsMatch(typeType.ToString(), typeRegex); } } }
mit
C#
1735a68369a4e79fa26e6b77d4a75013c1490360
Update Delegacja.cs
organizacjaJM/rezerwacjaKawa
Delegacja.cs
Delegacja.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DelegacjeGeneryczne { class Program { delegate void Delegacja(string s); static void Main(string[] args) { // delegacje void z max 16 argumentami typowymi. Liczba parematerow musi buyc taka sama jak typów Action<string, string> delAction = (p, q) => Console.WriteLine("Czy działa: " + p + q); delAction("ala", " ala kota"); Func<string, string> delFunc = p => p.ToUpper(); Console.WriteLine(delFunc("csharp")); } } } //dziala repo
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DelegacjeGeneryczne { class Program { delegate void Delegacja(string s); static void Main(string[] args) { // delegacje void z max 16 argumentami typowymi. Liczba parematerow musi buyc taka sama jak typów Action<string, string> delAction = (p, q) => Console.WriteLine("Czy działa: " + p + q); delAction("ala", " ala kota"); Func<string, string> delFunc = p => p.ToUpper(); Console.WriteLine(delFunc("csharp")); } } }
mit
C#
b737872521c908fb6c99caf5a8b8a71619eb3847
Add DoNotAwait for WinRT style tasks
pingzing/digi-transit-10
DigiTransit10/ExtensionMethods/TaskExtensions.cs
DigiTransit10/ExtensionMethods/TaskExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Foundation; namespace DigiTransit10.ExtensionMethods { public static class TaskExtensions { public static void DoNotAwait(this Task task) { } public static void DoNotAwait<T>(this Task<T> task) { } public static void DoNotAwait(this IAsyncAction task) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DigiTransit10.ExtensionMethods { public static class TaskExtensions { public static void DoNotAwait(this Task task) { } public static void DoNotAwait<T>(this Task<T> task) { } } }
mit
C#
7ddcae8f9646162e10ef5fad9b76505a5b3a2570
Fix in CosmosDbGremlinServer, should really fit into the common style of handling configuration.
ExRam/ExRam.Gremlinq
ExRam.Gremlinq.CosmosDb/CosmosDbGremlinServer.cs
ExRam.Gremlinq.CosmosDb/CosmosDbGremlinServer.cs
using Gremlin.Net.Driver; using Microsoft.Extensions.Options; namespace ExRam.Gremlinq.CosmosDb { public class CosmosDbGremlinServer : GremlinServer { public CosmosDbGremlinServer(IOptions<CosmosDbGraphConfiguration> configuration) : this(configuration.Value) { } private CosmosDbGremlinServer(CosmosDbGraphConfiguration configuration) : base( configuration.Hostname, configuration.Port, configuration.EnableSsl, $"/dbs/{configuration.Database}/colls/{configuration.GraphName}", configuration.AuthKey) { } } }
using Gremlin.Net.Driver; namespace ExRam.Gremlinq.CosmosDb { public class CosmosDbGremlinServer : GremlinServer { public CosmosDbGremlinServer(CosmosDbGraphConfiguration configuration) : base( configuration.Hostname, configuration.Port, configuration.EnableSsl, $"/dbs/{configuration.Database}/colls/{configuration.GraphName}", configuration.AuthKey) { } } }
mit
C#
5e7f8e7157ca278cc029fe66080cbffb2ce380fd
Add test for non invariant default locale and test for locale with collation
pgavlin/corefx,ravimeda/corefx,benpye/corefx,mmitche/corefx,wtgodbe/corefx,Yanjing123/corefx,shahid-pk/corefx,parjong/corefx,twsouthwick/corefx,mokchhya/corefx,ViktorHofer/corefx,dotnet-bot/corefx,n1ghtmare/corefx,wtgodbe/corefx,weltkante/corefx,alexperovich/corefx,Petermarcu/corefx,marksmeltzer/corefx,jcme/corefx,mellinoe/corefx,jcme/corefx,pallavit/corefx,JosephTremoulet/corefx,nchikanov/corefx,tijoytom/corefx,mmitche/corefx,nbarbettini/corefx,tijoytom/corefx,rjxby/corefx,the-dwyer/corefx,ravimeda/corefx,seanshpark/corefx,nchikanov/corefx,axelheer/corefx,ptoonen/corefx,dhoehna/corefx,the-dwyer/corefx,marksmeltzer/corefx,iamjasonp/corefx,tstringer/corefx,manu-silicon/corefx,cartermp/corefx,ViktorHofer/corefx,PatrickMcDonald/corefx,wtgodbe/corefx,axelheer/corefx,Ermiar/corefx,mokchhya/corefx,kkurni/corefx,billwert/corefx,PatrickMcDonald/corefx,alexandrnikitin/corefx,alphonsekurian/corefx,gkhanna79/corefx,zhenlan/corefx,YoupHulsebos/corefx,krytarowski/corefx,jlin177/corefx,JosephTremoulet/corefx,shimingsg/corefx,khdang/corefx,Petermarcu/corefx,iamjasonp/corefx,benjamin-bader/corefx,benpye/corefx,jlin177/corefx,heXelium/corefx,lggomez/corefx,shmao/corefx,dotnet-bot/corefx,richlander/corefx,dhoehna/corefx,alexandrnikitin/corefx,kkurni/corefx,alphonsekurian/corefx,iamjasonp/corefx,janhenke/corefx,jeremymeng/corefx,SGuyGe/corefx,Ermiar/corefx,akivafr123/corefx,pallavit/corefx,DnlHarvey/corefx,ViktorHofer/corefx,mazong1123/corefx,vidhya-bv/corefx-sorting,stephenmichaelf/corefx,wtgodbe/corefx,akivafr123/corefx,josguil/corefx,yizhang82/corefx,zhenlan/corefx,kkurni/corefx,benjamin-bader/corefx,twsouthwick/corefx,khdang/corefx,elijah6/corefx,pallavit/corefx,billwert/corefx,Yanjing123/corefx,SGuyGe/corefx,stone-li/corefx,Chrisboh/corefx,heXelium/corefx,rjxby/corefx,YoupHulsebos/corefx,alexperovich/corefx,parjong/corefx,jcme/corefx,ViktorHofer/corefx,690486439/corefx,nbarbettini/corefx,twsouthwick/corefx,krytarowski/corefx,mmitche/corefx,manu-silicon/corefx,alexperovich/corefx,MaggieTsang/corefx,lggomez/corefx,rahku/corefx,JosephTremoulet/corefx,krytarowski/corefx,rahku/corefx,krytarowski/corefx,PatrickMcDonald/corefx,weltkante/corefx,zhenlan/corefx,Jiayili1/corefx,ravimeda/corefx,MaggieTsang/corefx,marksmeltzer/corefx,weltkante/corefx,jhendrixMSFT/corefx,tijoytom/corefx,ptoonen/corefx,parjong/corefx,kkurni/corefx,shimingsg/corefx,Jiayili1/corefx,tstringer/corefx,dotnet-bot/corefx,Priya91/corefx-1,n1ghtmare/corefx,axelheer/corefx,cartermp/corefx,ellismg/corefx,stone-li/corefx,khdang/corefx,parjong/corefx,nbarbettini/corefx,iamjasonp/corefx,seanshpark/corefx,dhoehna/corefx,billwert/corefx,rubo/corefx,alphonsekurian/corefx,kkurni/corefx,rahku/corefx,manu-silicon/corefx,ViktorHofer/corefx,josguil/corefx,Jiayili1/corefx,DnlHarvey/corefx,alexperovich/corefx,MaggieTsang/corefx,shahid-pk/corefx,seanshpark/corefx,alexandrnikitin/corefx,cydhaselton/corefx,nbarbettini/corefx,mafiya69/corefx,ericstj/corefx,shmao/corefx,rjxby/corefx,richlander/corefx,mmitche/corefx,nchikanov/corefx,BrennanConroy/corefx,krk/corefx,dotnet-bot/corefx,gkhanna79/corefx,Ermiar/corefx,mazong1123/corefx,krk/corefx,tstringer/corefx,ericstj/corefx,vidhya-bv/corefx-sorting,690486439/corefx,gkhanna79/corefx,adamralph/corefx,ericstj/corefx,nbarbettini/corefx,rjxby/corefx,stephenmichaelf/corefx,stephenmichaelf/corefx,fgreinacher/corefx,Ermiar/corefx,lggomez/corefx,the-dwyer/corefx,mokchhya/corefx,mokchhya/corefx,Ermiar/corefx,gkhanna79/corefx,dotnet-bot/corefx,jlin177/corefx,mafiya69/corefx,Ermiar/corefx,cydhaselton/corefx,wtgodbe/corefx,elijah6/corefx,stone-li/corefx,axelheer/corefx,shmao/corefx,mellinoe/corefx,yizhang82/corefx,cydhaselton/corefx,shmao/corefx,janhenke/corefx,SGuyGe/corefx,mazong1123/corefx,richlander/corefx,YoupHulsebos/corefx,gregg-miskelly/corefx,BrennanConroy/corefx,cydhaselton/corefx,stephenmichaelf/corefx,fgreinacher/corefx,ellismg/corefx,khdang/corefx,mellinoe/corefx,zhenlan/corefx,gkhanna79/corefx,dsplaisted/corefx,shmao/corefx,rubo/corefx,billwert/corefx,krk/corefx,pallavit/corefx,gregg-miskelly/corefx,jeremymeng/corefx,Jiayili1/corefx,SGuyGe/corefx,DnlHarvey/corefx,jlin177/corefx,zhenlan/corefx,DnlHarvey/corefx,dhoehna/corefx,benpye/corefx,690486439/corefx,tstringer/corefx,ViktorHofer/corefx,dhoehna/corefx,ericstj/corefx,DnlHarvey/corefx,marksmeltzer/corefx,richlander/corefx,krk/corefx,nchikanov/corefx,gkhanna79/corefx,cartermp/corefx,Priya91/corefx-1,josguil/corefx,JosephTremoulet/corefx,mellinoe/corefx,MaggieTsang/corefx,manu-silicon/corefx,Priya91/corefx-1,shahid-pk/corefx,shimingsg/corefx,bitcrazed/corefx,690486439/corefx,benjamin-bader/corefx,Chrisboh/corefx,Jiayili1/corefx,dhoehna/corefx,benjamin-bader/corefx,dhoehna/corefx,weltkante/corefx,khdang/corefx,elijah6/corefx,rahku/corefx,tijoytom/corefx,billwert/corefx,krytarowski/corefx,Chrisboh/corefx,Ermiar/corefx,billwert/corefx,the-dwyer/corefx,krk/corefx,shmao/corefx,tstringer/corefx,rahku/corefx,parjong/corefx,nbarbettini/corefx,shimingsg/corefx,Petermarcu/corefx,pallavit/corefx,shahid-pk/corefx,yizhang82/corefx,bitcrazed/corefx,ericstj/corefx,pgavlin/corefx,jeremymeng/corefx,vidhya-bv/corefx-sorting,benpye/corefx,ellismg/corefx,jcme/corefx,janhenke/corefx,Jiayili1/corefx,ellismg/corefx,stephenmichaelf/corefx,Chrisboh/corefx,jlin177/corefx,adamralph/corefx,cydhaselton/corefx,Yanjing123/corefx,MaggieTsang/corefx,Petermarcu/corefx,josguil/corefx,Priya91/corefx-1,shahid-pk/corefx,akivafr123/corefx,weltkante/corefx,YoupHulsebos/corefx,krytarowski/corefx,ptoonen/corefx,cydhaselton/corefx,dotnet-bot/corefx,jhendrixMSFT/corefx,janhenke/corefx,YoupHulsebos/corefx,JosephTremoulet/corefx,mazong1123/corefx,gkhanna79/corefx,alexperovich/corefx,ravimeda/corefx,krk/corefx,YoupHulsebos/corefx,manu-silicon/corefx,ptoonen/corefx,ptoonen/corefx,SGuyGe/corefx,ravimeda/corefx,benpye/corefx,ravimeda/corefx,alphonsekurian/corefx,Priya91/corefx-1,yizhang82/corefx,mokchhya/corefx,mafiya69/corefx,elijah6/corefx,dotnet-bot/corefx,ptoonen/corefx,akivafr123/corefx,manu-silicon/corefx,Petermarcu/corefx,pgavlin/corefx,mellinoe/corefx,the-dwyer/corefx,nbarbettini/corefx,rjxby/corefx,DnlHarvey/corefx,cartermp/corefx,JosephTremoulet/corefx,alexandrnikitin/corefx,mokchhya/corefx,ericstj/corefx,the-dwyer/corefx,marksmeltzer/corefx,bitcrazed/corefx,seanshpark/corefx,benjamin-bader/corefx,alphonsekurian/corefx,tstringer/corefx,stone-li/corefx,twsouthwick/corefx,elijah6/corefx,jhendrixMSFT/corefx,dsplaisted/corefx,YoupHulsebos/corefx,stone-li/corefx,yizhang82/corefx,stone-li/corefx,adamralph/corefx,krk/corefx,twsouthwick/corefx,mafiya69/corefx,iamjasonp/corefx,jlin177/corefx,lggomez/corefx,alexandrnikitin/corefx,mmitche/corefx,ViktorHofer/corefx,Jiayili1/corefx,cartermp/corefx,benpye/corefx,wtgodbe/corefx,the-dwyer/corefx,iamjasonp/corefx,parjong/corefx,Petermarcu/corefx,tijoytom/corefx,jhendrixMSFT/corefx,rubo/corefx,richlander/corefx,shimingsg/corefx,fgreinacher/corefx,parjong/corefx,mazong1123/corefx,alexperovich/corefx,mafiya69/corefx,rjxby/corefx,seanshpark/corefx,kkurni/corefx,nchikanov/corefx,stephenmichaelf/corefx,Chrisboh/corefx,shimingsg/corefx,rjxby/corefx,Yanjing123/corefx,jcme/corefx,mmitche/corefx,benjamin-bader/corefx,jeremymeng/corefx,Yanjing123/corefx,yizhang82/corefx,MaggieTsang/corefx,iamjasonp/corefx,janhenke/corefx,gregg-miskelly/corefx,ellismg/corefx,BrennanConroy/corefx,jcme/corefx,yizhang82/corefx,lggomez/corefx,richlander/corefx,mafiya69/corefx,marksmeltzer/corefx,elijah6/corefx,dsplaisted/corefx,twsouthwick/corefx,PatrickMcDonald/corefx,jhendrixMSFT/corefx,690486439/corefx,n1ghtmare/corefx,JosephTremoulet/corefx,jhendrixMSFT/corefx,mellinoe/corefx,fgreinacher/corefx,akivafr123/corefx,lggomez/corefx,pallavit/corefx,twsouthwick/corefx,PatrickMcDonald/corefx,seanshpark/corefx,billwert/corefx,tijoytom/corefx,heXelium/corefx,axelheer/corefx,josguil/corefx,shahid-pk/corefx,nchikanov/corefx,janhenke/corefx,alphonsekurian/corefx,cartermp/corefx,Petermarcu/corefx,khdang/corefx,ptoonen/corefx,weltkante/corefx,ericstj/corefx,richlander/corefx,tijoytom/corefx,pgavlin/corefx,weltkante/corefx,shimingsg/corefx,n1ghtmare/corefx,alphonsekurian/corefx,rahku/corefx,n1ghtmare/corefx,nchikanov/corefx,rahku/corefx,SGuyGe/corefx,shmao/corefx,vidhya-bv/corefx-sorting,Priya91/corefx-1,bitcrazed/corefx,rubo/corefx,mazong1123/corefx,jeremymeng/corefx,manu-silicon/corefx,axelheer/corefx,mazong1123/corefx,heXelium/corefx,gregg-miskelly/corefx,DnlHarvey/corefx,elijah6/corefx,alexperovich/corefx,MaggieTsang/corefx,zhenlan/corefx,stephenmichaelf/corefx,mmitche/corefx,jlin177/corefx,krytarowski/corefx,stone-li/corefx,zhenlan/corefx,josguil/corefx,bitcrazed/corefx,ellismg/corefx,ravimeda/corefx,wtgodbe/corefx,lggomez/corefx,cydhaselton/corefx,seanshpark/corefx,jhendrixMSFT/corefx,rubo/corefx,marksmeltzer/corefx,Chrisboh/corefx,vidhya-bv/corefx-sorting
src/System.Globalization/tests/CultureInfo/CurrentCulture.cs
src/System.Globalization/tests/CultureInfo/CurrentCulture.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using Xunit; namespace System.Globalization.Tests { public class Test { [Fact] public void TestCurrentCulture() { // run all tests in one method to avoid multi-threading issues CultureInfo defaultCulture = CultureInfo.CurrentCulture; Assert.NotEqual(CultureInfo.InvariantCulture, defaultCulture); CultureInfo newCulture = new CultureInfo(defaultCulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "ar-SA" : "ja-JP"); CultureInfo.CurrentCulture = newCulture; Assert.Equal(CultureInfo.CurrentCulture, newCulture); newCulture = new CultureInfo("de-DE_phoneb"); CultureInfo.CurrentCulture = newCulture; Assert.Equal(CultureInfo.CurrentCulture, newCulture); Assert.Equal("de-DE_phoneb", newCulture.CompareInfo.Name); CultureInfo.CurrentCulture = defaultCulture; Assert.Equal(CultureInfo.CurrentCulture, defaultCulture); } [Fact] public void TestCurrentUICulture() { // run all tests in one method to avoid multi-threading issues CultureInfo defaultUICulture = CultureInfo.CurrentUICulture; Assert.NotEqual(CultureInfo.InvariantCulture, defaultUICulture); CultureInfo newUICulture = new CultureInfo(defaultUICulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "ar-SA" : "ja-JP"); CultureInfo.CurrentUICulture = newUICulture; Assert.Equal(CultureInfo.CurrentUICulture, newUICulture); newUICulture = new CultureInfo("de-DE_phoneb"); CultureInfo.CurrentUICulture = newUICulture; Assert.Equal(CultureInfo.CurrentUICulture, newUICulture); Assert.Equal("de-DE_phoneb", newUICulture.CompareInfo.Name); CultureInfo.CurrentUICulture = defaultUICulture; Assert.Equal(CultureInfo.CurrentUICulture, defaultUICulture); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using Xunit; namespace System.Globalization.Tests { public class Test { [Fact] public void TestCurrentCultures() { CultureInfo defaultCulture = CultureInfo.CurrentCulture; CultureInfo newCulture = new CultureInfo(defaultCulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "ar-SA" : "ja-JP"); CultureInfo defaultUICulture = CultureInfo.CurrentUICulture; CultureInfo newUICulture = new CultureInfo(defaultCulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "ar-SA" : "ja-JP"); CultureInfo.CurrentCulture = newCulture; Assert.Equal(CultureInfo.CurrentCulture, newCulture); CultureInfo.CurrentUICulture = newUICulture; Assert.Equal(CultureInfo.CurrentUICulture, newUICulture); CultureInfo.CurrentCulture = defaultCulture; Assert.Equal(CultureInfo.CurrentCulture, defaultCulture); CultureInfo.CurrentUICulture = defaultUICulture; Assert.Equal(CultureInfo.CurrentUICulture, defaultUICulture); } } }
mit
C#
949144af8268c4989af21e7f813555664f63106e
add comment.
Codeer-Software/Selenium.StandardControls,Codeer-Software/Selenium.StandardControls,Codeer-Software/Selenium.StandardControls
Project/Selenium.StandardControls/ElementInfo.cs
Project/Selenium.StandardControls/ElementInfo.cs
using OpenQA.Selenium; using System; namespace Selenium.StandardControls { //TODO need test. /// <summary> /// JavaScript Element Driver /// </summary> public class ElementInfo { private IWebElement Core { get; } public string Id => GetAttribute<string>("id"); public string InnerHtml => GetAttribute<string>("innerHTML"); public string InnerText => GetAttribute<string>("innerText"); public string Text => GetAttribute<string>("text"); public string Value => GetAttribute<string>("value"); public string CssClass => GetCssValue("className"); public string Width => GetCssValue("width"); public string Height => GetCssValue("height"); public string FontSize => GetCssValue("fontSize"); public string Font => GetCssValue("fontFamily"); //ToDo: bold = Firefox is 700. Other Browther is un know. public bool FontBold => GetCssValue("fontWeight") == "700" || GetCssValue("fontWeight") == "bold"; public bool FontItalic => GetCssValue("fontStyle") == "italic"; public bool TextUnderline => GetCssValue("textDecoration").Contains("underline"); public bool TextLineThrough => GetCssValue("textDecoration").Contains("line-through"); public string Color => GetCssValue("color"); public string BackGroundColor => GetCssValue("backgroundColor"); public string BackGroundImage => GetCssValue("backgroundImage"); public long TabIndex => GetAttribute<long>("tabIndex"); public string ImeMode => GetCssValue("imeMode"); public int? MaxLength => GetAttribute<int?>("maxLength"); public string TextAlign => GetCssValue("textAlign"); public ElementInfo(IWebElement core) { Core = core; } public T GetAttribute<T>(string name) { var o = Core.GetAttribute(name); if (typeof(T) == typeof(int?)) return (o == null) ? default(T) : (T)(object)int.Parse(o); if (typeof(T) == typeof(string)) return (T)(object)o; if (typeof(T) == typeof(long)) return (T)(object)long.Parse(o); throw new ArgumentOutOfRangeException(""); } public string GetCssValue(string name) => Core.GetCssValue(name); } }
using OpenQA.Selenium; using System; namespace Selenium.StandardControls { /// <summary> /// JavaScript Element Driver /// </summary> public class ElementInfo { private IWebElement Core { get; } public string Id => GetAttribute<string>("id"); public string InnerHtml => GetAttribute<string>("innerHTML"); public string InnerText => GetAttribute<string>("innerText"); public string Text => GetAttribute<string>("text"); public string Value => GetAttribute<string>("value"); public string CssClass => GetCssValue("className"); public string Width => GetCssValue("width"); public string Height => GetCssValue("height"); public string FontSize => GetCssValue("fontSize"); public string Font => GetCssValue("fontFamily"); //ToDo: bold = Firefox is 700. Other Browther is un know. public bool FontBold => GetCssValue("fontWeight") == "700" || GetCssValue("fontWeight") == "bold"; public bool FontItalic => GetCssValue("fontStyle") == "italic"; public bool TextUnderline => GetCssValue("textDecoration").Contains("underline"); public bool TextLineThrough => GetCssValue("textDecoration").Contains("line-through"); public string Color => GetCssValue("color"); public string BackGroundColor => GetCssValue("backgroundColor"); public string BackGroundImage => GetCssValue("backgroundImage"); public long TabIndex => GetAttribute<long>("tabIndex"); public string ImeMode => GetCssValue("imeMode"); public int? MaxLength => GetAttribute<int?>("maxLength"); public string TextAlign => GetCssValue("textAlign"); public ElementInfo(IWebElement core) { Core = core; } public T GetAttribute<T>(string name) { var o = Core.GetAttribute(name); if (typeof(T) == typeof(int?)) return (o == null) ? default(T) : (T)(object)int.Parse(o); if (typeof(T) == typeof(string)) return (T)(object)o; if (typeof(T) == typeof(long)) return (T)(object)long.Parse(o); throw new ArgumentOutOfRangeException(""); } public string GetCssValue(string name) => Core.GetCssValue(name); } }
apache-2.0
C#
a792284d85945ab378813fbfeeea217031ed6f18
Use completion
OmniSharp/omnisharp-vscode,OmniSharp/omnisharp-vscode,gregg-miskelly/omnisharp-vscode,OmniSharp/omnisharp-vscode,gregg-miskelly/omnisharp-vscode,gregg-miskelly/omnisharp-vscode,gregg-miskelly/omnisharp-vscode,OmniSharp/omnisharp-vscode,OmniSharp/omnisharp-vscode
test/integrationTests/testAssets/slnWithCsproj/src/app/completion.cs
test/integrationTests/testAssets/slnWithCsproj/src/app/completion.cs
using System; namespace singleCsproj { class Completion { static void shouldHaveCompletions(string[] args) { Completion a = new Completion(); } } }
using System; namespace singleCsproj { class Completion { static void shouldHaveCompletions(string[] args) { int[] a = new int[5]; } } }
mit
C#
d1f39ff2b2f50294ecc203f1f9c8d8683b167718
Add public Children property to TreeNode (#2633)
AntShares/AntShares
src/neo/IO/Caching/TreeNode.cs
src/neo/IO/Caching/TreeNode.cs
// Copyright (C) 2015-2021 The Neo Project. // // The neo is free software distributed under the MIT software license, // see the accompanying file LICENSE in the main directory of the // project or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without // modifications are permitted. using System.Collections.Generic; namespace Neo.IO.Caching { public class TreeNode<T> { private readonly List<TreeNode<T>> children = new(); public T Item { get; } public TreeNode<T> Parent { get; } public IReadOnlyList<TreeNode<T>> Children => children; internal TreeNode(T item, TreeNode<T> parent) { Item = item; Parent = parent; } public TreeNode<T> AddChild(T item) { TreeNode<T> child = new(item, this); children.Add(child); return child; } internal IEnumerable<T> GetItems() { yield return Item; foreach (var child in children) foreach (T item in child.GetItems()) yield return item; } } }
// Copyright (C) 2015-2021 The Neo Project. // // The neo is free software distributed under the MIT software license, // see the accompanying file LICENSE in the main directory of the // project or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without // modifications are permitted. using System.Collections.Generic; namespace Neo.IO.Caching { public class TreeNode<T> { public T Item { get; } public TreeNode<T> Parent { get; } private readonly List<TreeNode<T>> children = new(); internal TreeNode(T item, TreeNode<T> parent) { Item = item; Parent = parent; } public TreeNode<T> AddChild(T item) { TreeNode<T> child = new(item, this); children.Add(child); return child; } internal IEnumerable<T> GetItems() { yield return Item; foreach (var child in children) foreach (T item in child.GetItems()) yield return item; } } }
mit
C#
25245aeed503e7eab6de941693c869615694b3a7
add TrySetupStructure
NDark/ndinfrastructure,NDark/ndinfrastructure
Unity/NGUIUtil/NGUIMessageQueueControllerBase.cs
Unity/NGUIUtil/NGUIMessageQueueControllerBase.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class NGUIMessageQueueControllerBase : MonoBehaviour { public virtual string CurrentText { get{ return string.Empty;} set{ } } public virtual Vector3 CurrentTextPosition { get{ return Vector3.zero;} set{ } } public virtual Color CurrentTextColor { get{ return Color.black;} set{ } } public virtual void ShowUI( bool _Show ) { } public void QueueText( string _Text ) { m_MessageQueue.AddLast( _Text ) ; } void Awake() { SetupStructure() ; } // Use this for initialization void Start () { } // Update is called once per frame void Update () { MessageUpdate(); } protected virtual void MessageUpdate() { if( m_InAnimation ) { CheckAnimationEnd() ; } else if( m_MessageQueue.Count > 0 ) { RestartAnimation(m_MessageQueue.First.Value) ; m_MessageQueue.RemoveFirst() ; } } protected virtual void RestartAnimation( string _Text ) { /** Reset animation position */ UpdateText( _Text ) ; m_InAnimation = true ; } protected virtual void UpdateText( string _Text ) { // assign text. } protected virtual void CheckAnimationEnd() { // check animation has finished. /* if( m_MessageTweenPosition.isActiveAndEnabled == false && m_MessageTweenAlpha.isActiveAndEnabled == false ) { m_InAnimation = false ; if (0 == m_MessageQueue.Count) { ShowUI(false); } } */ } public virtual void TrySetupStructure() { if (!m_Initializaed) { SetupStructure(); } } protected virtual void SetupStructure() { m_Initializaed = true; } protected bool m_InAnimation = false ; protected LinkedList<string> m_MessageQueue = new LinkedList<string>() ; public bool IsInitialized { get { return m_Initializaed; } } protected bool m_Initializaed = false ; }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class NGUIMessageQueueControllerBase : MonoBehaviour { public virtual string CurrentText { get{ return string.Empty;} set{ } } public virtual Vector3 CurrentTextPosition { get{ return Vector3.zero;} set{ } } public virtual Color CurrentTextColor { get{ return Color.black;} set{ } } public virtual void ShowUI( bool _Show ) { } public void QueueText( string _Text ) { m_MessageQueue.AddLast( _Text ) ; } void Awake() { SetupStructure() ; } // Use this for initialization void Start () { } // Update is called once per frame void Update () { MessageUpdate(); } protected virtual void MessageUpdate() { if( m_InAnimation ) { CheckAnimationEnd() ; } else if( m_MessageQueue.Count > 0 ) { RestartAnimation(m_MessageQueue.First.Value) ; m_MessageQueue.RemoveFirst() ; } } protected virtual void RestartAnimation( string _Text ) { /** Reset animation position */ UpdateText( _Text ) ; m_InAnimation = true ; } protected virtual void UpdateText( string _Text ) { // assign text. } protected virtual void CheckAnimationEnd() { // check animation has finished. /* if( m_MessageTweenPosition.isActiveAndEnabled == false && m_MessageTweenAlpha.isActiveAndEnabled == false ) { m_InAnimation = false ; if (0 == m_MessageQueue.Count) { ShowUI(false); } } */ } protected virtual void SetupStructure() { } protected bool m_InAnimation = false ; protected LinkedList<string> m_MessageQueue = new LinkedList<string>() ; }
mit
C#
5b2cbf8f26da584dbc045e2132c04312a7e53fff
Disable test parallelization due to shared state problems
DotNetAnalyzers/StyleCopAnalyzers
StyleCop.Analyzers/StyleCop.Analyzers.Test/Properties/AssemblyInfo.cs
StyleCop.Analyzers/StyleCop.Analyzers.Test/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.InteropServices; using Xunit; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("StyleCop.Analyzers.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Tunnel Vision Laboratories, LLC")] [assembly: AssemblyProduct("StyleCop.Analyzers.Test")] [assembly: AssemblyCopyright("Copyright © Sam Harwell 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(false)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0.0-dev")] [assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly, DisableTestParallelization = true)]
using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("StyleCop.Analyzers.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Tunnel Vision Laboratories, LLC")] [assembly: AssemblyProduct("StyleCop.Analyzers.Test")] [assembly: AssemblyCopyright("Copyright © Sam Harwell 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(false)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0.0-dev")]
mit
C#
facccc22784b5c04f4e1b5d95841c3a4e446561a
Disable test to get clean build
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
resharper/test/src/Feature/Services/CodeCompletion/UnityEventFunctionCompletionListTest.cs
resharper/test/src/Feature/Services/CodeCompletion/UnityEventFunctionCompletionListTest.cs
using JetBrains.ReSharper.FeaturesTestFramework.Completion; using NUnit.Framework; namespace JetBrains.ReSharper.Plugins.Unity.Tests.Feature.Services.CodeCompletion { // TODO: This doesn't test automatic completion // The AutomaticCodeCompletionTestBase class is not in the SDK [TestUnity] public class UnityEventFunctionCompletionListTest : CodeCompletionTestBase { protected override CodeCompletionTestType TestType => CodeCompletionTestType.List; protected override string RelativeTestDataPath => @"codeCompletion\List"; protected override bool CheckAutomaticCompletionDefault() => true; //[Test] public void MonoBehaviour01() { DoNamedTest(); } [Test] public void MonoBehaviour02() { DoNamedTest(); } [Test] public void MonoBehaviour03() { DoNamedTest(); } [Test] public void MonoBehaviour04() { DoNamedTest(); } [Test] public void MonoBehaviour05() { DoNamedTest(); } [Test] public void MonoBehaviour06() { DoNamedTest(); } } }
using JetBrains.ReSharper.FeaturesTestFramework.Completion; using NUnit.Framework; namespace JetBrains.ReSharper.Plugins.Unity.Tests.Feature.Services.CodeCompletion { // TODO: This doesn't test automatic completion // The AutomaticCodeCompletionTestBase class is not in the SDK [TestUnity] public class UnityEventFunctionCompletionListTest : CodeCompletionTestBase { protected override CodeCompletionTestType TestType => CodeCompletionTestType.List; protected override string RelativeTestDataPath => @"codeCompletion\List"; protected override bool CheckAutomaticCompletionDefault() => true; [Test] public void MonoBehaviour01() { DoNamedTest(); } [Test] public void MonoBehaviour02() { DoNamedTest(); } [Test] public void MonoBehaviour03() { DoNamedTest(); } [Test] public void MonoBehaviour04() { DoNamedTest(); } [Test] public void MonoBehaviour05() { DoNamedTest(); } [Test] public void MonoBehaviour06() { DoNamedTest(); } } }
apache-2.0
C#
9d042be254de8652dd1b3d82da4fa95f3e28d0b6
Improve GetAssociatedFiber
David-Desmaisons/EasyActor
EasyActor/ActorExtension.cs
EasyActor/ActorExtension.cs
using EasyActor.Factories; namespace EasyActor { public static class ActorExtension { public static IFiber GetAssociatedFiber(this object rawimplementation) { var fiberProvider = rawimplementation as IFiberProvider; if (fiberProvider != null) return fiberProvider.Fiber; var description = ActorFactoryBase.GetCachedActor(rawimplementation); return description?.Fiber; } } }
using EasyActor.Factories; namespace EasyActor { public static class ActorExtension { public static IFiber GetAssociatedFiber(this object rawimplementation) { var description = ActorFactoryBase.GetCachedActor(rawimplementation); return description?.Fiber; } } }
mit
C#
f7c3f64e8756dc7542065bbd1ca3e46fd332d34e
Add macros
DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
Assets/MixedRealityToolkit/Extensions/TypeExtensions.cs
Assets/MixedRealityToolkit/Extensions/TypeExtensions.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.Reflection; namespace Microsoft.MixedReality.Toolkit { public static class TypeExtensions { #if !NETFX_CORE /// <summary> /// Returns a list of types for all classes that extend from the current type and are not abstract /// </summary> /// <param name="rootType">The class type from which to search for inherited classes</param> /// <returns>Null if rootType is not a class, otherwise returns list of types for sub-classes of rootType</returns> public static List<Type> GetAllSubClassesOf(this Type rootType) { if (!rootType.IsClass) return null; var results = new List<Type>(); foreach (var type in Assembly.GetAssembly(rootType).GetTypes()) { if (type.IsClass && !type.IsAbstract && type.IsSubclassOf(rootType)) { results.Add(type); } } return results; } #endif } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.Reflection; namespace Microsoft.MixedReality.Toolkit { public static class TypeExtensions { /// <summary> /// Returns a list of types for all classes that extend from the current type and are not abstract /// </summary> /// <param name="rootType">The class type from which to search for inherited classes</param> /// <returns>Null if rootType is not a class, otherwise returns list of types for sub-classes of rootType</returns> public static List<Type> GetAllSubClassesOf(this Type rootType) { if (!rootType.IsClass) return null; var results = new List<Type>(); foreach (var type in Assembly.GetAssembly(rootType).GetTypes()) { if (type.IsClass && !type.IsAbstract && type.IsSubclassOf(rootType)) { results.Add(type); } } return results; } } }
mit
C#
dbd6704fefd2f36c5cad66de0dbf5cfea18b65ec
Remove unnecessary attenuation set.
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.Client/Kitchen/EntitySystems/MicrowaveSystem.cs
Content.Client/Kitchen/EntitySystems/MicrowaveSystem.cs
using System; using Content.Client.Kitchen.Components; using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.Player; namespace Content.Client.Kitchen.EntitySystems { public class MicrowaveSystem : EntitySystem { public void StartSoundLoop(MicrowaveComponent microwave) { StopSoundLoop(microwave); microwave.PlayingStream = SoundSystem.Play(Filter.Local(), microwave.LoopingSound.GetSound(), microwave.Owner, AudioParams.Default.WithMaxDistance(5).WithLoop(true)); } public void StopSoundLoop(MicrowaveComponent microwave) { try { microwave.PlayingStream?.Stop(); } catch (Exception _) { // TODO: HOLY SHIT EXPOSE SOME DISPOSED PROPERTY ON PLAYING STREAM OR SOMETHING. } } } }
using System; using Content.Client.Kitchen.Components; using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.Player; namespace Content.Client.Kitchen.EntitySystems { public class MicrowaveSystem : EntitySystem { public void StartSoundLoop(MicrowaveComponent microwave) { StopSoundLoop(microwave); microwave.PlayingStream = SoundSystem.Play(Filter.Local(), microwave.LoopingSound.GetSound(), microwave.Owner, AudioParams.Default.WithAttenuation(1).WithMaxDistance(5).WithLoop(true)); } public void StopSoundLoop(MicrowaveComponent microwave) { try { microwave.PlayingStream?.Stop(); } catch (Exception _) { // TODO: HOLY SHIT EXPOSE SOME DISPOSED PROPERTY ON PLAYING STREAM OR SOMETHING. } } } }
mit
C#
c635c81672b33be9d2c84d500b233f6c86877bf0
bump version to 1.7.3
Franiac/TwitchLeecher
TwitchLeecher/GlobalAssemblyInfo.cs
TwitchLeecher/GlobalAssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyProduct("Twitch Leecher")] [assembly: AssemblyDescription("Twitch Broadcast Downloader")] [assembly: AssemblyCompany("Franiac")] [assembly: AssemblyCopyright("Copyright 2018 Dominik Rebitzer")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.7.3")] [assembly: ComVisible(false)]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyProduct("Twitch Leecher")] [assembly: AssemblyDescription("Twitch Broadcast Downloader")] [assembly: AssemblyCompany("Franiac")] [assembly: AssemblyCopyright("Copyright 2018 Dominik Rebitzer")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.7.2")] [assembly: ComVisible(false)]
mit
C#
38725222cadb6b2e7938f0943d17d25f09509b80
Add TOC to PERSTAT
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Jobs/PERSTATReportJob.cs
Battery-Commander.Web/Jobs/PERSTATReportJob.cs
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using FluentEmail.Core; using FluentEmail.Core.Models; using FluentScheduler; using Serilog; using System.Collections.Generic; using System.IO; namespace BatteryCommander.Web.Jobs { public class PERSTATReportJob : IJob { private static readonly ILogger Log = Serilog.Log.ForContext<PERSTATReportJob>(); private static IList<Address> Recipients => new List<Address>(new Address[] { FROM, new Address { Name = "2-116 FA BN TOC", EmailAddress = "ng.fl.flarng.list.ngfl-2-116-fa-bn-toc@mail.mil" } }); internal static Address FROM => new Address { Name = "C-2-116 FA", EmailAddress = "BatteryCommander@redleg.app" }; private readonly Database db; private readonly IFluentEmail emailSvc; public PERSTATReportJob(Database db, IFluentEmail emailSvc) { this.db = db; this.emailSvc = emailSvc; } public virtual void Execute() { foreach (var unit in UnitService.List(db).GetAwaiter().GetResult()) { // HACK - Configure the recipients and units that this is going to be wired up for Log.Information("Building PERSTAT report for {@unit} to {@recipients}", new { unit.Id, unit.Name }, Recipients); emailSvc .To(Recipients) .SetFrom(FROM.EmailAddress, FROM.Name) .Subject($"{unit.Name} | RED 1 PERSTAT") .UsingTemplateFromFile($"{Directory.GetCurrentDirectory()}/Views/Reports/Red1_Perstat.cshtml", unit) .Send(); } } } }
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using FluentEmail.Core; using FluentEmail.Core.Models; using FluentScheduler; using Serilog; using System.Collections.Generic; using System.IO; namespace BatteryCommander.Web.Jobs { public class PERSTATReportJob : IJob { private static readonly ILogger Log = Serilog.Log.ForContext<PERSTATReportJob>(); private static IList<Address> Recipients => new List<Address>(new Address[] { FROM // new Address { Name = "2-116 FA BN TOC", EmailAddress = "ng.fl.flarng.list.ngfl-2-116-fa-bn-toc@mail.mil" } }); internal static Address FROM => new Address { Name = "C-2-116 FA", EmailAddress = "BatteryCommander@redleg.app" }; private readonly Database db; private readonly IFluentEmail emailSvc; public PERSTATReportJob(Database db, IFluentEmail emailSvc) { this.db = db; this.emailSvc = emailSvc; } public virtual void Execute() { foreach (var unit in UnitService.List(db).GetAwaiter().GetResult()) { // HACK - Configure the recipients and units that this is going to be wired up for Log.Information("Building PERSTAT report for {@unit} to {@recipients}", new { unit.Id, unit.Name }, Recipients); emailSvc .To(Recipients) .SetFrom(FROM.EmailAddress, FROM.Name) .Subject($"{unit.Name} | RED 1 PERSTAT") .UsingTemplateFromFile($"{Directory.GetCurrentDirectory()}/Views/Reports/Red1_Perstat.cshtml", unit) .Send(); } } } }
mit
C#
dee08e4360b444fefb9d36f00c0457b0e39cc43f
Initialize to default values.
wasabii/Cogito,wasabii/Cogito
Cogito.Core/Reflection/MethodInfoExtensions.cs
Cogito.Core/Reflection/MethodInfoExtensions.cs
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Cogito.Reflection { public static class MethodInfoExtensions { /// <summary> /// Invokes the <see cref="MethodInfo"/> with the specified named parameters. /// </summary> /// <param name="self"></param> /// <param name="obj"></param> /// <param name="parameters"></param> /// <returns></returns> public static object InvokeWithNamedParameters(this MethodBase self, object obj, IDictionary<string, object> parameters) { return self.Invoke(obj, MapParameters(self, parameters)); } /// <summary> /// Maps the named parameters to a proper invocation array. /// </summary> /// <param name="method"></param> /// <param name="parameters"></param> /// <returns></returns> static object[] MapParameters(MethodBase method, IDictionary<string, object> parameters) { Contract.Requires<ArgumentNullException>(method != null); Contract.Requires<ArgumentNullException>(parameters != null); var argp = method.GetParameters(); var argn = argp.Select(i => i.Name).ToArray(); var argv = new object[argp.Length]; // set all parameters to default for (int i = 0; i < argv.Length; ++i) argv[i] = argp[i].ParameterType.IsValueType ? Activator.CreateInstance(argp[i].ParameterType) : null; // update parameters from dictionary foreach (var item in parameters) { var name = item.Key; var indx = Array.IndexOf(argn, name); if (indx > -1) argv[indx] = item.Value; } return argv; } } }
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Cogito.Reflection { public static class MethodInfoExtensions { /// <summary> /// Invokes the <see cref="MethodInfo"/> with the specified named parameters. /// </summary> /// <param name="self"></param> /// <param name="obj"></param> /// <param name="parameters"></param> /// <returns></returns> public static object InvokeWithNamedParameters(this MethodBase self, object obj, IDictionary<string, object> parameters) { return self.Invoke(obj, MapParameters(self, parameters)); } /// <summary> /// Maps the named parameters to a proper invocation array. /// </summary> /// <param name="method"></param> /// <param name="parameters"></param> /// <returns></returns> static object[] MapParameters(MethodBase method, IDictionary<string, object> parameters) { Contract.Requires<ArgumentNullException>(method != null); Contract.Requires<ArgumentNullException>(parameters != null); var argn = method.GetParameters().Select(p => p.Name).ToArray(); var args = new object[argn.Length]; // set all parameters to missing for (int i = 0; i < args.Length; ++i) args[i] = Type.Missing; foreach (var item in parameters) { var name = item.Key; var indx = Array.IndexOf(argn, name); if (indx > -1) args[indx] = item.Value; } return args; } } }
mit
C#
d5b2ce4d7b5bb864ae3856c975387d0964398987
Update version number
axomic/openasset-rest-cs
OpenAsset.RestClient.Library/Properties/AssemblyInfo.cs
OpenAsset.RestClient.Library/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("OpenAsset.RestClient.Library")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Axomic Ltd")] [assembly: AssemblyProduct("OpenAsset RestClient Library")] [assembly: AssemblyCopyright("Copyright © Axomic Ltd 2013-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("137fd3b7-9fa8-4003-a734-bb82cf0e2586")] // 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(AssemblyVersion.Version)] [assembly: AssemblyFileVersion(AssemblyVersion.Version)] internal static class AssemblyVersion { public const string Version = "1.1.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("OpenAsset.RestClient.Library")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Axomic Ltd")] [assembly: AssemblyProduct("OpenAsset RestClient Library")] [assembly: AssemblyCopyright("Copyright © Axomic Ltd 2013-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("137fd3b7-9fa8-4003-a734-bb82cf0e2586")] // 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(AssemblyVersion.Version)] [assembly: AssemblyFileVersion(AssemblyVersion.Version)] internal static class AssemblyVersion { public const string Version = "1.1.0.0"; }
mit
C#
a46a437142613a9b1fc1079f0f921bef667c921a
Change view
Branimir123/PhotoLife,Branimir123/PhotoLife,Branimir123/PhotoLife
PhotoLife/PhotoLife.Web/Views/Shared/_ShortPostPartial.cshtml
PhotoLife/PhotoLife.Web/Views/Shared/_ShortPostPartial.cshtml
@model PhotoLife.ViewModels.Post.ShortPostViewModel <div class="well"> <h2 class="media-heading"> @Html.ActionLink(Model.Title, "Details", new { controller = "Post", id = Model.Id }) </h2> <ul class="list-inline list-unstyled"> <li><span><i class="glyphicon glyphicon-calendar"></i> @string.Format("{0:D} at {0:HH:mm}", Model.DatePublished)</span></li> <li>|</li> <li> <img src="@Model.ImageUrl" alt="Alternate Text" /></li> <li> <span class="glyphicon glyphicon-star"></span> Rating: @Model.Votes.Count() </li> </ul> </div>
@model PhotoLife.ViewModels.Post.ShortPostViewModel <div class="well"> <h2 class="media-heading"> @Html.ActionLink(Model.Title, "Details", new { controller = "Post", id = Model.Id }) </h2> <ul class="list-inline list-unstyled"> <li><span><i class="glyphicon glyphicon-calendar"></i> @string.Format("{0:D} at {0:HH:mm}", Model.DatePublished)</span></li> <li>|</li> <li> <span class="glyphicon glyphicon-star"></span> Rating: @Model.Votes.Count() </li> </ul> </div>
mit
C#
6150747d78ab9cc308e95f27a592556a0d09c307
Update AssemblyInfo.cs
afuzzyllama/ProceduralVoxelMesh,PixelsForGlory/ProceduralVoxelMesh
ProceduralVoxelMesh/Properties/AssemblyInfo.cs
ProceduralVoxelMesh/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("ProceduralVoxelMesh")] [assembly: AssemblyDescription("Library to create procedural voxel meshes in Unity3D")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("afuzzyllama")] [assembly: AssemblyProduct("ProceduralVoxelMesh")] [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("4fe5e259-e4c2-49ca-892e-e3a952be5a65")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.0.0.0")] [assembly: AssemblyFileVersion("0.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("ProceduralVoxelMesh")] [assembly: AssemblyDescription("Library to create procedural voxel meshes in Unity3D")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("afuzzyllama")] [assembly: AssemblyProduct("ProceduralVoxelMesh")] [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("4fe5e259-e4c2-49ca-892e-e3a952be5a65")] // 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#
4ed2d15e592054ad5264f3391d34b90375a45bbe
fix Html.Submit
dpesheva/QuizFactory,dpesheva/QuizFactory
QuizFactory/HelperExtentions/HtmlExtentions.cs
QuizFactory/HelperExtentions/HtmlExtentions.cs
namespace HelperExtentions { using System; using System.Collections.Generic; using System.Web.Mvc; using System.Web.Mvc.Ajax; using System.Web.Routing; public static class HtmlExtentions { public static MvcHtmlString RawActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes) { var repID = Guid.NewGuid().ToString(); var lnk = ajaxHelper.ActionLink(repID, actionName, controllerName, routeValues, ajaxOptions, htmlAttributes); return MvcHtmlString.Create(lnk.ToString().Replace(repID, linkText)); } public static MvcHtmlString Submit(this HtmlHelper helper, object htmlAttributes) { var input = new TagBuilder("input"); var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes) as IDictionary<string, object>; input.MergeAttributes(attributes); input.Attributes.Add("type", "submit"); return new MvcHtmlString(input.ToString(TagRenderMode.Normal)); } } }
namespace HelperExtentions { using System; using System.Collections.Generic; using System.Web.Mvc; using System.Web.Mvc.Ajax; using System.Web.Routing; public static class HtmlExtentions { public static MvcHtmlString RawActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes) { var repID = Guid.NewGuid().ToString(); var lnk = ajaxHelper.ActionLink(repID, actionName, controllerName, routeValues, ajaxOptions, htmlAttributes); return MvcHtmlString.Create(lnk.ToString().Replace(repID, linkText)); } public static TagBuilder Submit(this HtmlHelper helper, object htmlAttributes) { var input = new TagBuilder("input"); var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes) as IDictionary<string, object>; input.MergeAttributes(attributes); input.Attributes.Add("typ", "submit"); return input; } } }
mit
C#
ffebc18949bf38ba1e93876d4c30344b27fc522e
Add comments
y-iihoshi/ThScoreFileConverter,y-iihoshi/ThScoreFileConverter
ThScoreFileConverter.Core/Models/Th075/SpellCardInfo.cs
ThScoreFileConverter.Core/Models/Th075/SpellCardInfo.cs
//----------------------------------------------------------------------- // <copyright file="SpellCardInfo.cs" company="None"> // Copyright (c) IIHOSHI Yoshinori. // Licensed under the BSD-2-Clause license. See LICENSE.txt file in the project root for full license information. // </copyright> //----------------------------------------------------------------------- namespace ThScoreFileConverter.Core.Models.Th075; /// <summary> /// Indicates information of a IMP spell card. /// </summary> public class SpellCardInfo { /// <summary> /// Initializes a new instance of the <see cref="SpellCardInfo"/> class. /// </summary> /// <param name="name">A name of the spell card.</param> /// <param name="enemy">The enemy character who use the spell card.</param> /// <param name="level">The level which the spell card is used.</param> public SpellCardInfo(string name, Chara enemy, Level level) { this.Name = name; this.Enemy = enemy; this.Level = level; } /// <summary> /// Gets a name of the current spell card. /// </summary> public string Name { get; } /// <summary> /// Gets the enemy character who uses the current spell card. /// </summary> public Chara Enemy { get; } /// <summary> /// Gets the level which the current spell card is used. /// </summary> public Level Level { get; } }
//----------------------------------------------------------------------- // <copyright file="SpellCardInfo.cs" company="None"> // Copyright (c) IIHOSHI Yoshinori. // Licensed under the BSD-2-Clause license. See LICENSE.txt file in the project root for full license information. // </copyright> //----------------------------------------------------------------------- #pragma warning disable SA1600 // Elements should be documented namespace ThScoreFileConverter.Core.Models.Th075; public class SpellCardInfo { public SpellCardInfo(string name, Chara enemy, Level level) { this.Name = name; this.Enemy = enemy; this.Level = level; } public string Name { get; } public Chara Enemy { get; } public Level Level { get; } }
bsd-2-clause
C#
057a21907b1a1bf35a308f606d36d208e8934c67
Bump assembly version to 4.0.321.
rubyu/CreviceApp,rubyu/CreviceApp
CreviceApp/Properties/AssemblyInfo.cs
CreviceApp/Properties/AssemblyInfo.cs
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("Crevice4")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Crevice4")] [assembly: AssemblyCopyright("Copyright @rubyu")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、このアセンブリ内の型は COM コンポーネントから // 参照できなくなります。COM からこのアセンブリ内の型にアクセスする必要がある場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("82b56652-6380-44ed-a193-742f7eef290f")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、次を使用してビルド番号とリビジョン番号を既定に設定できます // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("4.0.321.0")] [assembly: AssemblyFileVersion("4.0.321.0")] [assembly: NeutralResourcesLanguage("en")] [assembly: InternalsVisibleTo("Crevice4Tests")]
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("Crevice4")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Crevice4")] [assembly: AssemblyCopyright("Copyright @rubyu")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、このアセンブリ内の型は COM コンポーネントから // 参照できなくなります。COM からこのアセンブリ内の型にアクセスする必要がある場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("82b56652-6380-44ed-a193-742f7eef290f")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、次を使用してビルド番号とリビジョン番号を既定に設定できます // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: NeutralResourcesLanguage("en")] [assembly: InternalsVisibleTo("Crevice4Tests")]
mit
C#
da15e89cddba7a0d63d463ce5f713dbd8a64eb57
Bump version to 2.0
SonarSource-DotNet/sonarqube-roslyn-sdk,SonarSource-VisualStudio/sonarqube-roslyn-sdk
AssemblyInfo.Shared.cs
AssemblyInfo.Shared.cs
/* * SonarQube Roslyn SDK * Copyright (C) 2015-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyCompany("SonarSource and Microsoft")] [assembly: AssemblyCopyright("Copyright © SonarSource and Microsoft 2015-2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)]
/* * SonarQube Roslyn SDK * Copyright (C) 2015-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyCompany("SonarSource and Microsoft")] [assembly: AssemblyCopyright("Copyright © SonarSource and Microsoft 2015-2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)]
mit
C#
77f5ec3a4ec24dcc6b5df8b7b7fd2dd1a8657dd4
use checkbox label instead of tooltip
ppy/osu,peppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu
osu.Game/Graphics/UserInterfaceV2/OsuDirectorySelectorHiddenToggle.cs
osu.Game/Graphics/UserInterfaceV2/OsuDirectorySelectorHiddenToggle.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.Graphics; using osu.Game.Graphics.UserInterface; using osu.Game.Overlays; using osuTK; using osuTK.Graphics; namespace osu.Game.Graphics.UserInterfaceV2 { internal class OsuDirectorySelectorHiddenToggle : OsuCheckbox { public OsuDirectorySelectorHiddenToggle() { RelativeSizeAxes = Axes.None; AutoSizeAxes = Axes.None; Size = new Vector2(100, 50); Anchor = Anchor.CentreLeft; Origin = Anchor.CentreLeft; LabelText = "Show hidden items"; } [BackgroundDependencyLoader(true)] private void load(OverlayColourProvider? overlayColourProvider, OsuColour colours) { if (overlayColourProvider != null) return; Nub.AccentColour = colours.GreySeaFoamLighter; Nub.GlowingAccentColour = Color4.White; Nub.GlowColour = Color4.White; } } }
// 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.Graphics; using osu.Framework.Graphics.Cursor; using osu.Framework.Localisation; using osu.Game.Graphics.UserInterface; using osu.Game.Overlays; using osuTK.Graphics; namespace osu.Game.Graphics.UserInterfaceV2 { internal class OsuDirectorySelectorHiddenToggle : OsuCheckbox, IHasTooltip { public LocalisableString TooltipText => @"Show hidden items"; public OsuDirectorySelectorHiddenToggle() { RelativeSizeAxes = Axes.None; AutoSizeAxes = Axes.Both; Anchor = Anchor.CentreLeft; Origin = Anchor.CentreLeft; } [BackgroundDependencyLoader(true)] private void load(OverlayColourProvider? overlayColourProvider, OsuColour colours) { if (overlayColourProvider != null) return; Nub.AccentColour = colours.GreySeaFoamLighter; Nub.GlowingAccentColour = Color4.White; Nub.GlowColour = Color4.White; } } }
mit
C#
dcb1f347502b49af3791b5e8ab14af61c3273d1d
Use log/HEAD instead of HEAD to listen for updates
awaescher/RepoZ,awaescher/RepoZ
RepoZ.Api.Win/Git/DefaultRepositoryObserver.cs
RepoZ.Api.Win/Git/DefaultRepositoryObserver.cs
using RepoZ.Api.Git; using System; using System.IO; using System.Threading.Tasks; namespace RepoZ.Api.Win.Git { public class DefaultRepositoryObserver : IRepositoryObserver { private const string HEAD_LOG_FILE = @".git\logs\HEAD"; private string _path; private FileSystemWatcher _watcher; private IRepositoryReader _repositoryReader; public DefaultRepositoryObserver(IRepositoryReader repositoryReader) { _repositoryReader = repositoryReader; } public Action<Repository> OnAddOrChange { get; set; } public Action<string> OnDelete { get; set; } public void Setup(string path) { _path = path; _watcher = new FileSystemWatcher(_path, "HEAD"); _watcher.Created += _watcher_Created; _watcher.Changed += _watcher_Changed; _watcher.Deleted += _watcher_Deleted; _watcher.Renamed += _watcher_Renamed; _watcher.IncludeSubdirectories = true; } public void Observe() { _watcher.EnableRaisingEvents = true; } public void Stop() { _watcher.EnableRaisingEvents = false; } private void _watcher_Deleted(object sender, FileSystemEventArgs e) { if (!IsHead(e.FullPath)) return; NotifyHeadDeletion(e.FullPath); } private void _watcher_Renamed(object sender, RenamedEventArgs e) { if (!IsHead(e.OldFullPath)) return; NotifyHeadDeletion(e.OldFullPath); } private void _watcher_Changed(object sender, FileSystemEventArgs e) { if (!IsHead(e.FullPath)) return; EatRepo(e.FullPath); } private void _watcher_Created(object sender, FileSystemEventArgs e) { if (!IsHead(e.FullPath)) return; Task.Run(() => Task.Delay(5000)) .ContinueWith(t => EatRepo(e.FullPath)); } private bool IsHead(string path) { int index = GetGitPathEndFromHeadFile(path); return index == (path.Length - HEAD_LOG_FILE.Length); } private string GetRepositoryPathFromHead(string headFile) { int end = GetGitPathEndFromHeadFile(headFile); if (end < 0) return string.Empty; return headFile.Substring(0, end); } private int GetGitPathEndFromHeadFile(string path) => path.IndexOf(HEAD_LOG_FILE, StringComparison.OrdinalIgnoreCase); private void EatRepo(string path) { var repo = _repositoryReader.ReadRepository(path); if (repo?.WasFound ?? false) { OnAddOrChange?.Invoke(repo); } } private void NotifyHeadDeletion(string headFile) { string path = GetRepositoryPathFromHead(headFile); if (!string.IsNullOrEmpty(path)) OnDelete?.Invoke(path); } } }
using RepoZ.Api.Git; using System; using System.IO; using System.Threading.Tasks; namespace RepoZ.Api.Win.Git { public class DefaultRepositoryObserver : IRepositoryObserver { private const string HEAD_FILE = @".git\HEAD"; private string _path; private FileSystemWatcher _watcher; private IRepositoryReader _repositoryReader; public DefaultRepositoryObserver(IRepositoryReader repositoryReader) { _repositoryReader = repositoryReader; } public Action<Repository> OnAddOrChange { get; set; } public Action<string> OnDelete { get; set; } public void Setup(string path) { _path = path; _watcher = new FileSystemWatcher(_path, "HEAD"); _watcher.Created += _watcher_Created; _watcher.Changed += _watcher_Changed; _watcher.Deleted += _watcher_Deleted; _watcher.Renamed += _watcher_Renamed; _watcher.IncludeSubdirectories = true; } public void Observe() { _watcher.EnableRaisingEvents = true; } public void Stop() { _watcher.EnableRaisingEvents = false; } private void _watcher_Deleted(object sender, FileSystemEventArgs e) { if (!IsHead(e.FullPath)) return; NotifyHeadDeletion(e.FullPath); } private void _watcher_Renamed(object sender, RenamedEventArgs e) { if (!IsHead(e.OldFullPath)) return; NotifyHeadDeletion(e.OldFullPath); } private void _watcher_Changed(object sender, FileSystemEventArgs e) { if (!IsHead(e.FullPath)) return; EatRepo(e.FullPath); } private void _watcher_Created(object sender, FileSystemEventArgs e) { if (!IsHead(e.FullPath)) return; Task.Run(() => Task.Delay(5000)) .ContinueWith(t => EatRepo(e.FullPath)); } private bool IsHead(string path) { int index = GetGitPathEndFromHeadFile(path); return index == (path.Length - HEAD_FILE.Length); } private string GetRepositoryPathFromHead(string headFile) { int end = GetGitPathEndFromHeadFile(headFile); if (end < 0) return string.Empty; return headFile.Substring(0, end); } private int GetGitPathEndFromHeadFile(string path) => path.IndexOf(HEAD_FILE, StringComparison.OrdinalIgnoreCase); private void EatRepo(string path) { var repo = _repositoryReader.ReadRepository(path); if (repo?.WasFound ?? false) { OnAddOrChange?.Invoke(repo); } } private void NotifyHeadDeletion(string headFile) { string path = GetRepositoryPathFromHead(headFile); if (!string.IsNullOrEmpty(path)) OnDelete?.Invoke(path); } } }
mit
C#
bbedc3be60261d1e8ec01dc5cb39d2db36b633ab
Comment clarification
bogosoft/Collections.Async
Bogosoft.Collections.Async/ICursor.cs
Bogosoft.Collections.Async/ICursor.cs
using System; using System.Threading; using System.Threading.Tasks; namespace Bogosoft.Collections.Async { /// <summary> /// Represents a forward-only, iterable data structure. /// </summary> /// <typeparam name="T">The type of the object being traversed.</typeparam> public interface ICursor<T> : IDisposable { /// <summary> /// Get a value indicating whether the current cursor has been disposed of. /// </summary> bool IsDisposed { get; } /// <summary> /// Get a value indicating whether the current cursor has moved past its last record. /// </summary> bool IsExpended { get; } /// <summary> /// Get the item pointed at by the present position of the current cursor. /// </summary> /// <param name="token">A <see cref="CancellationToken"/> object.</param> /// <returns> /// The item at the present position of the current cursor. Note that the result of calling this method before calling /// <see cref="MoveNextAsync(CancellationToken)"/> for the first time is undefined. /// </returns> /// <exception cref="InvalidOperationException"> /// Implementations SHOULD throw an <see cref="InvalidOperationException"/> in the case that /// calling <see cref="MoveNextAsync(CancellationToken)"/> before this method would result in /// a value of false. /// </exception> Task<T> GetCurrentAsync(CancellationToken token); /// <summary> /// Advance the position of the current cursor and get a value indicating whether or not /// the resulting position is a valid record. /// </summary> /// <param name="token">A <see cref="CancellationToken"/> object.</param> /// <returns> /// True if the position of the cursor corresponds to a valid record; false otherwise. /// </returns> Task<bool> MoveNextAsync(CancellationToken token); } }
using System; using System.Threading; using System.Threading.Tasks; namespace Bogosoft.Collections.Async { /// <summary> /// Represents a forward-only, iterable data structure. /// </summary> /// <typeparam name="T">The type of the object being traversed.</typeparam> public interface ICursor<T> : IDisposable { /// <summary> /// Get a value indicating whether the current cursor has been disposed of. /// </summary> bool IsDisposed { get; } /// <summary> /// Get a value indicating whether the current cursor has moved past its last record. /// </summary> bool IsExpended { get; } /// <summary> /// Get the item pointed at by the present position of the current cursor. /// </summary> /// <param name="token">A <see cref="CancellationToken"/> object.</param> /// <returns>The item at the present position of the current cursor.</returns> /// <exception cref="InvalidOperationException"> /// Implementations SHOULD throw an <see cref="InvalidOperationException"/> in the case that /// calling <see cref="MoveNextAsync(CancellationToken)"/> before this method would result in /// a value of false. /// </exception> Task<T> GetCurrentAsync(CancellationToken token); /// <summary> /// Advance the position of the current cursor and get a value indicating whether or not /// the resulting position is a valid record. /// </summary> /// <param name="token">A <see cref="CancellationToken"/> object.</param> /// <returns> /// True if the position of the cursor corresponds to a valid record; false otherwise. /// </returns> Task<bool> MoveNextAsync(CancellationToken token); } }
mit
C#
3b059dee2b01732a7050b5e97fd8b4cef982af0a
Fix SoundBlock names
Yonom/CupCake
CupCake.Messages/Blocks/SoundBlock.cs
CupCake.Messages/Blocks/SoundBlock.cs
using System; namespace CupCake.Messages.Blocks { public enum SoundBlock { [Obsolete("Use SoundBlock.MusicPiano instead.")] BlockMusicPiano = Block.MusicPiano, [Obsolete("Use SoundBlock.MusicDrum instead.")] BlockMusicDrum = Block.MusicDrum, MusicPiano = Block.MusicPiano, MusicDrum = Block.MusicDrum } }
namespace CupCake.Messages.Blocks { public enum SoundBlock { BlockMusicPiano = Block.MusicPiano, BlockMusicDrum = Block.MusicDrum } }
mit
C#
38dd5d447dc1182f5f1240f23269521b4d773626
Add quotes to paths for Windows
awaescher/RepoZ,awaescher/RepoZ
grr/Messages/OpenDirectoryMessage.cs
grr/Messages/OpenDirectoryMessage.cs
using System.Diagnostics; using System.IO; using System.Linq; namespace grr.Messages { [System.Diagnostics.DebuggerDisplay("{GetRemoteCommand()}")] public class OpenDirectoryMessage : DirectoryMessage { public OpenDirectoryMessage(RepositoryFilterOptions filter) : base(filter) { } protected override void ExecuteExistingDirectory(string directory) { // use '/' for linux systems and bash command line (will work on cmd and powershell as well) directory = directory.Replace(@"\", "/"); if (Platform == "win") directory == $"\"{directory}\""; Process.Start(new ProcessStartInfo(directory) { UseShellExecute = true }); } } }
using System.Diagnostics; using System.IO; using System.Linq; namespace grr.Messages { [System.Diagnostics.DebuggerDisplay("{GetRemoteCommand()}")] public class OpenDirectoryMessage : DirectoryMessage { public OpenDirectoryMessage(RepositoryFilterOptions filter) : base(filter) { } protected override void ExecuteExistingDirectory(string directory) { // use '/' for linux systems and bash command line (will work on cmd and powershell as well) directory = directory.Replace(@"\", "/"); Process.Start(new ProcessStartInfo($"\"{directory}\"") { UseShellExecute = true }); } } }
mit
C#
3d1cda4161fd3c6c37a4d4f35197a4b6cee49e64
enable back data factory initialization during application start
AzureDay/2017-WebSite,AzureDay/2017-WebSite
TeamSpark.AzureDay.WebSite.Host/Global.asax.cs
TeamSpark.AzureDay.WebSite.Host/Global.asax.cs
using System; using System.Threading; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Microsoft.ApplicationInsights.Extensibility; using TeamSpark.AzureDay.WebSite.Config; using TeamSpark.AzureDay.WebSite.Host.Controllers; using TeamSpark.AzureDay.WebSite.Data; namespace TeamSpark.AzureDay.WebSite.Host { public class MvcApplication : HttpApplication { protected void Application_Start() { #region application insight TelemetryConfiguration.Active.InstrumentationKey = Configuration.ApplicationInsightInstrumentationKey; #endregion #region asp net mvc AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); #endregion #region initialize DataFactory.InitializeAsync().Wait(); #endregion } private void Application_BeginRequest(Object source, EventArgs e) { var application = (HttpApplication)source; var context = application.Context; string culture; var languageCookie = context.Request.Cookies[LanguageController.LANGUAGE_COOKIE]; if (languageCookie != null) { culture = languageCookie.Value; } else { if (context.Request.UserLanguages != null && context.Request.UserLanguages.Length > 0) { culture = context.Request.UserLanguages[0]; } else { culture = "en"; } } Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(culture); Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture; } } }
using System; using System.Threading; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Microsoft.ApplicationInsights.Extensibility; using TeamSpark.AzureDay.WebSite.Config; using TeamSpark.AzureDay.WebSite.Host.Controllers; //using TeamSpark.AzureDay.WebSite.Data; namespace TeamSpark.AzureDay.WebSite.Host { public class MvcApplication : HttpApplication { protected void Application_Start() { #region application insight TelemetryConfiguration.Active.InstrumentationKey = Configuration.ApplicationInsightInstrumentationKey; #endregion #region asp net mvc AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); #endregion #region initialize //DataFactory.InitializeAsync().Wait(); #endregion } private void Application_BeginRequest(Object source, EventArgs e) { var application = (HttpApplication)source; var context = application.Context; string culture; var languageCookie = context.Request.Cookies[LanguageController.LANGUAGE_COOKIE]; if (languageCookie != null) { culture = languageCookie.Value; } else { if (context.Request.UserLanguages != null && context.Request.UserLanguages.Length > 0) { culture = context.Request.UserLanguages[0]; } else { culture = "en"; } } Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(culture); Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture; } } }
mit
C#
c178a6e57fa5455417a97125fc6fe3213df54ea2
add ctor overloads for HttpSigningMessageHandler
claq2/IdentityModel.HttpSigning,IdentityModel/IdentityModel.HttpSigning
src/IdentityModel.HttpSigning/HttpClient/HttpSigningMessageHandler.cs
src/IdentityModel.HttpSigning/HttpClient/HttpSigningMessageHandler.cs
using IdentityModel.HttpSigning.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; namespace IdentityModel.HttpSigning { public class HttpSigningMessageHandler : DelegatingHandler { private static readonly ILog Logger = LogProvider.GetCurrentClassLogger(); private readonly Signature _signature; private readonly RequestSigningOptions _options; public HttpSigningMessageHandler(Signature signature, RequestSigningOptions options, HttpMessageHandler innerHandler) : base(innerHandler) { if (signature == null) throw new ArgumentNullException("signature"); _signature = signature; _options = options ?? new RequestSigningOptions(); } public HttpSigningMessageHandler(Signature signature, RequestSigningOptions options) : this(signature, options, new HttpClientHandler()) { } public HttpSigningMessageHandler(Signature signature, HttpMessageHandler innerHandler) : this(signature, null, innerHandler) { } public HttpSigningMessageHandler(Signature signature) : this(signature, null, new HttpClientHandler()) { } protected async override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { await ProcessSignatureAsync(request); return await base.SendAsync(request, cancellationToken); } public async Task ProcessSignatureAsync(HttpRequestMessage request) { var parameters = await _options.CreateEncodingParametersAsync(request); if (parameters != null) { Logger.Debug("Encoding parameters recieved; signing and adding pop token"); var token = _signature.Sign(parameters); request.AddPopToken(token); } else { Logger.Debug("No encoding parameters recieved; not adding pop token"); } } } }
using IdentityModel.HttpSigning.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; namespace IdentityModel.HttpSigning { public class HttpSigningMessageHandler : DelegatingHandler { private static readonly ILog Logger = LogProvider.GetCurrentClassLogger(); private readonly Signature _signature; private readonly RequestSigningOptions _options; public HttpSigningMessageHandler(Signature signature, RequestSigningOptions options, HttpMessageHandler innerHandler) : base(innerHandler) { if (signature == null) throw new ArgumentNullException("signature"); _signature = signature; _options = options ?? new RequestSigningOptions(); } public HttpSigningMessageHandler(Signature signature, HttpMessageHandler innerHandler) : this(signature, null, innerHandler) { } protected async override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { await ProcessSignatureAsync(request); return await base.SendAsync(request, cancellationToken); } public async Task ProcessSignatureAsync(HttpRequestMessage request) { var parameters = await _options.CreateEncodingParametersAsync(request); if (parameters != null) { Logger.Debug("Encoding parameters recieved; signing and adding pop token"); var token = _signature.Sign(parameters); request.AddPopToken(token); } else { Logger.Debug("No encoding parameters recieved; not adding pop token"); } } } }
apache-2.0
C#
f60eb55fbb5cbb33c64dfd49148d43205a5c481a
Implement "enable" event to reenable after "stop".
j-be/vj-servo-controller,j-be/vj-servo-controller,j-be/vj-servo-controller,j-be/vj-servo-controller,j-be/vj-servo-controller
Unity/ServoController/ServoControllerClient.cs
Unity/ServoController/ServoControllerClient.cs
using UnityEngine; using SocketIOClient; public class ServoControllerClient : AbstractSocketioClient { private static readonly string SOCKETIO_SERVER = "http://192.168.1.51:5000"; private static readonly string SOCKETIO_NAMESPACE = "/servo"; public ServoControllerClient() : base(SOCKETIO_SERVER, SOCKETIO_NAMESPACE){} /* -------------------- */ /* - Eventemitter - */ /* -------------------- */ public void EventSetServoPosition(long position) { Debug.LogWarning("Set servo to: " + position); this.Emit("moveTo", position); } public void EventStop() { this.Emit("stop"); } public void EventEnable() { this.Emit("enable"); } public void PullToLeft() { this.Emit("pullToLeft"); } public void PullToRight() { this.Emit("pullToRight"); } }
using UnityEngine; using SocketIOClient; public class ServoControllerClient : AbstractSocketioClient { private static readonly string SOCKETIO_SERVER = "http://192.168.1.51:5000"; private static readonly string SOCKETIO_NAMESPACE = "/servo"; public ServoControllerClient() : base(SOCKETIO_SERVER, SOCKETIO_NAMESPACE){} /* -------------------- */ /* - Eventemitter - */ /* -------------------- */ public void EventSetServoPosition(long position) { this.Emit("moveTo", position); } public void EventStop() { this.Emit("stop"); } public void PullToLeft() { this.Emit("pullToLeft"); } public void PullToRight() { this.Emit("pullToRight"); } }
mit
C#
31ef6185088579df1307aacd32e63c74ca3b2141
remove adding to ruleset singleton on build
chrismckelt/WebMinder,chrismckelt/WebMinder,chrismckelt/WebMinder
Core/Runners/Create.cs
Core/Runners/Create.cs
using System; using WebMinder.Core.Handlers; using WebMinder.Core.Rules; namespace WebMinder.Core.Runners { public class Create<TRuleSetHandler, TRuleRequest> where TRuleSetHandler : IRuleSetHandler<TRuleRequest> where TRuleRequest : IRuleRequest, new() { private static TRuleSetHandler _rule; private static IRuleRequest _request; public TRuleSetHandler Rule { get { return _rule; } } public static Create<TRuleSetHandler, TRuleRequest> On<T>(Action<T> setter = null) where T : IRuleRequest, new() { _rule = Activator.CreateInstance<TRuleSetHandler>(); _request = Activator.CreateInstance<T>(); if (setter != null) setter((T)_request); return AppendRule(); } internal void SetRule(TRuleSetHandler rule) { _rule = rule; } public Create<TRuleSetHandler, TRuleRequest> With(Action<TRuleSetHandler> setter) { setter(_rule); return AppendRule(); } public Create<TRuleSetHandler, TRuleRequest> Build() { return AppendRule(); } public static Create<TRuleSetHandler, TRuleRequest> AppendRule() { var result = new Create<TRuleSetHandler, TRuleRequest>(); result.SetRule(_rule); return result; } } }
using System; using WebMinder.Core.Handlers; using WebMinder.Core.Rules; namespace WebMinder.Core.Runners { public class Create<TRuleSetHandler, TRuleRequest> where TRuleSetHandler : IRuleSetHandler<TRuleRequest> where TRuleRequest : IRuleRequest, new() { private static TRuleSetHandler _rule; private static IRuleRequest _request; public TRuleSetHandler Rule { get { return _rule; } } public static Create<TRuleSetHandler, TRuleRequest> On<T>(Action<T> setter = null) where T : IRuleRequest, new() { _rule = Activator.CreateInstance<TRuleSetHandler>(); _request = Activator.CreateInstance<T>(); if (setter != null) setter((T)_request); return AppendRule(); } internal void SetRule(TRuleSetHandler rule) { _rule = rule; } public Create<TRuleSetHandler, TRuleRequest> With(Action<TRuleSetHandler> setter) { setter(_rule); return AppendRule(); } public Create<TRuleSetHandler, TRuleRequest> Build() { RuleSetRunner.Instance.AddRule<TRuleSetHandler>(_rule); return AppendRule(); } public static Create<TRuleSetHandler, TRuleRequest> AppendRule() { var result = new Create<TRuleSetHandler, TRuleRequest>(); result.SetRule(_rule); return result; } } }
apache-2.0
C#
d44cfb6b4d7a8a82ef3fbb15f41ca0323a3cf627
Remove unused call
BenPhegan/NuGet.Extensions
NuGet.Extensions.Tests/ReferenceAnalysers/ReferenceNugetifierTester.cs
NuGet.Extensions.Tests/ReferenceAnalysers/ReferenceNugetifierTester.cs
using System.Collections.Generic; using System.IO; using Moq; using NuGet.Common; using NuGet.Extensions.MSBuild; using NuGet.Extensions.ReferenceAnalysers; using NuGet.Extensions.Tests.Mocks; namespace NuGet.Extensions.Tests.ReferenceAnalysers { public class ReferenceNugetifierTester { private const string DefaultProjectPath = "c:\\isany.csproj"; public static List<ManifestDependency> CallNugetifyReferences(ReferenceNugetifier nugetifier, ISharedPackageRepository sharedPackageRepository = null, string defaultProjectPath = null, List<string> projectReferences = null) { sharedPackageRepository = sharedPackageRepository ?? new Mock<ISharedPackageRepository>().Object; defaultProjectPath = defaultProjectPath ?? DefaultProjectPath; projectReferences = projectReferences ?? new List<string>(); return nugetifier.CreateNuGetScaffolding(sharedPackageRepository, projectReferences); } public static ReferenceNugetifier BuildNugetifier(IFileSystem projectFileSystem = null, IVsProject vsProject = null, PackageReferenceFile packageReferenceFile = null, IPackageRepository packageRepository = null) { var console = new Mock<IConsole>(); var projectFileInfo = new FileInfo(DefaultProjectPath); var solutionRoot = new DirectoryInfo("c:\\isAnyFolder"); projectFileSystem = projectFileSystem ?? new MockFileSystem(solutionRoot.FullName); vsProject = vsProject ?? new Mock<IVsProject>().Object; packageReferenceFile = packageReferenceFile ?? new PackageReferenceFile(projectFileSystem, solutionRoot.FullName); packageRepository = packageRepository ?? new MockPackageRepository(); return new ReferenceNugetifier(console.Object, true, projectFileInfo, solutionRoot, projectFileSystem, vsProject, packageReferenceFile, packageRepository, "packages.config"); } } }
using System.Collections.Generic; using System.IO; using Moq; using NuGet.Common; using NuGet.Extensions.MSBuild; using NuGet.Extensions.ReferenceAnalysers; using NuGet.Extensions.Tests.Mocks; namespace NuGet.Extensions.Tests.ReferenceAnalysers { public class ReferenceNugetifierTester { private const string DefaultProjectPath = "c:\\isany.csproj"; public static List<ManifestDependency> CallNugetifyReferences(ReferenceNugetifier nugetifier, ISharedPackageRepository sharedPackageRepository = null, string defaultProjectPath = null, List<string> projectReferences = null) { sharedPackageRepository = sharedPackageRepository ?? new Mock<ISharedPackageRepository>().Object; defaultProjectPath = defaultProjectPath ?? DefaultProjectPath; projectReferences = projectReferences ?? new List<string>(); nugetifier.UpdateProjectFileReferenceHintPaths(); return nugetifier.CreateNuGetScaffolding(sharedPackageRepository, projectReferences); } public static ReferenceNugetifier BuildNugetifier(IFileSystem projectFileSystem = null, IVsProject vsProject = null, PackageReferenceFile packageReferenceFile = null, IPackageRepository packageRepository = null) { var console = new Mock<IConsole>(); var projectFileInfo = new FileInfo(DefaultProjectPath); var solutionRoot = new DirectoryInfo("c:\\isAnyFolder"); projectFileSystem = projectFileSystem ?? new MockFileSystem(solutionRoot.FullName); vsProject = vsProject ?? new Mock<IVsProject>().Object; packageReferenceFile = packageReferenceFile ?? new PackageReferenceFile(projectFileSystem, solutionRoot.FullName); packageRepository = packageRepository ?? new MockPackageRepository(); return new ReferenceNugetifier(console.Object, true, projectFileInfo, solutionRoot, projectFileSystem, vsProject, packageReferenceFile, packageRepository, "packages.config"); } } }
mit
C#
be062b0cae79f08ebd009abc20eb4c3c868244af
Include date in booked in fact
tvjames/eventstore-bnosql-sample,tvjames/eventstore-bnosql-sample
EventStorePlayConsole/BookedInFact.cs
EventStorePlayConsole/BookedInFact.cs
using System; using EventStore.ClientAPI; using System.Net; namespace EventStorePlayConsole { public class BookedInFact:Fact { public BookedInFact(string atValue, string someValue) { this.OccurredAt = DateTime.UtcNow; this.BookedInAtValue = atValue; this.PreviousBookingValue = someValue; } public DateTime OccurredAt { get; private set; } public string BookedInAtValue { get; private set; } public string PreviousBookingValue { get; private set; } public override string ToString() { return string.Format("[BookedInEvent: Id={0}, BookedInAtValue={1}, PreviousBookingValue={2}]", Id, BookedInAtValue, PreviousBookingValue); } } }
using System; using EventStore.ClientAPI; using System.Net; namespace EventStorePlayConsole { public class BookedInFact:Fact { public BookedInFact(string atValue, string someValue) { this.BookedInAtValue = atValue; this.PreviousBookingValue = someValue; } public string BookedInAtValue { get; private set; } public string PreviousBookingValue { get; private set; } public override string ToString() { return string.Format("[BookedInEvent: Id={0}, BookedInAtValue={1}, PreviousBookingValue={2}]", Id, BookedInAtValue, PreviousBookingValue); } } }
mit
C#
4009805617bf5c322efd92abadf483fcc9cf15b8
Make stats_only_admins a nullable bool, we're seeing this cause json deserialization exceptions when calling SlackClient.ConnectAsync()
Inumedia/SlackAPI
SlackAPI/TeamPreferences.cs
SlackAPI/TeamPreferences.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SlackAPI { public class TeamPreferences { public AuthMode auth_mode; public string[] default_channels; public bool display_real_names; public bool gateway_allow_irc_plain; public bool gateway_allow_irc_ssl; public bool gateway_allow_xmpp_ssl; public bool hide_referers; public int msg_edit_window_mins; public bool srvices_only_admins; public bool? stats_only_admins; public enum AuthMode { normal, saml, google } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SlackAPI { public class TeamPreferences { public AuthMode auth_mode; public string[] default_channels; public bool display_real_names; public bool gateway_allow_irc_plain; public bool gateway_allow_irc_ssl; public bool gateway_allow_xmpp_ssl; public bool hide_referers; public int msg_edit_window_mins; public bool srvices_only_admins; public bool stats_only_admins; public enum AuthMode { normal, saml, google } } }
mit
C#
876c65b883fab255f658ce38b3d1d71ea17ca8e6
Fix a migration
ekyoung/contact-repository,ekyoung/contact-repository
Source/Core/Bootstrapping/Migrations/Migration201312141425_CreateContactEmailAddressesTable.cs
Source/Core/Bootstrapping/Migrations/Migration201312141425_CreateContactEmailAddressesTable.cs
using FluentMigrator; namespace EthanYoung.ContactRepository.Bootstrapping.Migrations { [Migration(201312141425)] public class Migration201312141425_CreateContactEmailAddressesTable : Migration { public override void Up() { Create.Table("ContactEmailAddresses") .WithColumn("ContactId").AsInt64() .WithColumn("EmailAddress").AsString().NotNullable() .WithColumn("Nickname").AsString().Nullable() .WithColumn("IsPrimary").AsBoolean().NotNullable(); Create.ForeignKey("FK_ContactEmailAddresses_Contacts") .FromTable("ContactEmailAddresses").ForeignColumn("ContactId") .ToTable("Contacts").PrimaryColumn("ContactId"); } public override void Down() { Delete.Table("ContactEmailAddresses"); } } }
using FluentMigrator; namespace EthanYoung.ContactRepository.Bootstrapping.Migrations { [Migration(201312141425)] public class Migration201312141425_CreateContactEmailAddressesTable : Migration { public override void Up() { Create.Table("ContactEmailAddresses") .WithColumn("ContactId").AsInt64() .WithColumn("EmailAddress").AsString().NotNullable() .WithColumn("Nickname").AsString().Nullable() .WithColumn("IsPrimary").AsBoolean().NotNullable(); Create.ForeignKey("FK_ContactEmailAddresses_Contacts") .FromTable("ContactEmailAddresses").ForeignColumn("ContactId") .ToTable("Contacts").PrimaryColumn("ContactId"); } public override void Down() { Delete.ForeignKey("FK_ContactEmailAddresses_Contacts"); Delete.Table("ContactEmailAddresses"); } } }
mit
C#
fdf6bb76f56c2a6229cb64bff63cb70edb569dc1
fix broken build
joeaudette/cloudscribe.SimpleContent,joeaudette/cloudscribe.SimpleContent
src/cloudscribe.Core.SimpleContent.Integration/ViewModels/ProjectViewModel.cs
src/cloudscribe.Core.SimpleContent.Integration/ViewModels/ProjectViewModel.cs
 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace cloudscribe.Core.SimpleContent.Integration.ViewModels { public class ProjectViewModel { public string Title { get; set; } = "Blog"; public bool ShowTitle { get; set; } = false; public string Description { get; set; } = string.Empty; public string CopyrightNotice { get; set; } = string.Empty; public string Image { get; set; } = string.Empty; public int PostsPerPage { get; set; } = 5; public string PubDateFormat { get; set; } = "MMMM d. yyyy"; public bool IncludePubDateInPostUrls { get; set; } = true; //public string LocalMediaVirtualPath { get; set; } = "/media/images/"; public int DaysToComment { get; set; } = -1; public bool ModerateComments { get; set; } = true; public string CommentNotificationEmail { get; set; } = string.Empty; public int GravatarSize { get; set; } = 50; //public string DefaultPageSlug { get; set; } = "home"; //public bool UseDefaultPageAsRootNode { get; set; } = true; //public string AllowedEditRoles { get; set; } = "Administrators"; // if true automatically add the blog index //public bool AddBlogToPagesTree { get; set; } = true; //public int BlogPagePosition { get; set; } = 2; // right after home page //public string BlogPageText { get; set; } = "Blog"; //public string BlogPageNavComponentVisibility { get; set; } = "topnav"; public string RemoteFeedUrl { get; set; } = string.Empty; /// <summary> /// ie Feedburner User Agent fragment "FeedBurner" /// </summary> public string RemoteFeedProcessorUseAgentFragment { get; set; } = string.Empty; public bool UseMetaDescriptionInFeed { get; set; } = false; public int ChannelTimeToLive { get; set; } = 60; public string LanguageCode { get; set; } = "en-US"; public string ChannelCategoriesCsv { get; set; } = string.Empty; public string ManagingEditorEmail { get; set; } = string.Empty; public string ChannelRating { get; set; } = string.Empty; public string WebmasterEmail { get; set; } = string.Empty; } }
 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace cloudscribe.Core.SimpleContent.Integration.ViewModels { public class ProjectViewModel { #region Blog Settings public string Title { get; set; } = "Blog"; public bool ShowTitle { get; set; } = false; public string Description { get; set; } = string.Empty; public string CopyrightNotice { get; set; } = string.Empty; public string Image { get; set; } = string.Empty; public int PostsPerPage { get; set; } = 5; public string PubDateFormat { get; set; } = "MMMM d. yyyy"; public bool IncludePubDateInPostUrls { get; set; } = true; //public string LocalMediaVirtualPath { get; set; } = "/media/images/"; #region public int DaysToComment { get; set; } = -1; public bool ModerateComments { get; set; } = true; public string CommentNotificationEmail { get; set; } = string.Empty; public int GravatarSize { get; set; } = 50; #region Navigation Settings //public string DefaultPageSlug { get; set; } = "home"; //public bool UseDefaultPageAsRootNode { get; set; } = true; #endregion //public string AllowedEditRoles { get; set; } = "Administrators"; // if true automatically add the blog index //public bool AddBlogToPagesTree { get; set; } = true; //public int BlogPagePosition { get; set; } = 2; // right after home page //public string BlogPageText { get; set; } = "Blog"; //public string BlogPageNavComponentVisibility { get; set; } = "topnav"; #region Feed Settings public string RemoteFeedUrl { get; set; } = string.Empty; /// <summary> /// ie Feedburner User Agent fragment "FeedBurner" /// </summary> public string RemoteFeedProcessorUseAgentFragment { get; set; } = string.Empty; public bool UseMetaDescriptionInFeed { get; set; } = false; public int ChannelTimeToLive { get; set; } = 60; public string LanguageCode { get; set; } = "en-US"; public string ChannelCategoriesCsv { get; set; } = string.Empty; public string ManagingEditorEmail { get; set; } = string.Empty; public string ChannelRating { get; set; } = string.Empty; public string WebmasterEmail { get; set; } = string.Empty; #endregion } }
apache-2.0
C#
d3b4ed3a437d6b5649ef8032b39fdbbb5bfbfd71
Fix failing Navigation test.
modulexcite/DartVS,DartVS/DartVS,DartVS/DartVS,modulexcite/DartVS,modulexcite/DartVS,DartVS/DartVS
DanTup.DartAnalysis.Tests/Tests.cs
DanTup.DartAnalysis.Tests/Tests.cs
namespace DanTup.DartAnalysis.Tests { public abstract class Tests { protected const string SdkFolder = @"M:\Apps\Dart\sdk"; protected const string ServerScript = @"M:\Coding\Applications\DanTup.DartVS\Dart\AnalysisServer.dart"; protected const string SampleDartProject = @"M:\Coding\Applications\DanTup.DartVS\DanTup.DartAnalysis.Tests.SampleDartProject"; protected const string HelloWorldFile = SampleDartProject + @"\hello_world.dart"; protected const string SingleTypeErrorFile = SampleDartProject + @"\single_type_error.dart"; } }
namespace DanTup.DartAnalysis.Tests { public abstract class Tests { protected const string SdkFolder = @"M:\Apps\Dart\SDK"; protected const string ServerScript = @"M:\Coding\Applications\DanTup.DartVS\Dart\AnalysisServer.dart"; protected const string SampleDartProject = @"M:\Coding\Applications\DanTup.DartVS\DanTup.DartAnalysis.Tests.SampleDartProject"; protected const string HelloWorldFile = SampleDartProject + @"\hello_world.dart"; protected const string SingleTypeErrorFile = SampleDartProject + @"\single_type_error.dart"; } }
mit
C#
04de92ab43027aa37526ad1ed9826d1bf367c833
Update WalletWasabi/Services/Terminate/TerminateService.cs
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Services/Terminate/TerminateService.cs
WalletWasabi/Services/Terminate/TerminateService.cs
using System; using System.Threading; using System.Threading.Tasks; using WalletWasabi.Logging; namespace WalletWasabi.Services.Terminate { public class TerminateService { private Func<Task> _terminateApplicationAsync; private const long TerminateStatusIdle = 0; private const long TerminateStatusInProgress = 1; private const long TerminateStatusFinished = 2; private long _terminateStatus; public TerminateService(Func<Task> terminateApplicationAsync) { _terminateApplicationAsync = terminateApplicationAsync; AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; Console.CancelKeyPress += Console_CancelKeyPress; } private void CurrentDomain_ProcessExit(object? sender, EventArgs e) { Logger.LogDebug("ProcessExit was called."); // This must be a blocking call because after this the OS will terminate Wasabi process if exists. Terminate(); } private void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e) { Logger.LogWarning($"Process termination was requested using '{e.SpecialKey}' keyboard shortcut."); // This must be a blocking call because after this the OS will terminate Wasabi process if it exists. // In some cases CurrentDomain_ProcessExit is called after this by the OS. Terminate(); } /// <summary> /// Terminates the application. /// </summary> /// <remark>This is a blocking method. Note that program execution ends at the end of this method due to <see cref="Environment.Exit(int)"/> call.</remark> public void Terminate(int exitCode = 0) { var prevValue = Interlocked.CompareExchange(ref _terminateStatus, TerminateStatusInProgress, TerminateStatusIdle); Logger.LogTrace($"Terminate was called from ThreadId: {Thread.CurrentThread.ManagedThreadId}"); if (prevValue != TerminateStatusIdle) { // Secondary callers will be blocked until the end of the termination. while (_terminateStatus != TerminateFinished) { } return; } // First caller starts the terminate procedure. Logger.LogDebug("Start shutting down the application."); // Async termination has to be started on another thread otherwise there is a possibility of deadlock. // We still need to block the caller so ManualResetEvent applied. using ManualResetEvent resetEvent = new ManualResetEvent(false); Task.Run(async () => { try { await _terminateApplicationAsync().ConfigureAwait(false); } catch (Exception ex) { Logger.LogWarning(ex.ToTypeMessageString()); } resetEvent.Set(); }); resetEvent.WaitOne(); AppDomain.CurrentDomain.ProcessExit -= CurrentDomain_ProcessExit; Console.CancelKeyPress -= Console_CancelKeyPress; // Indicate that the termination procedure finished. So other callers can return. Interlocked.Exchange(ref _terminateStatus, TerminateFinished); Environment.Exit(exitCode); } public bool IsTerminateRequested => Interlocked.Read(ref _terminateStatus) > TerminateStatusIdle; } }
using System; using System.Threading; using System.Threading.Tasks; using WalletWasabi.Logging; namespace WalletWasabi.Services.Terminate { public class TerminateService { private Func<Task> _terminateApplicationAsync; private const long TerminateStatusIdle = 0; private const long TerminateStatusInProgress = 1; private const long TerminateFinished = 2; private long _terminateStatus; public TerminateService(Func<Task> terminateApplicationAsync) { _terminateApplicationAsync = terminateApplicationAsync; AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; Console.CancelKeyPress += Console_CancelKeyPress; } private void CurrentDomain_ProcessExit(object? sender, EventArgs e) { Logger.LogDebug("ProcessExit was called."); // This must be a blocking call because after this the OS will terminate Wasabi process if exists. Terminate(); } private void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e) { Logger.LogWarning($"Process termination was requested using '{e.SpecialKey}' keyboard shortcut."); // This must be a blocking call because after this the OS will terminate Wasabi process if it exists. // In some cases CurrentDomain_ProcessExit is called after this by the OS. Terminate(); } /// <summary> /// Terminates the application. /// </summary> /// <remark>This is a blocking method. Note that program execution ends at the end of this method due to <see cref="Environment.Exit(int)"/> call.</remark> public void Terminate(int exitCode = 0) { var prevValue = Interlocked.CompareExchange(ref _terminateStatus, TerminateStatusInProgress, TerminateStatusIdle); Logger.LogTrace($"Terminate was called from ThreadId: {Thread.CurrentThread.ManagedThreadId}"); if (prevValue != TerminateStatusIdle) { // Secondary callers will be blocked until the end of the termination. while (_terminateStatus != TerminateFinished) { } return; } // First caller starts the terminate procedure. Logger.LogDebug("Start shutting down the application."); // Async termination has to be started on another thread otherwise there is a possibility of deadlock. // We still need to block the caller so ManualResetEvent applied. using ManualResetEvent resetEvent = new ManualResetEvent(false); Task.Run(async () => { try { await _terminateApplicationAsync().ConfigureAwait(false); } catch (Exception ex) { Logger.LogWarning(ex.ToTypeMessageString()); } resetEvent.Set(); }); resetEvent.WaitOne(); AppDomain.CurrentDomain.ProcessExit -= CurrentDomain_ProcessExit; Console.CancelKeyPress -= Console_CancelKeyPress; // Indicate that the termination procedure finished. So other callers can return. Interlocked.Exchange(ref _terminateStatus, TerminateFinished); Environment.Exit(exitCode); } public bool IsTerminateRequested => Interlocked.Read(ref _terminateStatus) > TerminateStatusIdle; } }
mit
C#
52fd386d6d21efd377708f67daa59f0725902a81
Support LocalRedirectResult (#8112)
xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2
src/OrchardCore.Modules/OrchardCore.Forms/Filters/ExportModelStateAttribute.cs
src/OrchardCore.Modules/OrchardCore.Forms/Filters/ExportModelStateAttribute.cs
using System.Net; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using OrchardCore.Forms.Helpers; namespace OrchardCore.Forms.Filters { public class ExportModelStateAttribute : ModelStateTransferAttribute { public override void OnActionExecuted(ActionExecutedContext context) { // Only export if ModelState is not valid. if (context.ModelState != null && !context.ModelState.IsValid && IsRedirect(context)) { var controller = context.Controller as Controller; if (controller != null) { controller.TempData[Key] = ModelStateHelpers.SerializeModelState(context.ModelState); } } base.OnActionExecuted(context); } private bool IsRedirect(ActionExecutedContext context) { var result = context.Result; var statusCode = context.HttpContext.Response.StatusCode; return result is RedirectResult || result is RedirectToRouteResult || result is RedirectToActionResult || result is LocalRedirectResult || statusCode == (int)HttpStatusCode.Redirect || statusCode == (int)HttpStatusCode.TemporaryRedirect; } } }
using System.Net; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using OrchardCore.Forms.Helpers; namespace OrchardCore.Forms.Filters { public class ExportModelStateAttribute : ModelStateTransferAttribute { public override void OnActionExecuted(ActionExecutedContext context) { // Only export if ModelState is not valid. if (context.ModelState != null && !context.ModelState.IsValid && IsRedirect(context)) { var controller = context.Controller as Controller; if (controller != null) { controller.TempData[Key] = ModelStateHelpers.SerializeModelState(context.ModelState); } } base.OnActionExecuted(context); } private bool IsRedirect(ActionExecutedContext context) { var result = context.Result; var statusCode = context.HttpContext.Response.StatusCode; return result is RedirectResult || result is RedirectToRouteResult || result is RedirectToActionResult || statusCode == (int)HttpStatusCode.Redirect || statusCode == (int)HttpStatusCode.TemporaryRedirect; } } }
bsd-3-clause
C#
c3c47140d2e3d6671953042a03ef321f36ac7f29
Fix schedule stops not being ordered.
betrakiss/Tramline-5,betrakiss/Tramline-5
src/TramlineFive/TramlineFive/ViewModels/StopsViewModel.cs
src/TramlineFive/TramlineFive/ViewModels/StopsViewModel.cs
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using TramlineFive.ViewModels.Wrappers; namespace TramlineFive.ViewModels { public class StopsViewModel { public IList<StopViewModel> LineStops { get; private set; } public StopsViewModel(ScheduleChooserViewModel scheduleChooser) { scheduleChooserViewModel = scheduleChooser; LineStops = new ObservableCollection<StopViewModel>(); } public async Task LoadStops() { await scheduleChooserViewModel.SelectedDay.LoadStops(); LineStops = scheduleChooserViewModel.SelectedDay.Stops.OrderBy(s => s.Index).ToList(); } public string Title { get { return $"{scheduleChooserViewModel.SelectedLine.ShortName} - {scheduleChooserViewModel.SelectedDirection.Name.ToUpper()}"; } } private ScheduleChooserViewModel scheduleChooserViewModel; } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using TramlineFive.ViewModels.Wrappers; namespace TramlineFive.ViewModels { public class StopsViewModel { public IList<StopViewModel> LineStops { get; private set; } public StopsViewModel(ScheduleChooserViewModel scheduleChooser) { scheduleChooserViewModel = scheduleChooser; LineStops = new ObservableCollection<StopViewModel>(); } public async Task LoadStops() { await scheduleChooserViewModel.SelectedDay.LoadStops(); LineStops = scheduleChooserViewModel.SelectedDay.Stops.OrderBy(s => s.) foreach (StopViewModel stop in scheduleChooserViewModel.SelectedDay.Stops) LineStops.Add(stop); } public string Title { get { return $"{scheduleChooserViewModel.SelectedLine.ShortName} - {scheduleChooserViewModel.SelectedDirection.Name.ToUpper()}"; } } private ScheduleChooserViewModel scheduleChooserViewModel; } }
apache-2.0
C#
79711c50e2b06ddb07450d3a0cb852942db219d9
fix up debugger display so that the string format is around the right way
devkhan/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,rlugojr/octokit.net,alfhenrik/octokit.net,TattsGroup/octokit.net,gabrielweyer/octokit.net,octokit/octokit.net,devkhan/octokit.net,daukantas/octokit.net,thedillonb/octokit.net,dlsteuer/octokit.net,adamralph/octokit.net,shana/octokit.net,editor-tools/octokit.net,mminns/octokit.net,hahmed/octokit.net,fffej/octokit.net,gabrielweyer/octokit.net,shana/octokit.net,M-Zuber/octokit.net,brramos/octokit.net,mminns/octokit.net,rlugojr/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,ivandrofly/octokit.net,fake-organization/octokit.net,octokit/octokit.net,nsnnnnrn/octokit.net,kolbasov/octokit.net,M-Zuber/octokit.net,bslliw/octokit.net,shiftkey-tester/octokit.net,Sarmad93/octokit.net,SmithAndr/octokit.net,ChrisMissal/octokit.net,geek0r/octokit.net,cH40z-Lord/octokit.net,alfhenrik/octokit.net,magoswiat/octokit.net,dampir/octokit.net,octokit-net-test-org/octokit.net,TattsGroup/octokit.net,chunkychode/octokit.net,takumikub/octokit.net,shiftkey-tester/octokit.net,naveensrinivasan/octokit.net,gdziadkiewicz/octokit.net,gdziadkiewicz/octokit.net,octokit-net-test-org/octokit.net,shiftkey/octokit.net,SamTheDev/octokit.net,ivandrofly/octokit.net,dampir/octokit.net,nsrnnnnn/octokit.net,darrelmiller/octokit.net,kdolan/octokit.net,khellang/octokit.net,SmithAndr/octokit.net,Red-Folder/octokit.net,Sarmad93/octokit.net,chunkychode/octokit.net,shiftkey/octokit.net,khellang/octokit.net,hahmed/octokit.net,hitesh97/octokit.net,editor-tools/octokit.net,eriawan/octokit.net,SamTheDev/octokit.net,eriawan/octokit.net,forki/octokit.net,michaKFromParis/octokit.net,SLdragon1989/octokit.net,octokit-net-test/octokit.net,thedillonb/octokit.net
Octokit/Models/Response/Repository.cs
Octokit/Models/Response/Repository.cs
using System; using System.Diagnostics; using System.Globalization; namespace Octokit { [DebuggerDisplay("{DebuggerDisplay,nq}")] public class Repository { public string Url { get; set; } public string HtmlUrl { get; set; } public string CloneUrl { get; set; } public string GitUrl { get; set; } public string SshUrl { get; set; } public string SvnUrl { get; set; } public string MirrorUrl { get; set; } public int Id { get; set; } public User Owner { get; set; } public string Name { get; set; } public string FullName { get; set; } public string Description { get; set; } public string Homepage { get; set; } public string Language { get; set; } public bool Private { get; set; } public bool Fork { get; set; } public int ForksCount { get; set; } public int WatchersCount { get; set; } public string MasterBranch { get; set; } public int OpenIssuesCount { get; set; } public DateTimeOffset? PushedAt { get; set; } public DateTimeOffset CreatedAt { get; set; } public DateTimeOffset UpdatedAt { get; set; } public User Organization { get; set; } public Repository Parent { get; set; } public Repository Source { get; set; } public bool HasIssues { get; set; } public bool HasWiki { get; set; } public bool HasDownloads { get; set; } internal string DebuggerDisplay { get { return String.Format(CultureInfo.InvariantCulture, "Repository: Id: {0} Owner: {1}, Name: {2}", Id, Owner, Name); } } } }
using System; using System.Diagnostics; using System.Globalization; namespace Octokit { [DebuggerDisplay("{DebuggerDisplay,nq}")] public class Repository { public string Url { get; set; } public string HtmlUrl { get; set; } public string CloneUrl { get; set; } public string GitUrl { get; set; } public string SshUrl { get; set; } public string SvnUrl { get; set; } public string MirrorUrl { get; set; } public int Id { get; set; } public User Owner { get; set; } public string Name { get; set; } public string FullName { get; set; } public string Description { get; set; } public string Homepage { get; set; } public string Language { get; set; } public bool Private { get; set; } public bool Fork { get; set; } public int ForksCount { get; set; } public int WatchersCount { get; set; } public string MasterBranch { get; set; } public int OpenIssuesCount { get; set; } public DateTimeOffset? PushedAt { get; set; } public DateTimeOffset CreatedAt { get; set; } public DateTimeOffset UpdatedAt { get; set; } public User Organization { get; set; } public Repository Parent { get; set; } public Repository Source { get; set; } public bool HasIssues { get; set; } public bool HasWiki { get; set; } public bool HasDownloads { get; set; } internal string DebuggerDisplay { get { return String.Format(CultureInfo.InvariantCulture, "Repository: Id: {0} Owner: {1}, Name: {2}", Id, Name, Owner); } } } }
mit
C#
05e6f17f6e0daf80c852807f5f3103f67414b7a5
Set matrix pos
MrJaqbq/Unity3DFramework
Utils/Extensions/Vector3Extensions.cs
Utils/Extensions/Vector3Extensions.cs
using UnityEngine; public static class Vector3Extensions { public static Vector3 Multiply(Vector3 a, Vector3 b) { return new Vector3(a.x * b.x, a.y * b.y, a.z * b.z); } public static Vector3 GetPos(this Matrix4x4 matrix) { return matrix.GetColumn(3); } public static Vector3 GetScale(this Matrix4x4 matrix) { return new Vector3 ( matrix.GetColumn(0).magnitude, matrix.GetColumn(1).magnitude, matrix.GetColumn(2).magnitude ); } public static void SetPosition(this Matrix4x4 matrix, Vector3 newPos) { matrix.SetTRS(newPos, matrix.rotation, matrix.GetScale()); } public static void SetRotation(this Matrix4x4 matrix, Quaternion newRot) { matrix.SetTRS(matrix.GetPos(), newRot, matrix.GetScale()); } public static void Decompose(this Matrix4x4 matrix, out Vector3 pos, out Quaternion rot, out Vector3 scl) { pos = matrix.GetPos(); rot = matrix.rotation; scl = matrix.GetScale(); } }
using UnityEngine; public static class Vector3Extensions { public static Vector3 Multiply(Vector3 a, Vector3 b) { return new Vector3(a.x * b.x, a.y * b.y, a.z * b.z); } public static Vector3 GetPos(this Matrix4x4 matrix) { return matrix.GetColumn(3); } public static Vector3 GetScale(this Matrix4x4 matrix) { return new Vector3 ( matrix.GetColumn(0).magnitude, matrix.GetColumn(1).magnitude, matrix.GetColumn(2).magnitude ); } public static void SetRotation(this Matrix4x4 matrix, Quaternion newRot) { matrix.SetTRS(matrix.GetPos(), newRot, matrix.GetScale()); } public static void Decompose(this Matrix4x4 matrix, out Vector3 pos, out Quaternion rot, out Vector3 scl) { pos = matrix.GetPos(); rot = matrix.rotation; scl = matrix.GetScale(); } }
mit
C#
f491f893cfed74c690f4758fdd6a6ce259940648
Use CurrentUICulture for EditorConfig UI
shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,weltkante/roslyn,diryboy/roslyn,CyrusNajmabadi/roslyn,eriawan/roslyn,KevinRansom/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,sharwell/roslyn,sharwell/roslyn,eriawan/roslyn,KevinRansom/roslyn,diryboy/roslyn,KevinRansom/roslyn,mavasani/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,mavasani/roslyn,diryboy/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,bartdesmet/roslyn,weltkante/roslyn,dotnet/roslyn
src/EditorFeatures/Core/EditorConfigSettings/Data/AnalyzerSetting.cs
src/EditorFeatures/Core/EditorConfigSettings/Data/AnalyzerSetting.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data { internal class AnalyzerSetting { private readonly DiagnosticDescriptor _descriptor; private readonly AnalyzerSettingsUpdater _settingsUpdater; public AnalyzerSetting(DiagnosticDescriptor descriptor, ReportDiagnostic effectiveSeverity, AnalyzerSettingsUpdater settingsUpdater, Language language) { _descriptor = descriptor; _settingsUpdater = settingsUpdater; DiagnosticSeverity severity = default; if (effectiveSeverity == ReportDiagnostic.Default) { severity = descriptor.DefaultSeverity; } else if (effectiveSeverity.ToDiagnosticSeverity() is DiagnosticSeverity severity1) { severity = severity1; } var enabled = effectiveSeverity != ReportDiagnostic.Suppress; IsEnabled = enabled; Severity = severity; Language = language; } public string Id => _descriptor.Id; public string Title => _descriptor.Title.ToString(CultureInfo.CurrentUICulture); public string Description => _descriptor.Description.ToString(CultureInfo.CurrentUICulture); public string Category => _descriptor.Category; public DiagnosticSeverity Severity { get; private set; } public bool IsEnabled { get; private set; } public Language Language { get; } internal void ChangeSeverity(DiagnosticSeverity severity) { if (severity == Severity) return; Severity = severity; _settingsUpdater.QueueUpdate(this, severity); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data { internal class AnalyzerSetting { private readonly DiagnosticDescriptor _descriptor; private readonly AnalyzerSettingsUpdater _settingsUpdater; public AnalyzerSetting(DiagnosticDescriptor descriptor, ReportDiagnostic effectiveSeverity, AnalyzerSettingsUpdater settingsUpdater, Language language) { _descriptor = descriptor; _settingsUpdater = settingsUpdater; DiagnosticSeverity severity = default; if (effectiveSeverity == ReportDiagnostic.Default) { severity = descriptor.DefaultSeverity; } else if (effectiveSeverity.ToDiagnosticSeverity() is DiagnosticSeverity severity1) { severity = severity1; } var enabled = effectiveSeverity != ReportDiagnostic.Suppress; IsEnabled = enabled; Severity = severity; Language = language; } public string Id => _descriptor.Id; public string Title => _descriptor.Title.ToString(CultureInfo.CurrentCulture); public string Description => _descriptor.Description.ToString(CultureInfo.CurrentCulture); public string Category => _descriptor.Category; public DiagnosticSeverity Severity { get; private set; } public bool IsEnabled { get; private set; } public Language Language { get; } internal void ChangeSeverity(DiagnosticSeverity severity) { if (severity == Severity) return; Severity = severity; _settingsUpdater.QueueUpdate(this, severity); } } }
mit
C#
bf90119b542f043213f1330459b1766acdeed495
Clean up unnecessary usings for #3736
rgani/roslyn,khellang/roslyn,jamesqo/roslyn,AlekseyTs/roslyn,shyamnamboodiripad/roslyn,tmeschter/roslyn,SeriaWei/roslyn,jaredpar/roslyn,jasonmalinowski/roslyn,michalhosala/roslyn,khyperia/roslyn,cston/roslyn,davkean/roslyn,jmarolf/roslyn,KevinH-MS/roslyn,wvdd007/roslyn,ljw1004/roslyn,nguerrera/roslyn,reaction1989/roslyn,robinsedlaczek/roslyn,khellang/roslyn,TyOverby/roslyn,Shiney/roslyn,natgla/roslyn,xoofx/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,Maxwe11/roslyn,MattWindsor91/roslyn,AmadeusW/roslyn,zooba/roslyn,Giftednewt/roslyn,michalhosala/roslyn,MattWindsor91/roslyn,reaction1989/roslyn,ljw1004/roslyn,akrisiun/roslyn,orthoxerox/roslyn,jhendrixMSFT/roslyn,kelltrick/roslyn,KirillOsenkov/roslyn,AmadeusW/roslyn,natidea/roslyn,Pvlerick/roslyn,Pvlerick/roslyn,mavasani/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,AArnott/roslyn,natidea/roslyn,tannergooding/roslyn,pdelvo/roslyn,jeffanders/roslyn,sharadagrawal/Roslyn,AnthonyDGreen/roslyn,antonssonj/roslyn,tmat/roslyn,srivatsn/roslyn,xoofx/roslyn,Hosch250/roslyn,genlu/roslyn,CaptainHayashi/roslyn,rgani/roslyn,yeaicc/roslyn,aelij/roslyn,Maxwe11/roslyn,KiloBravoLima/roslyn,diryboy/roslyn,CaptainHayashi/roslyn,leppie/roslyn,gafter/roslyn,davkean/roslyn,jkotas/roslyn,ericfe-ms/roslyn,dpoeschl/roslyn,yeaicc/roslyn,agocke/roslyn,bkoelman/roslyn,drognanar/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,budcribar/roslyn,VSadov/roslyn,balajikris/roslyn,mmitche/roslyn,Hosch250/roslyn,natgla/roslyn,lorcanmooney/roslyn,pdelvo/roslyn,KevinRansom/roslyn,sharwell/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,OmarTawfik/roslyn,physhi/roslyn,nguerrera/roslyn,AArnott/roslyn,SeriaWei/roslyn,CyrusNajmabadi/roslyn,tannergooding/roslyn,bartdesmet/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,basoundr/roslyn,TyOverby/roslyn,amcasey/roslyn,jaredpar/roslyn,khyperia/roslyn,KevinRansom/roslyn,robinsedlaczek/roslyn,leppie/roslyn,vslsnap/roslyn,drognanar/roslyn,bkoelman/roslyn,balajikris/roslyn,srivatsn/roslyn,eriawan/roslyn,ericfe-ms/roslyn,brettfo/roslyn,sharadagrawal/Roslyn,jeffanders/roslyn,vslsnap/roslyn,Hosch250/roslyn,lorcanmooney/roslyn,khellang/roslyn,DustinCampbell/roslyn,MatthieuMEZIL/roslyn,vcsjones/roslyn,jcouv/roslyn,MatthieuMEZIL/roslyn,VSadov/roslyn,a-ctor/roslyn,diryboy/roslyn,heejaechang/roslyn,ErikSchierboom/roslyn,DustinCampbell/roslyn,michalhosala/roslyn,MattWindsor91/roslyn,stephentoub/roslyn,mmitche/roslyn,jamesqo/roslyn,tvand7093/roslyn,ValentinRueda/roslyn,jcouv/roslyn,physhi/roslyn,amcasey/roslyn,mavasani/roslyn,rgani/roslyn,sharwell/roslyn,OmarTawfik/roslyn,tvand7093/roslyn,vcsjones/roslyn,paulvanbrenk/roslyn,robinsedlaczek/roslyn,AArnott/roslyn,tmat/roslyn,AnthonyDGreen/roslyn,mattwar/roslyn,diryboy/roslyn,a-ctor/roslyn,Shiney/roslyn,drognanar/roslyn,mgoertz-msft/roslyn,DustinCampbell/roslyn,natidea/roslyn,KirillOsenkov/roslyn,wvdd007/roslyn,KirillOsenkov/roslyn,ValentinRueda/roslyn,gafter/roslyn,jmarolf/roslyn,cston/roslyn,aelij/roslyn,jhendrixMSFT/roslyn,AmadeusW/roslyn,brettfo/roslyn,jkotas/roslyn,pdelvo/roslyn,jamesqo/roslyn,xasx/roslyn,Pvlerick/roslyn,OmarTawfik/roslyn,genlu/roslyn,bbarry/roslyn,ljw1004/roslyn,bartdesmet/roslyn,nguerrera/roslyn,Maxwe11/roslyn,zooba/roslyn,akrisiun/roslyn,bbarry/roslyn,gafter/roslyn,Giftednewt/roslyn,xoofx/roslyn,wvdd007/roslyn,jasonmalinowski/roslyn,cston/roslyn,basoundr/roslyn,swaroop-sridhar/roslyn,mattscheffer/roslyn,akrisiun/roslyn,ericfe-ms/roslyn,AnthonyDGreen/roslyn,tvand7093/roslyn,bartdesmet/roslyn,dotnet/roslyn,weltkante/roslyn,eriawan/roslyn,panopticoncentral/roslyn,xasx/roslyn,sharadagrawal/Roslyn,weltkante/roslyn,stephentoub/roslyn,MichalStrehovsky/roslyn,shyamnamboodiripad/roslyn,kelltrick/roslyn,orthoxerox/roslyn,natgla/roslyn,xasx/roslyn,basoundr/roslyn,dotnet/roslyn,dpoeschl/roslyn,CaptainHayashi/roslyn,reaction1989/roslyn,jhendrixMSFT/roslyn,SeriaWei/roslyn,Shiney/roslyn,yeaicc/roslyn,davkean/roslyn,budcribar/roslyn,mmitche/roslyn,abock/roslyn,tmeschter/roslyn,dpoeschl/roslyn,brettfo/roslyn,agocke/roslyn,bbarry/roslyn,tmeschter/roslyn,srivatsn/roslyn,KevinRansom/roslyn,abock/roslyn,aelij/roslyn,heejaechang/roslyn,jkotas/roslyn,heejaechang/roslyn,amcasey/roslyn,kelltrick/roslyn,dotnet/roslyn,ValentinRueda/roslyn,paulvanbrenk/roslyn,ErikSchierboom/roslyn,mgoertz-msft/roslyn,KiloBravoLima/roslyn,budcribar/roslyn,swaroop-sridhar/roslyn,MatthieuMEZIL/roslyn,mavasani/roslyn,mattscheffer/roslyn,paulvanbrenk/roslyn,mgoertz-msft/roslyn,antonssonj/roslyn,mattwar/roslyn,abock/roslyn,mattwar/roslyn,panopticoncentral/roslyn,balajikris/roslyn,genlu/roslyn,jcouv/roslyn,jaredpar/roslyn,AlekseyTs/roslyn,mattscheffer/roslyn,vslsnap/roslyn,tannergooding/roslyn,MattWindsor91/roslyn,panopticoncentral/roslyn,bkoelman/roslyn,swaroop-sridhar/roslyn,leppie/roslyn,ErikSchierboom/roslyn,vcsjones/roslyn,MichalStrehovsky/roslyn,shyamnamboodiripad/roslyn,stephentoub/roslyn,khyperia/roslyn,Giftednewt/roslyn,VSadov/roslyn,CyrusNajmabadi/roslyn,lorcanmooney/roslyn,orthoxerox/roslyn,tmat/roslyn,agocke/roslyn,a-ctor/roslyn,TyOverby/roslyn,MichalStrehovsky/roslyn,KevinH-MS/roslyn,antonssonj/roslyn,KiloBravoLima/roslyn,sharwell/roslyn,jmarolf/roslyn,AlekseyTs/roslyn,jeffanders/roslyn,KevinH-MS/roslyn,physhi/roslyn,zooba/roslyn
src/VisualStudio/Core/SolutionExplorerShim/BrowseObjectAttributes.cs
src/VisualStudio/Core/SolutionExplorerShim/BrowseObjectAttributes.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 Microsoft.VisualStudio.LanguageServices.SolutionExplorer; using System; using System.ComponentModel; using System.Globalization; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { /// <summary> /// The attribute used for adding localized display names to properties /// </summary> [AttributeUsage(AttributeTargets.Property)] internal sealed class BrowseObjectDisplayNameAttribute : DisplayNameAttribute { private string m_key; private bool m_initialized; public BrowseObjectDisplayNameAttribute(string key) { m_key = key; } public override string DisplayName { get { if (!m_initialized) { base.DisplayNameValue = SolutionExplorerShim.ResourceManager.GetString(m_key, CultureInfo.CurrentUICulture); m_initialized = true; } return base.DisplayName; } } } }
// 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 Microsoft.VisualStudio.LanguageServices.SolutionExplorer; using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { /// <summary> /// The attribute used for adding localized display names to properties /// </summary> [AttributeUsage(AttributeTargets.Property)] internal sealed class BrowseObjectDisplayNameAttribute : DisplayNameAttribute { private string m_key; private bool m_initialized; public BrowseObjectDisplayNameAttribute(string key) { m_key = key; } public override string DisplayName { get { if (!m_initialized) { base.DisplayNameValue = SolutionExplorerShim.ResourceManager.GetString(m_key, CultureInfo.CurrentUICulture); m_initialized = true; } return base.DisplayName; } } } }
mit
C#
52e6ab9b95da41a479e517c63bad04ed29402c54
Fix Strong Personnality
sebavan/Bololens
Bounity/Assets/Bololens/Scripts/Personality/BuiltIn/StrongPersonality.cs
Bounity/Assets/Bololens/Scripts/Personality/BuiltIn/StrongPersonality.cs
using System; using System.Collections; using System.Collections.Generic; using Bololens.Core; using UnityEngine; namespace Bololens.Personality.BuiltIn { /// <summary> /// Default Strong personality of the bot. /// /// The last feelings in win. /// </summary> /// <seealso cref="Bololens.Personality.BuiltIn.BaseBuiltInPersonality" /> public class StrongPersonality : BaseBuiltInPersonality { /// <summary> /// Combines the feeling. /// </summary> /// <param name="emotion">The emotion to add in the mix.</param> /// <param name="quantity">The quantity (in arbitrary units).</param> /// <returns> /// The new dominant feeling. /// </returns> public override Emotions CombineFeeling(Emotions emotion, float quantity) { Emotions latestEmotion = Emotions.Neutral; foreach (var registeredEmotion in feelings.Keys) { if (feelings[registeredEmotion] != 0) { latestEmotion = registeredEmotion; } feelings[registeredEmotion] = 0; } if (emotion == Emotions.Neutral) { return latestEmotion; } return emotion; } } }
using System; using System.Collections; using System.Collections.Generic; using Bololens.Core; using UnityEngine; namespace Bololens.Personality.BuiltIn { /// <summary> /// Default Strong personality of the bot. /// /// All feelings are rated the same but the bot will not stay neutral. /// </summary> /// <seealso cref="Bololens.Personality.BuiltIn.BaseBuiltInPersonality" /> public class StrongPersonality : BaseBuiltInPersonality { /// <summary> /// Combines the feeling. /// </summary> /// <param name="emotion">The emotion to add in the mix.</param> /// <param name="quantity">The quantity (in arbitrary units).</param> /// <returns> /// The new dominant feeling. /// </returns> public override Emotions CombineFeeling(Emotions emotion, float quantity) { if (feelings.ContainsKey(emotion)) { quantity += feelings[emotion]; } feelings[emotion] = quantity; // Return the only one we have. if (feelings.Count == 1) { foreach (var registeredEmotion in feelings) { return registeredEmotion.Key; } } var max = 0.0f; foreach (var registeredEmotion in feelings) { // Discard neutral as it as strong feelings. if (registeredEmotion.Key != Emotions.Neutral && registeredEmotion.Value > max) { dominantFeeling = registeredEmotion.Key; max = registeredEmotion.Value; } } return dominantFeeling; } } }
mit
C#
1c2240e12d0f968a2afc80289179fa02978a9853
remove AssemblyInformationalVersion
chsword/ResizingServer
source/ResizingClient/Properties/AssemblyInfo.cs
source/ResizingClient/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("ResizingClient")] [assembly: AssemblyDescription("Client for ResizingServer https://github.com/chsword/ResizingServer")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("chsword")] [assembly: AssemblyProduct("ResizingClient")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("0a9d7a29-99b7-46a5-8370-56c0e2e454a3")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.3")] [assembly: AssemblyFileVersion("1.0.0.3")] //[assembly: AssemblyInformationalVersion("1.0.0.3")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("ResizingClient")] [assembly: AssemblyDescription("Client for ResizingServer https://github.com/chsword/ResizingServer")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("chsword")] [assembly: AssemblyProduct("ResizingClient")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("0a9d7a29-99b7-46a5-8370-56c0e2e454a3")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.3")] [assembly: AssemblyFileVersion("1.0.0.3")] [assembly: AssemblyInformationalVersion("1.0.0.3")]
apache-2.0
C#
3d84c5b843ccacf6214c13a386ff4c8e7e0caee5
Clean analyzer warnings on test projects
clariuslabs/clide,clariuslabs/clide,clariuslabs/clide
src/Clide.IntegrationTests/GlobalSuppressions.cs
src/Clide.IntegrationTests/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("Style", "IDE1006:Naming Styles", Justification = "We use lower-case BDD style naming for tests")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "xUnit1024:Test methods cannot have overloads", Justification = "We re-declare the methods in the derived class to annotate with inline data/theory.")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "For unit tests, no public API.")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "VSTHRD012:Provide JoinableTaskFactory where allowed", Justification = "For unit tests, no public API.")]
 // 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("Style", "IDE1006:Naming Styles", Justification = "We use lower-case BDD style naming for tests")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "xUnit1024:Test methods cannot have overloads", Justification = "We re-declare the methods in the derived class to annotate with inline data/theory.")]
mit
C#
4dddcc468b4800ed9f5ba3b16943d48ffd659a2f
fix title case command
andy-kohne/VSElixir
VSElixir/Commands/TitleCaseCommand.cs
VSElixir/Commands/TitleCaseCommand.cs
using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.Shell; using System; using System.ComponentModel.Design; using System.Globalization; namespace VSElixir.Commands { internal sealed class TitleCaseCommand { public const int CommandId = 2; private readonly Package _package; private IServiceProvider ServiceProvider => _package; public static TitleCaseCommand Instance { get; private set; } public static void Initialize(Package package) { Instance = new TitleCaseCommand(package); } private TitleCaseCommand(Package package) { if (package == null) throw new ArgumentNullException(nameof(package)); _package = package; var commandService = ServiceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (commandService != null) { var menuCommandId = new CommandID(new Guid(VSElixirPackage.EditorCommandSetGuidString), CommandId); var menuItem = new MenuCommand(MenuItemCallback, menuCommandId); commandService.AddCommand(menuItem); } } private void MenuItemCallback(object sender, EventArgs e) { var dte2 = (DTE2)ServiceProvider.GetService(typeof(DTE)); var textSelection = dte2.ActiveWindow.Document.Selection as TextSelection; if (!string.IsNullOrEmpty(textSelection?.Text)) { var textInfo = CultureInfo.CurrentCulture.TextInfo; textSelection.Text = textInfo.ToTitleCase(textSelection.Text); } } } }
using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.Shell; using System; using System.ComponentModel.Design; using System.Globalization; namespace VSElixir.Commands { internal sealed class TitleCaseCommand { public const int CommandId = 2; private readonly Package _package; private IServiceProvider ServiceProvider => _package; public static TitleCaseCommand Instance { get; private set; } public static void Initialize(Package package) { Instance = new TitleCaseCommand(package); } private TitleCaseCommand(Package package) { if (package == null) throw new ArgumentNullException(nameof(package)); _package = package; var commandService = ServiceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (commandService != null) { var menuCommandId = new CommandID(new Guid(VSElixirPackage.EditorCommandSetGuidString), CommandId); var menuItem = new MenuCommand(MenuItemCallback, menuCommandId); commandService.AddCommand(menuItem); } } private void MenuItemCallback(object sender, EventArgs e) { var dte2 = (DTE2)ServiceProvider.GetService(typeof(DTE)); var textSelection = dte2.ActiveWindow.Selection as TextSelection; if (!string.IsNullOrEmpty(textSelection?.Text)) { var textInfo = CultureInfo.CurrentCulture.TextInfo; textSelection.Text = textInfo.ToTitleCase(textSelection.Text); } } } }
mit
C#
4831134151e808b8fae256ac5ecf0b90c4df43fb
Make MajorName Required
CS297Sp16/LCC_Co-op_Site,CS297Sp16/LCC_Co-op_Site,CS297Sp16/LCC_Co-op_Site
Coop_Listing_Site/Coop_Listing_Site/Models/ViewModels/MajorViewModel.cs
Coop_Listing_Site/Coop_Listing_Site/Models/ViewModels/MajorViewModel.cs
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Coop_Listing_Site.Models.ViewModels { public class MajorViewModel { public MajorViewModel() { Opportunities = new List<Opportunity>(); } public MajorViewModel(Major major) { MajorID = major.MajorID; MajorName = major.MajorName; Department = major.Department; Opportunities = major.Opportunities; } public int MajorID { get; set; } public Department Department { get; set; } [Required, Display(Name = "Major Name")] public string MajorName { get; set; } public ICollection<Opportunity> Opportunities { get; set; } public Major ToMajor() { var major = new Major(); major.MajorID = MajorID; major.MajorName = MajorName; major.Department = Department; major.Opportunities = Opportunities; return major; } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Coop_Listing_Site.Models.ViewModels { public class MajorViewModel { public MajorViewModel() { Opportunities = new List<Opportunity>(); } public MajorViewModel(Major major) { MajorID = major.MajorID; MajorName = major.MajorName; Department = major.Department; Opportunities = major.Opportunities; } public int MajorID { get; set; } public Department Department { get; set; } [Display(Name = "Major Name")] public string MajorName { get; set; } public ICollection<Opportunity> Opportunities { get; set; } public Major ToMajor() { var major = new Major(); major.MajorID = MajorID; major.MajorName = MajorName; major.Department = Department; major.Opportunities = Opportunities; return major; } } }
mit
C#
600c66fa83b8f790f39c8a961f26570cd584ed27
Add more tests for puzzle 14
martincostello/project-euler
src/ProjectEuler.Tests/Puzzles/Puzzle014Tests.cs
src/ProjectEuler.Tests/Puzzles/Puzzle014Tests.cs
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using Xunit; /// <summary> /// A class containing tests for the <see cref="Puzzle014"/> class. This class cannot be inherited. /// </summary> public static class Puzzle014Tests { [Fact] public static void Puzzle014_Returns_Correct_Solution() { // Arrange object expected = 837799; // Act and Assert Puzzles.AssertSolution<Puzzle014>(expected); } [Theory] [InlineData(1L, new long[] { 1 })] [InlineData(2L, new long[] { 2, 1 })] [InlineData(3L, new long[] { 3, 10, 5, 16, 8, 4, 2, 1 })] [InlineData(4L, new long[] { 4, 2, 1 })] [InlineData(13L, new long[] { 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 })] public static void Puzzle014_GetCollatzSequence_Returns_Correct_Sequence(long start, long[] expected) { // Act var actual = Puzzle014.GetCollatzSequence(start); // Assert Assert.Equal(expected, actual); } } }
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using Xunit; /// <summary> /// A class containing tests for the <see cref="Puzzle014"/> class. This class cannot be inherited. /// </summary> public static class Puzzle014Tests { [Fact] public static void Puzzle014_Returns_Correct_Solution() { // Arrange object expected = 837799; // Act and Assert Puzzles.AssertSolution<Puzzle014>(expected); } [Fact] public static void Puzzle_014_GetCollatzSequence_Returns_Correct_Sequence() { // Arrange long start = 13; var expected = new long[] { 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 }; // Act var actual = Puzzle014.GetCollatzSequence(start); // Assert Assert.Equal(expected, actual); } } }
apache-2.0
C#
39bdfdb6bd1b44096d7d5b7815c2ef624e735f04
Add consumer BIC and failure reason properties to bancontact response (#238)
Viincenttt/MollieApi,Viincenttt/MollieApi
Mollie.Api/Models/Payment/Response/Specific/BancontactPaymentResponse.cs
Mollie.Api/Models/Payment/Response/Specific/BancontactPaymentResponse.cs
using System; namespace Mollie.Api.Models.Payment.Response.Specific { public class BancontactPaymentResponse : PaymentResponse { public BancontactPaymentResponseDetails Details { get; set; } } public class BancontactPaymentResponseDetails { /// <summary> /// Only available if the payment is completed - The last four digits of the card number. /// </summary> public string CardNumber { get; set; } /// <summary> /// Only available if the payment is completed - Unique alphanumeric representation of card, usable for /// identifying returning customers. This field is deprecated as of November 28th, 2019. The fingerprint /// is now unique per transaction what makes it not usefull anymore for identifying returning customers. /// Use the consumerAccount field instead. /// </summary> [Obsolete(@"This field is deprecated as of November 28th, 2019. The fingerprint is now unique per transaction what makes it not usefull anymore for identifying returning customers. Use the consumerAccount field instead.")] public string CardFingerprint { get; set; } /// <summary> /// Only available if requested during payment creation - The QR code that can be scanned by the mobile /// Bancontact application. This enables the desktop to mobile feature. /// </summary> public QrCode QrCode { get; set; } /// <summary> /// Only available if the payment is completed – The consumer’s bank account. This may be an IBAN, or it may be a domestic account number. /// </summary> public string ConsumerAccount { get; set; } /// <summary> /// Only available if the payment is completed – The consumer’s name. /// </summary> public string ConsumerName { get; set; } /// <summary> /// Only available if the payment is completed – The consumer’s bank’s BIC / SWIFT code. /// </summary> public string ConsumerBic { get; set; } /// <summary> /// The reason why the payment did not succeed. Only available when there's a reason known. /// </summary> public string FailureReason { get; set; } } }
using System; namespace Mollie.Api.Models.Payment.Response.Specific { public class BancontactPaymentResponse : PaymentResponse { public BancontactPaymentResponseDetails Details { get; set; } } public class BancontactPaymentResponseDetails { /// <summary> /// Only available if the payment is completed - The last four digits of the card number. /// </summary> public string CardNumber { get; set; } /// <summary> /// Only available if the payment is completed - Unique alphanumeric representation of card, usable for /// identifying returning customers. This field is deprecated as of November 28th, 2019. The fingerprint /// is now unique per transaction what makes it not usefull anymore for identifying returning customers. /// Use the consumerAccount field instead. /// </summary> [Obsolete(@"This field is deprecated as of November 28th, 2019. The fingerprint is now unique per transaction what makes it not usefull anymore for identifying returning customers. Use the consumerAccount field instead.")] public string CardFingerprint { get; set; } /// <summary> /// Only available if requested during payment creation - The QR code that can be scanned by the mobile /// Bancontact application. This enables the desktop to mobile feature. /// </summary> public QrCode QrCode { get; set; } /// <summary> /// Only available if the payment is completed – The consumer’s bank account. This may be an IBAN, or it may be a domestic account number. /// </summary> public string ConsumerAccount { get; set; } /// <summary> /// Only available if the payment is completed – The consumer’s name. /// </summary> public string ConsumerName { get; set; } } }
mit
C#
d3646865fb8b7b379baf771a7dac389c603e5789
Remove tests task from CI
olsh/todoist-net
build.cake
build.cake
#tool "nuget:?package=OpenCover" #addin "Cake.Incubator" var target = Argument("target", "Default"); var extensionsVersion = Argument("version", "1.1.4"); var buildConfiguration = "Release"; var projectName = "Todoist.Net"; var testProjectName = "Todoist.Net.Tests"; var projectFolder = string.Format("./src/{0}/", projectName); var testProjectFolder = string.Format("./src/{0}/", testProjectName); Task("UpdateBuildVersion") .WithCriteria(BuildSystem.AppVeyor.IsRunningOnAppVeyor) .Does(() => { var buildNumber = BuildSystem.AppVeyor.Environment.Build.Number; BuildSystem.AppVeyor.UpdateBuildVersion(string.Format("{0}.{1}", extensionsVersion, buildNumber)); }); Task("NugetRestore") .Does(() => { DotNetCoreRestore(); }); Task("UpdateAssemblyVersion") .Does(() => { var assemblyFile = string.Format("{0}/Properties/AssemblyInfo.cs", projectFolder); AssemblyInfoSettings assemblySettings = new AssemblyInfoSettings(); assemblySettings.Title = projectName; assemblySettings.FileVersion = extensionsVersion; assemblySettings.Version = extensionsVersion; assemblySettings.InternalsVisibleTo = new [] { testProjectName }; CreateAssemblyInfo(assemblyFile, assemblySettings); }); Task("Build") .IsDependentOn("NugetRestore") .IsDependentOn("UpdateAssemblyVersion") .Does(() => { MSBuild(string.Format("{0}.sln", projectName), new MSBuildSettings { Verbosity = Verbosity.Minimal, Configuration = buildConfiguration }); }); Task("Test") .IsDependentOn("Build") .Does(() => { var settings = new DotNetCoreTestSettings { Configuration = buildConfiguration }; DotNetCoreTest(testProjectFolder, settings); }); Task("CodeCoverage") .IsDependentOn("Build") .Does(() => { var settings = new DotNetCoreTestSettings { Configuration = buildConfiguration }; OpenCover(tool => { tool.DotNetCoreTest(testProjectFolder, settings); }, new FilePath("./coverage.xml"), new OpenCoverSettings() .WithFilter("+[Todoist.Net]*") .WithFilter("-[Todoist.Net.Tests]*")); }); Task("NugetPack") .IsDependentOn("Build") .Does(() => { var settings = new DotNetCorePackSettings { Configuration = buildConfiguration, OutputDirectory = "." }; DotNetCorePack(projectFolder, settings); }); Task("CreateArtifact") .IsDependentOn("NugetPack") .WithCriteria(BuildSystem.AppVeyor.IsRunningOnAppVeyor) .Does(() => { BuildSystem.AppVeyor.UploadArtifact(string.Format("{0}.{1}.nupkg", projectName, extensionsVersion)); BuildSystem.AppVeyor.UploadArtifact(string.Format("{0}.{1}.symbols.nupkg", projectName, extensionsVersion)); }); Task("Default") .IsDependentOn("Test") .IsDependentOn("NugetPack"); Task("CI") .IsDependentOn("UpdateBuildVersion") .IsDependentOn("CodeCoverage") .IsDependentOn("CreateArtifact"); RunTarget(target);
#tool "nuget:?package=OpenCover" #addin "Cake.Incubator" var target = Argument("target", "Default"); var extensionsVersion = Argument("version", "1.1.4"); var buildConfiguration = "Release"; var projectName = "Todoist.Net"; var testProjectName = "Todoist.Net.Tests"; var projectFolder = string.Format("./src/{0}/", projectName); var testProjectFolder = string.Format("./src/{0}/", testProjectName); Task("UpdateBuildVersion") .WithCriteria(BuildSystem.AppVeyor.IsRunningOnAppVeyor) .Does(() => { var buildNumber = BuildSystem.AppVeyor.Environment.Build.Number; BuildSystem.AppVeyor.UpdateBuildVersion(string.Format("{0}.{1}", extensionsVersion, buildNumber)); }); Task("NugetRestore") .Does(() => { DotNetCoreRestore(); }); Task("UpdateAssemblyVersion") .Does(() => { var assemblyFile = string.Format("{0}/Properties/AssemblyInfo.cs", projectFolder); AssemblyInfoSettings assemblySettings = new AssemblyInfoSettings(); assemblySettings.Title = projectName; assemblySettings.FileVersion = extensionsVersion; assemblySettings.Version = extensionsVersion; assemblySettings.InternalsVisibleTo = new [] { testProjectName }; CreateAssemblyInfo(assemblyFile, assemblySettings); }); Task("Build") .IsDependentOn("NugetRestore") .IsDependentOn("UpdateAssemblyVersion") .Does(() => { MSBuild(string.Format("{0}.sln", projectName), new MSBuildSettings { Verbosity = Verbosity.Minimal, Configuration = buildConfiguration }); }); Task("Test") .IsDependentOn("Build") .Does(() => { var settings = new DotNetCoreTestSettings { Configuration = buildConfiguration }; DotNetCoreTest(testProjectFolder, settings); }); Task("CodeCoverage") .IsDependentOn("Build") .Does(() => { var settings = new DotNetCoreTestSettings { Configuration = buildConfiguration }; OpenCover(tool => { tool.DotNetCoreTest(testProjectFolder, settings); }, new FilePath("./coverage.xml"), new OpenCoverSettings() .WithFilter("+[Todoist.Net]*") .WithFilter("-[Todoist.Net.Tests]*")); }); Task("NugetPack") .IsDependentOn("Build") .Does(() => { var settings = new DotNetCorePackSettings { Configuration = buildConfiguration, OutputDirectory = "." }; DotNetCorePack(projectFolder, settings); }); Task("CreateArtifact") .IsDependentOn("NugetPack") .WithCriteria(BuildSystem.AppVeyor.IsRunningOnAppVeyor) .Does(() => { BuildSystem.AppVeyor.UploadArtifact(string.Format("{0}.{1}.nupkg", projectName, extensionsVersion)); BuildSystem.AppVeyor.UploadArtifact(string.Format("{0}.{1}.symbols.nupkg", projectName, extensionsVersion)); }); Task("Default") .IsDependentOn("Test") .IsDependentOn("NugetPack"); Task("CI") .IsDependentOn("UpdateBuildVersion") .IsDependentOn("Test") .IsDependentOn("CodeCoverage") .IsDependentOn("CreateArtifact"); RunTarget(target);
mit
C#
620b6a462452789e59a2f7f6358fdc13796674d7
Make all NodeSemverTests go through SemVersionRange.ParseNpm
maxhauser/semver
Semver.Test/TestCases/NpmRangeContainsTestCase.cs
Semver.Test/TestCases/NpmRangeContainsTestCase.cs
using Semver.Ranges; namespace Semver.Test.TestCases { /// <summary> /// An individual test case for whether an npm range contains a version /// </summary> public class NpmRangeContainsTestCase { public static NpmRangeContainsTestCase NpmIncludes(string range, string version, bool includeAllPrerelease = false) => new NpmRangeContainsTestCase(range, includeAllPrerelease, version, true); public static NpmRangeContainsTestCase NpmExcludes(string range, string version, bool includeAllPrerelease = false) => new NpmRangeContainsTestCase(range, includeAllPrerelease, version, false); private NpmRangeContainsTestCase(string range, bool includeAllPrerelease, string version, bool versionIncluded) { Range = range; IncludeAllPrerelease = includeAllPrerelease; Version = SemVersion.Parse(version, SemVersionStyles.Strict); VersionIncluded = versionIncluded; } public string Range { get; } public bool IncludeAllPrerelease { get; } public SemVersion Version { get; } public bool VersionIncluded { get; } public override string ToString() { var includes = VersionIncluded ? "includes" : "excludes"; return $"{ToRangeString()} {includes} {Version}"; } public void Assert() { var rangeSet = SemVersionRange.ParseNpm(Range, IncludeAllPrerelease); if (VersionIncluded) Xunit.Assert.True(rangeSet.Contains(Version), $"{ToRangeString()} should include {Version}"); else Xunit.Assert.False(rangeSet.Contains(Version), $"{ToRangeString()} should exclude {Version}"); } private string ToRangeString() => IncludeAllPrerelease ? Range + " w/ Prerelease" : Range; } }
using Semver.Ranges; namespace Semver.Test.TestCases { /// <summary> /// An individual test case for whether an npm range contains a version /// </summary> public class NpmRangeContainsTestCase { public static NpmRangeContainsTestCase NpmIncludes(string range, string version, bool includeAllPrerelease = false) => new NpmRangeContainsTestCase(range, includeAllPrerelease, version, true); public static NpmRangeContainsTestCase NpmExcludes(string range, string version, bool includeAllPrerelease = false) => new NpmRangeContainsTestCase(range, includeAllPrerelease, version, false); private NpmRangeContainsTestCase(string range, bool includeAllPrerelease, string version, bool versionIncluded) { Range = range; IncludeAllPrerelease = includeAllPrerelease; Version = SemVersion.Parse(version, SemVersionStyles.Strict); VersionIncluded = versionIncluded; } public string Range { get; } public bool IncludeAllPrerelease { get; } public SemVersion Version { get; } public bool VersionIncluded { get; } public override string ToString() { var includes = VersionIncluded ? "includes" : "excludes"; return $"{ToRangeString()} {includes} {Version}"; } public void Assert() { #pragma warning disable CS0618 // Type or member is obsolete var rangeSet = SemVersionRangeSet.ParseNpm(Range, IncludeAllPrerelease); #pragma warning restore CS0618 // Type or member is obsolete if (VersionIncluded) Xunit.Assert.True(rangeSet.Contains(Version), $"{ToRangeString()} should include {Version}"); else Xunit.Assert.False(rangeSet.Contains(Version), $"{ToRangeString()} should exclude {Version}"); } private string ToRangeString() => IncludeAllPrerelease ? Range + " w/ Prerelease" : Range; } }
mit
C#
d06fd299cd6395ce7237adc52b2ed8a0764e9add
Fix bracket editor crash when no round description is present (#5107)
ppy/osu,EVAST9919/osu,ZLima12/osu,smoogipoo/osu,peppy/osu,ppy/osu,peppy/osu,EVAST9919/osu,johnneijzen/osu,ppy/osu,smoogipooo/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,ZLima12/osu,UselessToucan/osu,NeoAdonis/osu,2yangk23/osu,peppy/osu-new,johnneijzen/osu,2yangk23/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu
osu.Game.Tournament/Screens/Ladder/Components/DrawableTournamentRound.cs
osu.Game.Tournament/Screens/Ladder/Components/DrawableTournamentRound.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 JetBrains.Annotations; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Tournament.Models; using osuTK.Graphics; namespace osu.Game.Tournament.Screens.Ladder.Components { public class DrawableTournamentRound : CompositeDrawable { [UsedImplicitly] private readonly Bindable<string> name; [UsedImplicitly] private readonly Bindable<string> description; public DrawableTournamentRound(TournamentRound round, bool losers = false) { OsuSpriteText textName; OsuSpriteText textDescription; AutoSizeAxes = Axes.Both; InternalChild = new FillFlowContainer { Direction = FillDirection.Vertical, AutoSizeAxes = Axes.Both, Children = new Drawable[] { textDescription = new OsuSpriteText { Colour = Color4.Black, Origin = Anchor.TopCentre, Anchor = Anchor.TopCentre }, textName = new OsuSpriteText { Font = OsuFont.GetFont(weight: FontWeight.Bold), Colour = Color4.Black, Origin = Anchor.TopCentre, Anchor = Anchor.TopCentre }, } }; name = round.Name.GetBoundCopy(); name.BindValueChanged(n => textName.Text = ((losers ? "Losers " : "") + round.Name).ToUpper(), true); description = round.Description.GetBoundCopy(); description.BindValueChanged(n => textDescription.Text = round.Description.Value?.ToUpper(), true); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using JetBrains.Annotations; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Tournament.Models; using osuTK.Graphics; namespace osu.Game.Tournament.Screens.Ladder.Components { public class DrawableTournamentRound : CompositeDrawable { [UsedImplicitly] private readonly Bindable<string> name; [UsedImplicitly] private readonly Bindable<string> description; public DrawableTournamentRound(TournamentRound round, bool losers = false) { OsuSpriteText textName; OsuSpriteText textDescription; AutoSizeAxes = Axes.Both; InternalChild = new FillFlowContainer { Direction = FillDirection.Vertical, AutoSizeAxes = Axes.Both, Children = new Drawable[] { textDescription = new OsuSpriteText { Colour = Color4.Black, Origin = Anchor.TopCentre, Anchor = Anchor.TopCentre }, textName = new OsuSpriteText { Font = OsuFont.GetFont(weight: FontWeight.Bold), Colour = Color4.Black, Origin = Anchor.TopCentre, Anchor = Anchor.TopCentre }, } }; name = round.Name.GetBoundCopy(); name.BindValueChanged(n => textName.Text = ((losers ? "Losers " : "") + round.Name).ToUpper(), true); description = round.Name.GetBoundCopy(); description.BindValueChanged(n => textDescription.Text = round.Description.Value.ToUpper(), true); } } }
mit
C#
d74d0dc6ffe33b491bb1ea4188748fe605232265
Remove usage of CFBoolean.[True|False]Object in monomac
mono/maccore,jorik041/maccore,cwensley/maccore
src/QuickLook/Thumbnail.cs
src/QuickLook/Thumbnail.cs
// // MacOS Quicklook Thumbnail support // // Authors: // Miguel de Icaza // // Copyright 2012, Xamarin Inc // // 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. // #if MONOMAC using System; using MonoMac.Foundation; using MonoMac.CoreFoundation; using MonoMac.CoreGraphics; using System.Drawing; using System.Runtime.InteropServices; namespace MonoMac.QuickLook { public static partial class QLThumbnailImage { [DllImport(Constants.QuickLookLibrary)] extern static IntPtr QLThumbnailImageCreate (IntPtr allocator, IntPtr url, System.Drawing.SizeF maxThumbnailSize, IntPtr options); public static CGImage Create (NSUrl url, SizeF maxThumbnailSize, float scaleFactor = 1, bool iconMode = false) { NSMutableDictionary dictionary = null; if (scaleFactor != 1 && iconMode != false) { dictionary = new NSMutableDictionary (); dictionary.LowlevelSetObject ((NSNumber) scaleFactor, OptionScaleFactorKey.Handle); dictionary.LowlevelSetObject (iconMode ? CFBoolean.True.Handle : CFBoolean.False.Handle, OptionIconModeKey.Handle); } var handle = QLThumbnailImageCreate (IntPtr.Zero, url.Handle, maxThumbnailSize, dictionary == null ? IntPtr.Zero : dictionary.Handle); GC.KeepAlive (dictionary); if (handle != null) return new CGImage (handle, true); return null; } } } #endif
// // MacOS Quicklook Thumbnail support // // Authors: // Miguel de Icaza // // Copyright 2012, Xamarin Inc // // 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. // #if MONOMAC using System; using MonoMac.Foundation; using MonoMac.CoreFoundation; using MonoMac.CoreGraphics; using System.Drawing; using System.Runtime.InteropServices; namespace MonoMac.QuickLook { public static partial class QLThumbnailImage { [DllImport(Constants.QuickLookLibrary)] extern static IntPtr QLThumbnailImageCreate (IntPtr allocator, IntPtr url, System.Drawing.SizeF maxThumbnailSize, IntPtr options); public static CGImage Create (NSUrl url, SizeF maxThumbnailSize, float scaleFactor = 1, bool iconMode = false) { NSDictionary dictionary; if (scaleFactor != 1 && iconMode != false){ dictionary = NSDictionary.FromObjectsAndKeys (new NSObject [] { (NSNumber) scaleFactor, iconMode ? CFBoolean.TrueObject : CFBoolean.FalseObject }, new NSObject [] { OptionScaleFactorKey, OptionIconModeKey }); } else dictionary = null; var handle = QLThumbnailImageCreate (IntPtr.Zero, url.Handle, maxThumbnailSize, dictionary == null ? IntPtr.Zero : dictionary.Handle); GC.KeepAlive (dictionary); if (handle != null) return new CGImage (handle, true); return null; } } } #endif
apache-2.0
C#
90b46fb13e388d92e81550564b9e187eadfbf1ab
Update Class1.cs
Zetozz/Tymczasowe
Dzien37/DokumentyPacjenci/Class1.cs
Dzien37/DokumentyPacjenci/Class1.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DokumentyPacjenci { public class Class1 { void a() { static int i = 0; string Imie; // dodaelm komentaz //aaaa //dodalem se komenta } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DokumentyPacjenci { public class Class1 { void a() { static int i = 0; string Imie; // dodaelm komentaz //aaaa } } }
mit
C#
cb9ea11a98cd47d989c07732e21656021105586b
Fix crashing due to missing history in LFR
ROMaster2/LiveSplit,LiveSplit/LiveSplit,ROMaster2/LiveSplit,ROMaster2/LiveSplit,kugelrund/LiveSplit,kugelrund/LiveSplit,Glurmo/LiveSplit,kugelrund/LiveSplit,Glurmo/LiveSplit,Glurmo/LiveSplit
LiveSplit/LiveSplit.Core/Model/Comparisons/LastFinishedRunComparisonGenerator.cs
LiveSplit/LiveSplit.Core/Model/Comparisons/LastFinishedRunComparisonGenerator.cs
using LiveSplit.Options; using System; using System.Linq; namespace LiveSplit.Model.Comparisons { public class LastFinishedRunComparisonGenerator : IComparisonGenerator { public IRun Run { get; set; } public const string ComparisonName = "Last Finished Run"; public const string ShortComparisonName = "Last Run"; public string Name => ComparisonName; public LastFinishedRunComparisonGenerator(IRun run) { Run = run; } public void Generate(TimingMethod method) { Attempt? mostRecentFinished = null; foreach (var attempt in Run.AttemptHistory.Reverse()) { if (attempt.Time[method] != null) { mostRecentFinished = attempt; break; } } TimeSpan? totalTime = TimeSpan.Zero; for (var ind = 0; ind < Run.Count; ind++) { TimeSpan? segmentTime = null; if (mostRecentFinished != null && Run[ind].SegmentHistory.ContainsKey(mostRecentFinished.Value.Index)) segmentTime = Run[ind].SegmentHistory[mostRecentFinished.Value.Index][method]; else totalTime = null; var time = new Time(Run[ind].Comparisons[Name]); if (totalTime != null && segmentTime != null) { totalTime += segmentTime; time[method] = totalTime; } else time[method] = null; Run[ind].Comparisons[Name] = time; } } public void Generate(ISettings settings) { Generate(TimingMethod.RealTime); Generate(TimingMethod.GameTime); } } }
using LiveSplit.Options; using System; using System.Linq; namespace LiveSplit.Model.Comparisons { public class LastFinishedRunComparisonGenerator : IComparisonGenerator { public IRun Run { get; set; } public const string ComparisonName = "Last Finished Run"; public const string ShortComparisonName = "Last Run"; public string Name => ComparisonName; public LastFinishedRunComparisonGenerator(IRun run) { Run = run; } public void Generate(TimingMethod method) { Attempt? mostRecentFinished = null; foreach (var attempt in Run.AttemptHistory.Reverse()) { if (attempt.Time[method] != null) { mostRecentFinished = attempt; break; } } TimeSpan? totalTime = TimeSpan.Zero; for (var ind = 0; ind < Run.Count; ind++) { TimeSpan? segmentTime; if (mostRecentFinished != null) segmentTime = Run[ind].SegmentHistory[mostRecentFinished.Value.Index][method]; else segmentTime = null; var time = new Time(Run[ind].Comparisons[Name]); if (totalTime != null && segmentTime != null) { totalTime += segmentTime; time[method] = totalTime; } else time[method] = null; Run[ind].Comparisons[Name] = time; } } public void Generate(ISettings settings) { Generate(TimingMethod.RealTime); Generate(TimingMethod.GameTime); } } }
mit
C#
f275e764449e05ed3b5d3568702b25ffb4f76d41
configure tokenhandle to own the TokenHandleClaim table data
yfann/AuthorizationServer,IdentityModel/AuthorizationServer,IdentityModel/AuthorizationServer,yfann/AuthorizationServer,s093294/Thinktecture.AuthorizationServer,s093294/Thinktecture.AuthorizationServer
source/Thinktecture.AuthorizationServer.EF/AuthorizationServerContext.cs
source/Thinktecture.AuthorizationServer.EF/AuthorizationServerContext.cs
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using Thinktecture.AuthorizationServer.Models; namespace Thinktecture.AuthorizationServer.EF { public class AuthorizationServerContext : DbContext { public AuthorizationServerContext() : base("AuthorizationServerContext") { } public DbSet<GlobalConfiguration> GlobalConfiguration { get; set; } public DbSet<Application> Applications { get; set; } public DbSet<Scope> Scopes { get; set; } public DbSet<Client> Clients { get; set; } public DbSet<ClientRedirectUri> ClientRedirectUris { get; set; } public DbSet<SigningKey> SigningKeys { get; set; } public DbSet<TokenHandle> TokenHandles { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Client>().HasMany(x => x.RedirectUris).WithRequired(); modelBuilder.Entity<Application>().HasMany(x => x.Scopes).WithRequired(); modelBuilder.Entity<Scope>().HasMany(x => x.AllowedClients).WithMany(); modelBuilder.Entity<TokenHandle>().HasMany(x => x.Scopes).WithMany(); modelBuilder.Entity<TokenHandle>().HasMany(x => x.ResourceOwner).WithRequired(); } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using Thinktecture.AuthorizationServer.Models; namespace Thinktecture.AuthorizationServer.EF { public class AuthorizationServerContext : DbContext { public AuthorizationServerContext() : base("AuthorizationServerContext") { } public DbSet<GlobalConfiguration> GlobalConfiguration { get; set; } public DbSet<Application> Applications { get; set; } public DbSet<Scope> Scopes { get; set; } public DbSet<Client> Clients { get; set; } public DbSet<ClientRedirectUri> ClientRedirectUris { get; set; } public DbSet<SigningKey> SigningKeys { get; set; } public DbSet<TokenHandle> TokenHandles { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Client>().HasMany(x => x.RedirectUris).WithRequired(); modelBuilder.Entity<Application>().HasMany(x => x.Scopes).WithRequired(); modelBuilder.Entity<Scope>().HasMany(x => x.AllowedClients).WithMany(); modelBuilder.Entity<TokenHandle>().HasMany(x => x.Scopes).WithMany(); } } }
bsd-3-clause
C#
9f3de48a3fe5e8a1be9d52f3fb98331c7fc2dbc9
Fix typo in last fix
HelloKitty/Booma.Proxy
src/Booma.Proxy.Client.Unity.Ship/Factory/LobbyLocalPlayerWorldObjectFactory.cs
src/Booma.Proxy.Client.Unity.Ship/Factory/LobbyLocalPlayerWorldObjectFactory.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Guardians; using UnityEngine; namespace Booma.Proxy { [AdditionalRegisterationAs(typeof(IFactoryCreatable<GameObject, LocalPlayerWorldRepresentationCreationContext>))] [SceneTypeCreate(GameSceneType.LobbyDefault)] public sealed class LobbyLocalPlayerWorldObjectFactory : IFactoryCreatable<GameObject, LocalPlayerWorldRepresentationCreationContext>, IGameInitializable { private IRoomCollection Rooms { get; } private IWorldObjectToEntityMappable WorldPlayerMap { get; } private INetworkPlayerPrefabProvider PrefabProvider { get; } /// <inheritdoc /> public LobbyLocalPlayerWorldObjectFactory([NotNull] IRoomCollection rooms, [NotNull] IWorldObjectToEntityMappable worldPlayerMap, [NotNull] INetworkPlayerPrefabProvider prefabProvider) { Rooms = rooms ?? throw new ArgumentNullException(nameof(rooms)); WorldPlayerMap = worldPlayerMap ?? throw new ArgumentNullException(nameof(worldPlayerMap)); PrefabProvider = prefabProvider ?? throw new ArgumentNullException(nameof(prefabProvider)); } /// <inheritdoc /> public GameObject Create(LocalPlayerWorldRepresentationCreationContext context) { GameObject player = GameObject.Instantiate(PrefabProvider.LocalPlayerPrefab, context.SpawnData.AssociatedObject.Position, context.SpawnData.AssociatedObject.Rotation); //TODO: How should we handle rooms? //Rooms.DefaultRoom.TryEnter(player); return player; } //TODO: This is kinda a hack to get into the scene /// <inheritdoc /> public Task OnGameInitialized() { return Task.CompletedTask; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Guardians; using UnityEngine; namespace Booma.Proxy { [AdditionalRegisterationAs(typeof(IFactoryCreatable<GameObject, LocalPlayerWorldRepresentationCreationContext))] [SceneTypeCreate(GameSceneType.LobbyDefault)] public sealed class LobbyLocalPlayerWorldObjectFactory : IFactoryCreatable<GameObject, LocalPlayerWorldRepresentationCreationContext>, IGameInitializable { private IRoomCollection Rooms { get; } private IWorldObjectToEntityMappable WorldPlayerMap { get; } private INetworkPlayerPrefabProvider PrefabProvider { get; } /// <inheritdoc /> public LobbyLocalPlayerWorldObjectFactory([NotNull] IRoomCollection rooms, [NotNull] IWorldObjectToEntityMappable worldPlayerMap, [NotNull] INetworkPlayerPrefabProvider prefabProvider) { Rooms = rooms ?? throw new ArgumentNullException(nameof(rooms)); WorldPlayerMap = worldPlayerMap ?? throw new ArgumentNullException(nameof(worldPlayerMap)); PrefabProvider = prefabProvider ?? throw new ArgumentNullException(nameof(prefabProvider)); } /// <inheritdoc /> public GameObject Create(LocalPlayerWorldRepresentationCreationContext context) { GameObject player = GameObject.Instantiate(PrefabProvider.LocalPlayerPrefab, context.SpawnData.AssociatedObject.Position, context.SpawnData.AssociatedObject.Rotation); //TODO: How should we handle rooms? //Rooms.DefaultRoom.TryEnter(player); return player; } //TODO: This is kinda a hack to get into the scene /// <inheritdoc /> public Task OnGameInitialized() { return Task.CompletedTask; } } }
agpl-3.0
C#
fe359ce47335595369810203725ecddc977e62cd
Update Assets/MRTK/Examples/Demos/HandTracking/Scripts/LeapCoreAssetsDetector.cs
DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
Assets/MRTK/Examples/Demos/HandTracking/Scripts/LeapCoreAssetsDetector.cs
Assets/MRTK/Examples/Demos/HandTracking/Scripts/LeapCoreAssetsDetector.cs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using UnityEngine; using UnityEngine.UI; namespace Microsoft.MixedReality.Toolkit.Examples.Demos { /// <summary> /// Detects if the Leap Motion Data Provider can be used given the current unity project configuration and displays a message /// to the LeapMotionHandTrackingExample menu panel. /// </summary> public class LeapCoreAssetsDetector : MonoBehaviour { void Start() { var text = gameObject.GetComponent<Text>(); #if LEAPMOTIONCORE_PRESENT #if UNITY_WSA && !UNITY_EDITOR text.text = "The Leap Data Provider can only be used on the UWP platform in the editor and NOT in a UWP build."; text.color = Color.yellow; #else text.text = "The Leap Data Provider can be used in this project"; text.color = Color.green; #endif // UNITY_WSA && !UNITY_EDITOR #else text.text = "This project has not met the requirements to use the Leap Data Provider. For more information, visit the MRTK Leap Motion Documentation"; text.color = Color.red; #endif } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using UnityEngine; using UnityEngine.UI; namespace Microsoft.MixedReality.Toolkit.Examples.Demos { /// <summary> /// Detects if the Leap Motion Data Provider can be used given the current unity project configuration and displays a message /// to the LeapMotionHandTrackingExample menu panel. /// </summary> public class LeapCoreAssetsDetector : MonoBehaviour { void Start() { var text = gameObject.GetComponent<Text>(); #if LEAPMOTIONCORE_PRESENT #if UNITY_WSA && !UNITY_EDITOR text.text = "The Leap Data Provider can only be used on the UWP platform in the editor and NOT in a UWP Build."; text.color = Color.yellow; #else text.text = "The Leap Data Provider can be used in this project"; text.color = Color.green; #endif // UNITY_WSA && !UNITY_EDITOR #else text.text = "This project has not met the requirements to use the Leap Data Provider. For more information, visit the MRTK Leap Motion Documentation"; text.color = Color.red; #endif } } }
mit
C#
c72a4adb2b68e6b6c10745584aa42347926e6a44
Change implementation of SlowMemoryStream to fix hanging test
smatsson/tusdotnet,tusdotnet/tusdotnet,tusdotnet/tusdotnet,tusdotnet/tusdotnet,tusdotnet/tusdotnet,smatsson/tusdotnet
Source/tusdotnet.test/Helpers/SlowMemoryStream.cs
Source/tusdotnet.test/Helpers/SlowMemoryStream.cs
using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace tusdotnet.test.Helpers { /// <summary> /// The SlowMemoryStream adds a 100 ms delay on every ReadAsync. /// </summary> public class SlowMemoryStream : Stream { private readonly MemoryStream _stream; /// <summary> /// Default constructor. /// </summary> /// <param name="buffer">The buffer to read from</param> public SlowMemoryStream(byte[] buffer) { _stream = new MemoryStream(buffer); } public override bool CanRead => _stream.CanRead; public override bool CanSeek => _stream.CanSeek; public override bool CanWrite => false; public override long Length => _stream.Length; public override long Position { get { return _stream.Position; } set { _stream.Position = value; } } public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { await Task.Delay(100); // Note: Do not use the provided cancellation token but let the disk store cancel the read instead. return await _stream.ReadAsync(buffer, offset, count, CancellationToken.None); } public override long Seek(long offset, SeekOrigin origin) => throw new NotImplementedException(); public override int Read(byte[] buffer, int offset, int count) => throw new NotImplementedException(); public override void SetLength(long value) => throw new NotImplementedException(); public override void Flush() => throw new NotImplementedException(); public override void Write(byte[] buffer, int offset, int count) => throw new NotImplementedException(); } }
using System.IO; using System.Threading; namespace tusdotnet.test.Helpers { /// <summary> /// The SlowMemoryStream adds a 100 ms delay on every read. /// </summary> public class SlowMemoryStream : MemoryStream { /// <summary> /// Default constructor. /// </summary> /// <param name="buffer">The buffer to read from</param> public SlowMemoryStream(byte[] buffer) : base(buffer) { } public override int Read(byte[] buffer, int offset, int count) { Thread.Sleep(100); return base.Read(buffer, offset, count); } } }
mit
C#
9a319e3f96c6a6c6b7fea7c733b7e3450fdbf610
Add missing space
smoogipoo/osu,EVAST9919/osu,NeoAdonis/osu,peppy/osu-new,peppy/osu,ppy/osu,smoogipooo/osu,UselessToucan/osu,johnneijzen/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu,peppy/osu,2yangk23/osu,NeoAdonis/osu,ZLima12/osu,2yangk23/osu,NeoAdonis/osu,peppy/osu,ppy/osu,smoogipoo/osu,johnneijzen/osu,smoogipoo/osu,EVAST9919/osu,ZLima12/osu
osu.Game.Tournament/Screens/Editors/IModelBacked.cs
osu.Game.Tournament/Screens/Editors/IModelBacked.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. namespace osu.Game.Tournament.Screens.Editors { /// <summary> /// Provides a mechanism to access a related model from a representing class. /// </summary> /// <typeparam name="TModel">The type of model.</typeparam> public interface IModelBacked<out TModel> { /// <summary> /// The model. /// </summary> TModel Model { get; } } }
// 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. namespace osu.Game.Tournament.Screens.Editors { /// <summary> /// Provides a mechanism to access a related model from a representing class. /// </summary> /// <typeparam name="TModel">The type of model.</typeparam> public interface IModelBacked<out TModel> { /// <summary> /// The model. /// </summary> TModel Model { get; } } }
mit
C#
9cfe2496cd3c28fef89d7cb8f9f4558c461a1e4a
Add new entities to context
denismaster/dcs,denismaster/dcs,denismaster/dcs,denismaster/dcs
src/Diploms.DataLayer/DiplomContext.cs
src/Diploms.DataLayer/DiplomContext.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Diploms.Core; namespace Diploms.DataLayer { public class DiplomContext : DbContext { public DbSet<Institute> Institutes { get; set; } public DbSet<Department> Departments { get; set; } public DbSet<Speciality> Specialities { get; set; } public DbSet<TeacherPosition> TeachersPositions { get; set; } public DbSet<Teacher> Teachers { get; set; } public DbSet<Group> Groups { get; set; } public DbSet<Student> Students { get; set; } public DbSet<Period> Periods { get; set; } public DbSet<DiplomWork> DiplomWorks { get; set; } public DbSet<DiplomWorkMaterial> DiplomWorkMaterials { get; set; } public DbSet<GostControlTry> GostControlTries { get; set; } public DbSet<ImplementationStage> ImplementationStages { get; set; } public DbSet<CustomStage> CustomStages { get; set; } public DbSet<User> Users { get; set; } public DbSet<Role> Roles { get; set; } public DiplomContext() : base() { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<UserRole>() .HasKey(t => new { t.UserId, t.RoleId }); modelBuilder.Entity<UserRole>() .HasOne(pt => pt.User) .WithMany(p => p.Roles) .HasForeignKey(pt => pt.UserId); modelBuilder.Entity<UserRole>() .HasOne(pt => pt.Role) .WithMany(t => t.Users) .HasForeignKey(pt => pt.RoleId); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //TODO: Use appsettings.json or environment variable, not the string here. optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=diploms;UserId=postgres;Password=12345678;Pooling=true"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Diploms.Core; namespace Diploms.DataLayer { public class DiplomContext : DbContext { public DbSet<Institute> Institutes { get; set; } public DbSet<Department> Departments { get; set; } public DbSet<Speciality> Specialities { get; set; } public DbSet<User> Users { get; set; } public DbSet<Role> Roles { get; set; } public DiplomContext() : base() { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<UserRole>() .HasKey(t => new { t.UserId, t.RoleId }); modelBuilder.Entity<UserRole>() .HasOne(pt => pt.User) .WithMany(p => p.Roles) .HasForeignKey(pt => pt.UserId); modelBuilder.Entity<UserRole>() .HasOne(pt => pt.Role) .WithMany(t => t.Users) .HasForeignKey(pt => pt.RoleId); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //TODO: Use appsettings.json or environment variable, not the string here. optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=diploms;UserId=postgres;Password=12345678;Pooling=true"); } } }
mit
C#
6f951551db443441cb60e41b2d475e4e8115b237
Fix ArgumentNullException
zbrad/nuproj,ericstj/nuproj,AArnott/nuproj,DavidAnson/nuproj,kovalikp/nuproj,oliver-feng/nuproj,DavidAnson/nuproj,nuproj/nuproj,faustoscardovi/nuproj,PedroLamas/nuproj,NN---/nuproj
src/NuProj.Tasks/ReadPackagesConfig.cs
src/NuProj.Tasks/ReadPackagesConfig.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using System.Xml.XPath; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace NuProj.Tasks { public class ReadPackagesConfig : Task { [Required] public string PackagesConfigPath { get; set; } [Output] public ITaskItem[] Packages { get; set; } public override bool Execute() { var document = XDocument.Load(PackagesConfigPath); var packageElements = document.XPathSelectElements("/packages/package"); Packages = packageElements.Select(ConvertPackageElement).ToArray(); return true; } protected ITaskItem ConvertPackageElement(XElement element) { var idAttribute = element.Attribute("id"); var versionAttribute = element.Attribute("version"); var targetFrameworkAttribute = element.Attribute("targetFramework"); var id = idAttribute.Value; var version = versionAttribute.Value; var targetFramework = targetFrameworkAttribute == null ? null : targetFrameworkAttribute.Value; var packageDirectoryPath = GetPackageDirectoryPath(PackagesConfigPath, id, version); var metadata = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); metadata.Add("Version", version); if (targetFramework != null) metadata.Add("TargetFramework", targetFramework); metadata.Add("PackageDirectoryPath", packageDirectoryPath); var item = new TaskItem(id, metadata); return item; } private static string GetPackageDirectoryPath(string packagesConfigPath, string packageId, string packageVersion) { var packageDirectoryName = packageId + "." + packageVersion; var candidateFolder = Path.GetDirectoryName(packagesConfigPath); while (candidateFolder != null) { var packageDirectoryPath = Path.Combine(candidateFolder, "packages", packageDirectoryName); if (Directory.Exists(packageDirectoryPath)) return packageDirectoryPath; candidateFolder = Path.GetDirectoryName(candidateFolder); } return string.Empty; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using System.Xml.XPath; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace NuProj.Tasks { public class ReadPackagesConfig : Task { [Required] public string PackagesConfigPath { get; set; } [Output] public ITaskItem[] Packages { get; set; } public override bool Execute() { var document = XDocument.Load(PackagesConfigPath); var packageElements = document.XPathSelectElements("/packages/package"); Packages = packageElements.Select(ConvertPackageElement).ToArray(); return true; } protected ITaskItem ConvertPackageElement(XElement element) { var idAttribute = element.Attribute("id"); var versionAttribute = element.Attribute("version"); var targetFrameworkAttribute = element.Attribute("targetFramework"); var id = idAttribute.Value; var version = versionAttribute.Value; var targetFramework = targetFrameworkAttribute == null ? null : targetFrameworkAttribute.Value; var packageDirectoryPath = GetPackageDirectoryPath(PackagesConfigPath, id, version); var metadata = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); metadata.Add("Version", version); if (targetFramework != null) metadata.Add("TargetFramework", targetFramework); metadata.Add("PackageDirectoryPath", packageDirectoryPath); var item = new TaskItem(id, metadata); return item; } private static string GetPackageDirectoryPath(string packagesConfigPath, string packageId, string packageVersion) { var packageDirectoryName = packageId + "." + packageVersion; var candidateFolder = Path.GetDirectoryName(packagesConfigPath); while (candidateFolder != null) { var packageDirectoryPath = Path.Combine(candidateFolder, "packages", packageDirectoryName); if (Directory.Exists(packageDirectoryPath)) return packageDirectoryPath; candidateFolder = Path.GetDirectoryName(candidateFolder); } return null; } } }
mit
C#
2538d219a61d43ef6b8fb1b6035180f1c63f02b5
remove wait for service stopped
gigya/microdot
tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/WarmupTestService/WarmupTestServiceHostWithSiloHostFake.cs
tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/WarmupTestService/WarmupTestServiceHostWithSiloHostFake.cs
using System.Threading; using System.Threading.Tasks; using Gigya.Microdot.Fakes; using Gigya.Microdot.Hosting.HttpService; using Gigya.Microdot.Hosting.Validators; using Gigya.Microdot.Interfaces; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.CalculatorService; using Gigya.Microdot.SharedLogic; using Ninject; using NSubstitute; namespace Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.WarmupTestService { public class WarmupTestServiceHostWithSiloHostFake : CalculatorServiceHost { private IDependantClassFake _dependantClassFake = Substitute.For<IDependantClassFake>(); private TaskCompletionSource<bool> _hostDisposedEvent = new TaskCompletionSource<bool>(); protected override void Configure(IKernel kernel, OrleansCodeConfig commonConfig) { kernel.Rebind<ServiceValidator>().To<MockServiceValidator>().InSingletonScope(); kernel.Rebind<IMetricsInitializer>().To<MetricsInitializerFake>(); kernel.Rebind<GigyaSiloHost>().To<GigyaSiloHostFake>(); kernel.Rebind<IDependantClassFake>().ToConstant(_dependantClassFake); kernel.Rebind<ILog>().To<NullLog>(); kernel.Rebind<IServiceInterfaceMapper>().To<OrleansServiceInterfaceMapper>(); kernel.Rebind<IAssemblyProvider>().To<AssemblyProvider>(); ServiceArguments args = new ServiceArguments(basePortOverride:9555); kernel.Rebind<ServiceArguments>().ToConstant(args); kernel.Rebind<WarmupTestServiceHostWithSiloHostFake>().ToConstant(this); } public async Task StopHost() { await WaitForServiceStartedAsync(); Stop(); //await WaitForServiceGracefullyStoppedAsync(); //Dispose(); _hostDisposedEvent.SetResult(true); } public async Task WaitForHostDisposed() { await _hostDisposedEvent.Task; } } }
using System.Threading; using System.Threading.Tasks; using Gigya.Microdot.Fakes; using Gigya.Microdot.Hosting.HttpService; using Gigya.Microdot.Hosting.Validators; using Gigya.Microdot.Interfaces; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.CalculatorService; using Gigya.Microdot.SharedLogic; using Ninject; using NSubstitute; namespace Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.WarmupTestService { public class WarmupTestServiceHostWithSiloHostFake : CalculatorServiceHost { private IDependantClassFake _dependantClassFake = Substitute.For<IDependantClassFake>(); private TaskCompletionSource<bool> _hostDisposedEvent = new TaskCompletionSource<bool>(); protected override void Configure(IKernel kernel, OrleansCodeConfig commonConfig) { kernel.Rebind<ServiceValidator>().To<MockServiceValidator>().InSingletonScope(); kernel.Rebind<IMetricsInitializer>().To<MetricsInitializerFake>(); kernel.Rebind<GigyaSiloHost>().To<GigyaSiloHostFake>(); kernel.Rebind<IDependantClassFake>().ToConstant(_dependantClassFake); kernel.Rebind<ILog>().To<NullLog>(); kernel.Rebind<IServiceInterfaceMapper>().To<OrleansServiceInterfaceMapper>(); kernel.Rebind<IAssemblyProvider>().To<AssemblyProvider>(); ServiceArguments args = new ServiceArguments(basePortOverride:9555); kernel.Rebind<ServiceArguments>().ToConstant(args); kernel.Rebind<WarmupTestServiceHostWithSiloHostFake>().ToConstant(this); } public async Task StopHost() { await WaitForServiceStartedAsync(); Stop(); await WaitForServiceGracefullyStoppedAsync(); //Dispose(); _hostDisposedEvent.SetResult(true); } public async Task WaitForHostDisposed() { await _hostDisposedEvent.Task; } } }
apache-2.0
C#
c33f6c39213ff186a91a4a18e4c8dd15ec40b990
update namespace post merge of #3242
elastic/elasticsearch-net,elastic/elasticsearch-net
src/Tests/Reproduce/GithubIssue3231.cs
src/Tests/Reproduce/GithubIssue3231.cs
using Elasticsearch.Net; using FluentAssertions; using System; using Elastic.Xunit.XunitPlumbing; using Tests.Framework; using Tests.Framework.ManagedElasticsearch.Clusters; using Xunit; namespace Tests.Reproduce { public class GithubIssue3231 : IClusterFixture<ReadOnlyCluster> { private readonly ReadOnlyCluster _cluster; public GithubIssue3231(ReadOnlyCluster cluster) { _cluster = cluster; } [I] public void CatIndicesUsesThrowExceptionsFromConnectionSettingsWhenRequestSettingsAreNotSetTest() { var client = TestClient.GetClient(connectionSettings => connectionSettings.ThrowExceptions()); Action catIndicesRequest = () => client.LowLevel.CatIndices<StringResponse>("non-existing-index"); catIndicesRequest.ShouldThrow<ElasticsearchClientException>(); } } }
using Elasticsearch.Net; using FluentAssertions; using System; using Tests.Framework; using Tests.Framework.ManagedElasticsearch.Clusters; using Xunit; namespace Tests.Reproduce { public class GithubIssue3231 : IClusterFixture<ReadOnlyCluster> { private readonly ReadOnlyCluster _cluster; public GithubIssue3231(ReadOnlyCluster cluster) { _cluster = cluster; } [I] public void CatIndicesUsesThrowExceptionsFromConnectionSettingsWhenRequestSettingsAreNotSetTest() { var client = TestClient.GetClient(connectionSettings => connectionSettings.ThrowExceptions()); Action catIndicesRequest = () => client.LowLevel.CatIndices<StringResponse>("non-existing-index"); catIndicesRequest.ShouldThrow<ElasticsearchClientException>(); } } }
apache-2.0
C#
2c01a8142baf521eb9955ed97c18cede0e623407
fix typo
rohmano/azure-powershell,dulems/azure-powershell,AzureRT/azure-powershell,zhencui/azure-powershell,hungmai-msft/azure-powershell,devigned/azure-powershell,naveedaz/azure-powershell,arcadiahlyy/azure-powershell,pankajsn/azure-powershell,shuagarw/azure-powershell,zhencui/azure-powershell,shuagarw/azure-powershell,yantang-msft/azure-powershell,zhencui/azure-powershell,seanbamsft/azure-powershell,rohmano/azure-powershell,TaraMeyer/azure-powershell,nemanja88/azure-powershell,jtlibing/azure-powershell,AzureAutomationTeam/azure-powershell,krkhan/azure-powershell,haocs/azure-powershell,rohmano/azure-powershell,yantang-msft/azure-powershell,TaraMeyer/azure-powershell,arcadiahlyy/azure-powershell,AzureRT/azure-powershell,juvchan/azure-powershell,pankajsn/azure-powershell,rohmano/azure-powershell,arcadiahlyy/azure-powershell,seanbamsft/azure-powershell,krkhan/azure-powershell,jtlibing/azure-powershell,krkhan/azure-powershell,zhencui/azure-powershell,alfantp/azure-powershell,shuagarw/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,zhencui/azure-powershell,zhencui/azure-powershell,hovsepm/azure-powershell,yoavrubin/azure-powershell,seanbamsft/azure-powershell,devigned/azure-powershell,dulems/azure-powershell,hovsepm/azure-powershell,alfantp/azure-powershell,dulems/azure-powershell,ClogenyTechnologies/azure-powershell,akurmi/azure-powershell,juvchan/azure-powershell,CamSoper/azure-powershell,nemanja88/azure-powershell,rohmano/azure-powershell,AzureRT/azure-powershell,stankovski/azure-powershell,Matt-Westphal/azure-powershell,pankajsn/azure-powershell,jtlibing/azure-powershell,CamSoper/azure-powershell,seanbamsft/azure-powershell,stankovski/azure-powershell,TaraMeyer/azure-powershell,atpham256/azure-powershell,stankovski/azure-powershell,akurmi/azure-powershell,devigned/azure-powershell,yoavrubin/azure-powershell,hungmai-msft/azure-powershell,akurmi/azure-powershell,juvchan/azure-powershell,dulems/azure-powershell,stankovski/azure-powershell,ClogenyTechnologies/azure-powershell,ankurchoubeymsft/azure-powershell,yantang-msft/azure-powershell,atpham256/azure-powershell,pankajsn/azure-powershell,atpham256/azure-powershell,naveedaz/azure-powershell,dulems/azure-powershell,yoavrubin/azure-powershell,AzureAutomationTeam/azure-powershell,seanbamsft/azure-powershell,ankurchoubeymsft/azure-powershell,yantang-msft/azure-powershell,stankovski/azure-powershell,CamSoper/azure-powershell,devigned/azure-powershell,haocs/azure-powershell,CamSoper/azure-powershell,ClogenyTechnologies/azure-powershell,naveedaz/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,krkhan/azure-powershell,Matt-Westphal/azure-powershell,hovsepm/azure-powershell,krkhan/azure-powershell,nemanja88/azure-powershell,naveedaz/azure-powershell,AzureRT/azure-powershell,alfantp/azure-powershell,Matt-Westphal/azure-powershell,AzureRT/azure-powershell,hungmai-msft/azure-powershell,shuagarw/azure-powershell,haocs/azure-powershell,alfantp/azure-powershell,atpham256/azure-powershell,yoavrubin/azure-powershell,atpham256/azure-powershell,Matt-Westphal/azure-powershell,hovsepm/azure-powershell,hungmai-msft/azure-powershell,nemanja88/azure-powershell,ankurchoubeymsft/azure-powershell,ankurchoubeymsft/azure-powershell,Matt-Westphal/azure-powershell,AzureAutomationTeam/azure-powershell,hovsepm/azure-powershell,juvchan/azure-powershell,akurmi/azure-powershell,arcadiahlyy/azure-powershell,atpham256/azure-powershell,yoavrubin/azure-powershell,krkhan/azure-powershell,pankajsn/azure-powershell,yantang-msft/azure-powershell,akurmi/azure-powershell,shuagarw/azure-powershell,AzureAutomationTeam/azure-powershell,hungmai-msft/azure-powershell,rohmano/azure-powershell,alfantp/azure-powershell,naveedaz/azure-powershell,haocs/azure-powershell,TaraMeyer/azure-powershell,juvchan/azure-powershell,naveedaz/azure-powershell,devigned/azure-powershell,AzureRT/azure-powershell,CamSoper/azure-powershell,jtlibing/azure-powershell,yantang-msft/azure-powershell,seanbamsft/azure-powershell,TaraMeyer/azure-powershell,hungmai-msft/azure-powershell,jtlibing/azure-powershell,pankajsn/azure-powershell,nemanja88/azure-powershell,ankurchoubeymsft/azure-powershell,haocs/azure-powershell,arcadiahlyy/azure-powershell
src/ResourceManager/Network/Commands.Network/ExpressRouteCircuit/Authorization/AzureExpressRouteCircuitAuthorizationBase.cs
src/ResourceManager/Network/Commands.Network/ExpressRouteCircuit/Authorization/AzureExpressRouteCircuitAuthorizationBase.cs
// ---------------------------------------------------------------------------------- // // Copyright 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. // ---------------------------------------------------------------------------------- using System.Management.Automation; using MNM = Microsoft.Azure.Management.Network.Models; namespace Microsoft.Azure.Commands.Network { using System.Collections.Generic; public class AzureExpressRouteCircuitAuthorizationBase : NetworkBaseCmdlet { [Parameter( Mandatory = false, HelpMessage = "The name of the Authorization")] [ValidateNotNullOrEmpty] public virtual string Name { get; set; } } }
// ---------------------------------------------------------------------------------- // // Copyright 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. // ---------------------------------------------------------------------------------- using System.Management.Automation; using MNM = Microsoft.Azure.Management.Network.Models; namespace Microsoft.Azure.Commands.Network { using System.Collections.Generic; public class AzureExpressRouteCircuitAuthorizationBase : NetworkBaseCmdlet { [Parameter( Mandatory = false, HelpMessage = "The name of the Peering")] [ValidateNotNullOrEmpty] public virtual string Name { get; set; } } }
apache-2.0
C#
47cd92fc8cd9a29be28eda952ff68b6e283cddda
rename parameter
acple/ParsecSharp
ParsecSharp/Core/ParsecException.cs
ParsecSharp/Core/ParsecException.cs
using System; namespace ParsecSharp { public class ParsecException : Exception { public ParsecException(string message) : base(message) { } public ParsecException(string message, Exception innerException) : base(message, innerException) { } } }
using System; namespace ParsecSharp { public class ParsecException : Exception { public ParsecException(string message) : base(message) { } public ParsecException(string message, Exception exception) : base(message, exception) { } } }
mit
C#
693b00459ad26946336afd304d5d3e20c629de62
Fix ghost orbit not syncing to other clients
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.Shared/Follower/Components/OrbitVisualsComponent.cs
Content.Shared/Follower/Components/OrbitVisualsComponent.cs
using Robust.Shared.Animations; using Robust.Shared.GameStates; namespace Content.Shared.Follower.Components; [RegisterComponent] [NetworkedComponent] public sealed class OrbitVisualsComponent : Component { /// <summary> /// How long should the orbit animation last in seconds, before being randomized? /// </summary> public float OrbitLength = 2.0f; /// <summary> /// How far away from the entity should the orbit be, before being randomized? /// </summary> public float OrbitDistance = 1.0f; /// <summary> /// How long should the orbit stop animation last in seconds? /// </summary> public float OrbitStopLength = 1.0f; /// <summary> /// How far along in the orbit, from 0 to 1, is this entity? /// </summary> [Animatable] public float Orbit { get; set; } = 0.0f; }
using Robust.Shared.Animations; namespace Content.Shared.Follower.Components; [RegisterComponent] public sealed class OrbitVisualsComponent : Component { /// <summary> /// How long should the orbit animation last in seconds, before being randomized? /// </summary> public float OrbitLength = 2.0f; /// <summary> /// How far away from the entity should the orbit be, before being randomized? /// </summary> public float OrbitDistance = 1.0f; /// <summary> /// How long should the orbit stop animation last in seconds? /// </summary> public float OrbitStopLength = 1.0f; /// <summary> /// How far along in the orbit, from 0 to 1, is this entity? /// </summary> [Animatable] public float Orbit { get; set; } = 0.0f; }
mit
C#
1abb00ca4e60b3123526243f2ffe52d51a1dd36b
Remove cast
mstrother/BmpListener
src/BmpListener/Bmp/RouteMonitoring.cs
src/BmpListener/Bmp/RouteMonitoring.cs
using BmpListener.Bgp; namespace BmpListener.Bmp { public class RouteMonitoring : BmpMessage { public RouteMonitoring(byte[] data) : base(data) { var offset = Constants.BmpCommonHeaderLength + Constants.BmpPerPeerHeaderLength; Decode(data, offset); } public BgpMessage BgpMessage { get; set; } public void Decode(byte[] data, int offset) { BgpMessage = BgpMessage.Create(data, offset); } } }
using BmpListener.Bgp; namespace BmpListener.Bmp { public class RouteMonitoring : BmpMessage { public RouteMonitoring(byte[] data) : base(data) { var offset = Constants.BmpCommonHeaderLength + Constants.BmpPerPeerHeaderLength; Decode(data, offset); } public BgpMessage BgpMessage { get; set; } public void Decode(byte[] data, int offset) { BgpMessage = (BgpUpdateMessage)BgpMessage.Create(data, offset); } } }
mit
C#
cfa47905fb7dcc3dd7f49a7bbbd7e0480e594ea7
Add PsiFeaturesImplZone for parent settings key.
JetBrains/resharper-cyclomatic-complexity,JetBrains/resharper-cyclomatic-complexity,JetBrains/resharper-cyclomatic-complexity,JetBrains/resharper-cyclomatic-complexity,JetBrains/resharper-cyclomatic-complexity
src/CyclomaticComplexity/ZoneMarker.cs
src/CyclomaticComplexity/ZoneMarker.cs
using JetBrains.Application.BuildScript.Application.Zones; using JetBrains.ReSharper.Resources.Shell; namespace JetBrains.ReSharper.Plugins.CyclomaticComplexity { [ZoneMarker] public class ZoneMarker : IRequire<PsiFeaturesImplZone> { } }
using JetBrains.Application.BuildScript.Application.Zones; namespace JetBrains.ReSharper.Plugins.CyclomaticComplexity { [ZoneMarker] public class ZoneMarker { } }
apache-2.0
C#
397294554e0d94bec3825515fb195d5d6826ad15
Add data_frozen node role (#5322) (#5324)
elastic/elasticsearch-net,elastic/elasticsearch-net
src/Nest/Cluster/NodesInfo/NodeRole.cs
src/Nest/Cluster/NodesInfo/NodeRole.cs
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System.Runtime.Serialization; using Elasticsearch.Net; namespace Nest { // TODO: Make a string in 8.0 [StringEnum] public enum NodeRole { [EnumMember(Value = "master")] Master, [EnumMember(Value = "data")] Data, [EnumMember(Value = "data_cold")] DataCold, [EnumMember(Value = "data_frozen")] DataFrozen, [EnumMember(Value = "data_content")] DataContent, [EnumMember(Value = "data_hot")] DataHot, [EnumMember(Value = "data_warm")] DataWarm, [EnumMember(Value = "client")] Client, [EnumMember(Value = "ingest")] Ingest, [EnumMember(Value = "ml")] MachineLearning, [EnumMember(Value = "voting_only")] VotingOnly, [EnumMember(Value = "transform")] Transform, [EnumMember(Value = "remote_cluster_client")] RemoteClusterClient, [EnumMember(Value = "coordinating_only")] CoordinatingOnly, } }
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System.Runtime.Serialization; using Elasticsearch.Net; namespace Nest { // TODO: Make a string in 8.0 [StringEnum] public enum NodeRole { [EnumMember(Value = "master")] Master, [EnumMember(Value = "data")] Data, [EnumMember(Value = "data_cold")] DataCold, [EnumMember(Value = "data_content")] DataContent, [EnumMember(Value = "data_hot")] DataHot, [EnumMember(Value = "data_warm")] DataWarm, [EnumMember(Value = "client")] Client, [EnumMember(Value = "ingest")] Ingest, [EnumMember(Value = "ml")] MachineLearning, [EnumMember(Value = "voting_only")] VotingOnly, [EnumMember(Value = "transform")] Transform, [EnumMember(Value = "remote_cluster_client")] RemoteClusterClient, [EnumMember(Value = "coordinating_only")] CoordinatingOnly, } }
apache-2.0
C#
8cef8983730650cdd70658f8117ea861f42a1733
Use same channel throughout Subscribe
pardahlman/RawRabbit,northspb/RawRabbit
src/RawRabbit/Operations/Subscriber.cs
src/RawRabbit/Operations/Subscriber.cs
using System; using System.Threading.Tasks; using RawRabbit.Common; using RawRabbit.Configuration.Subscribe; using RawRabbit.Consumer.Abstraction; using RawRabbit.Context; using RawRabbit.Context.Enhancer; using RawRabbit.Context.Provider; using RawRabbit.Logging; using RawRabbit.Operations.Abstraction; using RawRabbit.Serialization; namespace RawRabbit.Operations { public class Subscriber<TMessageContext> : OperatorBase, ISubscriber<TMessageContext> where TMessageContext : IMessageContext { private readonly IConsumerFactory _consumerFactory; private readonly IMessageContextProvider<TMessageContext> _contextProvider; private readonly IContextEnhancer _contextEnhancer; private readonly ILogger _logger = LogManager.GetLogger<Subscriber<TMessageContext>>(); public Subscriber(IChannelFactory channelFactory, IConsumerFactory consumerFactory, IMessageSerializer serializer, IMessageContextProvider<TMessageContext> contextProvider, IContextEnhancer contextEnhancer) : base(channelFactory, serializer) { _consumerFactory = consumerFactory; _contextProvider = contextProvider; _contextEnhancer = contextEnhancer; } public void SubscribeAsync<T>(Func<T, TMessageContext, Task> subscribeMethod, SubscriptionConfiguration config) { var channel = ChannelFactory.CreateChannel(); DeclareQueue(config.Queue, channel); DeclareExchange(config.Exchange, channel); BindQueue(config.Queue, config.Exchange, config.RoutingKey, channel); var consumer = _consumerFactory.CreateConsumer(config, channel); consumer.OnMessageAsync = (o, args) => { var body = Serializer.Deserialize<T>(args.Body); var context = _contextProvider.ExtractContext(args.BasicProperties.Headers[PropertyHeaders.Context]); _contextEnhancer.WireUpContextFeatures(context, consumer, args); return subscribeMethod(body, context); }; consumer.Model.BasicConsume(config.Queue.FullQueueName, config.NoAck, consumer); _logger.LogDebug($"Setting up a consumer on queue {config.Queue.QueueName} with NoAck set to {config.NoAck}."); } public override void Dispose() { _logger.LogDebug("Disposing Subscriber."); base.Dispose(); (_consumerFactory as IDisposable)?.Dispose(); } } }
using System; using System.Threading.Tasks; using RawRabbit.Common; using RawRabbit.Configuration.Subscribe; using RawRabbit.Consumer.Abstraction; using RawRabbit.Context; using RawRabbit.Context.Enhancer; using RawRabbit.Context.Provider; using RawRabbit.Logging; using RawRabbit.Operations.Abstraction; using RawRabbit.Serialization; namespace RawRabbit.Operations { public class Subscriber<TMessageContext> : OperatorBase, ISubscriber<TMessageContext> where TMessageContext : IMessageContext { private readonly IConsumerFactory _consumerFactory; private readonly IMessageContextProvider<TMessageContext> _contextProvider; private readonly IContextEnhancer _contextEnhancer; private readonly ILogger _logger = LogManager.GetLogger<Subscriber<TMessageContext>>(); public Subscriber(IChannelFactory channelFactory, IConsumerFactory consumerFactory, IMessageSerializer serializer, IMessageContextProvider<TMessageContext> contextProvider, IContextEnhancer contextEnhancer) : base(channelFactory, serializer) { _consumerFactory = consumerFactory; _contextProvider = contextProvider; _contextEnhancer = contextEnhancer; } public void SubscribeAsync<T>(Func<T, TMessageContext, Task> subscribeMethod, SubscriptionConfiguration config) { DeclareQueue(config.Queue); DeclareExchange(config.Exchange); BindQueue(config.Queue, config.Exchange, config.RoutingKey); SubscribeAsync(config, subscribeMethod); } private void SubscribeAsync<T>(SubscriptionConfiguration cfg, Func<T, TMessageContext, Task> subscribeMethod) { var consumer = _consumerFactory.CreateConsumer(cfg, ChannelFactory.CreateChannel()); consumer.OnMessageAsync = (o, args) => { var body = Serializer.Deserialize<T>(args.Body); var context = _contextProvider.ExtractContext(args.BasicProperties.Headers[PropertyHeaders.Context]); _contextEnhancer.WireUpContextFeatures(context, consumer, args); return subscribeMethod(body, context); }; consumer.Model.BasicConsume(cfg.Queue.FullQueueName, cfg.NoAck, consumer); _logger.LogDebug($"Setting up a consumer on queue {cfg.Queue.QueueName} with NoAck set to {cfg.NoAck}."); } public override void Dispose() { _logger.LogDebug("Disposing Subscriber."); base.Dispose(); (_consumerFactory as IDisposable)?.Dispose(); } } }
mit
C#
1e651595caeed545510aeb65a067283996b02034
bump version
ParticularLabs/SetStartupProjects
src/SetStartupProjects/AssemblyInfo.cs
src/SetStartupProjects/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle("SetStartupProjects")] [assembly: AssemblyProduct("SetStartupProjects")] [assembly: AssemblyCopyright("Copyright © NServiceBus Ltd")] [assembly: AssemblyVersion("0.2.0")] [assembly: AssemblyFileVersion("0.2.0")] [assembly: InternalsVisibleTo("Tests")]
using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle("SetStartupProjects")] [assembly: AssemblyProduct("SetStartupProjects")] [assembly: AssemblyCopyright("Copyright © NServiceBus Ltd")] [assembly: AssemblyVersion("0.1.1")] [assembly: AssemblyFileVersion("0.1.1")] [assembly: InternalsVisibleTo("Tests")]
mit
C#
792d59e6a6f3edf2a2bae75d22ab30ac88599074
increment minor version
jwChung/Experimentalism,jwChung/Experimentalism
build/CommonAssemblyInfo.cs
build/CommonAssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.1.0")] [assembly: AssemblyInformationalVersion("0.1.0")] /* * Version 0.1.0 * * - TheoremAttribute is test attribute specified on method to indicate * test-case which is the same with FactAttribute of xunit. * * - TheoremAttribute supports parameterized test, which is the same with * TheoryAttribute of xunit. */
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.1.0")] [assembly: AssemblyInformationalVersion("0.1.0-pre01")] /* * Version 0.1.0-pre01 */
mit
C#
8b93e4ebcb2f69c35c6d81657030907244085890
Bump version to 2.0.0-alpha1
HangfireIO/Hangfire.Dashboard.Authorization
Hangfire.Dashboard.Authorization/Properties/AssemblyInfo.cs
Hangfire.Dashboard.Authorization/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Hangfire.Dashboard.Authorization")] [assembly: AssemblyDescription("Some authorization filters for Hangfire's Dashboard.")] [assembly: AssemblyProduct("Hangfire")] [assembly: AssemblyCopyright("Copyright © 2014 Sergey Odinokov")] // 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("34dd541a-5bdb-402f-8ec0-9aac8e3331ae")] [assembly: AssemblyInformationalVersion("2.0.0-alpha1")] [assembly: AssemblyVersion("2.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Hangfire.Dashboard.Authorization")] [assembly: AssemblyDescription("Some authorization filters for Hangfire's Dashboard.")] [assembly: AssemblyProduct("Hangfire")] [assembly: AssemblyCopyright("Copyright © 2014 Sergey Odinokov")] // 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("34dd541a-5bdb-402f-8ec0-9aac8e3331ae")] [assembly: AssemblyInformationalVersion("1.0.1")] [assembly: AssemblyVersion("1.0.1")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
8b6cff2ebfcf2487906b8951260b43d563640b88
Update AzureTableStorageExtensions.cs
tiksn/TIKSN-Framework
TIKSN.Core/Data/AzureStorage/AzureTableStorageExtensions.cs
TIKSN.Core/Data/AzureStorage/AzureTableStorageExtensions.cs
using Microsoft.Azure.Cosmos.Table; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace TIKSN.Data.AzureStorage { public static class AzureTableStorageExtensions { public static Task<IEnumerable<T>> RetrieveAllAsync<T>(this IAzureTableStorageQueryRepository<T> repository, CancellationToken cancellationToken) where T : ITableEntity { if (repository == null) throw new System.ArgumentNullException(nameof(repository)); var filters = new Dictionary<string, object>(); return repository.SearchAsync(filters, cancellationToken); } public static Task<IEnumerable<T>> SearchAsync<T>(this IAzureTableStorageQueryRepository<T> repository, string fieldName, object givenValue, CancellationToken cancellationToken) where T : ITableEntity { if (repository == null) throw new System.ArgumentNullException(nameof(repository)); var filters = new Dictionary<string, object>(); filters.Add(fieldName, givenValue); return repository.SearchAsync(filters, cancellationToken); } } }
using Microsoft.WindowsAzure.Storage.Table; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace TIKSN.Data.AzureStorage { public static class AzureTableStorageExtensions { public static Task<IEnumerable<T>> RetrieveAllAsync<T>(this IAzureTableStorageQueryRepository<T> repository, CancellationToken cancellationToken) where T : ITableEntity { if (repository == null) throw new System.ArgumentNullException(nameof(repository)); var filters = new Dictionary<string, object>(); return repository.SearchAsync(filters, cancellationToken); } public static Task<IEnumerable<T>> SearchAsync<T>(this IAzureTableStorageQueryRepository<T> repository, string fieldName, object givenValue, CancellationToken cancellationToken) where T : ITableEntity { if (repository == null) throw new System.ArgumentNullException(nameof(repository)); var filters = new Dictionary<string, object>(); filters.Add(fieldName, givenValue); return repository.SearchAsync(filters, cancellationToken); } } }
mit
C#
e927b549803ee4de869814568e178289156ca934
Add Orleans Cake & Docker tests
ASP-NET-MVC-Boilerplate/Templates,ASP-NET-MVC-Boilerplate/Templates,ASP-NET-Core-Boilerplate/Templates,ASP-NET-Core-Boilerplate/Templates,ASP-NET-Core-Boilerplate/Templates
Tests/Boxed.Templates.FunctionalTest/OrleansTemplateTest.cs
Tests/Boxed.Templates.FunctionalTest/OrleansTemplateTest.cs
namespace Boxed.Templates.FunctionalTest { using System; using System.Linq; using System.Threading.Tasks; using Boxed.DotnetNewTest; using Xunit; using Xunit.Abstractions; public class OrleansTemplateTest { private const string TemplateName = "orleans"; private const string SolutionFileName = "OrleansTemplate.sln"; public OrleansTemplateTest(ITestOutputHelper testOutputHelper) { if (testOutputHelper is null) { throw new ArgumentNullException(nameof(testOutputHelper)); } TestLogger.WriteMessage = testOutputHelper.WriteLine; } [Theory] [Trait("IsUsingDocker", "false")] [Trait("IsUsingDotnetRun", "false")] [InlineData("OrleansDefaults")] [InlineData("OrleansStyleCop", "style-cop=true")] [InlineData("OrleansNoHealthCheck", "health-check=false")] public async Task RestoreBuild_OrleansDefaults_SuccessfulAsync(string name, params string[] arguments) { await InstallTemplateAsync().ConfigureAwait(false); using (var tempDirectory = TempDirectory.NewTempDirectory()) { var dictionary = arguments .Select(x => x.Split('=', StringSplitOptions.RemoveEmptyEntries)) .ToDictionary(x => x.First(), x => x.Last()); var project = await tempDirectory.DotnetNewAsync(TemplateName, name, dictionary).ConfigureAwait(false); await project.DotnetRestoreAsync().ConfigureAwait(false); await project.DotnetBuildAsync().ConfigureAwait(false); } } [Theory] [Trait("IsUsingDocker", "true")] [Trait("IsUsingDotnetRun", "false")] [InlineData("OrleansDefaults")] [InlineData("OrleansNoDocker", "docker=false")] public async Task Cake_ApiDefaults_SuccessfulAsync(string name, params string[] arguments) { await InstallTemplateAsync().ConfigureAwait(false); using (var tempDirectory = TempDirectory.NewTempDirectory()) { var dictionary = arguments .Select(x => x.Split('=', StringSplitOptions.RemoveEmptyEntries)) .ToDictionary(x => x.First(), x => x.Last()); var project = await tempDirectory.DotnetNewAsync(TemplateName, name, dictionary).ConfigureAwait(false); await project.DotnetToolRestoreAsync().ConfigureAwait(false); await project.DotnetCakeAsync(timeout: TimeSpan.FromMinutes(5)).ConfigureAwait(false); } } private static Task InstallTemplateAsync() => DotnetNew.InstallAsync<OrleansTemplateTest>(SolutionFileName); } }
namespace Boxed.Templates.FunctionalTest { using System; using System.Linq; using System.Threading.Tasks; using Boxed.DotnetNewTest; using Xunit; using Xunit.Abstractions; public class OrleansTemplateTest { private const string TemplateName = "orleans"; private const string SolutionFileName = "OrleansTemplate.sln"; public OrleansTemplateTest(ITestOutputHelper testOutputHelper) { if (testOutputHelper is null) { throw new ArgumentNullException(nameof(testOutputHelper)); } TestLogger.WriteMessage = testOutputHelper.WriteLine; } [Theory] [Trait("IsUsingDocker", "false")] [Trait("IsUsingDotnetRun", "false")] [InlineData("OrleansDefaults")] [InlineData("OrleansStyleCop", "style-cop=true")] [InlineData("OrleansNoHealthCheck", "health-check=false")] public async Task RestoreBuild_OrleansDefaults_SuccessfulAsync(string name, params string[] arguments) { await InstallTemplateAsync().ConfigureAwait(false); using (var tempDirectory = TempDirectory.NewTempDirectory()) { var dictionary = arguments .Select(x => x.Split('=', StringSplitOptions.RemoveEmptyEntries)) .ToDictionary(x => x.First(), x => x.Last()); var project = await tempDirectory.DotnetNewAsync(TemplateName, name, dictionary).ConfigureAwait(false); await project.DotnetRestoreAsync().ConfigureAwait(false); await project.DotnetBuildAsync().ConfigureAwait(false); } } private static Task InstallTemplateAsync() => DotnetNew.InstallAsync<OrleansTemplateTest>(SolutionFileName); } }
mit
C#
89cfdbe700d28cedf4acb6e9db705cae0b77aa11
Add Kick Message Capability
Luke-Wolf/wolfybot
WolfyBot.BotCommands/ProxyDetectionCommand/ProxyDetector.cs
WolfyBot.BotCommands/ProxyDetectionCommand/ProxyDetector.cs
// // Copyright 2014 luke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Net.Sockets; using WolfyBot.Core; using System.Threading; using System.Collections.Generic; using System.Net; namespace ProxyDetectionCommand { public class ProxyDetector:IBotCommand { public ProxyDetector (int[] ports, string kickmessage = "") { portsToScan = ports; CommandWords = new List<String> (); CommandWords.Add ("JOIN"); ParameterWords = new List<string> (); TrailingParameterWords = new List<string> (); kickMessage = kickmessage; } #region IBotCommand implementation public event EventHandler<IRCMessage> ScriptMessage; public void Execute (object sender, IRCMessage message) { var hostname = message.Host.Split ('@') [1]; var entry = Dns.GetHostEntry (hostname); if (IsBehindProxy (entry.AddressList)) { OnScriptMessage (IRCMessageFactory.BuildBanMessage (message.Channel, message.Prefix)); OnScriptMessage (IRCMessageFactory.BuildKickCommandMessage (message.Channel, message.Prefix.Split ('!') [0], kickMessage)); } } static bool IsBehindProxy (IPAddress[] addresses) { var client = new TcpClient (); foreach (var address in addresses) { foreach (var port in portsToScan) { try { client.Connect (address, port); client.Close (); return true; } catch (Exception ex) { //intentionally empty, if the ports aren't open they're //not behind a proxy } } } return false; } public void OnScriptMessage (IRCMessage e) { EventHandler<IRCMessage> handler = ScriptMessage; if (handler != null) { handler (this, e); } } public List<string> CommandWords { get; set; } public List<string> ParameterWords { get; set; } public List<string> TrailingParameterWords { get; set; } static int[] portsToScan; static String kickMessage; #endregion } }
// // Copyright 2014 luke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Net.Sockets; using WolfyBot.Core; using System.Threading; using System.Collections.Generic; using System.Net; namespace ProxyDetectionCommand { public class ProxyDetector:IBotCommand { public ProxyDetector (int[] ports) { portsToScan = ports; CommandWords = new List<String> (); CommandWords.Add ("JOIN"); ParameterWords = new List<string> (); TrailingParameterWords = new List<string> (); } #region IBotCommand implementation public event EventHandler<IRCMessage> ScriptMessage; public void Execute (object sender, IRCMessage message) { var hostname = message.Host.Split ('@') [1]; var entry = Dns.GetHostEntry (hostname); if (IsBehindProxy (entry.AddressList)) { OnScriptMessage (IRCMessageFactory.BuildBanMessage (message.Channel, message.Prefix)); } } static bool IsBehindProxy (IPAddress[] addresses) { var client = new TcpClient (); foreach (var address in addresses) { foreach (var port in portsToScan) { try { client.Connect (address, port); client.Close (); return true; } catch (Exception ex) { //intentionally empty, if the ports aren't open they're //not behind a proxy } } } return false; } public void OnScriptMessage (IRCMessage e) { EventHandler<IRCMessage> handler = ScriptMessage; if (handler != null) { handler (this, e); } } public List<string> CommandWords { get; set; } public List<string> ParameterWords { get; set; } public List<string> TrailingParameterWords { get; set; } static int[] portsToScan; #endregion } }
apache-2.0
C#
913f12d544b9ebaaa7f12bbd4cb806fa3e97eda0
Make user lookup case-insensitive
RightpointLabs/Pourcast,RightpointLabs/Pourcast,RightpointLabs/Pourcast,RightpointLabs/Pourcast,RightpointLabs/Pourcast
RightpointLabs.Pourcast.Infrastructure/Persistence/Repositories/UserRepository.cs
RightpointLabs.Pourcast.Infrastructure/Persistence/Repositories/UserRepository.cs
using System; namespace RightpointLabs.Pourcast.Infrastructure.Persistence.Repositories { using System.Collections.Generic; using System.Linq; using RightpointLabs.Pourcast.Domain.Models; using RightpointLabs.Pourcast.Domain.Repositories; using RightpointLabs.Pourcast.Infrastructure.Persistence.Collections; public class UserRepository : EntityRepository<User>, IUserRepository { public UserRepository(UserCollectionDefinition userCollectionDefinition) : base(userCollectionDefinition) { } public User GetByUsername(string username) { // TODO: use a Regex so we can drop the ToList() and push the work to Mongo return Queryable.ToList().SingleOrDefault(x => string.Equals(x.Username, username, StringComparison.InvariantCultureIgnoreCase)); } public IEnumerable<User> GetUsersInRole(string id) { return Queryable.Where(x => x.RoleIds.Contains(id)); } } }
namespace RightpointLabs.Pourcast.Infrastructure.Persistence.Repositories { using System.Collections.Generic; using System.Linq; using RightpointLabs.Pourcast.Domain.Models; using RightpointLabs.Pourcast.Domain.Repositories; using RightpointLabs.Pourcast.Infrastructure.Persistence.Collections; public class UserRepository : EntityRepository<User>, IUserRepository { public UserRepository(UserCollectionDefinition userCollectionDefinition) : base(userCollectionDefinition) { } public User GetByUsername(string username) { return Queryable.SingleOrDefault(x => x.Username == username); } public IEnumerable<User> GetUsersInRole(string id) { return Queryable.Where(x => x.RoleIds.Contains(id)); } } }
mit
C#
fed954d950c5f20cefc06c2e118a6d660b996558
Replace Boolean with bool so we can remove System
leoshaw/exercism-solutions
csharp/leap/Year.cs
csharp/leap/Year.cs
public class Year { public static bool IsLeap(int i) { if (i % 4 != 0) { return false; } if (i % 100 == 0) { if (i % 400 != 0) { return false; } } return true; } }
using System; public class Year { public static Boolean IsLeap(int i) { if (i % 4 != 0) { return false; } if (i % 100 == 0) { if (i % 400 != 0) { return false; } } return true; } }
mit
C#
89fd2c219ff8792ee2d6a551f540ae65d93f0f11
fix bug for api key
mspjp/201612hackathonyokohama,mspjp/201612hackathonyokohama,mspjp/201612hackathonyokohama
csharp/SampleBot/BotLibrary/ApiKey.cs
csharp/SampleBot/BotLibrary/ApiKey.cs
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BotLibrary { public class ApiKey { public Dictionary<string, string> Keys { get; set; } private ApiKey() { Keys = new Dictionary<string, string>(); Keys.Add("FACE_APIKEY",Properties.Resources.FACE_APIKEY); Keys.Add("DOCOMO_APIKEY", Properties.Resources.DOCOMO_APIKEY); } private static ApiKey _instance; public static ApiKey Instance { get { if (_instance == null) _instance = new ApiKey(); return _instance; } } } }
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BotLibrary { public class ApiKey { public Dictionary<string, string> Keys { get; set; } private ApiKey() { Keys.Add("FACE_APIKEY",Properties.Resources.FACE_APIKEY); Keys.Add("DOCOMO_APIKEY", Properties.Resources.DOCOMO_APIKEY); } private static ApiKey _instance; public static ApiKey Instance { get { if (_instance == null) _instance = new ApiKey(); return _instance; } } } }
mit
C#
2493a9536bf9e8bf2bf9429131e768c5384df86d
Update Promise.cs
drew-r/Maverick
Promise.cs
Promise.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Maverick { public class Promise { public Promise(Func<object> asyncOp) { Scheduler.Request(); task = new Task(() => { try { _result = asyncOp(); } catch(Exception e) { _taskException = e; if (_exceptionCallback != null) { Scheduler.Enqueue(() => _exceptionCallback(_taskException)); } return; } if (_successCallback != null) { Scheduler.Enqueue(() => _successCallback(_result)); } }); task.Start(); } readonly Task task; dynamic _result = null; Action<object> _successCallback; public Promise success(Action<object> cb) { _successCallback = cb; if (_result != null) { Scheduler.Enqueue(() => _successCallback(_result)); } return this; } Exception _taskException; Action<object> _exceptionCallback; public Promise error(Action<object> cb) { _exceptionCallback = cb; if (_taskException != null) { Scheduler.Enqueue(() => _exceptionCallback(_taskException)) } return this; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Maverick { public class Promise { public Promise(Func<object> asyncOp) { Scheduler.Request(); task = new Task(() => { result = asyncOp(); }); try { task.Start(); } catch (Exception e) { raiseException(_taskException); } } dynamic result = null; readonly Task task; public Promise success(Action<object> cb) { task.ContinueWith((t) => Scheduler.Enqueue((i) => cb(result))); return this; } void raiseException(Exception e) { _taskException = e; if (_exceptionCallback != null) { Scheduler.Enqueue(() => _exceptionCallback(_taskException)); } } Exception _taskException; Action<object> _exceptionCallback; public Promise error(Action<object> cb) { _exceptionCallback = cb; if (_taskException != null) { raiseException(_taskException); } return this; } } }
mit
C#
267bef959fd7049dcf80557196cd211e3f81686f
Remove unnecessary cache type specification
NeoAdonis/osu,NeoAdonis/osu,peppy/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu
osu.Game/Beatmaps/IBeatSyncProvider.cs
osu.Game/Beatmaps/IBeatSyncProvider.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using osu.Framework.Allocation; using osu.Framework.Audio.Track; using osu.Framework.Timing; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Graphics.Containers; namespace osu.Game.Beatmaps { /// <summary> /// Provides various data sources which allow for synchronising visuals to a known beat. /// Primarily intended for use with <see cref="BeatSyncedContainer"/>. /// </summary> [Cached] public interface IBeatSyncProvider { ControlPointInfo? ControlPoints { get; } IClock? Clock { get; } ChannelAmplitudes? Amplitudes { get; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using osu.Framework.Allocation; using osu.Framework.Audio.Track; using osu.Framework.Timing; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Graphics.Containers; namespace osu.Game.Beatmaps { /// <summary> /// Provides various data sources which allow for synchronising visuals to a known beat. /// Primarily intended for use with <see cref="BeatSyncedContainer"/>. /// </summary> [Cached(typeof(IBeatSyncProvider))] public interface IBeatSyncProvider { ControlPointInfo? ControlPoints { get; } IClock? Clock { get; } ChannelAmplitudes? Amplitudes { get; } } }
mit
C#