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 |
|---|---|---|---|---|---|---|---|---|
9f6cb140907aa83bacde7321ac6d3f98d55d4a83 | Adjust polymorphism rules for base class | dhawalharsora/connectedcare-sdk,SnapMD/connectedcare-sdk | SnapMD.VirtualCare.LeopardonSso/AbstractJwt.cs | SnapMD.VirtualCare.LeopardonSso/AbstractJwt.cs | using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using System.Security.Claims;
namespace SnapMD.VirtualCare.LeopardonSso
{
public abstract class AbstractJwt
{
protected readonly JwtSecurityTokenHandler SecurityTokenHandler = new JwtSecurityTokenHandler();
protected virtual string Audience { get; }
protected virtual string Issuer { get; }
protected virtual SignatureProvider SignatureProvider => null;
protected abstract SigningCredentials SigningCredentials { get; }
protected virtual TokenValidationParameters TokenValidationParameters =>
new TokenValidationParameters
{
ValidAudience = Audience,
ValidIssuer = Issuer
};
public virtual ClaimsPrincipal Parse(string token)
{
SecurityToken securityToken;
return SecurityTokenHandler.ValidateToken(token, TokenValidationParameters, out securityToken);
}
protected virtual string CreateToken(List<Claim> claims, bool encrypted = true)
{
if (claims == null)
{
throw new ArgumentNullException("claims");
}
var token = SecurityTokenHandler.CreateToken(
subject: new ClaimsIdentity(claims),
audience: Audience,
issuer: Issuer,
signingCredentials: SigningCredentials,
signatureProvider: SignatureProvider);
return encrypted ? SecurityTokenHandler.WriteToken(token) : token.ToString();
}
}
}
| using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using System.Security.Claims;
namespace SnapMD.VirtualCare.LeopardonSso
{
public abstract class AbstractJwt
{
protected readonly JwtSecurityTokenHandler SecurityTokenHandler = new JwtSecurityTokenHandler();
protected abstract string Audience { get; }
protected abstract string Issuer { get; }
protected virtual SignatureProvider SignatureProvider => null;
protected abstract SigningCredentials SigningCredentials { get; }
protected virtual TokenValidationParameters TokenValidationParameters =>
new TokenValidationParameters
{
ValidAudience = Audience,
ValidIssuer = Issuer
};
public virtual ClaimsPrincipal Parse(string token)
{
SecurityToken securityToken;
return SecurityTokenHandler.ValidateToken(token, TokenValidationParameters, out securityToken);
}
protected virtual string CreateToken(List<Claim> claims, bool encrypted = true)
{
if (claims == null)
{
throw new ArgumentNullException("claims");
}
var token = SecurityTokenHandler.CreateToken(
subject: new ClaimsIdentity(claims),
audience: Audience,
issuer: Issuer,
signingCredentials: SigningCredentials,
signatureProvider: SignatureProvider);
return encrypted ? SecurityTokenHandler.WriteToken(token) : token.ToString();
}
}
}
| apache-2.0 | C# |
df5ebc2b0f0085ca2b93688387706d10f6f19be3 | Update Configuration to use Roslyn 4.2.0.0 | OmniSharp/omnisharp-roslyn,OmniSharp/omnisharp-roslyn | src/OmniSharp.Abstractions/Configuration.cs | src/OmniSharp.Abstractions/Configuration.cs | namespace OmniSharp
{
internal static class Configuration
{
public static bool ZeroBasedIndices = false;
public const string RoslynVersion = "4.2.0.0";
public const string RoslynPublicKeyToken = "31bf3856ad364e35";
public readonly static string RoslynFeatures = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.Features");
public readonly static string RoslynCSharpFeatures = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.CSharp.Features");
public readonly static string RoslynOmniSharpExternalAccess = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.ExternalAccess.OmniSharp");
public readonly static string RoslynOmniSharpExternalAccessCSharp = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.CSharp");
public readonly static string RoslynWorkspaces = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.Workspaces");
public readonly static string OmniSharpMiscProjectName = "OmniSharpMiscellaneousFiles";
private static string GetRoslynAssemblyFullName(string name)
{
return $"{name}, Version={RoslynVersion}, Culture=neutral, PublicKeyToken={RoslynPublicKeyToken}";
}
}
}
| namespace OmniSharp
{
internal static class Configuration
{
public static bool ZeroBasedIndices = false;
public const string RoslynVersion = "4.1.0.0";
public const string RoslynPublicKeyToken = "31bf3856ad364e35";
public readonly static string RoslynFeatures = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.Features");
public readonly static string RoslynCSharpFeatures = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.CSharp.Features");
public readonly static string RoslynOmniSharpExternalAccess = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.ExternalAccess.OmniSharp");
public readonly static string RoslynOmniSharpExternalAccessCSharp = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.CSharp");
public readonly static string RoslynWorkspaces = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.Workspaces");
public readonly static string OmniSharpMiscProjectName = "OmniSharpMiscellaneousFiles";
private static string GetRoslynAssemblyFullName(string name)
{
return $"{name}, Version={RoslynVersion}, Culture=neutral, PublicKeyToken={RoslynPublicKeyToken}";
}
}
}
| mit | C# |
e5a01e4e95be34050ee235b05559f3788a561787 | Tweak doc comments for consistency | markembling/MarkEmbling.Utils,markembling/MarkEmbling.Utilities | src/MarkEmbling.Utilities/Extensions/EnumExtensions.cs | src/MarkEmbling.Utilities/Extensions/EnumExtensions.cs | using System;
using System.ComponentModel;
using System.Reflection;
namespace MarkEmbling.Utilities.Extensions {
public static class EnumExtensions {
/// <summary>
/// Gets the description of an enumeration value
///
/// If there is no description attribute for this enumeration value, the
/// raw name of the value is provided.
/// </summary>
/// <param name="value">Current enum value</param>
/// <returns>Description or raw name</returns>
public static string GetDescription(this Enum value) {
var field = value.GetType().GetRuntimeField(value.ToString());
var attribute = field.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
/// <summary>
/// Gets the underlying numeric value of an enumeration value
/// </summary>
/// <param name="value">Current enum value</param>
/// <returns>Underlying numeric value</returns>
public static object GetUnderlyingValue(this Enum value) {
var type = Enum.GetUnderlyingType(value.GetType());
return Convert.ChangeType(value, type);
}
/// <summary>
/// Gets the underlying numeric value of an enumeration value
/// </summary>
/// <typeparam name="T">Underlying numeric type of the enum</typeparam>
/// <param name="value">Current enum value</param>
/// <returns>Underlying numeric value as T</returns>
public static T GetUnderlyingValue<T>(this Enum value) {
var enumType = value.GetType();
var underlyingType = Enum.GetUnderlyingType(enumType);
var expectedType = typeof(T);
if (underlyingType != expectedType)
throw new InvalidOperationException(
string.Format(
"{0} has the underlying type of {1} instead of {2}",
enumType.Name,
underlyingType.Name,
expectedType.Name));
return (T)Convert.ChangeType(value, expectedType);
}
}
}
| using System;
using System.ComponentModel;
using System.Reflection;
namespace MarkEmbling.Utilities.Extensions {
public static class EnumExtensions {
/// <summary>
/// Gets the description of an enumeration field
///
/// If there is no description attribute for this enumeration value, the
/// raw name of the field is provided.
/// </summary>
/// <param name="value">Current enum value</param>
/// <returns>Description or raw name</returns>
public static string GetDescription(this Enum value) {
var field = value.GetType().GetRuntimeField(value.ToString());
var attribute = field.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
/// <summary>
/// Gets the underlying numeric value of an enumeration value
/// </summary>
/// <param name="value">Current enum value</param>
/// <returns>Underlying numeric value</returns>
public static object GetUnderlyingValue(this Enum value) {
var type = Enum.GetUnderlyingType(value.GetType());
return Convert.ChangeType(value, type);
}
/// <summary>
/// Gets the underlying numeric value of an enumeration value
/// </summary>
/// <typeparam name="T">Underlying numeric type of the enum</typeparam>
/// <param name="value">Current enum value</param>
/// <returns>Underlying numeric value as T</returns>
public static T GetUnderlyingValue<T>(this Enum value) {
var enumType = value.GetType();
var underlyingType = Enum.GetUnderlyingType(enumType);
var expectedType = typeof(T);
if (underlyingType != expectedType)
throw new InvalidOperationException(
string.Format(
"{0} has the underlying type of {1} instead of {2}",
enumType.Name,
underlyingType.Name,
expectedType.Name));
return (T)Convert.ChangeType(value, expectedType);
}
}
}
| mit | C# |
70a1eb6d9a2222ba6a2b5027b1a82b82b9b9d014 | remove failing test | pcalin/nunit,cPetru/nunit-params,ChrisMaddock/nunit,pflugs30/nunit,NikolayPianikov/nunit,appel1/nunit,mikkelbu/nunit,Green-Bug/nunit,Green-Bug/nunit,JustinRChou/nunit,JohanO/nunit,jnm2/nunit,acco32/nunit,Green-Bug/nunit,agray/nunit,OmicronPersei/nunit,acco32/nunit,danielmarbach/nunit,jnm2/nunit,Suremaker/nunit,JohanO/nunit,cPetru/nunit-params,ggeurts/nunit,mjedrzejek/nunit,jadarnel27/nunit,ggeurts/nunit,nivanov1984/nunit,acco32/nunit,mjedrzejek/nunit,nivanov1984/nunit,OmicronPersei/nunit,agray/nunit,agray/nunit,ChrisMaddock/nunit,danielmarbach/nunit,danielmarbach/nunit,jadarnel27/nunit,NikolayPianikov/nunit,mikkelbu/nunit,nunit/nunit,Suremaker/nunit,JohanO/nunit,nunit/nunit,pflugs30/nunit,pcalin/nunit,appel1/nunit,JustinRChou/nunit,pcalin/nunit | src/NUnitFramework/tests/Assertions/AssertPassTests.cs | src/NUnitFramework/tests/Assertions/AssertPassTests.cs | // ***********************************************************************
// Copyright (c) 2009 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
namespace NUnit.Framework.Assertions
{
[TestFixture]
public class AssertPassTests
{
[Test]
public void ThrowsSuccessException()
{
Assert.That(
() => Assert.Pass(),
Throws.TypeOf<SuccessException>());
}
[Test]
public void ThrowsSuccessExceptionWithMessage()
{
Assert.That(
() => Assert.Pass("MESSAGE"),
Throws.TypeOf<SuccessException>().With.Message.EqualTo("MESSAGE"));
}
[Test]
public void ThrowsSuccessExceptionWithMessageAndArgs()
{
Assert.That(
() => Assert.Pass("MESSAGE: {0}+{1}={2}", 2, 2, 4),
Throws.TypeOf<SuccessException>().With.Message.EqualTo("MESSAGE: 2+2=4"));
}
[Test]
public void AssertPassReturnsSuccess()
{
Assert.Pass("This test is OK!");
}
[Test]
public void SubsequentFailureIsIrrelevant()
{
Assert.Pass("This test is OK!");
Assert.Fail("No it's NOT!");
}
}
}
| // ***********************************************************************
// Copyright (c) 2009 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
namespace NUnit.Framework.Assertions
{
[TestFixture]
public class AssertPassTests
{
[Test]
public void ThrowsSuccessException()
{
Assert.That(
() => Assert.Pass(),
Throws.TypeOf<SuccessException>());
}
[Test]
public void ThrowsSuccessExceptionWithMessage()
{
Assert.That(
() => Assert.Pass("MESSAGE"),
Throws.TypeOf<SuccessException>().With.Message.EqualTo("MESSAGE"));
}
[Test]
public void ThrowsSuccessExceptionWithMessageAndArgs()
{
Assert.That(
() => Assert.Pass("MESSAGE: {0}+{1}={2}", 2, 2, 4),
Throws.TypeOf<SuccessException>().With.Message.EqualTo("MESSAGE: 2+2=4"));
}
[Test]
public void AssertPassReturnsSuccess()
{
Assert.Pass("This test is OK!");
}
[Test]
public void FailingTestForTestingBuild()
{
Assert.Fail("Fail the build");
}
[Test]
public void SubsequentFailureIsIrrelevant()
{
Assert.Pass("This test is OK!");
Assert.Fail("No it's NOT!");
}
}
}
| mit | C# |
ee7bf028f782d3fc39eb514c08b95d498d9b3722 | Adjust GuildExtensions per Voltana's feedback | AntiTcb/Discord.Net,LassieME/Discord.Net,Joe4evr/Discord.Net,Confruggy/Discord.Net,RogueException/Discord.Net | src/Discord.Net/WebSocket/Extensions/GuildExtensions.cs | src/Discord.Net/WebSocket/Extensions/GuildExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace Discord.WebSocket.Extensions
{
// TODO: Docstrings
public static class GuildExtensions
{
// Channels
public static IGuildChannel GetChannel(this IGuild guild, ulong id) =>
GetSocketGuild(guild).GetChannel(id);
public static ITextChannel GetTextChannel(this IGuild guild, ulong id) =>
GetSocketGuild(guild).GetChannel(id) as ITextChannel;
public static IEnumerable<ITextChannel> GetTextChannels(this IGuild guild) =>
GetSocketGuild(guild).Channels.Select(c => c as ITextChannel).Where(c => c != null);
public static IVoiceChannel GetVoiceChannel(this IGuild guild, ulong id) =>
GetSocketGuild(guild).GetChannel(id) as IVoiceChannel;
public static IEnumerable<IVoiceChannel> GetVoiceChannels(this IGuild guild) =>
GetSocketGuild(guild).Channels.Select(c => c as IVoiceChannel).Where(c => c != null);
// Users
public static IGuildUser GetCurrentUser(this IGuild guild) =>
GetSocketGuild(guild).CurrentUser;
public static IGuildUser GetUser(this IGuild guild, ulong id) =>
GetSocketGuild(guild).GetUser(id);
public static IReadOnlyCollection<IGuildUser> GetUsers(this IGuild guild) =>
GetSocketGuild(guild).Members;
public static int GetUserCount(this IGuild guild) =>
GetSocketGuild(guild).MemberCount;
public static int GetCachedUserCount(this IGuild guild) =>
GetSocketGuild(guild).DownloadedMemberCount;
internal static SocketGuild GetSocketGuild(IGuild guild)
{
var socketGuild = guild as SocketGuild;
if (socketGuild == null)
throw new InvalidOperationException("This extension method is only valid on WebSocket Entities");
return socketGuild;
}
}
}
| using System.Collections.Generic;
using System.Linq;
namespace Discord.WebSocket.Extensions
{
// TODO: Docstrings
public static class GuildExtensions
{
// Channels
public static IGuildChannel GetChannel(this IGuild guild, ulong id) =>
(guild as SocketGuild).GetChannel(id);
public static ITextChannel GetTextChannel(this IGuild guild, ulong id) =>
(guild as SocketGuild).GetChannel(id) as ITextChannel;
public static IEnumerable<ITextChannel> GetTextChannels(this IGuild guild) =>
(guild as SocketGuild).Channels.Select(c => c as ITextChannel).Where(c => c != null);
public static IVoiceChannel GetVoiceChannel(this IGuild guild, ulong id) =>
(guild as SocketGuild).GetChannel(id) as IVoiceChannel;
public static IEnumerable<IVoiceChannel> GetVoiceChannels(this IGuild guild) =>
(guild as SocketGuild).Channels.Select(c => c as IVoiceChannel).Where(c => c != null);
// Users
public static IGuildUser GetCurrentUser(this IGuild guild) =>
(guild as SocketGuild).CurrentUser;
public static IGuildUser GetUser(this IGuild guild, ulong id) =>
(guild as SocketGuild).GetUser(id);
public static IEnumerable<IGuildUser> GetUsers(this IGuild guild) =>
(guild as SocketGuild).Members;
public static int GetUserCount(this IGuild guild) =>
(guild as SocketGuild).MemberCount;
public static int GetCachedUserCount(this IGuild guild) =>
(guild as SocketGuild).DownloadedMemberCount;
}
}
| mit | C# |
c9e111b8f1004990f24d983e324da40af128cd46 | Support running tests when mscorlib contains ValueTuple | DotNetAnalyzers/StyleCopAnalyzers | StyleCop.Analyzers/StyleCop.Analyzers.Test/Helpers/MetadataReferences.cs | StyleCop.Analyzers/StyleCop.Analyzers.Test/Helpers/MetadataReferences.cs | // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.Helpers
{
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
/// <summary>
/// Metadata references used to create test projects.
/// </summary>
internal static class MetadataReferences
{
internal static readonly MetadataReference CorlibReference = MetadataReference.CreateFromFile(typeof(object).Assembly.Location).WithAliases(ImmutableArray.Create("global", "corlib"));
internal static readonly MetadataReference SystemReference = MetadataReference.CreateFromFile(typeof(System.Diagnostics.Debug).Assembly.Location).WithAliases(ImmutableArray.Create("global", "system"));
internal static readonly MetadataReference SystemCoreReference = MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location);
internal static readonly MetadataReference CSharpSymbolsReference = MetadataReference.CreateFromFile(typeof(CSharpCompilation).Assembly.Location);
internal static readonly MetadataReference CodeAnalysisReference = MetadataReference.CreateFromFile(typeof(Compilation).Assembly.Location);
internal static readonly MetadataReference SystemRuntimeReference;
internal static readonly MetadataReference SystemValueTupleReference;
static MetadataReferences()
{
if (typeof(string).Assembly.GetType("System.ValueTuple", false) != null)
{
// mscorlib contains ValueTuple, so no need to add a separate reference
SystemRuntimeReference = null;
SystemValueTupleReference = null;
}
else
{
Assembly systemRuntime = AppDomain.CurrentDomain.GetAssemblies().SingleOrDefault(x => x.GetName().Name == "System.Runtime");
if (systemRuntime != null)
{
SystemRuntimeReference = MetadataReference.CreateFromFile(systemRuntime.Location);
}
Assembly systemValueTuple = AppDomain.CurrentDomain.GetAssemblies().SingleOrDefault(x => x.GetName().Name == "System.ValueTuple");
if (systemValueTuple != null)
{
SystemValueTupleReference = MetadataReference.CreateFromFile(systemValueTuple.Location);
}
}
}
}
}
| // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.Helpers
{
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
/// <summary>
/// Metadata references used to create test projects.
/// </summary>
internal static class MetadataReferences
{
internal static readonly MetadataReference CorlibReference = MetadataReference.CreateFromFile(typeof(object).Assembly.Location).WithAliases(ImmutableArray.Create("global", "corlib"));
internal static readonly MetadataReference SystemReference = MetadataReference.CreateFromFile(typeof(System.Diagnostics.Debug).Assembly.Location).WithAliases(ImmutableArray.Create("global", "system"));
internal static readonly MetadataReference SystemCoreReference = MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location);
internal static readonly MetadataReference CSharpSymbolsReference = MetadataReference.CreateFromFile(typeof(CSharpCompilation).Assembly.Location);
internal static readonly MetadataReference CodeAnalysisReference = MetadataReference.CreateFromFile(typeof(Compilation).Assembly.Location);
internal static readonly MetadataReference SystemRuntimeReference;
internal static readonly MetadataReference SystemValueTupleReference;
static MetadataReferences()
{
Assembly systemRuntime = AppDomain.CurrentDomain.GetAssemblies().SingleOrDefault(x => x.GetName().Name == "System.Runtime");
if (systemRuntime != null)
{
SystemRuntimeReference = MetadataReference.CreateFromFile(systemRuntime.Location);
}
Assembly systemValueTuple = AppDomain.CurrentDomain.GetAssemblies().SingleOrDefault(x => x.GetName().Name == "System.ValueTuple");
if (systemValueTuple != null)
{
SystemValueTupleReference = MetadataReference.CreateFromFile(systemValueTuple.Location);
}
}
}
}
| mit | C# |
482565d1e04eb3614d94891ee035eb5bcbe97243 | Update PowerShellExceptionTelemeter.cs | tiksn/TIKSN-Framework | TIKSN.Framework.Core/Analytics/Telemetry/PowerShellExceptionTelemeter.cs | TIKSN.Framework.Core/Analytics/Telemetry/PowerShellExceptionTelemeter.cs | using System;
using System.Management.Automation;
using System.Threading.Tasks;
namespace TIKSN.Analytics.Telemetry
{
public class PowerShellExceptionTelemeter : IExceptionTelemeter
{
private readonly Cmdlet cmdlet;
public PowerShellExceptionTelemeter(Cmdlet cmdlet) => this.cmdlet = cmdlet;
public Task TrackException(Exception exception, TelemetrySeverityLevel severityLevel)
{
this.cmdlet.WriteError(new ErrorRecord(exception, null, ErrorCategory.InvalidOperation, null));
return Task.FromResult<object>(null);
}
public Task TrackException(Exception exception)
{
this.cmdlet.WriteError(new ErrorRecord(exception, null, ErrorCategory.InvalidOperation, null));
return Task.FromResult<object>(null);
}
}
}
| using System;
using System.Management.Automation;
using System.Threading.Tasks;
namespace TIKSN.Analytics.Telemetry
{
public class PowerShellExceptionTelemeter : IExceptionTelemeter
{
private readonly Cmdlet cmdlet;
public PowerShellExceptionTelemeter(Cmdlet cmdlet)
{
this.cmdlet = cmdlet;
}
public Task TrackException(Exception exception, TelemetrySeverityLevel severityLevel)
{
cmdlet.WriteError(new ErrorRecord(exception, null, ErrorCategory.InvalidOperation, null));
return Task.FromResult<object>(null);
}
public Task TrackException(Exception exception)
{
cmdlet.WriteError(new ErrorRecord(exception, null, ErrorCategory.InvalidOperation, null));
return Task.FromResult<object>(null);
}
}
} | mit | C# |
055a2de029b6f45c1211f8db95dd6e41b4a50c96 | Build error resolved | Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist | Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs | Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs | using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRespository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption)
{
singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id;
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement);
}
_dbContext.SaveChanges();
}
}
}
| using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRespository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption)
{
singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id;
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement);
}
_dbContext.SaveChanges();
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption)
{
singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id;
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement);
}
_dbContext.SaveChanges();
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
| mit | C# |
4e7b173708528c4969a11cf09a4642ade1894357 | Fix Removing Update callback while iterating the same queue and priority may skip an update of that queue and priority. Now remove updates is delayed until just before trying to execute that queue | forestrf/Scheduler | Project/Scheduler/SchedulerLib/Ashkatchap/Scheduler/Scripts/Updater.cs | Project/Scheduler/SchedulerLib/Ashkatchap/Scheduler/Scripts/Updater.cs | using Ashkatchap.Shared.Collections;
using System;
using System.Threading;
using UnityEngine.Profiling;
namespace Ashkatchap.Updater {
public class Updater {
private readonly ThreadSafeRingBuffer_MultiProducer_SingleConsumer<Action> queuedUpdateCallbacks = new ThreadSafeRingBuffer_MultiProducer_SingleConsumer<Action>(256);
private readonly UnorderedList<ActionWrapped>[] recurrentCallbacks = new UnorderedList<ActionWrapped>[256];
private readonly UnorderedList<UpdateReference>[] delayedRemoves = new UnorderedList<UpdateReference>[256];
private readonly Thread mainThread;
private int nextRecurrentId;
public Updater(int initialSize = 16, int stepIncrement = 16) {
mainThread = Thread.CurrentThread;
for (int i = 0; i < recurrentCallbacks.Length; i++) {
recurrentCallbacks[i] = new UnorderedList<ActionWrapped>(initialSize, stepIncrement);
delayedRemoves[i] = new UnorderedList<UpdateReference>(initialSize, stepIncrement);
}
}
public bool InMainThread() {
return mainThread == Thread.CurrentThread;
}
public void Execute() {
Profiler.BeginSample("Queue Iterate");
for (int i = 0; i < recurrentCallbacks.Length; i++) {
var queue = recurrentCallbacks[i];
Profiler.BeginSample("Execute Delayed Deletes");
var delayedQueue = delayedRemoves[i];
while (delayedQueue.Size > 0) {
var reference = delayedQueue.ExtractLast();
for (int j = 0; j < queue.Size; j++) {
if (queue.elements[j].id == reference.id) {
queue.RemoveAt(j);
break;
}
}
}
Profiler.EndSample();
for (int j = 0; j < queue.Size; j++) {
try {
queue.elements[j].action();
}
catch (Exception e) {
Logger.Error(e.ToString());
}
}
}
Profiler.EndSample();
Profiler.BeginSample("One Time Callbacks");
Action action;
while (queuedUpdateCallbacks.TryDequeue(out action)) action();
Profiler.EndSample();
}
public UpdateReference AddUpdateCallback(Action method, byte order = Scheduler.DEFAULT_PRIORITY) {
var aw = new ActionWrapped(nextRecurrentId++, method);
recurrentCallbacks[order].Add(aw);
return new UpdateReference(aw.id, order);
}
public void RemoveUpdateCallback(UpdateReference reference) {
delayedRemoves[reference.order].Add(reference);
}
public void QueueCallback(Action method) {
queuedUpdateCallbacks.Enqueue(method);
Logger.Debug("Queued Update Callback");
}
private struct ActionWrapped {
public Action action;
public long id;
public ActionWrapped(long id, Action action) {
this.id = id;
this.action = action;
}
}
}
}
| using Ashkatchap.Shared.Collections;
using System;
using System.Threading;
using UnityEngine.Profiling;
namespace Ashkatchap.Updater {
public class Updater {
private readonly ThreadSafeRingBuffer_MultiProducer_SingleConsumer<Action> queuedUpdateCallbacks = new ThreadSafeRingBuffer_MultiProducer_SingleConsumer<Action>(256);
private readonly UnorderedList<ActionWrapped>[] recurrentCallbacks = new UnorderedList<ActionWrapped>[256];
private readonly Thread mainThread;
private int nextRecurrentId;
public Updater() {
mainThread = Thread.CurrentThread;
for (int i = 0; i < recurrentCallbacks.Length; i++) {
recurrentCallbacks[i] = new UnorderedList<ActionWrapped>(16, 16);
}
}
public bool InMainThread() {
return mainThread == Thread.CurrentThread;
}
public void Execute() {
Profiler.BeginSample("Queue Iterate");
for (int i = 0; i < recurrentCallbacks.Length; i++) {
var queue = recurrentCallbacks[i];
for (int j = 0; j < queue.Size; j++) {
try {
queue.elements[j].action();
}
catch (Exception e) {
Logger.Error(e.ToString());
}
}
}
Profiler.EndSample();
Profiler.BeginSample("One Time Callbacks");
Action action;
while (queuedUpdateCallbacks.TryDequeue(out action)) action();
Profiler.EndSample();
}
public UpdateReference AddUpdateCallback(Action method, byte order = Scheduler.DEFAULT_PRIORITY) {
var aw = new ActionWrapped(nextRecurrentId++, method);
recurrentCallbacks[order].Add(aw);
return new UpdateReference(aw.id, order);
}
public void RemoveUpdateCallback(UpdateReference reference) {
var list = recurrentCallbacks[reference.order];
for (int i = 0; i < list.Size; i++) {
if (list.elements[i].id == reference.id) {
list.RemoveAt(i);
return;
}
}
}
public void QueueCallback(Action method) {
queuedUpdateCallbacks.Enqueue(method);
Logger.Debug("Queued Update Callback");
}
private struct ActionWrapped {
public Action action;
public long id;
public ActionWrapped(long id, Action action) {
this.id = id;
this.action = action;
}
}
}
}
| mit | C# |
dec75678d55b7b498815ca7cb23c0dfc89919afa | Add GetPropertySelector | WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common | src/WeihanLi.Common/Helpers/ExpressionHelper.cs | src/WeihanLi.Common/Helpers/ExpressionHelper.cs | using System.Linq.Expressions;
namespace WeihanLi.Common.Helpers;
public static class ExpressionHelper
{
public static Expression<Func<T, bool>> True<T>()
{
return ConstantExpressions<T>.TrueExpression;
}
public static Expression<Func<T, bool>> False<T>()
{
return ConstantExpressions<T>.FalseExpression;
}
public static Expression<Func<T, TProperty>> GetPropertySelector<T, TProperty>(string propertyName)
{
var arg = Expression.Parameter(typeof(T), "x");
var property = Expression.Property(arg, propertyName);
var exp = Expression.Lambda<Func<T, TProperty>>(property, new ParameterExpression[] { arg });
return exp;
}
private static class ConstantExpressions<T>
{
public static readonly Expression<Func<T, bool>> TrueExpression = t => true;
public static readonly Expression<Func<T, bool>> FalseExpression = t => false;
}
}
| using System.Linq.Expressions;
namespace WeihanLi.Common.Helpers;
public static class ExpressionHelper
{
public static Expression<Func<T, bool>> True<T>()
{
return ConstantExpressions<T>.TrueExpression;
}
public static Expression<Func<T, bool>> False<T>()
{
return ConstantExpressions<T>.FalseExpression;
}
private static class ConstantExpressions<T>
{
public static readonly Expression<Func<T, bool>> TrueExpression = t => true;
public static readonly Expression<Func<T, bool>> FalseExpression = t => false;
}
}
| mit | C# |
9f3a137da5d56985b32c4393fa84fd7dd8d276bd | Reword ISampleChannel.Stop xmldoc to better describe what it's doing | ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework | osu.Framework/Audio/Sample/ISampleChannel.cs | osu.Framework/Audio/Sample/ISampleChannel.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.Framework.Audio.Sample
{
/// <summary>
/// A channel playing back an audio sample.
/// </summary>
public interface ISampleChannel : IHasAmplitudes
{
/// <summary>
/// Start playback.
/// </summary>
/// <param name="restart">Whether to restart the sample from the beginning.</param>
void Play(bool restart = true);
/// <summary>
/// Stop playback and reset position to beginning of sample.
/// </summary>
void Stop();
/// <summary>
/// Whether the sample is playing.
/// </summary>
bool Playing { get; }
/// <summary>
/// Whether the sample has finished playback.
/// </summary>
bool Played { get; }
/// <summary>
/// States if this sample should repeat.
/// </summary>
bool Looping { get; set; }
/// <summary>
/// The length of the underlying sample, in milliseconds.
/// </summary>
double Length { 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.Framework.Audio.Sample
{
/// <summary>
/// A channel playing back an audio sample.
/// </summary>
public interface ISampleChannel : IHasAmplitudes
{
/// <summary>
/// Start playback.
/// </summary>
/// <param name="restart">Whether to restart the sample from the beginning.</param>
void Play(bool restart = true);
/// <summary>
/// Stop playback.
/// </summary>
void Stop();
/// <summary>
/// Whether the sample is playing.
/// </summary>
bool Playing { get; }
/// <summary>
/// Whether the sample has finished playback.
/// </summary>
bool Played { get; }
/// <summary>
/// States if this sample should repeat.
/// </summary>
bool Looping { get; set; }
/// <summary>
/// The length of the underlying sample, in milliseconds.
/// </summary>
double Length { get; }
}
}
| mit | C# |
cb39a88c5192bf353199728542b0c1c36ae8e95b | Fix HR not affecting slider repeats and ticks | NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,naoey/osu,peppy/osu-new,DrabWeb/osu,peppy/osu,smoogipoo/osu,peppy/osu,2yangk23/osu,ZLima12/osu,2yangk23/osu,peppy/osu,ppy/osu,johnneijzen/osu,UselessToucan/osu,EVAST9919/osu,NeoAdonis/osu,ppy/osu,Frontear/osuKyzer,UselessToucan/osu,Nabile-Rahmani/osu,smoogipoo/osu,ZLima12/osu,naoey/osu,smoogipooo/osu,naoey/osu,EVAST9919/osu,smoogipoo/osu,DrabWeb/osu,DrabWeb/osu,johnneijzen/osu,ppy/osu | osu.Game.Rulesets.Osu/Mods/OsuModHardRock.cs | osu.Game.Rulesets.Osu/Mods/OsuModHardRock.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.UI;
using OpenTK;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModHardRock : ModHardRock, IApplicableToHitObject<OsuHitObject>
{
public override double ScoreMultiplier => 1.06;
public override bool Ranked => true;
public void ApplyToHitObject(OsuHitObject hitObject)
{
hitObject.Position = new Vector2(hitObject.Position.X, OsuPlayfield.BASE_SIZE.Y - hitObject.Y);
var slider = hitObject as Slider;
if (slider == null)
return;
slider.HeadCircle.Position = new Vector2(slider.HeadCircle.Position.X, OsuPlayfield.BASE_SIZE.Y - slider.HeadCircle.Position.Y);
slider.TailCircle.Position = new Vector2(slider.TailCircle.Position.X, OsuPlayfield.BASE_SIZE.Y - slider.TailCircle.Position.Y);
slider.NestedHitObjects.OfType<SliderTick>().ForEach(h => h.Position = new Vector2(h.Position.X, OsuPlayfield.BASE_SIZE.Y - h.Position.Y));
slider.NestedHitObjects.OfType<RepeatPoint>().ForEach(h => h.Position = new Vector2(h.Position.X, OsuPlayfield.BASE_SIZE.Y - h.Position.Y));
var newControlPoints = new List<Vector2>();
slider.ControlPoints.ForEach(c => newControlPoints.Add(new Vector2(c.X, -c.Y)));
slider.ControlPoints = newControlPoints;
slider.Curve?.Calculate(); // Recalculate the slider curve
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.UI;
using OpenTK;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModHardRock : ModHardRock, IApplicableToHitObject<OsuHitObject>
{
public override double ScoreMultiplier => 1.06;
public override bool Ranked => true;
public void ApplyToHitObject(OsuHitObject hitObject)
{
hitObject.Position = new Vector2(hitObject.Position.X, OsuPlayfield.BASE_SIZE.Y - hitObject.Y);
var slider = hitObject as Slider;
if (slider == null)
return;
slider.HeadCircle.Position = new Vector2(slider.HeadCircle.Position.X, OsuPlayfield.BASE_SIZE.Y - slider.HeadCircle.Position.Y);
slider.TailCircle.Position = new Vector2(slider.TailCircle.Position.X, OsuPlayfield.BASE_SIZE.Y - slider.TailCircle.Position.Y);
var newControlPoints = new List<Vector2>();
slider.ControlPoints.ForEach(c => newControlPoints.Add(new Vector2(c.X, -c.Y)));
slider.ControlPoints = newControlPoints;
slider.Curve?.Calculate(); // Recalculate the slider curve
}
}
}
| mit | C# |
e88e921f3f6d1f885314fbf6c5dca5cdd6dcb213 | Update Program.cs | tinohager/Nager.Date,tinohager/Nager.Date,tinohager/Nager.Date | Src/Nager.Date.TestConsole/Program.cs | Src/Nager.Date.TestConsole/Program.cs | using System;
using System.Linq;
using Nager.Date.Extensions;
using System.Diagnostics;
namespace Nager.Date.TestConsole
{
class Program
{
static void Main(string[] args)
{
Test3();
Console.ReadLine();
}
private static void Test1()
{
var date = DateTime.Today;
var countryCode = CountryCode.US;
do
{
date = date.AddDays(1);
} while (DateSystem.IsPublicHoliday(date, countryCode) || date.IsWeekend(countryCode));
}
private static void Test2()
{
var publicHolidays = DateSystem.GetPublicHoliday(2017, CountryCode.CH);
foreach (var publicHoliday in publicHolidays)
{
Console.WriteLine("{0:dd.MM.yyyy} {1} {2}", publicHoliday.Date, publicHoliday.LocalName, publicHoliday.Global);
}
}
private static void Test3()
{
//performane test
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 10000; i++)
{
var x = DateSystem.IsPublicHoliday(new DateTime(2017, 07, 04), CountryCode.JP);
}
sw.Stop();
Console.WriteLine("Elapsed time: " + sw.ElapsedMilliseconds + "ms");
}
}
}
| using System;
using System.Linq;
using Nager.Date.Extensions;
using System.Diagnostics;
namespace Nager.Date.TestConsole
{
class Program
{
static void Main(string[] args)
{
Test3();
Console.ReadLine();
}
private static void Test1()
{
var date = DateTime.Today;
var countryCode = CountryCode.US;
do
{
date = date.AddDays(1);
} while (DateSystem.IsPublicHoliday(date, countryCode) || date.IsWeekend(countryCode));
}
private static void Test2()
{
var publicHolidays = DateSystem.GetPublicHoliday(CountryCode.CH, 2017);
foreach (var publicHoliday in publicHolidays)
{
Console.WriteLine("{0:dd.MM.yyyy} {1} {2}", publicHoliday.Date, publicHoliday.LocalName, publicHoliday.Global);
}
}
private static void Test3()
{
//performane test
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 10000; i++)
{
var x = DateSystem.IsPublicHoliday(new DateTime(2017, 07, 04), CountryCode.US);
}
sw.Stop();
Console.WriteLine("Elapsed time: " + sw.ElapsedMilliseconds + "ms");
}
}
}
| mit | C# |
46dfc87c1bb1712e8c52c6c6c4d1622b7055272d | update test | miniactor/dev | src/MiniActor/MiniActor.Tests/UnitTest2.cs | src/MiniActor/MiniActor.Tests/UnitTest2.cs | using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MiniActor.Tests
{
[TestClass]
public class UnitTest2
{
private static int _counterAct = 0;
private static string _result = "";
public class SomeActor : MiniActor
{
public SomeActor()
{
Receive<string>(m =>
{
_result += m;
_counterAct++;
});
}
}
[TestMethod]
public void actor_test2()
{
var messanger = new MiniActorMessanger();
const int total = 20000;
string result = "";
foreach (var i in Enumerable.Range(0, total))
{
result += i.ToString();
messanger.Tell<SomeActor>(i.ToString());
}
var counter = 0;
foreach (var i in Enumerable.Range(0, total))
{
counter++;
try
{
Task.WaitAll(Task.Delay(TimeSpan.FromMilliseconds(1)));
Assert.AreEqual(total, _counterAct);
break;
}
catch (Exception)
{
}
}
Assert.IsTrue(counter < total);
Assert.AreEqual(result, _result);
}
}
} | using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MiniActor.Tests
{
[TestClass]
public class UnitTest2
{
private static int _counterAct = 0;
public class SomeActor : MiniActor
{
public SomeActor()
{
Receive<Guid>(m =>
{
_counterAct++;
});
}
}
[TestMethod]
public void actor_test2()
{
var messanger = new MiniActorMessanger();
const int total = 100000;
foreach (var i in Enumerable.Range(0, total))
{
messanger.Tell<SomeActor>(Guid.NewGuid());
}
var counter = 0;
foreach (var i in Enumerable.Range(0, total))
{
counter++;
try
{
Task.WaitAll(Task.Delay(TimeSpan.FromMilliseconds(1)));
Assert.AreEqual(total, _counterAct);
break;
}
catch (Exception)
{
}
}
Assert.IsTrue(counter < total);
}
}
} | mit | C# |
c2e302f8bbd7115616fc7de39a859a6dea45b8cf | Allow tracking from old Discord domain in the app (discordapp.com) | chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker | app/Server/Service/ServerStartup.cs | app/Server/Service/ServerStartup.cs | using System.Diagnostics.CodeAnalysis;
using System.Text.Json.Serialization;
using DHT.Server.Database;
using DHT.Server.Endpoints;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace DHT.Server.Service {
public class Startup {
public void ConfigureServices(IServiceCollection services) {
services.Configure<JsonOptions>(options => {
options.SerializerOptions.NumberHandling = JsonNumberHandling.Strict;
});
services.AddCors(cors => {
cors.AddDefaultPolicy(builder => {
builder.WithOrigins("https://discord.com", "https://discordapp.com").AllowCredentials().AllowAnyMethod().AllowAnyHeader();
});
});
}
[SuppressMessage("ReSharper", "UnusedMember.Global")]
public void Configure(IApplicationBuilder app, IHostApplicationLifetime lifetime, IDatabaseFile db, ServerParameters parameters) {
app.UseRouting();
app.UseCors();
app.UseEndpoints(endpoints => {
TrackChannelEndpoint trackChannel = new(db, parameters);
endpoints.MapPost("/track-channel", async context => await trackChannel.Handle(context));
TrackUsersEndpoint trackUsers = new(db, parameters);
endpoints.MapPost("/track-users", async context => await trackUsers.Handle(context));
TrackMessagesEndpoint trackMessages = new(db, parameters);
endpoints.MapPost("/track-messages", async context => await trackMessages.Handle(context));
});
}
}
}
| using System.Diagnostics.CodeAnalysis;
using System.Text.Json.Serialization;
using DHT.Server.Database;
using DHT.Server.Endpoints;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace DHT.Server.Service {
public class Startup {
public void ConfigureServices(IServiceCollection services) {
services.Configure<JsonOptions>(options => {
options.SerializerOptions.NumberHandling = JsonNumberHandling.Strict;
});
services.AddCors(cors => {
cors.AddDefaultPolicy(builder => {
builder.WithOrigins("https://discord.com").AllowCredentials().AllowAnyMethod().AllowAnyHeader();
});
});
}
[SuppressMessage("ReSharper", "UnusedMember.Global")]
public void Configure(IApplicationBuilder app, IHostApplicationLifetime lifetime, IDatabaseFile db, ServerParameters parameters) {
app.UseRouting();
app.UseCors();
app.UseEndpoints(endpoints => {
TrackChannelEndpoint trackChannel = new(db, parameters);
endpoints.MapPost("/track-channel", async context => await trackChannel.Handle(context));
TrackUsersEndpoint trackUsers = new(db, parameters);
endpoints.MapPost("/track-users", async context => await trackUsers.Handle(context));
TrackMessagesEndpoint trackMessages = new(db, parameters);
endpoints.MapPost("/track-messages", async context => await trackMessages.Handle(context));
});
}
}
}
| mit | C# |
f78fc1f423d6c6effc590d12426957a0ff20b21f | 添加 SessionFactory.Default | chinadev/Restful,linli8/Restful | src/Restful/Restful.Data/SessionFactory.cs | src/Restful/Restful.Data/SessionFactory.cs | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
namespace Restful.Data
{
public static class SessionFactory
{
/// <summary>
/// 获取或设置 Web.config 或 App.config 文件中配置的默认连接字符串节点名称
/// </summary>
public static string Default { get; set; }
#region CreateDefaultSession
/// <summary>
/// 创建默认的 Session
/// </summary>
/// <returns></returns>
public static ISession CreateDefaultSession()
{
if( string.IsNullOrEmpty( Default ) == false )
{
return CreateSession( Default );
}
string providerName = ConfigurationManager.ConnectionStrings[0].ProviderName;
string connectionString = ConfigurationManager.ConnectionStrings[0].ConnectionString;
return CreateSession( providerName, connectionString );
}
#endregion
#region CreateSession
/// <summary>
/// 根据配置文件中指定的名称创建 Session
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static ISession CreateSession( string name )
{
string providerName = ConfigurationManager.ConnectionStrings[name].ProviderName;
string connectionString = ConfigurationManager.ConnectionStrings[name].ConnectionString;
return CreateSession( providerName, connectionString );
}
/// <summary>
/// 根据指定提供程序和连接字符串创建 Session
/// </summary>
/// <param name="providerName"></param>
/// <param name="connectionStr"></param>
/// <returns></returns>
public static ISession CreateSession( string providerName, string connectionStr )
{
ISessionFactory factory = SessionFactories.GetFactory( providerName );
return factory.CreateSession( connectionStr );
}
#endregion
}
}
| using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
namespace Restful.Data
{
public static class SessionFactory
{
#region CreateDefaultSession
/// <summary>
/// 创建默认的 Session
/// </summary>
/// <returns></returns>
public static ISession CreateDefaultSession()
{
string name = ConfigurationManager.ConnectionStrings[0].Name;
return CreateSession( name );
}
#endregion
#region CreateSession
/// <summary>
/// 根据配置文件中指定的名称创建 Session
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static ISession CreateSession( string name )
{
string providerName = ConfigurationManager.ConnectionStrings[name].ProviderName;
string connectionString = ConfigurationManager.ConnectionStrings[name].ConnectionString;
return CreateSession( providerName, connectionString );
}
/// <summary>
/// 根据指定提供程序和连接字符串创建 Session
/// </summary>
/// <param name="providerName"></param>
/// <param name="connectionStr"></param>
/// <returns></returns>
public static ISession CreateSession( string providerName, string connectionStr )
{
ISessionFactory factory = SessionFactories.GetFactory( providerName );
return factory.CreateSession( connectionStr );
}
#endregion
}
}
| apache-2.0 | C# |
a5e86232761103e61bd33960876cf09c49e24b4e | Add IsSearchable property to tokens. | AmadeusW/SourceBrowser,AmadeusW/SourceBrowser,CodeConnect/SourceBrowser,CodeConnect/SourceBrowser,AmadeusW/SourceBrowser | src/SourceBrowser.Generator/Model/Token.cs | src/SourceBrowser.Generator/Model/Token.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SourceBrowser.Generator.Model
{
public class Token
{
public string FullName { get; }
public string Type { get; }
public int LineNumber { get; }
public ICollection<Trivia> LeadingTrivia { get; }
public string Value { get; }
public ICollection<Trivia> TrailingTrivia { get; }
public ILink Link { get; }
public bool IsDeclaration { get; }
public bool IsSearchable { get; }
public DocumentModel Document { get; }
public Token(DocumentModel document, string fullName, string value, string type, int lineNumber, bool isDeclaration = false, bool isSearchable = false)
{
Document = document;
FullName = fullName;
Value = value;
Type = type;
LineNumber = lineNumber;
IsDeclaration = isDeclaration;
IsSearchable = isSearchable;
}
private Token(Token oldToken, ILink link) :
this(oldToken.Document, oldToken.FullName, oldToken.Value, oldToken.Type, oldToken.LineNumber, oldToken.IsDeclaration, oldToken.IsSearchable)
{
Link = link;
LeadingTrivia = oldToken.LeadingTrivia;
TrailingTrivia = oldToken.TrailingTrivia;
}
private Token(Token oldToken, ICollection<Trivia> leading, ICollection<Trivia> trailing) :
this(oldToken.Document, oldToken.FullName, oldToken.Value, oldToken.Type, oldToken.LineNumber, oldToken.IsDeclaration, oldToken.IsSearchable)
{
Link = oldToken.Link;
LeadingTrivia = leading;
TrailingTrivia = trailing;
}
/// <summary>
/// Create a new token with the provided link.
/// </summary>
/// <returns>A new token containing the provided link.</returns>
public Token WithLink(ILink link)
{
var newToken = new Token(this, link);
return newToken;
}
/// <summary>
/// Creates a new token with the provided trivia.
/// </summary>
/// <returns>A new token containing the provided trivia.</returns>
public Token WithTrivia(ICollection<Trivia> leading, ICollection<Trivia> trailing)
{
var newToken = new Token(this, leading, trailing);
return newToken;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SourceBrowser.Generator.Model
{
public class Token
{
public string FullName { get; }
public string Type { get; }
public int LineNumber { get; }
public ICollection<Trivia> LeadingTrivia { get; }
public string Value { get; }
public ICollection<Trivia> TrailingTrivia { get; }
public ILink Link { get; }
public bool IsDeclaration { get; }
public DocumentModel Document { get; }
public Token(DocumentModel document, string fullName, string value, string type, int lineNumber, bool isDeclaration = false)
{
Document = document;
FullName = fullName;
Value = value;
Type = type;
LineNumber = lineNumber;
IsDeclaration = isDeclaration;
}
private Token(Token oldToken, ILink link) : this(oldToken.Document, oldToken.FullName, oldToken.Value, oldToken.Type, oldToken.LineNumber, oldToken.IsDeclaration)
{
Link = link;
LeadingTrivia = oldToken.LeadingTrivia;
TrailingTrivia = oldToken.TrailingTrivia;
}
private Token(Token oldToken, ICollection<Trivia> leading, ICollection<Trivia> trailing) :
this(oldToken.Document, oldToken.FullName, oldToken.Value, oldToken.Type, oldToken.LineNumber, oldToken.IsDeclaration)
{
Link = oldToken.Link;
LeadingTrivia = leading;
TrailingTrivia = trailing;
}
/// <summary>
/// Create a new token with the provided link.
/// </summary>
/// <returns>A new token containing the provided link.</returns>
public Token WithLink(ILink link)
{
var newToken = new Token(this, link);
return newToken;
}
/// <summary>
/// Creates a new token with the provided trivia.
/// </summary>
/// <returns>A new token containing the provided trivia.</returns>
public Token WithTrivia(ICollection<Trivia> leading, ICollection<Trivia> trailing)
{
var newToken = new Token(this, leading, trailing);
return newToken;
}
}
}
| mit | C# |
5fbb57e48ab29cc02b610f355f4f02cb9587ede4 | Use platform-independent directory separator char | rwwilden/AspNet5Localization | src/Localization.JsonLocalizer/Localization.JsonLocalizer/LocalizerUtil.cs | src/Localization.JsonLocalizer/Localization.JsonLocalizer/LocalizerUtil.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Localization.JsonLocalizer.StringLocalizer
{
internal static class LocalizerUtil
{
internal static string TrimPrefix(string name, string prefix)
{
if (name.StartsWith(prefix, StringComparison.Ordinal))
{
return name.Substring(prefix.Length);
}
return name;
}
internal static IEnumerable<string> ExpandPaths(string name, string baseName)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
return ExpandPathIterator(name, baseName);
}
private static IEnumerable<string> ExpandPathIterator(string name, string baseName)
{
StringBuilder expansion = new StringBuilder();
// Start replacing periods, starting at the beginning.
var components = name.Split(new[] { '.' }, StringSplitOptions.None);
for (var i = 0; i < components.Length; i++)
{
for (var j = 0; j < components.Length; j++)
{
expansion.Append(components[j]).Append(j < i ? Path.DirectorySeparatorChar : '.');
}
yield return expansion.ToString();
expansion.Clear();
}
// Do the same with the name where baseName prefix is removed.
var nameWithoutPrefix = TrimPrefix(name, baseName).Substring(1);
var componentsWithoutPrefix = nameWithoutPrefix.Split(new[] { '.' }, StringSplitOptions.None);
for (var i = 0; i < componentsWithoutPrefix.Length; i++)
{
for (var j = 0; j < componentsWithoutPrefix.Length; j++)
{
expansion.Append(componentsWithoutPrefix[j]).Append(j < i ? Path.DirectorySeparatorChar : '.');
}
yield return expansion.ToString();
expansion.Clear();
}
}
}
}
| using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
namespace Localization.JsonLocalizer.StringLocalizer
{
internal static class LocalizerUtil
{
internal static string TrimPrefix(string name, string prefix)
{
if (name.StartsWith(prefix, StringComparison.Ordinal))
{
return name.Substring(prefix.Length);
}
return name;
}
internal static IEnumerable<string> ExpandPaths(string name, string baseName)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
return ExpandPathIterator(name, baseName);
}
private static IEnumerable<string> ExpandPathIterator(string name, string baseName)
{
StringBuilder expansion = new StringBuilder();
// Start replacing periods, starting at the beginning.
var components = name.Split(new[] { '.' }, StringSplitOptions.None);
for (var i = 0; i < components.Length; i++)
{
for (var j = 0; j < components.Length; j++)
{
expansion.Append(components[j]).Append(j < i ? '\\' : '.');
}
yield return expansion.ToString();
expansion.Clear();
}
// Do the same with the name where baseName prefix is removed.
var nameWithoutPrefix = TrimPrefix(name, baseName).Substring(1);
var componentsWithoutPrefix = nameWithoutPrefix.Split(new[] { '.' }, StringSplitOptions.None);
for (var i = 0; i < componentsWithoutPrefix.Length; i++)
{
for (var j = 0; j < componentsWithoutPrefix.Length; j++)
{
expansion.Append(componentsWithoutPrefix[j]).Append(j < i ? '\\' : '.');
}
yield return expansion.ToString();
expansion.Clear();
}
}
}
}
| mit | C# |
240ee37a2319adb05b0f434211ce16e26df7612b | Remove unused using | blorgbeard/pickles,irfanah/pickles,blorgbeard/pickles,blorgbeard/pickles,magicmonty/pickles,irfanah/pickles,dirkrombauts/pickles,blorgbeard/pickles,picklesdoc/pickles,dirkrombauts/pickles,irfanah/pickles,ludwigjossieaux/pickles,dirkrombauts/pickles,dirkrombauts/pickles,irfanah/pickles,magicmonty/pickles,picklesdoc/pickles,picklesdoc/pickles,magicmonty/pickles,ludwigjossieaux/pickles,picklesdoc/pickles,magicmonty/pickles,ludwigjossieaux/pickles | src/Pickles/Pickles/DocumentationBuilders/HTML/HtmlDescriptionFormatter.cs | src/Pickles/Pickles/DocumentationBuilders/HTML/HtmlDescriptionFormatter.cs | #region License
/*
Copyright [2011] [Jeffrey Cameron]
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.
*/
#endregion
using System;
using System.Xml.Linq;
using PicklesDoc.Pickles.Extensions;
namespace PicklesDoc.Pickles.DocumentationBuilders.HTML
{
public class HtmlDescriptionFormatter
{
private readonly MarkdownProvider markdown;
private readonly XNamespace xmlns;
public HtmlDescriptionFormatter(MarkdownProvider markdown)
{
this.markdown = markdown;
this.xmlns = HtmlNamespace.Xhtml;
}
public XElement Format(string descriptionText)
{
if (String.IsNullOrEmpty(descriptionText)) return null;
string markdownResult = "<div>" + this.markdown.Transform(descriptionText) + "</div>";
XElement descriptionElements = XElement.Parse(markdownResult);
descriptionElements.SetAttributeValue("class", "description");
descriptionElements.MoveToNamespace(this.xmlns);
return descriptionElements;
}
}
} | #region License
/*
Copyright [2011] [Jeffrey Cameron]
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.
*/
#endregion
using System;
using System.Xml.Linq;
using MarkdownDeep;
using PicklesDoc.Pickles.Extensions;
namespace PicklesDoc.Pickles.DocumentationBuilders.HTML
{
public class HtmlDescriptionFormatter
{
private readonly MarkdownProvider markdown;
private readonly XNamespace xmlns;
public HtmlDescriptionFormatter(MarkdownProvider markdown)
{
this.markdown = markdown;
this.xmlns = HtmlNamespace.Xhtml;
}
public XElement Format(string descriptionText)
{
if (String.IsNullOrEmpty(descriptionText)) return null;
string markdownResult = "<div>" + this.markdown.Transform(descriptionText) + "</div>";
XElement descriptionElements = XElement.Parse(markdownResult);
descriptionElements.SetAttributeValue("class", "description");
descriptionElements.MoveToNamespace(this.xmlns);
return descriptionElements;
}
}
} | apache-2.0 | C# |
b9bf3a1829002036201e96c8359519add545e172 | Make mania scroll downwards by default | smoogipoo/osu,ZLima12/osu,2yangk23/osu,DrabWeb/osu,peppy/osu-new,ZLima12/osu,DrabWeb/osu,EVAST9919/osu,DrabWeb/osu,naoey/osu,peppy/osu,ppy/osu,johnneijzen/osu,UselessToucan/osu,UselessToucan/osu,naoey/osu,ppy/osu,peppy/osu,NeoAdonis/osu,johnneijzen/osu,peppy/osu,naoey/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,EVAST9919/osu,NeoAdonis/osu,smoogipooo/osu,NeoAdonis/osu,UselessToucan/osu,2yangk23/osu | osu.Game.Rulesets.Mania/Configuration/ManiaConfigManager.cs | osu.Game.Rulesets.Mania/Configuration/ManiaConfigManager.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Configuration.Tracking;
using osu.Game.Configuration;
using osu.Game.Rulesets.Configuration;
using osu.Game.Rulesets.Mania.UI;
namespace osu.Game.Rulesets.Mania.Configuration
{
public class ManiaConfigManager : RulesetConfigManager<ManiaSetting>
{
public ManiaConfigManager(SettingsStore settings, RulesetInfo ruleset, int? variant = null)
: base(settings, ruleset, variant)
{
}
protected override void InitialiseDefaults()
{
base.InitialiseDefaults();
Set(ManiaSetting.ScrollTime, 1500.0, 50.0, 10000.0, 50.0);
Set(ManiaSetting.ScrollDirection, ManiaScrollingDirection.Down);
}
public override TrackedSettings CreateTrackedSettings() => new TrackedSettings
{
new TrackedSetting<double>(ManiaSetting.ScrollTime, v => new SettingDescription(v, "Scroll Time", $"{v}ms"))
};
}
public enum ManiaSetting
{
ScrollTime,
ScrollDirection
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Configuration.Tracking;
using osu.Game.Configuration;
using osu.Game.Rulesets.Configuration;
using osu.Game.Rulesets.Mania.UI;
namespace osu.Game.Rulesets.Mania.Configuration
{
public class ManiaConfigManager : RulesetConfigManager<ManiaSetting>
{
public ManiaConfigManager(SettingsStore settings, RulesetInfo ruleset, int? variant = null)
: base(settings, ruleset, variant)
{
}
protected override void InitialiseDefaults()
{
base.InitialiseDefaults();
Set(ManiaSetting.ScrollTime, 1500.0, 50.0, 10000.0, 50.0);
Set(ManiaSetting.ScrollDirection, ManiaScrollingDirection.Up);
}
public override TrackedSettings CreateTrackedSettings() => new TrackedSettings
{
new TrackedSetting<double>(ManiaSetting.ScrollTime, v => new SettingDescription(v, "Scroll Time", $"{v}ms"))
};
}
public enum ManiaSetting
{
ScrollTime,
ScrollDirection
}
}
| mit | C# |
5bd09a4a30ec343a7aa78224522041a8121021ec | Rename inner lambda parameter | NeoAdonis/osu,smoogipooo/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu-new,NeoAdonis/osu,ppy/osu,peppy/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,smoogipoo/osu | osu.Game.Rulesets.Osu/Skinning/Legacy/LegacyReverseArrow.cs | osu.Game.Rulesets.Osu/Skinning/Legacy/LegacyReverseArrow.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Diagnostics;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osu.Game.Skinning;
namespace osu.Game.Rulesets.Osu.Skinning.Legacy
{
public class LegacyReverseArrow : CompositeDrawable
{
[Resolved(canBeNull: true)]
private DrawableHitObject drawableHitObject { get; set; }
private Drawable proxy;
[BackgroundDependencyLoader]
private void load(ISkinSource skinSource)
{
AutoSizeAxes = Axes.Both;
string lookupName = new OsuSkinComponent(OsuSkinComponents.ReverseArrow).LookupName;
var skin = skinSource.FindProvider(s => s.GetTexture(lookupName) != null);
InternalChild = skin?.GetAnimation(lookupName, true, true) ?? Empty();
}
protected override void LoadComplete()
{
base.LoadComplete();
proxy = CreateProxy();
if (drawableHitObject != null)
{
drawableHitObject.HitObjectApplied += onHitObjectApplied;
onHitObjectApplied(drawableHitObject);
}
}
private void onHitObjectApplied(DrawableHitObject drawableObject)
{
Debug.Assert(proxy.Parent == null);
// see logic in LegacySliderHeadHitCircle.
(drawableObject as DrawableSliderRepeat)?.DrawableSlider
.OverlayElementContainer.Add(proxy);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (drawableHitObject != null)
drawableHitObject.HitObjectApplied -= onHitObjectApplied;
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Diagnostics;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osu.Game.Skinning;
namespace osu.Game.Rulesets.Osu.Skinning.Legacy
{
public class LegacyReverseArrow : CompositeDrawable
{
[Resolved(canBeNull: true)]
private DrawableHitObject drawableHitObject { get; set; }
private Drawable proxy;
[BackgroundDependencyLoader]
private void load(ISkinSource skinSource)
{
AutoSizeAxes = Axes.Both;
string lookupName = new OsuSkinComponent(OsuSkinComponents.ReverseArrow).LookupName;
var skin = skinSource.FindProvider(skin => skin.GetTexture(lookupName) != null);
InternalChild = skin?.GetAnimation(lookupName, true, true) ?? Empty();
}
protected override void LoadComplete()
{
base.LoadComplete();
proxy = CreateProxy();
if (drawableHitObject != null)
{
drawableHitObject.HitObjectApplied += onHitObjectApplied;
onHitObjectApplied(drawableHitObject);
}
}
private void onHitObjectApplied(DrawableHitObject drawableObject)
{
Debug.Assert(proxy.Parent == null);
// see logic in LegacySliderHeadHitCircle.
(drawableObject as DrawableSliderRepeat)?.DrawableSlider
.OverlayElementContainer.Add(proxy);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (drawableHitObject != null)
drawableHitObject.HitObjectApplied -= onHitObjectApplied;
}
}
}
| mit | C# |
e969ca8974d621eb4a089231f65b684f1a3d4f60 | Remove unused using statement that rider could not identify | UselessToucan/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,ppy/osu,peppy/osu-new,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,ppy/osu,smoogipooo/osu | osu.Game/Screens/OnlinePlay/Components/RoomLocalUserInfo.cs | osu.Game/Screens/OnlinePlay/Components/RoomLocalUserInfo.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
namespace osu.Game.Screens.OnlinePlay.Components
{
public class RoomLocalUserInfo : OnlinePlayComposite
{
private OsuSpriteText attemptDisplay;
public RoomLocalUserInfo()
{
AutoSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader]
private void load()
{
InternalChild = new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
attemptDisplay = new OsuSpriteText
{
Font = OsuFont.GetFont(weight: FontWeight.Bold, size: 14)
},
}
};
}
protected override void LoadComplete()
{
base.LoadComplete();
MaxAttempts.BindValueChanged(_ => updateAttempts());
UserScore.BindValueChanged(_ => updateAttempts(), true);
}
private void updateAttempts()
{
if (MaxAttempts.Value != null)
{
attemptDisplay.Text = $"Maximum attempts: {MaxAttempts.Value:N0}";
if (UserScore.Value != null)
{
int remaining = MaxAttempts.Value.Value - UserScore.Value.PlaylistItemAttempts.Sum(a => a.Attempts);
attemptDisplay.Text += $" ({remaining} remaining)";
}
}
else
{
attemptDisplay.Text = string.Empty;
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
namespace osu.Game.Screens.OnlinePlay.Components
{
public class RoomLocalUserInfo : OnlinePlayComposite
{
private OsuSpriteText attemptDisplay;
public RoomLocalUserInfo()
{
AutoSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader]
private void load()
{
InternalChild = new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
attemptDisplay = new OsuSpriteText
{
Font = OsuFont.GetFont(weight: FontWeight.Bold, size: 14)
},
}
};
}
protected override void LoadComplete()
{
base.LoadComplete();
MaxAttempts.BindValueChanged(_ => updateAttempts());
UserScore.BindValueChanged(_ => updateAttempts(), true);
}
private void updateAttempts()
{
if (MaxAttempts.Value != null)
{
attemptDisplay.Text = $"Maximum attempts: {MaxAttempts.Value:N0}";
if (UserScore.Value != null)
{
int remaining = MaxAttempts.Value.Value - UserScore.Value.PlaylistItemAttempts.Sum(a => a.Attempts);
attemptDisplay.Text += $" ({remaining} remaining)";
}
}
else
{
attemptDisplay.Text = string.Empty;
}
}
}
}
| mit | C# |
bf7a80a586fe0e3a7b4afa819da2def91901b9da | Set cursor lockstate to default on scene load | NitorInc/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare,Barleytree/NitoriWare | Assets/Scripts/Global/GameController.cs | Assets/Scripts/Global/GameController.cs | using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Events;
using System.Collections;
public class GameController : MonoBehaviour
{
public static GameController instance;
public const CursorLockMode DefaultCursorMode = CursorLockMode.None;
#pragma warning disable 0649
[SerializeField]
private bool disableCursor;
[SerializeField]
private SceneShifter _sceneShifter;
[SerializeField]
private Sprite[] controlSprites;
[SerializeField]
private UnityEvent onSceneLoad;
[SerializeField]
private DiscordController _discord;
#pragma warning restore 0649
private string startScene;
public SceneShifter sceneShifter => _sceneShifter;
public DiscordController discord => _discord;
void Awake()
{
if (instance != null)
{
Destroy(gameObject);
return;
}
startScene = gameObject.scene.name;
DontDestroyOnLoad(transform.gameObject);
instance = this;
Cursor.visible = !disableCursor;
Cursor.lockState = DefaultCursorMode;
Application.targetFrameRate = 60;
AudioListener.pause = false;
SceneManager.sceneLoaded += onSceneLoaded;
}
private void Update()
{
//Debug features
if (Debug.isDebugBuild)
{
//Shift+R to reset all prefs
if ((Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) && Input.GetKeyDown(KeyCode.R))
PlayerPrefs.DeleteAll();
}
}
void onSceneLoaded(Scene scene, LoadSceneMode mode)
{
if (PauseManager.exitedWhilePaused)
{
AudioListener.pause = false;
Time.timeScale = 1f;
Cursor.visible = true;
Cursor.lockState = DefaultCursorMode;
PauseManager.exitedWhilePaused = false;
}
onSceneLoad.Invoke();
}
public Sprite getControlSprite(MicrogameTraits.ControlScheme controlScheme)
{
return controlSprites[(int)controlScheme];
}
public string getStartScene() => startScene;
}
| using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Events;
using System.Collections;
public class GameController : MonoBehaviour
{
public static GameController instance;
public const CursorLockMode DefaultCursorMode = CursorLockMode.None;
#pragma warning disable 0649
[SerializeField]
private bool disableCursor;
[SerializeField]
private SceneShifter _sceneShifter;
[SerializeField]
private Sprite[] controlSprites;
[SerializeField]
private UnityEvent onSceneLoad;
[SerializeField]
private DiscordController _discord;
#pragma warning restore 0649
private string startScene;
public SceneShifter sceneShifter => _sceneShifter;
public DiscordController discord => _discord;
void Awake()
{
if (instance != null)
{
Destroy(gameObject);
return;
}
startScene = gameObject.scene.name;
DontDestroyOnLoad(transform.gameObject);
instance = this;
Cursor.visible = !disableCursor;
Cursor.lockState = DefaultCursorMode;
Application.targetFrameRate = 60;
AudioListener.pause = false;
SceneManager.sceneLoaded += onSceneLoaded;
}
private void Update()
{
//Debug features
if (Debug.isDebugBuild)
{
//Shift+R to reset all prefs
if ((Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) && Input.GetKeyDown(KeyCode.R))
PlayerPrefs.DeleteAll();
}
}
void onSceneLoaded(Scene scene, LoadSceneMode mode)
{
if (PauseManager.exitedWhilePaused)
{
AudioListener.pause = false;
Time.timeScale = 1f;
PauseManager.exitedWhilePaused = false;
Cursor.visible = true;
}
onSceneLoad.Invoke();
}
public Sprite getControlSprite(MicrogameTraits.ControlScheme controlScheme)
{
return controlSprites[(int)controlScheme];
}
public string getStartScene() => startScene;
}
| mit | C# |
363cd678afa476362bd01518d0844222e2644667 | Update OutputBand.cs | LANDIS-II-Foundation/Landis-Spatial-Modeling-Library | src/RasterIO.Gdal/OutputBand.cs | src/RasterIO.Gdal/OutputBand.cs | // Contributors:
// James Domingo, Green Code LLC
using Landis.SpatialModeling;
using System;
namespace Landis.RasterIO.Gdal
{
public class OutputBand<T> : IOutputBand
where T : struct
{
private RasterBandWriter<T> rasterBandWriter;
private IPixelBandGetter<T> pixelBandGetter;
private BlockDimensions blockDimensions;
private BandBuffer<T> bandBuffer;
private bool hasData;
public OutputBand(RasterBandWriter<T> rasterBandWriter,
IPixelBandGetter<T> pixelBandGetter)
{
this.rasterBandWriter = rasterBandWriter;
this.pixelBandGetter = pixelBandGetter;
blockDimensions = rasterBandWriter.BlockSize;
bandBuffer = new BandBuffer<T>(blockDimensions, new Dimensions(rasterBandWriter.Rows, rasterBandWriter.Columns));
hasData = false;
}
/// <summary>
/// Write the value of the corresponding band in the buffer pixel to
/// the raster band.
/// </summary>
public void WriteValueFromBufferPixel()
{
// Get the band value from the pixel band
T bandValue = pixelBandGetter.GetValue();
bandBuffer.WriteValue(bandValue);
hasData = true;
if (bandBuffer.AtEnd)
WriteBuffer();
}
private void WriteBuffer()
{
foreach (BandBlock<T> block in bandBuffer.Blocks)
rasterBandWriter.WriteBlock(block);
bandBuffer.Reset();
hasData = false;
}
public void Flush()
{
if (hasData)
WriteBuffer();
}
}
}
| // Copyright 2010 Green Code LLC
// All rights reserved.
//
// The copyright holders license this file under the New (3-clause) BSD
// License (the "License"). You may not use this file except in
// compliance with the License. A copy of the License is available at
//
// http://www.opensource.org/licenses/BSD-3-Clause
//
// and is included in the NOTICE.txt file distributed with this work.
//
// Contributors:
// James Domingo, Green Code LLC
using Landis.SpatialModeling;
using System;
namespace Landis.RasterIO.Gdal
{
public class OutputBand<T> : IOutputBand
where T : struct
{
private RasterBandWriter<T> rasterBandWriter;
private IPixelBandGetter<T> pixelBandGetter;
private BlockDimensions blockDimensions;
private BandBuffer<T> bandBuffer;
private bool hasData;
public OutputBand(RasterBandWriter<T> rasterBandWriter,
IPixelBandGetter<T> pixelBandGetter)
{
this.rasterBandWriter = rasterBandWriter;
this.pixelBandGetter = pixelBandGetter;
blockDimensions = rasterBandWriter.BlockSize;
bandBuffer = new BandBuffer<T>(blockDimensions, new Dimensions(rasterBandWriter.Rows, rasterBandWriter.Columns));
hasData = false;
}
/// <summary>
/// Write the value of the corresponding band in the buffer pixel to
/// the raster band.
/// </summary>
public void WriteValueFromBufferPixel()
{
// Get the band value from the pixel band
T bandValue = pixelBandGetter.GetValue();
bandBuffer.WriteValue(bandValue);
hasData = true;
if (bandBuffer.AtEnd)
WriteBuffer();
}
private void WriteBuffer()
{
foreach (BandBlock<T> block in bandBuffer.Blocks)
rasterBandWriter.WriteBlock(block);
bandBuffer.Reset();
hasData = false;
}
public void Flush()
{
if (hasData)
WriteBuffer();
}
}
}
| apache-2.0 | C# |
c1db055739eca4b3b35931f63551480eb3796663 | Update MiniKanren.cs | wallymathieu/csharp_ukanren,wallymathieu/csharp_ukanren | lib/MiniKanren.cs | lib/MiniKanren.cs | using System;
namespace MicroKanren{
public class Cons<T1,T2>{
//attr_reader :car, :cdr
public T1 Car{get;private set;}
public T2 Cdr{get;private set;}
//# Returns a Cons cell (read: instance) that is also marked as such for
//# later identification.
public Cons(T1 car,T2 cdr){ //def initialize(car, cdr)
Car=car; Cdr = cdr;
}//end
//# Converts Lisp AST to a String. Algorithm is a recursive implementation of
//# http://www.mat.uc.pt/~pedro/cientificos/funcional/lisp/gcl_22.html#SEC1238.
public override String ToString(){
return ToString(false);
}
public String ToString(bool consInCdr){
var str = new StringBuilder(consInCdr ? "" : "(");
/*def to_s(cons_in_cdr = false)
str = cons_in_cdr ? '' : '('
str += self.car.is_a?(Cons) ? self.car.to_s : atom_string(self.car)
str += case self.cdr
when Cons
' ' + self.cdr.to_s(true)
when NilClass
''
else
' . ' + atom_string(self.cdr)
end
cons_in_cdr ? str : str << ')'
end*/
}
/*def ==(other)
other.is_a?(Cons) ? self.car == other.car && self.cdr == other.cdr : false
end*/
//private
/*def atom_string(node)
case node
when NilClass, Array, String
node.inspect
else
node.to_s
end
end*/
}
}
| using System;
namespace MicroKanren{
public class Cons<T1,T2>{
//attr_reader :car, :cdr
public T1 Car{get;private set;}
public T2 Cdr{get;private set;}
//# Returns a Cons cell (read: instance) that is also marked as such for
//# later identification.
public Cons(T1 car,T2 cdr){ //def initialize(car, cdr)
Car=car; Cdr = cdr;
}//end
//# Converts Lisp AST to a String. Algorithm is a recursive implementation of
//# http://www.mat.uc.pt/~pedro/cientificos/funcional/lisp/gcl_22.html#SEC1238.
/*def to_s(cons_in_cdr = false)
str = cons_in_cdr ? '' : '('
str += self.car.is_a?(Cons) ? self.car.to_s : atom_string(self.car)
str += case self.cdr
when Cons
' ' + self.cdr.to_s(true)
when NilClass
''
else
' . ' + atom_string(self.cdr)
end
cons_in_cdr ? str : str << ')'
end*/
/*def ==(other)
other.is_a?(Cons) ? self.car == other.car && self.cdr == other.cdr : false
end*/
//private
/*def atom_string(node)
case node
when NilClass, Array, String
node.inspect
else
node.to_s
end
end*/
}
}
| mit | C# |
b64ca7d5b7ed0af80828fd5fc1d6ba463fbfe6d1 | add more unit tests for relative panel | wieslawsoltes/Perspex,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,Perspex/Perspex,AvaloniaUI/Avalonia,akrisiun/Perspex,jkoritzinsky/Avalonia,Perspex/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,grokys/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex | tests/Avalonia.Controls.UnitTests/RelativePanelTests.cs | tests/Avalonia.Controls.UnitTests/RelativePanelTests.cs | using Avalonia.Controls.Shapes;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class RelativePanelTests
{
[Fact]
public void Lays_Out_1_Child_Next_the_other()
{
var rect1 = new Rectangle { Height = 20, Width = 20 };
var rect2 = new Rectangle { Height = 20, Width = 20 };
var target = new RelativePanel
{
VerticalAlignment = Layout.VerticalAlignment.Top,
HorizontalAlignment = Layout.HorizontalAlignment.Left,
Children =
{
rect1, rect2
}
};
RelativePanel.SetAlignLeftWithPanel(rect1 , true);
RelativePanel.SetRightOf(rect2, rect1);
target.Measure(new Size(400, 400));
target.Arrange(new Rect(target.DesiredSize));
Assert.Equal(new Size(40, 20), target.Bounds.Size);
Assert.Equal(new Rect(0, 0, 20, 20), target.Children[0].Bounds);
Assert.Equal(new Rect(20, 0, 20, 20), target.Children[1].Bounds);
}
public void Lays_Out_1_Child_Below_the_other()
{
var rect1 = new Rectangle { Height = 20, Width = 20 };
var rect2 = new Rectangle { Height = 20, Width = 20 };
var target = new RelativePanel
{
VerticalAlignment = Layout.VerticalAlignment.Top,
HorizontalAlignment = Layout.HorizontalAlignment.Left,
Children =
{
rect1, rect2
}
};
RelativePanel.SetAlignLeftWithPanel(rect1, true);
RelativePanel.SetBelow(rect2, rect1);
target.Measure(new Size(400, 400));
target.Arrange(new Rect(target.DesiredSize));
Assert.Equal(new Size(20, 40), target.Bounds.Size);
Assert.Equal(new Rect(0, 0, 20, 20), target.Children[0].Bounds);
Assert.Equal(new Rect(0, 20, 20, 20), target.Children[1].Bounds);
}
}
}
| using Avalonia.Controls.Shapes;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class RelativePanelTests
{
[Fact]
public void Lays_Out_1_Child_Below_the_other()
{
var rect1 = new Rectangle { Height = 20, Width = 20 };
var rect2 = new Rectangle { Height = 20, Width = 20 };
var target = new RelativePanel
{
Children =
{
rect1, rect2
}
};
RelativePanel.SetAlignLeftWithPanel(rect1 , true);
RelativePanel.SetBelow(rect2, rect1);
target.Measure(new Size(400, 400));
target.Arrange(new Rect(target.DesiredSize));
Assert.Equal(new Size(20, 40), target.Bounds.Size);
Assert.Equal(new Rect(0, 0, 20, 20), target.Children[0].Bounds);
Assert.Equal(new Rect(0, 20, 20, 20), target.Children[1].Bounds);
}
}
}
| mit | C# |
1f4604f3aa4ef9b799ba8d6a17b1434fb98ac7d2 | Fix problem when setting WebGL build to fullscreen | p-dahlback/ld-35 | Assets/Scripts/_Utils/CameraAspectAdjuster.cs | Assets/Scripts/_Utils/CameraAspectAdjuster.cs | using UnityEngine;
using System.Collections;
public class CameraAspectAdjuster : MonoBehaviour
{
public Camera mainCamera;
public float targetAspectRatio;
private float latestWindowAspectRatio;
void Awake ()
{
latestWindowAspectRatio = targetAspectRatio;
AdjustIfNeeded ();
}
void Update ()
{
AdjustIfNeeded ();
}
void AdjustIfNeeded ()
{
float windowAspectRatio = (float)Screen.width / (float)Screen.height;
if (windowAspectRatio != latestWindowAspectRatio) {
float scale = windowAspectRatio / targetAspectRatio;
// if scaled height is less than current height, add letterbox
if (scale < 1.0f) {
Rect rect = mainCamera.rect;
rect.width = 1.0f;
rect.height = scale;
rect.x = 0;
rect.y = (1.0f - scale) / 2.0f;
mainCamera.rect = rect;
} else if (scale > 1.0f) { // add pillarbox
float scalewidth = 1.0f / scale;
Rect rect = mainCamera.rect;
rect.width = scalewidth;
rect.height = 1.0f;
rect.x = (1.0f - scalewidth) / 2.0f;
rect.y = 0;
mainCamera.rect = rect;
} else {
Rect rect = mainCamera.rect;
rect.width = 1.0f;
rect.height = 1.0f;
rect.x = 0;
rect.y = 0;
mainCamera.rect = rect;
}
latestWindowAspectRatio = windowAspectRatio;
}
}
}
| using UnityEngine;
using System.Collections;
public class CameraAspectAdjuster : MonoBehaviour
{
public Camera mainCamera;
public float targetAspectRatio;
// Use this for initialization
void Awake ()
{
float windowAspectRatio = (float)Screen.width / (float)Screen.height;
float scale = windowAspectRatio / targetAspectRatio;
// if scaled height is less than current height, add letterbox
if (scale < 1.0f) {
Rect rect = mainCamera.rect;
rect.width = 1.0f;
rect.height = scale;
rect.x = 0;
rect.y = (1.0f - scale) / 2.0f;
mainCamera.rect = rect;
} else if (scale > 1.0f) { // add pillarbox
float scalewidth = 1.0f / scale;
Rect rect = mainCamera.rect;
rect.width = scalewidth;
rect.height = 1.0f;
rect.x = (1.0f - scalewidth) / 2.0f;
rect.y = 0;
mainCamera.rect = rect;
}
}
}
| apache-2.0 | C# |
a7b994db80d3c43a840c0384676c1450a99fc8bc | Use TLS 1.2 for test suite | JetBrains/YouTrackSharp,JetBrains/YouTrackSharp | tests/YouTrackSharp.Tests/Infrastructure/Connections.cs | tests/YouTrackSharp.Tests/Infrastructure/Connections.cs | using System.Collections.Generic;
using System.Net.Http;
using System.Security.Authentication;
namespace YouTrackSharp.Tests.Infrastructure
{
public class Connections
{
public static string ServerUrl
=> "https://ytsharp.myjetbrains.com/youtrack/";
public static Connection UnauthorizedConnection =>
new BearerTokenConnection(ServerUrl, "invalidtoken", handler => ConfigureTestsHandler(handler));
public static Connection Demo1Token =>
new BearerTokenConnection(ServerUrl, "perm:ZGVtbzE=.WW91VHJhY2tTaGFycA==.AX3uf8RYk3y2bupWA1xyd9BhAHoAxc", handler => ConfigureTestsHandler(handler));
public static Connection Demo2Token =>
new BearerTokenConnection(ServerUrl, "perm:ZGVtbzI=.WW91VHJhY2tTaGFycA==.GQEOl33LyTtmJvhWuz0Q629wbo8dk0", handler => ConfigureTestsHandler(handler));
public static Connection Demo3Token =>
new BearerTokenConnection(ServerUrl, "perm:ZGVtbzM=.WW91VHJhY2tTaGFycA==.L04RdcCnjyW2UPCVg1qyb6dQflpzFy", handler => ConfigureTestsHandler(handler));
public static class TestData
{
public static readonly List<object[]> ValidConnections
= new List<object[]>
{
new object[] { Demo1Token },
new object[] { Demo2Token }
};
public static readonly List<object[]> InvalidConnections
= new List<object[]>
{
new object[] { UnauthorizedConnection }
};
}
private static void ConfigureTestsHandler(HttpClientHandler handler)
{
handler.SslProtocols = SslProtocols.Tls12;
}
}
} | using System.Collections.Generic;
namespace YouTrackSharp.Tests.Infrastructure
{
public class Connections
{
public static string ServerUrl
=> "https://ytsharp.myjetbrains.com/youtrack/";
public static Connection UnauthorizedConnection =>
new BearerTokenConnection(ServerUrl, "invalidtoken");
public static Connection Demo1Token =>
new BearerTokenConnection(ServerUrl, "perm:ZGVtbzE=.WW91VHJhY2tTaGFycA==.AX3uf8RYk3y2bupWA1xyd9BhAHoAxc");
public static Connection Demo2Token =>
new BearerTokenConnection(ServerUrl, "perm:ZGVtbzI=.WW91VHJhY2tTaGFycA==.GQEOl33LyTtmJvhWuz0Q629wbo8dk0");
public static Connection Demo3Token =>
new BearerTokenConnection(ServerUrl, "perm:ZGVtbzM=.WW91VHJhY2tTaGFycA==.L04RdcCnjyW2UPCVg1qyb6dQflpzFy");
public static class TestData
{
public static readonly List<object[]> ValidConnections
= new List<object[]>
{
new object[] { Demo1Token },
new object[] { Demo2Token }
};
public static readonly List<object[]> InvalidConnections
= new List<object[]>
{
new object[] { UnauthorizedConnection }
};
}
}
} | apache-2.0 | C# |
d24528aa79fd6eee9324428b8f05dc658b2d0d7f | Update NatashaInitializer.cs | NMSLanX/Natasha | src/Natasha.CSharp/Natasha.CSharp.All/NatashaInitializer.cs | src/Natasha.CSharp/Natasha.CSharp.All/NatashaInitializer.cs | using Natasha.CSharp;
using System;
using System.Threading.Tasks;
public static class NatashaInitializer
{
private static bool _hasInitialize;
/// <summary>
/// 初始化 Natasha 组件
/// </summary>
public static async Task Initialize()
{
if (!_hasInitialize)
{
NatashaComponentRegister.RegistDomain<NatashaAssemblyDomain>();
NatashaComponentRegister.RegistCompiler<NatashaCSharpCompiler>();
NatashaComponentRegister.RegistSyntax<NatashaCSharpSyntax>();
_hasInitialize = true;
}
}
/// <summary>
/// 初始化 Natasha 组件并预热
/// </summary>
/// <returns></returns>
public static async Task InitializeAndPreheating()
{
if (!_hasInitialize)
{
Initialize();
var action = NDelegate.RandomDomain().Action("");
action();
action.DisposeDomain();
}
}
}
| using Natasha.CSharp;
using System;
using System.Threading.Tasks;
public class NatashaInitializer
{
/// <summary>
/// 初始化 Natasha 组件
/// </summary>
public static void Initialize()
{
NatashaComponentRegister.RegistDomain<NatashaAssemblyDomain>();
NatashaComponentRegister.RegistCompiler<NatashaCSharpCompiler>();
NatashaComponentRegister.RegistSyntax<NatashaCSharpSyntax>();
}
/// <summary>
/// 初始化 Natasha 组件并预热
/// </summary>
/// <returns></returns>
public static async Task InitializeAndPreheating()
{
Initialize();
var action = NDelegate.RandomDomain().Action("");
action();
action.DisposeDomain();
}
}
| mpl-2.0 | C# |
4699ca6beade795c0df02106f8c11e1ef0a2f9e9 | Revert back strategy for ImageSource - ApplicationBundle | daniel-luberda/FFImageLoading,kalarepa/FFImageLoading,AndreiMisiukevich/FFImageLoading,molinch/FFImageLoading,petlack/FFImageLoading,luberda-molinet/FFImageLoading | FFImageLoading.Droid/Work/StreamResolver/ApplicationBundleStreamResolver.cs | FFImageLoading.Droid/Work/StreamResolver/ApplicationBundleStreamResolver.cs | using System;
using Android.Graphics.Drawables;
using System.IO;
using FFImageLoading.Work;
using Android.Content;
using Android.Content.Res;
using System.Threading.Tasks;
namespace FFImageLoading
{
public class ApplicationBundleStreamResolver : IStreamResolver
{
private Context Context {
get {
return global::Android.App.Application.Context.ApplicationContext;
}
}
public async Task<WithLoadingResult<Stream>> GetStream(string identifier)
{
return WithLoadingResult.Encapsulate(Context.Assets.Open(identifier, Access.Streaming), LoadingResult.ApplicationBundle);
}
public void Dispose() {
}
}
}
| using System;
using Android.Graphics.Drawables;
using System.IO;
using FFImageLoading.Work;
using Android.Content;
using Android.Content.Res;
using System.Threading.Tasks;
namespace FFImageLoading
{
public class ApplicationBundleStreamResolver : IStreamResolver
{
private Context Context {
get {
return global::Android.App.Application.Context.ApplicationContext;
}
}
public async Task<WithLoadingResult<Stream>> GetStream(string identifier)
{
var resourceId = Context.Resources.GetIdentifier (identifier.ToLower (), "drawable", Context.PackageName);
Stream stream = null;
if (resourceId != 0)
{
stream = Context.Resources.OpenRawResource (resourceId);
}
return WithLoadingResult.Encapsulate(stream, LoadingResult.ApplicationBundle);
}
public void Dispose() {
}
}
}
| mit | C# |
a4dadb0a2a070fa2ed65f9da06071d1fe2d4e500 | Add company name to assembly. | moxiecode/moxie,moxiecode/moxie,moxiecode/moxie,moxiecode/moxie | src/silverlight/Properties/AssemblyInfo.cs | src/silverlight/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("Moxie")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ephox")]
[assembly: AssemblyProduct("Moxie")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("56cfcb5a-d997-4823-929c-d8bbf3027007")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Moxie")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Moxie")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("56cfcb5a-d997-4823-929c-d8bbf3027007")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| agpl-3.0 | C# |
2288dded656cdc13916a159bb792f8e0eb07929d | 添加一个备注。 | yoyocms/YoYoCms.AbpProjectTemplate,yoyocms/YoYoCms.AbpProjectTemplate,yoyocms/YoYoCms.AbpProjectTemplate | src/YoYoCms.AbpProjectTemplate.WebApi/WebApi/Providers/OAuthOptions.cs | src/YoYoCms.AbpProjectTemplate.WebApi/WebApi/Providers/OAuthOptions.cs | using System;
using Abp.Dependency;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
namespace YoYoCms.AbpProjectTemplate.WebApi.Providers
{
/// <summary>
/// Class OAuthOptions.
/// </summary>
public class OAuthOptions
{
/// <summary>
/// Gets or sets the server options.
/// </summary>
/// <value>The server options.</value>
private static OAuthAuthorizationServerOptions _serverOptions;
/// <summary>
/// Creates the server options.
/// </summary>
/// <returns>OAuthAuthorizationServerOptions.</returns>
public static OAuthAuthorizationServerOptions CreateServerOptions()
{
if (_serverOptions == null)
{
var provider = IocManager.Instance.Resolve<SimpleAuthorizationServerProvider>();
var refreshTokenProvider = IocManager.Instance.Resolve<SimpleRefreshTokenProvider>();
_serverOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/oauth/token"),
Provider = provider,
RefreshTokenProvider = refreshTokenProvider,
AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(30),
AllowInsecureHttp = true
};
}
//todo:考虑在最外面包一层数据,感觉问题不大。。下午研究研究,看看可以实验下不。
return _serverOptions;
}
}
} | using System;
using Abp.Dependency;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
namespace YoYoCms.AbpProjectTemplate.WebApi.Providers
{
/// <summary>
/// Class OAuthOptions.
/// </summary>
public class OAuthOptions
{
/// <summary>
/// Gets or sets the server options.
/// </summary>
/// <value>The server options.</value>
private static OAuthAuthorizationServerOptions _serverOptions;
/// <summary>
/// Creates the server options.
/// </summary>
/// <returns>OAuthAuthorizationServerOptions.</returns>
public static OAuthAuthorizationServerOptions CreateServerOptions()
{
if (_serverOptions == null)
{
var provider = IocManager.Instance.Resolve<SimpleAuthorizationServerProvider>();
var refreshTokenProvider = IocManager.Instance.Resolve<SimpleRefreshTokenProvider>();
_serverOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/oauth/token"),
Provider = provider,
RefreshTokenProvider = refreshTokenProvider,
AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(30),
AllowInsecureHttp = true
};
}
return _serverOptions;
}
}
} | apache-2.0 | C# |
de97a90148f59183fc7b1337d78c362a47e70efc | Improve feedback on invalid key. (#12) | flamestream/taction,flamestream/taction,flamestream/taction | App/JsonConverter/KeyCommandListConverter.cs | App/JsonConverter/KeyCommandListConverter.cs | using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using WindowsInput.Native;
namespace Taction.JsonConverter {
internal class KeyCommandListConverter : Newtonsoft.Json.JsonConverter {
public override bool CanWrite => false;
public override bool CanRead => true;
public override bool CanConvert(Type objectType) {
return objectType == typeof(KeyCommand);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
throw new InvalidOperationException("Not supported");
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
var str = serializer.Deserialize<string>(reader);
var errMsg = AttemptParseValue(str, out var keyCodes);
if (errMsg != null) {
App.Instance.Config.LoadLayoutErrors.Add(string.Format("Key command input '{0}': {1}", str, errMsg));
return null;
}
var o = new KeyCommand {
KeyCodes = keyCodes
};
return o;
}
public static string AttemptParseValue(string input, out List<VirtualKeyCode> keyCodes) {
var errMsgs = new List<string>();
keyCodes = new List<VirtualKeyCode>();
// Sanity
input = input.Trim();
var keyIds = input.Split(' ');
foreach (var keyId in keyIds) {
// Sanity
if (keyId.Length == 0)
continue;
// Valid Key ID check
var enumType = typeof(VirtualKeyCode);
if (!Enum.IsDefined(enumType, keyId)) {
errMsgs.Add(string.Format("Key ID '{0}' is not valid", keyId));
continue;
}
var virtualKeyCode = (VirtualKeyCode)Enum.Parse(enumType, keyId);
keyCodes.Add(virtualKeyCode);
}
// Error exists check
if (errMsgs.Count != 0)
return string.Join("; ", errMsgs);
return null;
}
}
}
| using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using WindowsInput.Native;
namespace Taction.JsonConverter {
internal class KeyCommandListConverter : Newtonsoft.Json.JsonConverter {
public override bool CanWrite => false;
public override bool CanRead => true;
public override bool CanConvert(Type objectType) {
return objectType == typeof(KeyCommand);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
throw new InvalidOperationException("Not supported");
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
var str = serializer.Deserialize<string>(reader);
if (!TryParseValue(str, out var keyCodes))
throw new FormatException("Invalid key found");
var o = new KeyCommand {
KeyCodes = keyCodes
};
return o;
}
public static bool TryParseValue(string input, out List<VirtualKeyCode> keyCodes) {
keyCodes = new List<VirtualKeyCode>();
var keyIds = input.Split(' ');
foreach (var keyId in keyIds) {
// Valid Key ID check
var enumType = typeof(VirtualKeyCode);
if (!Enum.IsDefined(enumType, keyId))
return false;
var virtualKeyCode = (VirtualKeyCode)Enum.Parse(enumType, keyId);
keyCodes.Add(virtualKeyCode);
}
return true;
}
}
}
| mit | C# |
df6486eec49fd42e0d90ede3a783636d98c25e52 | Rework resolvers DI registration (automatic) | csf-dev/agiil,csf-dev/agiil,csf-dev/agiil,csf-dev/agiil | Agiil.Bootstrap/ObjectMaps/AutomapperResolversModule.cs | Agiil.Bootstrap/ObjectMaps/AutomapperResolversModule.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Agiil.ObjectMaps.Resolvers;
using Autofac;
namespace Agiil.Bootstrap.ObjectMaps
{
public class AutomapperResolversModule : Module
{
protected override void Load(ContainerBuilder builder)
{
var types = GetCandidateTypes();
foreach(var type in types)
{
if(type.IsGenericTypeDefinition)
{
builder.RegisterGeneric(type);
}
else
{
builder.RegisterType(type);
}
}
}
IEnumerable<Type> GetCandidateTypes()
{
var marker = typeof(IResolversNamespaceMarker);
var searchNamespace = marker.Namespace;
return (from type in marker.Assembly.GetExportedTypes()
where
type.Namespace.StartsWith(searchNamespace, StringComparison.InvariantCulture)
&& type.IsClass
&& !type.IsAbstract
&& type.IsAssignableTo<string>()
select type);
}
}
}
| using System;
using Agiil.ObjectMaps;
using Autofac;
namespace Agiil.Bootstrap.ObjectMaps
{
public class AutomapperResolversModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<IdentityValueResolver>();
builder.RegisterGeneric(typeof(GetEntityByIdentityValueResolver<>));
builder.RegisterGeneric(typeof(GetEntityByIdentityResolver<>));
builder.RegisterGeneric(typeof(CreateIdentityResolver<>));
}
}
}
| mit | C# |
8399588cfe7ce89f101c2d8f1e141bef96113fa4 | Fix typo for Currently. | tim-hoff/Xamarin.Plugins,predictive-technology-laboratory/Xamarin.Plugins,JC-Chris/Xamarin.Plugins,labdogg1003/Xamarin.Plugins,jamesmontemagno/Xamarin.Plugins,LostBalloon1/Xamarin.Plugins,monostefan/Xamarin.Plugins | Battery/Battery/Battery.Plugin.Abstractions/IBattery.cs | Battery/Battery/Battery.Plugin.Abstractions/IBattery.cs | using System;
namespace Battery.Plugin.Abstractions
{
/// <summary>
/// Interface for Battery
/// </summary>
public interface IBattery : IDisposable
{
/// <summary>
/// Current battery level 0 - 100
/// </summary>
int RemainingChargePercent { get; }
/// <summary>
/// Current status of the battery
/// </summary>
BatteryStatus Status { get; }
/// <summary>
/// Currently how the battery is being charged.
/// </summary>
PowerSource PowerSource { get; }
/// <summary>
/// Event handler when battery changes
/// </summary>
event BatteryChangedEventHandler BatteryChanged;
}
/// <summary>
/// Arguments to pass to event handlers
/// </summary>
public class BatteryChangedEventArgs : EventArgs
{
/// <summary>
/// If the battery level is considered low
/// </summary>
public bool IsLow { get; set; }
/// <summary>
/// Gets if there is an active internet connection
/// </summary>
public int RemainingChargePercent { get; set; }
/// <summary>
/// Current status of battery
/// </summary>
public BatteryStatus Status { get; set; }
/// <summary>
/// Get the source of power.
/// </summary>
public PowerSource PowerSource { get; set; }
}
/// <summary>
/// Battery Level changed event handlers
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public delegate void BatteryChangedEventHandler(object sender, BatteryChangedEventArgs e);
}
| using System;
namespace Battery.Plugin.Abstractions
{
/// <summary>
/// Interface for Battery
/// </summary>
public interface IBattery : IDisposable
{
/// <summary>
/// Current battery level 0 - 100
/// </summary>
int RemainingChargePercent { get; }
/// <summary>
/// Current status of the battery
/// </summary>
BatteryStatus Status { get; }
/// <summary>
/// Currenlty how the battery is being charged.
/// </summary>
PowerSource PowerSource { get; }
/// <summary>
/// Event handler when battery changes
/// </summary>
event BatteryChangedEventHandler BatteryChanged;
}
/// <summary>
/// Arguments to pass to event handlers
/// </summary>
public class BatteryChangedEventArgs : EventArgs
{
/// <summary>
/// If the battery level is considered low
/// </summary>
public bool IsLow { get; set; }
/// <summary>
/// Gets if there is an active internet connection
/// </summary>
public int RemainingChargePercent { get; set; }
/// <summary>
/// Current status of battery
/// </summary>
public BatteryStatus Status { get; set; }
/// <summary>
/// Get the source of power.
/// </summary>
public PowerSource PowerSource { get; set; }
}
/// <summary>
/// Battery Level changed event handlers
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public delegate void BatteryChangedEventHandler(object sender, BatteryChangedEventArgs e);
}
| mit | C# |
cc2ee36c102c127b1a73068d2ee72bec96bfb4eb | Add LocalVariables to CompleteExternalTask | jlucansky/Camunda.Api.Client | Camunda.Api.Client/ExternalTask/CompleteExternalTask.cs | Camunda.Api.Client/ExternalTask/CompleteExternalTask.cs | using System.Collections.Generic;
namespace Camunda.Api.Client.ExternalTask
{
public class CompleteExternalTask
{
/// <summary>
/// The id of the worker that completes the task. Must match the id of the worker who has most recently locked the task.
/// </summary>
public string WorkerId;
/// <summary>
/// Dictionary containing variable key-value pairs.
/// </summary>
public Dictionary<string, VariableValue> Variables;
/// <summary>
/// Dictionary containing variable key-value pairs. Local variables are set only in the scope of external task.
/// </summary>
public Dictionary<string, VariableValue> LocalVariables;
public CompleteExternalTask SetVariable(string name, object value)
{
Variables = (Variables ?? new Dictionary<string, VariableValue>()).Set(name, value);
return this;
}
/// <summary>
/// Local variables are set only in the scope of external task.
/// </summary>
public CompleteExternalTask SetLocalVariable(string name, object value)
{
LocalVariables = (LocalVariables ?? new Dictionary<string, VariableValue>()).Set(name, value);
return this;
}
}
} | using System.Collections.Generic;
namespace Camunda.Api.Client.ExternalTask
{
public class CompleteExternalTask
{
/// <summary>
/// The id of the worker that completes the task. Must match the id of the worker who has most recently locked the task.
/// </summary>
public string WorkerId;
/// <summary>
/// Dictionary containing variable key-value pairs.
/// </summary>
public Dictionary<string, VariableValue> Variables;
public CompleteExternalTask SetVariable(string name, object value)
{
Variables = (Variables ?? new Dictionary<string, VariableValue>()).Set(name, value);
return this;
}
}
} | mit | C# |
33366cb8b86189f8979e92d0f7a5354322a1df8f | migrate test to protocol builder and fix tests | cbcrc/LinkIt | HeterogeneousDataSources.Tests/LoadLinkProtocolTests.cs | HeterogeneousDataSources.Tests/LoadLinkProtocolTests.cs | using System;
using ApprovalTests.Reporters;
using HeterogeneousDataSources.Tests.Shared;
using NUnit.Framework;
namespace HeterogeneousDataSources.Tests
{
[UseReporter(typeof(DiffReporter))]
[TestFixture]
public class LoadLinkProtocolTests
{
[Test]
public void LoadLink_ShouldDisposeLoader()
{
var loadLinkProtocolBuilder = new LoadLinkProtocolBuilder();
loadLinkProtocolBuilder.For<WithoutReferenceLinkedSource>()
.IsRoot<string>();
var fakeReferenceLoader = new FakeReferenceLoader2<SingleReferenceContent, string>(reference => reference.Id);
var sut = loadLinkProtocolBuilder.Build(fakeReferenceLoader);
var actual = sut.LoadLink<WithoutReferenceLinkedSource>("dont-care");
Assert.That(fakeReferenceLoader.IsDisposed, Is.True);
}
[Test]
public void LoadLink_ModelIdIsNull_ShouldThrow() {
var loadLinkProtocolBuilder = new LoadLinkProtocolBuilder();
loadLinkProtocolBuilder.For<WithoutReferenceLinkedSource>();
var fakeReferenceLoader = new FakeReferenceLoader2<SingleReferenceContent, string>(reference => reference.Id);
var sut = loadLinkProtocolBuilder.Build(fakeReferenceLoader);
TestDelegate act = () => sut.LoadLink<WithoutReferenceLinkedSource>(null);
Assert.That(
act,
Throws
.InstanceOf<ArgumentNullException>()
.With.Message.ContainsSubstring("modelId")
);
}
[Test]
public void LoadLink_NotARootLinkedSourceType_ShouldThrow() {
var loadLinkProtocolBuilder = new LoadLinkProtocolBuilder();
loadLinkProtocolBuilder.For<WithoutReferenceLinkedSource>();
var fakeReferenceLoader = new FakeReferenceLoader2<SingleReferenceContent, string>(reference => reference.Id);
var sut = loadLinkProtocolBuilder.Build(fakeReferenceLoader);
TestDelegate act = () => sut.LoadLink<WithoutReferenceLinkedSource>("dont-care");
Assert.That(
act,
Throws.ArgumentException.With.Message.ContainsSubstring("WithoutReferenceLinkedSource")
);
}
}
public class WithoutReferenceLinkedSource : ILinkedSource<Image> {
public Image Model { get; set; }
}
} | using System;
using System.Collections.Generic;
using ApprovalTests.Reporters;
using HeterogeneousDataSources.LoadLinkExpressions;
using HeterogeneousDataSources.Tests.Shared;
using NUnit.Framework;
namespace HeterogeneousDataSources.Tests
{
[UseReporter(typeof(DiffReporter))]
[TestFixture]
public class LoadLinkProtocolTests
{
[Test]
public void LoadLink_ShouldDisposeLoader()
{
var referenceLoader = new FakeReferenceLoader();
var sut = new LoadLinkProtocol(referenceLoader,
new LoadLinkConfig(
new List<ILoadLinkExpression>{
new RootLoadLinkExpression<WithoutReferenceLinkedSource, Image, string>(),
}
)
);
var actual = sut.LoadLink<WithoutReferenceLinkedSource>("dont-care");
Assert.That(referenceLoader.IsDisposed, Is.True);
}
[Test]
public void LoadLink_ModelIdIsNull_ShouldThrow() {
var referenceLoader = new FakeReferenceLoader();
var sut = new LoadLinkProtocol(referenceLoader,
new LoadLinkConfig( new List<ILoadLinkExpression>{} )
);
TestDelegate act = () => sut.LoadLink<WithoutReferenceLinkedSource>(null);
Assert.That(
act,
Throws
.InstanceOf<ArgumentNullException>()
.With.Message.ContainsSubstring("modelId")
);
}
[Test]
public void LoadLink_NotARootLinkedSourceType_ShouldThrow() {
var referenceLoader = new FakeReferenceLoader();
var sut = new LoadLinkProtocol(referenceLoader,
new LoadLinkConfig(new List<ILoadLinkExpression> { })
);
TestDelegate act = () => sut.LoadLink<WithoutReferenceLinkedSource>("dont-care");
Assert.That(
act,
Throws.ArgumentException.With.Message.ContainsSubstring("WithoutReferenceLinkedSource")
);
}
}
public class WithoutReferenceLinkedSource : ILinkedSource<Image> {
public Image Model { get; set; }
}
} | mit | C# |
93e3b15119edb56397ae3778227dab9b22f6fe47 | Move using directives outside of namespace | fluentassertions/fluentassertions,fluentassertions/fluentassertions,dennisdoomen/fluentassertions,jnyrup/fluentassertions,dennisdoomen/fluentassertions,jnyrup/fluentassertions | Tests/FluentAssertions.Specs/Execution/IgnoringFailuresAssertionStrategy.cs | Tests/FluentAssertions.Specs/Execution/IgnoringFailuresAssertionStrategy.cs | using System.Collections.Generic;
using FluentAssertions.Execution;
namespace FluentAssertions.Specs.Execution
{
internal class IgnoringFailuresAssertionStrategy : IAssertionStrategy
{
public IEnumerable<string> FailureMessages => new string[0];
public void HandleFailure(string message)
{
}
public IEnumerable<string> DiscardFailures() => new string[0];
public void ThrowIfAny(IDictionary<string, object> context)
{
}
}
}
| namespace FluentAssertions.Specs.Execution
{
using System.Collections.Generic;
using FluentAssertions.Execution;
internal class IgnoringFailuresAssertionStrategy : IAssertionStrategy
{
public IEnumerable<string> FailureMessages => new string[0];
public void HandleFailure(string message)
{
}
public IEnumerable<string> DiscardFailures() => new string[0];
public void ThrowIfAny(IDictionary<string, object> context)
{
}
}
}
| apache-2.0 | C# |
143fb2808bcf034a1cbb4231fc19424972a22ca4 | Update CommandAttribute.cs | RogueException/Discord.Net,AntiTcb/Discord.Net | src/Discord.Net.Commands/Attributes/CommandAttribute.cs | src/Discord.Net.Commands/Attributes/CommandAttribute.cs | using System;
namespace Discord.Commands
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class CommandAttribute : Attribute
{
public string Text { get; }
public RunMode RunMode { get; set; } = RunMode.Default;
public bool? IgnoreExtraArgs { get; }
public CommandAttribute()
{
Text = null;
}
public CommandAttribute(string text)
{
Text = text;
}
public CommandAttribute(string text, bool ignoreExtraArgs)
{
Text = text;
IgnoreExtraArgs = ignoreExtraArgs;
}
}
}
| using System;
namespace Discord.Commands
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class CommandAttribute : Attribute
{
public string Text { get; }
public RunMode RunMode { get; set; } = RunMode.Default;
public bool? IgnoreExtraArgs { get; private set; }
public CommandAttribute()
{
Text = null;
}
public CommandAttribute(string text)
{
Text = text;
}
public CommandAttribute(string text, bool ignoreExtraArgs)
{
Text = text;
IgnoreExtraArgs = ignoreExtraArgs;
}
}
}
| mit | C# |
d16bba0207d4a8fbc0cab850e149b0d4ee5757ca | Update AboutBooleans.cs | NotMyself/DotNetCoreKoans | Koans/AboutBooleans.cs | Koans/AboutBooleans.cs | using Xunit;
using DotNetCoreKoans.Engine;
using System;
namespace DotNetCoreKoans.Koans
{
public class AboutBooleans : Koan
{
// The bool type represents boolean logical quantities.
// The only possible values of bool are true and false.
// No standard conversions exists between bool and other types.
// bool is a simple type and is a Alias of System.Boolean, these
// can be used interchangeably.
[Step(1)]
public void TrueIsTreatedAsTrue()
{
// true is true
Assert.Equal(true, FILL_ME_IN);
}
[Step(2)]
public void FalseIsTreatedAsFalse()
{
// false is false
Assert.Equal(false, FILL_ME_IN);
}
[Step(3)]
public void TrueIsNotFalse()
{
// true is not false
Assert.NotEqual(true, FILL_ME_IN);
}
[Step(4)]
public void BoolIsAReservedWordOfSystemBoolean()
{
// bool is a Alias of System.Boolean
Assert.Equal(typeof(System.Boolean), typeof(FillMeIn));
}
[Step(5)]
public void NoOtherTypeConvertsToBool()
{
var otherTypes = new object[]
{
"not a bool",
1, 0,
null,
new object[0]
};
foreach(var otherType in otherTypes)
{
Assert.True(otherType is bool); // no other type can cast to bool
}
}
}
}
| using Xunit;
using DotNetCoreKoans.Engine;
using System;
namespace DotNetCoreKoans.Koans
{
public class AboutBooleans : Koan
{
// The bool type represents boolean logical quantities.
// The only possible values of bool are true and false.
// No standard conversions exists between bool and other types.
// bool is a simple type and is a Alias of System.Boolean, these
// can be used interchangeably.
[Step(1)]
public void TrueIsTreatedAsTrue()
{
// true is true
Assert.Equal(true, FILL_ME_IN);
}
[Step(2)]
public void FalseIsTreatedAsFalse()
{
// false is false
Assert.Equal(false, FILL_ME_IN);
}
[Step(3)]
public void TrueIsNotFalse()
{
// true is not false
Assert.NotEqual(true, FILL_ME_IN);
}
[Step(4)]
public void BoolIsAReservedWordOfSystemBoolean()
{
// bool is a Alias of System.Boolean
Assert.Equal(typeof(System.Boolean), typeof(FillMeIn));
[Step(5)]
public void NoOtherTypeConvertsToBool()
{
var otherTypes = new object[]
{
"not a bool",
1, 0,
null,
new object[0]
};
foreach(var otherType in otherTypes)
{
Assert.True(otherType is bool); // no other type can cast to bool
}
}
}
}
| mit | C# |
9e32fde403a171e75622e4ad4e5d43076bad9173 | Add scripts folder initialization | scriptcs-contrib/scriptcs-mef | sample/ScriptCompositionSample/Program.cs | sample/ScriptCompositionSample/Program.cs | using ScriptCs.ComponentModel.Composition;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.IO;
namespace ScriptCompositionSample
{
internal class Program
{
private static void Main(string[] args)
{
var program = new Program();
program.Compose();
program.Greeter.Greet("Hello MEF1!");
}
[Import]
public IGreeter Greeter { get; set; }
public void Compose()
{
// You can add script by script
//var catalog = new ScriptCsCatalog(new[] { "Test.csx" }, typeof(IGreeter));
// Or an entire folder
InitializeScripts();
var catalog = new ScriptCsCatalog("Scripts", typeof(IGreeter));
var container = new CompositionContainer(catalog);
var batch = new CompositionBatch();
batch.AddPart(this);
container.Compose(batch);
}
private void InitializeScripts()
{
if (!Directory.Exists("Scripts"))
{
Directory.CreateDirectory("Scripts");
}
File.Copy("Test.csx", "Scripts/Test.csx");
}
}
} | using ScriptCs.ComponentModel.Composition;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
namespace ScriptCompositionSample
{
internal class Program
{
private static void Main(string[] args)
{
var program = new Program();
program.Compose();
program.Greeter.Greet("Hello MEF1!");
}
[Import]
public IGreeter Greeter { get; set; }
public void Compose()
{
//var catalog = new ScriptCsCatalog(new[] { "Test.csx" }, typeof(IGreeter));
var catalog = new ScriptCsCatalog("Scripts", typeof(IGreeter));
var container = new CompositionContainer(catalog);
var batch = new CompositionBatch();
batch.AddPart(this);
container.Compose(batch);
}
}
} | apache-2.0 | C# |
2eabd87fcfc5886a6bec66d6b45d964d66af59aa | Tweak pluralisation method (TODO: rules) | markembling/MarkEmbling.Utilities,markembling/MarkEmbling.Utils | MarkEmbling.Utils/Extensions/StringGrammarExtensions.cs | MarkEmbling.Utils/Extensions/StringGrammarExtensions.cs | using System.Collections.Generic;
using MarkEmbling.Utils.Grammar;
using MarkEmbling.Utils.Grammar.Rules;
namespace MarkEmbling.Utils.Extensions {
public static class StringGrammarExtensions {
/// <summary>
/// Apply the given grammar rules to the input string
/// </summary>
/// <param name="str">Current string instance</param>
/// <param name="rules">Rules to apply</param>
public static string PerformGrammarTransformation(this string str, IEnumerable<IGrammarTransformRule> rules) {
var transformer = new GrammarTransformer(rules);
return transformer.Transform(str);
}
/// <summary>
/// Apply default (naive English) pluralisation rules based on count
/// </summary>
/// <param name="str">Current string instance</param>
/// <param name="count">Number to apply pluralisation rules against</param>
public static string Pluralise(this string str, int count) {
return count == 1 ?
str :
PerformGrammarTransformation(str, DefaultRuleSets.Plural);
//return Pluralise(str, count, str + "s");
}
/// <summary>
/// Return either the single form (the current string) or the given plural form,
/// based on the provided count.
/// </summary>
/// <param name="str">Current string instance</param>
/// <param name="count">Number to apply pluralisation rules against</param>
/// <param name="multipleForm">Alternate plural form of the word</param>
public static string Pluralise(this string str, int count, string multipleForm) {
return count == 1 ? str : multipleForm;
}
/// <summary>
/// Apply default (naive English) possession rules
/// </summary>
/// <param name="str">Current string instance</param>
public static string Possessive(this string str) {
return PerformGrammarTransformation(str, DefaultRuleSets.Possessive);
}
}
} | using System.Collections.Generic;
using MarkEmbling.Utils.Grammar;
using MarkEmbling.Utils.Grammar.Rules;
namespace MarkEmbling.Utils.Extensions {
public static class StringGrammarExtensions {
/// <summary>
/// Return either the single form (the current string) or the given plural form,
/// based on the provided count.
/// </summary>
/// <param name="str">Current string instance</param>
/// <param name="count">Number to apply pluralisation rules against</param>
/// <param name="multipleForm">Alternate plural form of the word</param>
public static string Pluralise(this string str, int count, string multipleForm) {
// Note than .NET 4 also has PluralizationService inside System.Data.Entity.Design,
// but that would then cause a dependancy on the full .NET 4.0 framework (i.e. not
// work under the client profile. I'm not happy to do that...
return count == 1 ? str : multipleForm;
}
/// <summary>
/// Naive pluralisation method (simply adds an S to the end of the word if the
/// given count is not one.
/// </summary>
/// <param name="str">Current string instance</param>
/// <param name="count">Number to apply pluralisation rules against</param>
public static string Pluralise(this string str, int count) {
return Pluralise(str, count, str + "s");
}
/// <summary>
/// Apply default (naive English) possession rules
/// </summary>
/// <param name="str">Current string instance</param>
public static string Possessive(this string str) {
return PerformGrammarTransformation(str, DefaultRuleSets.Possessive);
}
/// <summary>
/// Apply the given grammar rules to the input string
/// </summary>
/// <param name="str">Current string instance</param>
/// <param name="rules">Rules to apply</param>
public static string PerformGrammarTransformation(this string str, IEnumerable<IGrammarTransformRule> rules) {
var transformer = new GrammarTransformer(rules);
return transformer.Transform(str);
}
}
} | mit | C# |
ed2c36202d804ff86b757764f61500dfd2ecf361 | Update GetEquipmentItemByIdQuery.cs | NinjaVault/NinjaHive,NinjaVault/NinjaHive | NinjaHive.Contract/Queries/GetEquipmentItemByIdQuery.cs | NinjaHive.Contract/Queries/GetEquipmentItemByIdQuery.cs | using System;
using NinjaHive.Contract.DTOs;
using NinjaHive.Core;
namespace NinjaHive.Contract.Queries
{
public class GetEquipmentItemByIdQuery : IQuery<EquipmentItem>
{
public Guid EquipmentItemId { get; set; }
}
}
| using System;
using NinjaHive.Contract.DTOs;
using NinjaHive.Core;
namespace NinjaHive.Contract.Queries
{
public class GetEquipmentItemByIdQuery : IQuery<EquipmentItem>
{
public Guid EquipmentItemId;
}
}
| apache-2.0 | C# |
6410efe0b63d17a96ab7ed66c390dffb0de6b6af | remove area registration | Pondidum/NuCache,Pondidum/NuCache,Pondidum/NuCache | NuCache/Global.asax.cs | NuCache/Global.asax.cs | using System.Web;
using System.Web.Http;
namespace NuCache
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class WebApiApplication : HttpApplication
{
protected void Application_Start()
{
ConfigureContainer.Register(GlobalConfiguration.Configuration);
ConfigureRoutes.Register(GlobalConfiguration.Configuration);
ConfigureErrorHandling.Register(GlobalConfiguration.Configuration);
}
}
} | using System.Web;
using System.Web.Http;
using System.Web.Mvc;
namespace NuCache
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class WebApiApplication : HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
ConfigureContainer.Register(GlobalConfiguration.Configuration);
ConfigureRoutes.Register(GlobalConfiguration.Configuration);
ConfigureErrorHandling.Register(GlobalConfiguration.Configuration);
}
}
} | lgpl-2.1 | C# |
8d55f080823eeb72d7643eca8bcb42cd0a7923f7 | Modify AssemblyFileVersion dependent on icu_ver build type | conniey/icu-dotnet,ermshiperete/icu-dotnet,conniey/icu-dotnet,sillsdev/icu-dotnet,sillsdev/icu-dotnet,ermshiperete/icu-dotnet | source/icu.net/Properties/AssemblyInfo.cs | source/icu.net/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("icu.net")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SIL International")]
[assembly: AssemblyProduct("icu.net")]
[assembly: AssemblyCopyright("Copyright © SIL International 2007")]
[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("3439151b-347b-4321-9f2f-d5fa28b46477")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
// (The AssemblyVersion needs to match the version that Palaso builds against.)
// (The AssemblyFileVersion matches the ICU version number we're building against.)
[assembly: AssemblyVersion("4.2.1.0")]
#if ICU_VERSION_40
[assembly: AssemblyFileVersion("4.2.1.*")]
#if ICU_VERSION_48
[assembly: AssemblyFileVersion("4.8.1.1")]
#else
[assembly: AssemblyFileVersion("5.0.0.2")]
#endif
//Location of the public/private key pair for strong naming this assembly --TA 7 Oct 2008
[assembly: AssemblyKeyFile("icu.net.snk")]
| 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("icu.net")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SIL International")]
[assembly: AssemblyProduct("icu.net")]
[assembly: AssemblyCopyright("Copyright © SIL International 2007")]
[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("3439151b-347b-4321-9f2f-d5fa28b46477")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
// (The AssemblyVersion needs to match the version that Palaso builds against.)
// (The AssemblyFileVersion matches the ICU version number we're building against.)
[assembly: AssemblyVersion("4.2.1.0")]
[assembly: AssemblyFileVersion("4.8.1.1")]
//Location of the public/private key pair for strong naming this assembly --TA 7 Oct 2008
[assembly: AssemblyKeyFile("icu.net.snk")]
| mit | C# |
a6cf1f900c16edb73fed4f664fe181e4864c3964 | Comment change | belgaard/Leantest,belgaard/Leantest,belgaard/Leantest | AspNetCore/LeanTestWebApplicationFactory.cs | AspNetCore/LeanTestWebApplicationFactory.cs | using System;
using LeanTest.Core.ExecutionHandling;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
namespace LeanTest
{
/// <summary>
/// This web application factory encapsulates factories for initializing a composition root and an IoC container, respectively.
/// These factories are used to create a context builder in the implementation of the <c>ICreateContextBuilder</c> interface.
/// The .NET Core web application factory is documented here
/// https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.testing.webapplicationfactory-1?view=aspnetcore-3.0
/// </summary>
/// <typeparam name="TEntryPoint">The entry point, typically the <c>Startup</c> class.</typeparam>
/// <remarks>
/// - Note that lean testing encourages that a context builder, and thus the IoC container, is created from scratch before each test.
/// This class makes it easy to follow this principle.
/// - This web application factory has been designed to be used with the ContextBuilderFactory.Initialize which takes an ICreateContextBuilder interface
/// as a parameter. Note that unlike the initialisation methods of AspNetCoreContextBuilderFactory, there is no automatic disposing of the factory -
/// you have to do that yourself in in each test class through the IFactoryAccess interface on the context builder.</remarks>
public class LeanTestWebApplicationFactory<TEntryPoint> : WebApplicationFactory<TEntryPoint>, IFactoryAccess, ICreateContextBuilder where TEntryPoint : class
{
private readonly Action<IServiceCollection> _initializeCompositionRoot;
private readonly Func<IServiceProvider, IIocContainer> _iocContainerFactory;
/// <summary>ctor</summary>
/// <param name="initializeCompositionRoot">Factory for initializing the composition root.</param>
/// <param name="iocContainerFactory">Factory for creating an IoC container fro scratch.</param>
public LeanTestWebApplicationFactory(Action<IServiceCollection> initializeCompositionRoot, Func<IServiceProvider, IIocContainer> iocContainerFactory)
{
_initializeCompositionRoot = initializeCompositionRoot;
_iocContainerFactory = iocContainerFactory;
}
/// <inheritdoc />
public ContextBuilder CreateContextBuilder => new WebApplicationFactoryContextBuilder<TEntryPoint>(this, _iocContainerFactory(Services));
/// <inheritdoc />
protected override void ConfigureWebHost(IWebHostBuilder builder) => builder.ConfigureTestServices(_initializeCompositionRoot);
}
} | using System;
using LeanTest.Core.ExecutionHandling;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
namespace LeanTest
{
/// <summary>
/// This web application factory encapsulates factories for initializing a composition root and an IoC container, respectively.
/// These factories are used to create a context builder in the implementation of the <c>ICreateContextBuilder</c> interface.
/// The .NET Core web application factory is documented here
/// https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.testing.webapplicationfactory-1?view=aspnetcore-3.0&viewFallbackFrom=aspnetcore-3.1
/// </summary>
/// <typeparam name="TEntryPoint">The entry point, typically the <c>Startup</c> class.</typeparam>
/// <remarks>
/// - Note that lean testing encourages that a context builder, and thus the IoC container, is created from scratch before each test.
/// This class makes it easy to follow this principle.
/// - This web application factory has been designed to be used with the ContextBuilderFactory.Initialize which takes an ICreateContextBuilder interface
/// as a parameter. Note that unlike the initialisation methods of AspNetCoreContextBuilderFactory, there is no automatic disposing of the factory -
/// you have to do that yourself in in each test class through the IFactoryAccess interface on the context builder.</remarks>
public class LeanTestWebApplicationFactory<TEntryPoint> : WebApplicationFactory<TEntryPoint>, IFactoryAccess, ICreateContextBuilder where TEntryPoint : class
{
private readonly Action<IServiceCollection> _initializeCompositionRoot;
private readonly Func<IServiceProvider, IIocContainer> _iocContainerFactory;
/// <summary>ctor</summary>
/// <param name="initializeCompositionRoot">Factory for initializing the composition root.</param>
/// <param name="iocContainerFactory">Factory for creating an IoC container fro scratch.</param>
public LeanTestWebApplicationFactory(Action<IServiceCollection> initializeCompositionRoot, Func<IServiceProvider, IIocContainer> iocContainerFactory)
{
_initializeCompositionRoot = initializeCompositionRoot;
_iocContainerFactory = iocContainerFactory;
}
/// <inheritdoc />
public ContextBuilder CreateContextBuilder => new WebApplicationFactoryContextBuilder<TEntryPoint>(this, _iocContainerFactory(Services));
/// <inheritdoc />
protected override void ConfigureWebHost(IWebHostBuilder builder) => builder.ConfigureTestServices(_initializeCompositionRoot);
}
} | mit | C# |
6381152047d377529d84c1bce600e6f16953699d | Send back result in OpenLink | github/VisualStudio,github/VisualStudio,github/VisualStudio | src/GitHub.VisualStudio/Menus/OpenLink.cs | src/GitHub.VisualStudio/Menus/OpenLink.cs | using GitHub.Extensions;
using GitHub.Services;
using Microsoft.VisualStudio.Shell;
using System;
using System.ComponentModel.Composition;
using NullGuard;
using System.Threading.Tasks;
using GitHub.Api;
namespace GitHub.VisualStudio.Menus
{
[Export(typeof(IDynamicMenuHandler))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class OpenLink: LinkMenuBase, IDynamicMenuHandler
{
[ImportingConstructor]
public OpenLink([Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider, ISimpleApiClientFactory apiFactory)
: base(serviceProvider, apiFactory)
{
}
public Guid Guid => GuidList.guidContextMenuSet;
public int CmdId => PkgCmdIDList.openLinkCommand;
public async void Activate([AllowNull]object data = null)
{
var isgithub = await IsGitHubRepo();
if (!isgithub)
return;
var link = GenerateLink();
if (link == null)
return;
var browser = ServiceProvider.GetExportedValue<IVisualStudioBrowser>();
browser?.OpenUrl(link.ToUri());
}
public bool CanShow()
{
Task<bool> githubRepoCheckTask = IsGitHubRepo();
githubRepoCheckTask.Wait(250);
return githubRepoCheckTask.Result;
}
}
}
| using GitHub.Extensions;
using GitHub.Services;
using Microsoft.VisualStudio.Shell;
using System;
using System.ComponentModel.Composition;
using NullGuard;
using System.Threading.Tasks;
using GitHub.Api;
namespace GitHub.VisualStudio.Menus
{
[Export(typeof(IDynamicMenuHandler))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class OpenLink: LinkMenuBase, IDynamicMenuHandler
{
[ImportingConstructor]
public OpenLink([Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider, ISimpleApiClientFactory apiFactory)
: base(serviceProvider, apiFactory)
{
}
public Guid Guid => GuidList.guidContextMenuSet;
public int CmdId => PkgCmdIDList.openLinkCommand;
public async void Activate([AllowNull]object data = null)
{
var isgithub = await IsGitHubRepo();
if (!isgithub)
return;
var link = GenerateLink();
if (link == null)
return;
var browser = ServiceProvider.GetExportedValue<IVisualStudioBrowser>();
browser?.OpenUrl(link.ToUri());
}
public bool CanShow()
{
return IsGitHubRepo().Wait(250);
}
}
}
| mit | C# |
4160ec5f36bdc98454c2df66bf87c6ef99500743 | Update _Layout.cshtml | pacoferre/polymercrud,pacoferre/polymercrud,pacoferre/polymercrud | src/PolymerCRUD/Views/Shared/_Layout.cshtml | src/PolymerCRUD/Views/Shared/_Layout.cshtml | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="generator" content="Polymer CRUD">
<title>@ViewData["Title"] - Polymer CRUD</title>
<!-- Place favicon.ico in the `app/` directory -->
<!-- Chrome for Android theme color -->
<meta name="theme-color" content="#2E3AA1">
<!-- Web Application Manifest -->
<link rel="manifest" href="manifest.json">
<!-- Tile color for Win8 -->
<meta name="msapplication-TileColor" content="#3372DF">
<!-- Add to homescreen for Chrome on Android -->
<meta name="mobile-web-app-capable" content="yes">
<meta name="application-name" content="PSK">
<link rel="icon" sizes="192x192" href="images/touch/chrome-touch-icon-192x192.png">
<!-- Add to homescreen for Safari on iOS -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Polymer CRUD">
<link rel="apple-touch-icon" href="images/touch/apple-touch-icon.png">
<!-- Tile icon for Win8 (144x144) -->
<meta name="msapplication-TileImage" content="images/touch/ms-touch-icon-144x144-precomposed.png">
<!-- Because this project uses vulcanize this should be your only html import
in this file. All other imports should go in elements.html -->
<link rel="import" href="~/elements/elements.html">
@RenderSection("subelements", required: false)
<!-- For shared styles, shared-styles.html import in elements.html -->
<style is="custom-style" include="shared-styles"></style>
<environment names="Development">
<link rel="stylesheet" href="~/css/main.css" />
<script src="~/lib/webcomponentsjs/webcomponents-lite.js" asp-append-version="true"></script>
</environment>
<environment names="Staging,Production">
<link rel="stylesheet" href="~/css/main.min.css" asp-append-version="true" />
<script src="~/lib/webcomponentsjs/webcomponents-lite.js" asp-append-version="true"></script>
</environment>
</head>
<body unresolved>
@RenderBody()
@*<environment names="Development">
<script src="~/js/app.js" asp-append-version="true"></script>
</environment>
<environment names="Staging,Production">
<script src="~/js/app.min.js" asp-append-version="true"></script>
</environment>*@
@RenderSection("scripts", required: false)
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="generator" content="Polymer CRUD">
<title>@ViewData["Title"] - Polymer CRUD</title>
<!-- Place favicon.ico in the `app/` directory -->
<!-- Chrome for Android theme color -->
<meta name="theme-color" content="#2E3AA1">
<!-- Web Application Manifest -->
<link rel="manifest" href="manifest.json">
<!-- Tile color for Win8 -->
<meta name="msapplication-TileColor" content="#3372DF">
<!-- Add to homescreen for Chrome on Android -->
<meta name="mobile-web-app-capable" content="yes">
<meta name="application-name" content="PSK">
<link rel="icon" sizes="192x192" href="images/touch/chrome-touch-icon-192x192.png">
<!-- Add to homescreen for Safari on iOS -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Social Wave Deck">
<link rel="apple-touch-icon" href="images/touch/apple-touch-icon.png">
<!-- Tile icon for Win8 (144x144) -->
<meta name="msapplication-TileImage" content="images/touch/ms-touch-icon-144x144-precomposed.png">
<!-- Because this project uses vulcanize this should be your only html import
in this file. All other imports should go in elements.html -->
<link rel="import" href="~/elements/elements.html">
@RenderSection("subelements", required: false)
<!-- For shared styles, shared-styles.html import in elements.html -->
<style is="custom-style" include="shared-styles"></style>
<environment names="Development">
<link rel="stylesheet" href="~/css/main.css" />
<script src="~/lib/webcomponentsjs/webcomponents-lite.js" asp-append-version="true"></script>
</environment>
<environment names="Staging,Production">
<link rel="stylesheet" href="~/css/main.min.css" asp-append-version="true" />
<script src="~/lib/webcomponentsjs/webcomponents-lite.js" asp-append-version="true"></script>
</environment>
</head>
<body unresolved>
@RenderBody()
@*<environment names="Development">
<script src="~/js/app.js" asp-append-version="true"></script>
</environment>
<environment names="Staging,Production">
<script src="~/js/app.min.js" asp-append-version="true"></script>
</environment>*@
@RenderSection("scripts", required: false)
</body>
</html>
| mit | C# |
be6bf65c1120fda0b0f585bb3dd51d2f1577eab6 | Fix unnecessary cast reported by R# | fearthecowboy/pinvoke,AArnott/pinvoke,jmelosegui/pinvoke,vbfox/pinvoke | src/Windows.Core.Tests/NullableGuidTests.cs | src/Windows.Core.Tests/NullableGuidTests.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.
using System;
using PInvoke;
using Xunit;
public class NullableGuidTests
{
private readonly Guid testGuid = Guid.NewGuid();
[Fact]
public void ConstructorSetValue()
{
Assert.Equal(new NullableGuid(this.testGuid).Value, this.testGuid);
Assert.Equal(new NullableGuid().Value, default(Guid));
}
[Fact]
public void CanCastToNullableGuid()
{
Assert.Equal(((NullableGuid)this.testGuid).Value, this.testGuid);
Assert.Equal((NullableGuid)((Guid?)null), null);
Assert.Equal(((NullableGuid)((Guid?)this.testGuid)).Value, this.testGuid);
}
[Fact]
public void CanCastFromNullableGuid()
{
Assert.Equal((Guid)((NullableGuid)this.testGuid), this.testGuid);
Assert.Equal((Guid?)((NullableGuid)this.testGuid), this.testGuid);
Assert.Equal((Guid?)((NullableGuid)null), null);
}
[Fact]
public void CastFromNullableGuidToInt32ThrowOnNull()
{
Assert.Throws<ArgumentNullException>(() =>
(Guid)((NullableGuid)null));
}
} | // 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.
using System;
using PInvoke;
using Xunit;
public class NullableGuidTests
{
private readonly Guid testGuid = Guid.NewGuid();
[Fact]
public void ConstructorSetValue()
{
Assert.Equal(new NullableGuid(this.testGuid).Value, (Guid)this.testGuid);
Assert.Equal(new NullableGuid().Value, default(Guid));
}
[Fact]
public void CanCastToNullableGuid()
{
Assert.Equal(((NullableGuid)this.testGuid).Value, (Guid)this.testGuid);
Assert.Equal((NullableGuid)((Guid?)null), null);
Assert.Equal(((NullableGuid)((Guid?)this.testGuid)).Value, (Guid)this.testGuid);
}
[Fact]
public void CanCastFromNullableGuid()
{
Assert.Equal((Guid)((NullableGuid)this.testGuid), (Guid)this.testGuid);
Assert.Equal((Guid?)((NullableGuid)this.testGuid), (Guid?)this.testGuid);
Assert.Equal((Guid?)((NullableGuid)null), null);
}
[Fact]
public void CastFromNullableGuidToInt32ThrowOnNull()
{
Assert.Throws<ArgumentNullException>(() =>
(Guid)((NullableGuid)null));
}
} | mit | C# |
a38546a8d54e77111fddf30623106016b16130d9 | fix ChangePassword style | Jeffiy/ZBlog-Net,Jeffiy/ZBlog-Net,Jeffiy/ZBlog-Net | src/ZBlog/Views/Admin/ChangePassword.cshtml | src/ZBlog/Views/Admin/ChangePassword.cshtml | @model ChangePasswordViewModel
@{
ViewData["Title"] = "Change Password";
}
<h2>@ViewData["Title"]</h2>
<form asp-controller="Admin" asp-action="ChangePassword" method="post" class="form-horizontal" role="form">
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<div class="am-form-group">
<label asp-for="OldPassword" class="col-md-2 am-form-label"></label>
<div class="col-md-10">
<input asp-for="OldPassword" class="am-form-field" />
<span asp-validation-for="OldPassword" class="text-danger"></span>
</div>
</div>
<div class="am-form-group">
<label asp-for="NewPassword" class="col-md-2 am-form-label"></label>
<div class="col-md-10">
<input asp-for="NewPassword" class="am-form-field" />
<span asp-validation-for="NewPassword" class="text-danger"></span>
</div>
</div>
<div class="am-form-group">
<label asp-for="ConfirmPassword" class="col-md-2 am-form-label"></label>
<div class="col-md-10">
<input asp-for="ConfirmPassword" class="am-form-field" />
<span asp-validation-for="ConfirmPassword" class="text-danger"></span>
</div>
</div>
<div class="am-form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="am-btn am-btn-primary">Change password</button>
</div>
</div>
</form>
@section Scripts {
@{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}
| @model ChangePasswordViewModel
@{
ViewData["Title"] = "Change Password";
}
<h2>@ViewData["Title"].</h2>
<form asp-controller="Manage" asp-action="ChangePassword" method="post" class="form-horizontal" role="form">
<h4>Change Password Form</h4>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="OldPassword" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="OldPassword" class="form-control" />
<span asp-validation-for="OldPassword" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="NewPassword" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="NewPassword" class="form-control" />
<span asp-validation-for="NewPassword" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="ConfirmPassword" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="ConfirmPassword" class="form-control" />
<span asp-validation-for="ConfirmPassword" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-default">Change password</button>
</div>
</div>
</form>
@section Scripts {
@{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}
| mit | C# |
4c17e697641fc0fd3320973157c15a967b234793 | Fix non-Windows builds. | ejball/XmlDocMarkdown | tools/Build/Build.cs | tools/Build/Build.cs | using System;
using System.Linq;
using Faithlife.Build;
using static Faithlife.Build.BuildUtility;
using static Faithlife.Build.DotNetRunner;
return BuildRunner.Execute(args, build =>
{
var dotNetBuildSettings = new DotNetBuildSettings
{
NuGetApiKey = Environment.GetEnvironmentVariable("NUGET_API_KEY"),
};
build.AddDotNetTargets(dotNetBuildSettings);
build.Target("generate-docs")
.Describe("Generates documentation")
.DependsOn("build")
.Does(() => GenerateDocs(verify: false));
build.Target("verify-docs")
.Describe("Verifies generated documentation")
.DependsOn("build")
.Does(() => GenerateDocs(verify: true));
build.Target("test")
.DependsOn("verify-docs");
void GenerateDocs(bool verify)
{
var configuration = dotNetBuildSettings.GetConfiguration();
var projects = new[]
{
("XmlDocMarkdown.Core", "../src/XmlDocMarkdown.Core"),
("ExampleAssembly", "../tests/ExampleAssembly"),
};
var xmlDocGenPath = FindFiles($"tools/XmlDocGen/bin/{configuration}/net*/XmlDocGen.dll").First();
foreach (var (assembly, sourcePath) in projects)
RunDotNet(xmlDocGenPath, assembly, "docs", verify ? "--verify" : null, "--source", sourcePath, "--newline", "lf", "--clean");
}
});
| using System;
using System.Linq;
using Faithlife.Build;
using static Faithlife.Build.AppRunner;
using static Faithlife.Build.BuildUtility;
return BuildRunner.Execute(args, build =>
{
var dotNetBuildSettings = new DotNetBuildSettings
{
NuGetApiKey = Environment.GetEnvironmentVariable("NUGET_API_KEY"),
};
build.AddDotNetTargets(dotNetBuildSettings);
build.Target("generate-docs")
.Describe("Generates documentation")
.DependsOn("build")
.Does(() => GenerateDocs(verify: false));
build.Target("verify-docs")
.Describe("Verifies generated documentation")
.DependsOn("build")
.Does(() => GenerateDocs(verify: true));
build.Target("test")
.DependsOn("verify-docs");
void GenerateDocs(bool verify)
{
var configuration = dotNetBuildSettings.GetConfiguration();
var projects = new[]
{
new[] { "XmlDocMarkdown.Core", "docs", verify ? "--verify" : null, "--source", "../src/XmlDocMarkdown.Core", "--newline", "lf", "--clean" },
new[] { "ExampleAssembly", "docs", verify ? "--verify" : null, "--source", "../tests/ExampleAssembly", "--newline", "lf", "--clean" },
};
var xmlDocGenPath = FindFiles($"tools/XmlDocGen/bin/{configuration}/net*/XmlDocGen.exe").First();
foreach (var args in projects)
RunApp(xmlDocGenPath, new AppRunnerSettings { Arguments = args, IsFrameworkApp = true });
}
});
| mit | C# |
4671fc6c71c539f354dfd9d5d776761298e4d244 | Update MvxPresenterHelpers.cs | Cheesebaron/Cheesebaron.MvxPlugins,Ideine/Cheesebaron.MvxPlugins,Ideine/Cheesebaron.MvxPlugins,Cheesebaron/Cheesebaron.MvxPlugins | FormsPresenters/Core/MvxPresenterHelpers.cs | FormsPresenters/Core/MvxPresenterHelpers.cs | // MvxPresenterHelpers.cs
// 2015 (c) Copyright Cheesebaron. http://ostebaronen.dk
// Cheesebaron.MvxPlugins.FormsPresenters is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Tomasz Cielecii, @cheesebaron, mvxplugins@ostebaronen.dk
using System;
using System.Linq;
using System.Reflection;
using Cirrious.CrossCore;
using Cirrious.CrossCore.IoC;
using Cirrious.MvvmCross.ViewModels;
using Xamarin.Forms;
namespace Cheesebaron.MvxPlugins.FormsPresenters.Core
{
public static class MvxPresenterHelpers
{
public static IMvxViewModel LoadViewModel(MvxViewModelRequest request)
{
var viewModelLoader = Mvx.Resolve<IMvxViewModelLoader>();
var viewModel = viewModelLoader.LoadViewModel(request, null);
return viewModel;
}
public static Page CreatePage(MvxViewModelRequest request)
{
var viewModelName = request.ViewModelType.Name;
var pageName = viewModelName.Replace("ViewModel", "Page");
var pageType = request.ViewModelType.GetTypeInfo().Assembly.CreatableTypes()
.FirstOrDefault(t => t.Name == pageName);
if (pageType == null)
{
Mvx.Trace("Page not found for {0}", pageName);
return null;
}
var page = Activator.CreateInstance(pageType) as Page;
if (page == null)
{
Mvx.Error("Failed to create ContentPage {0}", pageName);
}
return page;
}
}
}
| using System;
using System.Linq;
using System.Reflection;
using Cirrious.CrossCore;
using Cirrious.CrossCore.IoC;
using Cirrious.MvvmCross.ViewModels;
using Xamarin.Forms;
namespace Cheesebaron.MvxPlugins.FormsPresenters.Core
{
public static class MvxPresenterHelpers
{
public static IMvxViewModel LoadViewModel(MvxViewModelRequest request)
{
var viewModelLoader = Mvx.Resolve<IMvxViewModelLoader>();
var viewModel = viewModelLoader.LoadViewModel(request, null);
return viewModel;
}
public static Page CreatePage(MvxViewModelRequest request)
{
var viewModelName = request.ViewModelType.Name;
var pageName = viewModelName.Replace("ViewModel", "Page");
var pageType = request.ViewModelType.GetTypeInfo().Assembly.CreatableTypes()
.FirstOrDefault(t => t.Name == pageName);
if (pageType == null)
{
Mvx.Trace("Page not found for {0}", pageName);
return null;
}
var page = Activator.CreateInstance(pageType) as Page;
if (page == null)
{
Mvx.Error("Failed to create ContentPage {0}", pageName);
}
return page;
}
}
}
| apache-2.0 | C# |
51ea2068329d46feefa98e45261489534a69641b | 添加数据库连接、接收http返回、登录、注册等功能 | RS-GIS-Geeks/View-Spot-of-City | View-Spot-of-City/View-Spot-of-City/App.xaml.cs | View-Spot-of-City/View-Spot-of-City/App.xaml.cs | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using View_Spot_of_City.helper;
using View_Spot_of_City.UIControls.Helper;
using View_Spot_of_City.UIControls.Progress;
using View_Spot_of_City.UIControls.Form;
using System.Windows.Media;
namespace View_Spot_of_City
{
/// <summary>
/// App.xaml 的交互逻辑
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
//(new LoginDlg()).ShowDialog();
//验证License
if (!RegisterMaster.CanStart())
{
Environment.Exit(0);
}
base.OnStartup(e);
}
}
}
| using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using View_Spot_of_City.helper;
using View_Spot_of_City.UIControls.Helper;
using View_Spot_of_City.UIControls.Progress;
using View_Spot_of_City.UIControls.Form;
using System.Windows.Media;
namespace View_Spot_of_City
{
/// <summary>
/// App.xaml 的交互逻辑
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
(new LoginDlg()).ShowDialog();
//验证License
if (!RegisterMaster.CanStart())
{
Environment.Exit(0);
}
base.OnStartup(e);
}
}
}
| apache-2.0 | C# |
4c9cfdfa49f996de82b0cd00944e518a8028fd3e | Refactor MetallKefer, convert health and speed to public | emazzotta/unity-tower-defense | Assets/Scripts/MetallKefer.cs | Assets/Scripts/MetallKefer.cs | using UnityEngine;
using System.Collections;
public class MetallKefer : MonoBehaviour {
private GameController game;
private GameObject[] baseBuildable;
private GameObject nextWaypiont;
private int currentWaypointIndex = 0;
public int health;
public int movementSpeed;
void Start () {
this.game = GameObject.FindObjectOfType<GameController>();
this.nextWaypiont = this.game.getWaypoints () [this.currentWaypointIndex];
this.setInitialPosition ();
}
void Update() {
this.moveToNextWaypoint ();
if (this.transform.position.Equals( this.nextWaypiont.transform.position )) {
this.SetNextWaypoint ();
}
}
void SetNextWaypoint() {
if (this.currentWaypointIndex < this.game.getWaypoints ().Length - 1) {
this.currentWaypointIndex += 1;
this.nextWaypiont = this.game.getWaypoints () [this.currentWaypointIndex];
this.nextWaypiont.GetComponent<Renderer> ().material.color = Utils.getRandomColor();
}
}
private void setInitialPosition() {
this.transform.position = this.nextWaypiont.transform.position;
}
private void moveToNextWaypoint() {
float step = movementSpeed * Time.deltaTime;
Vector3 lookRotation = nextWaypiont.transform.position - this.transform.position;
if (lookRotation != Vector3.zero) {
var targetRotation = Quaternion.LookRotation(lookRotation);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 5 * Time.deltaTime);
this.transform.position = Vector3.MoveTowards(transform.position, this.nextWaypiont.transform.position, step);
}
}
public void TakeDamage(int damage) {
health -= damage;
if (this.gameObject && health <= 0) {
Destroy (this.gameObject);
}
}
public int GetHealth() {
return this.health;
}
}
| using UnityEngine;
using System.Collections;
public class MetallKefer : MonoBehaviour {
private GameController game;
private GameObject[] baseBuildable;
private GameObject nextWaypiont;
private int health;
private int currentWaypointIndex = 0;
private int movementSpeed = 2;
void Start () {
this.health = 100;
this.game = GameObject.FindObjectOfType<GameController>();
this.nextWaypiont = this.game.getWaypoints () [this.currentWaypointIndex];
this.setInitialPosition ();
}
void Update() {
this.moveToNextWaypoint ();
if (this.transform.position.Equals( this.nextWaypiont.transform.position )) {
this.SetNextWaypoint ();
}
}
void SetNextWaypoint() {
if (this.currentWaypointIndex < this.game.getWaypoints ().Length - 1) {
this.currentWaypointIndex += 1;
this.nextWaypiont = this.game.getWaypoints () [this.currentWaypointIndex];
this.nextWaypiont.GetComponent<Renderer> ().material.color = Utils.getRandomColor();
}
}
private void setInitialPosition() {
this.transform.position = this.nextWaypiont.transform.position;
}
private void moveToNextWaypoint() {
float step = movementSpeed * Time.deltaTime;
Vector3 lookRotation = nextWaypiont.transform.position - this.transform.position;
if (lookRotation != Vector3.zero) {
var targetRotation = Quaternion.LookRotation(lookRotation);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 5 * Time.deltaTime);
this.transform.position = Vector3.MoveTowards(transform.position, this.nextWaypiont.transform.position, step);
}
}
public void TakeDamage(int damage) {
health -= damage;
if (this.gameObject && health <= 0) {
Destroy (this.gameObject);
}
}
public int GetHealth() {
return this.health;
}
}
| mit | C# |
78994f95872e4ba6084123788a0a8a13af6d53d4 | Update Property.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D | src/Core2D/ViewModels/Data/Property.cs | src/Core2D/ViewModels/Data/Property.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using Core2D.Attributes;
namespace Core2D.Data
{
/// <summary>
/// Data property.
/// </summary>
public class Property : ObservableObject, IProperty
{
private string _value;
/// <inheritdoc/>
[Content]
public string Value
{
get => _value;
set => Update(ref _value, value);
}
/// <inheritdoc/>
public override object Copy(IDictionary<object, object> shared)
{
return new Property()
{
Name = this.Name,
Value = this.Value
};
}
/// <inheritdoc/>
public override string ToString() => _value.ToString();
/// <summary>
/// Check whether the <see cref="Value"/> property has changed from its default value.
/// </summary>
/// <returns>Returns true if the property has changed; otherwise, returns false.</returns>
public virtual bool ShouldSerializeValue() => !string.IsNullOrWhiteSpace(_value);
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Core2D.Attributes;
namespace Core2D.Data
{
/// <summary>
/// Data property.
/// </summary>
public class Property : ObservableObject, IProperty
{
private string _value;
/// <inheritdoc/>
[Content]
public string Value
{
get => _value;
set => Update(ref _value, value);
}
/// <inheritdoc/>
public override object Copy(IDictionary<object, object> shared)
{
return new Property()
{
Name = this.Name,
Value = this.Value
};
}
/// <inheritdoc/>
public override string ToString() => _value.ToString();
/// <summary>
/// Check whether the <see cref="Value"/> property has changed from its default value.
/// </summary>
/// <returns>Returns true if the property has changed; otherwise, returns false.</returns>
public virtual bool ShouldSerializeValue() => !string.IsNullOrWhiteSpace(_value);
}
}
| mit | C# |
339b1435cbec74153b511544fffc7022c3de1353 | fix OS-specific path in test | dasMulli/cli,ravimeda/cli,johnbeisner/cli,johnbeisner/cli,livarcocc/cli-1,harshjain2/cli,dasMulli/cli,blackdwarf/cli,blackdwarf/cli,livarcocc/cli-1,johnbeisner/cli,blackdwarf/cli,harshjain2/cli,svick/cli,dasMulli/cli,livarcocc/cli-1,EdwardBlair/cli,svick/cli,Faizan2304/cli,Faizan2304/cli,svick/cli,blackdwarf/cli,ravimeda/cli,harshjain2/cli,ravimeda/cli,EdwardBlair/cli,Faizan2304/cli,EdwardBlair/cli | test/dotnet-msbuild.Tests/GivenDotnetCacheInvocation.cs | test/dotnet-msbuild.Tests/GivenDotnetCacheInvocation.cs | // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.DotNet.Tools.Cache;
using FluentAssertions;
using Xunit;
using System;
using System.Linq;
using System.IO;
namespace Microsoft.DotNet.Cli.MSBuild.Tests
{
public class GivenDotnetCacheInvocation
{
const string ExpectedPrefix = "exec <msbuildpath> /m /v:m /t:ComposeCache <project>";
static readonly string[] ArgsPrefix = { "-e", "<project>" };
[Theory]
[InlineData("-e")]
[InlineData("--entries")]
public void ItAddsProjectToMsbuildInvocation(string optionName)
{
var msbuildPath = "<msbuildpath>";
string[] args = new string[] { optionName, "<project>" };
CacheCommand.FromArgs(args, msbuildPath)
.GetProcessStartInfo().Arguments.Should().Be($"{ExpectedPrefix}");
}
[Theory]
[InlineData(new string[] { "-f", "<tfm>" }, @"/p:TargetFramework=<tfm>")]
[InlineData(new string[] { "--framework", "<tfm>" }, @"/p:TargetFramework=<tfm>")]
[InlineData(new string[] { "-r", "<rid>" }, @"/p:RuntimeIdentifier=<rid>")]
[InlineData(new string[] { "--runtime", "<rid>" }, @"/p:RuntimeIdentifier=<rid>")]
public void MsbuildInvocationIsCorrect(string[] args, string expectedAdditionalArgs)
{
args = ArgsPrefix.Concat(args).ToArray();
expectedAdditionalArgs = (string.IsNullOrEmpty(expectedAdditionalArgs) ? "" : $" {expectedAdditionalArgs}");
var msbuildPath = "<msbuildpath>";
CacheCommand.FromArgs(args, msbuildPath)
.GetProcessStartInfo().Arguments.Should().Be($"{ExpectedPrefix}{expectedAdditionalArgs}");
}
[Theory]
[InlineData("-o")]
[InlineData("--output")]
public void ItAddsOutputPathToMsBuildInvocation(string optionName)
{
string path = Directory.GetCurrentDirectory();
var args = ArgsPrefix.Concat(new string[] { optionName, path }).ToArray();
var msbuildPath = "<msbuildpath>";
CacheCommand.FromArgs(args, msbuildPath)
.GetProcessStartInfo().Arguments.Should().Be($"{ExpectedPrefix} /p:ComposeDir={Path.GetFullPath(path)}");
}
}
}
| // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.DotNet.Tools.Cache;
using FluentAssertions;
using Xunit;
using System;
using System.Linq;
using System.IO;
namespace Microsoft.DotNet.Cli.MSBuild.Tests
{
public class GivenDotnetCacheInvocation
{
const string ExpectedPrefix = "exec <msbuildpath> /m /v:m /t:ComposeCache <project>";
static readonly string[] ArgsPrefix = { "-e", "<project>" };
[Theory]
[InlineData("-e")]
[InlineData("--entries")]
public void ItAddsProjectToMsbuildInvocation(string optionName)
{
var msbuildPath = "<msbuildpath>";
string[] args = new string[] { optionName, "<project>" };
CacheCommand.FromArgs(args, msbuildPath)
.GetProcessStartInfo().Arguments.Should().Be($"{ExpectedPrefix}");
}
[Theory]
[InlineData(new string[] { "-f", "<tfm>" }, @"/p:TargetFramework=<tfm>")]
[InlineData(new string[] { "--framework", "<tfm>" }, @"/p:TargetFramework=<tfm>")]
[InlineData(new string[] { "-r", "<rid>" }, @"/p:RuntimeIdentifier=<rid>")]
[InlineData(new string[] { "--runtime", "<rid>" }, @"/p:RuntimeIdentifier=<rid>")]
public void MsbuildInvocationIsCorrect(string[] args, string expectedAdditionalArgs)
{
args = ArgsPrefix.Concat(args).ToArray();
expectedAdditionalArgs = (string.IsNullOrEmpty(expectedAdditionalArgs) ? "" : $" {expectedAdditionalArgs}");
var msbuildPath = "<msbuildpath>";
CacheCommand.FromArgs(args, msbuildPath)
.GetProcessStartInfo().Arguments.Should().Be($"{ExpectedPrefix}{expectedAdditionalArgs}");
}
[Theory]
[InlineData("-o")]
[InlineData("--output")]
public void ItAddsOutputPathToMsBuildInvocation(string optionName)
{
string path = "/some/path";
var args = ArgsPrefix.Concat(new string[] { optionName, path }).ToArray();
var msbuildPath = "<msbuildpath>";
CacheCommand.FromArgs(args, msbuildPath)
.GetProcessStartInfo().Arguments.Should().Be($"{ExpectedPrefix} /p:ComposeDir={Path.GetFullPath(path)}");
}
}
}
| mit | C# |
e143467a5d868be7b8bb1ce1ebd5b12af62e8c01 | Add curly braces around the nested statement in if block | mike-rowley/XamarinMediaManager,martijn00/XamarinMediaManager,mike-rowley/XamarinMediaManager,martijn00/XamarinMediaManager | MediaManager/Platforms/Ios/Video/PlayerViewController.cs | MediaManager/Platforms/Ios/Video/PlayerViewController.cs | using AVKit;
namespace MediaManager.Platforms.Ios.Video
{
public class PlayerViewController : AVPlayerViewController
{
protected MediaManagerImplementation MediaManager => CrossMediaManager.Apple;
public override void ViewWillDisappear(bool animated)
{
base.ViewWillDisappear(animated);
if (MediaManager.MediaPlayer.VideoView == View.Superview)
{
MediaManager.MediaPlayer.VideoView = null;
}
Player = null;
}
}
}
| using AVKit;
namespace MediaManager.Platforms.Ios.Video
{
public class PlayerViewController : AVPlayerViewController
{
protected MediaManagerImplementation MediaManager => CrossMediaManager.Apple;
public override void ViewWillDisappear(bool animated)
{
base.ViewWillDisappear(animated);
if (MediaManager.MediaPlayer.VideoView == View.Superview)
MediaManager.MediaPlayer.VideoView = null;
Player = null;
}
}
}
| mit | C# |
29d616317fe0ad64331fee68288323b1b6abd2c2 | Update Message.cs | hprose/hprose-dotnet | src/Hprose.RPC/Plugins/Push/Message.cs | src/Hprose.RPC/Plugins/Push/Message.cs | /*--------------------------------------------------------*\
| |
| hprose |
| |
| Official WebSite: https://hprose.com |
| |
| Message.cs |
| |
| Message class for C#. |
| |
| LastModified: Feb 2, 2019 |
| Author: Ma Bingyao <andot@hprose.com> |
| |
\*________________________________________________________*/
namespace Hprose.RPC.Plugins.Push {
public struct Message {
public object Data;
public string From;
}
} | /*--------------------------------------------------------*\
| |
| hprose |
| |
| Official WebSite: https://hprose.com |
| |
| Message.cs |
| |
| Message class for C#. |
| |
| LastModified: Feb 2, 2019 |
| Author: Ma Bingyao <andot@hprose.com> |
| |
\*________________________________________________________*/
using Hprose.IO;
namespace Hprose.RPC.Plugins.Push {
public struct Message {
public object Data;
public string From;
}
} | mit | C# |
6adb08bf8e338a368af11775849464f79a6f856c | Update ListPipelinesOperation.cs | grzesiek-galezowski/component-based-test-tool | ComponentBasedTestTool/Components/AzurePipelines/ListPipelinesOperation.cs | ComponentBasedTestTool/Components/AzurePipelines/ListPipelinesOperation.cs | using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ExtensionPoints.ImplementedByComponents;
using ExtensionPoints.ImplementedByContext;
using Flurl.Http;
using Playground;
namespace Components.AzurePipelines;
public class ListPipelinesOperation : IComponentOperation
{
public async Task RunAsync(CancellationToken token)
{
var organization = "grzesiekgalezowski";
var project = "grzesiekgalezowski";
// LIST of pipelines request
var jsonAsync = await $"https://dev.azure.com/{organization}/{project}/_apis/pipelines?api-version=7.1-preview.1"
.GetJsonAsync<ListOfPipelines>();
var pipelineIds = jsonAsync.Value.Select(p => p.Id);
Console.WriteLine(string.Join(',', pipelineIds));
}
public void InitializeParameters(IOperationParametersListBuilder parameters)
{
throw new NotImplementedException();
}
public void StoreParameters(IPersistentStorage destination)
{
throw new NotImplementedException();
}
} | using System;
using System.Threading;
using System.Threading.Tasks;
using ExtensionPoints.ImplementedByComponents;
using ExtensionPoints.ImplementedByContext;
namespace Components.AzurePipelines;
public class ListPipelinesOperation : IComponentOperation
{
public async Task RunAsync(CancellationToken token)
{
throw new NotImplementedException();
}
public void InitializeParameters(IOperationParametersListBuilder parameters)
{
throw new NotImplementedException();
}
public void StoreParameters(IPersistentStorage destination)
{
throw new NotImplementedException();
}
} | mit | C# |
27bae7e191f11241a7c2d914a46923f26e08997e | Resolve a New Issue Where Background Does Not Immediately Refresh on Change | tommcclean/PortalCMS,tommcclean/PortalCMS,tommcclean/PortalCMS | Portal.CMS.Web/Areas/PageBuilder/Views/Section/_EditBackgroundImage.cshtml | Portal.CMS.Web/Areas/PageBuilder/Views/Section/_EditBackgroundImage.cshtml | @model Portal.CMS.Web.Areas.PageBuilder.ViewModels.Section.EditBackgroundImageViewModel
@{
Layout = "";
}
@Scripts.Render("~/Plugins/ImageSelector/Scripts")
@Scripts.Render("~/Resources/JavaScript/Plugins/Pagination")
<script type="text/javascript">
function submit()
{
EditablePopover.ShowSpinner(@Model.PageAssociationId);
$.ajax({
type: "POST",
url: "/PageBuilder/Section/EditBackgroundImage",
headers: EditablePopover.GenerateAntiForgeryHeader(),
data: $('#editBackgroundImageForm').serialize(),
success: function ()
{
EditablePopover.OnSuccess("Edit Background Image", 'fa-picture-o', '@Model.PageAssociationId');
PageBuilder.Helpers.ReloadSection(@Model.SectionId);
},
error: function ()
{
EditablePopover.OnError("Edit Background Image", 'fa-picture-o', '@Model.PageAssociationId');
EditablePopover.HideSpinner(@Model.PageAssociationId);
}
});
}
</script>
<form id="editBackgroundImageForm">
@Html.HiddenFor(x => x.PageAssociationId)
@Html.HiddenFor(x => x.SectionId)
@Html.HiddenFor(x => x.BackgroundImageId)
<div id="editable-popover-spinner" class="spinner" data-association="@Model.PageAssociationId" style="display: none;"></div>
<div id="editable-popover-content" data-association="@Model.PageAssociationId">
<div id="editable-popover-spinner" class="spinner" data-association="@Model.PageAssociationId" style="display: none;"></div>
<div id="editable-popover-info" class="alert alert-warning" data-association="@Model.PageAssociationId" role="alert">Select a single image to display in the background of your Section.</div>
<div class="x2 tab-pane image-selector single">
@Html.Partial("_RenderPopoverPage", Model.MediaLibrary)
</div>
<div class="footer">
<div class="btn primary" onclick="submit();"><span class="fa fa-check"></span><span class="hidden-xs">Save</span></div>
<div class="btn" onclick="EditablePopover.Destroy();"><span class="fa fa-times"></span><span class="hidden-xs">Cancel</span></div>
</div>
</div>
</form> | @model Portal.CMS.Web.Areas.PageBuilder.ViewModels.Section.EditBackgroundImageViewModel
@{
Layout = "";
}
@Scripts.Render("~/Plugins/ImageSelector/Scripts")
@Scripts.Render("~/Resources/JavaScript/Plugins/Pagination")
<script type="text/javascript">
function submit()
{
EditablePopover.ShowSpinner(@Model.PageAssociationId);
$.ajax({
type: "POST",
url: "/PageBuilder/Section/EditBackgroundImage",
headers: EditablePopover.GenerateAntiForgeryHeader(),
data: $('#editBackgroundImageForm').serialize(),
success: function ()
{
EditablePopover.OnSuccess("Edit Background Image", 'fa-picture-o', '@Model.PageAssociationId');
PageBuilder.Helpers.ReloadSection(@Model.PageAssociationId);
},
error: function ()
{
EditablePopover.OnError("Edit Background Image", 'fa-picture-o', '@Model.PageAssociationId');
EditablePopover.HideSpinner(@Model.PageAssociationId);
}
});
}
</script>
<form id="editBackgroundImageForm">
@Html.HiddenFor(x => x.PageAssociationId)
@Html.HiddenFor(x => x.SectionId)
@Html.HiddenFor(x => x.BackgroundImageId)
<div id="editable-popover-spinner" class="spinner" data-association="@Model.PageAssociationId" style="display: none;"></div>
<div id="editable-popover-content" data-association="@Model.PageAssociationId">
<div id="editable-popover-spinner" class="spinner" data-association="@Model.PageAssociationId" style="display: none;"></div>
<div id="editable-popover-info" class="alert alert-warning" data-association="@Model.PageAssociationId" role="alert">Select a single image to display in the background of your Section.</div>
<div class="x2 tab-pane image-selector single">
@Html.Partial("_RenderPopoverPage", Model.MediaLibrary)
</div>
<div class="footer">
<div class="btn primary" onclick="submit();"><span class="fa fa-check"></span><span class="hidden-xs">Save</span></div>
<div class="btn" onclick="EditablePopover.Destroy();"><span class="fa fa-times"></span><span class="hidden-xs">Cancel</span></div>
</div>
</div>
</form> | mit | C# |
22bb0a4915a384eab86c890384fa9c9410bf0a74 | comment out unused variables | Liwoj/Metrics.NET,mnadel/Metrics.NET,Liwoj/Metrics.NET,mnadel/Metrics.NET,cvent/Metrics.NET,ntent-ad/Metrics.NET,Recognos/Metrics.NET,huoxudong125/Metrics.NET,MetaG8/Metrics.NET,cvent/Metrics.NET,MetaG8/Metrics.NET,alhardy/Metrics.NET,alhardy/Metrics.NET,DeonHeyns/Metrics.NET,huoxudong125/Metrics.NET,etishor/Metrics.NET,MetaG8/Metrics.NET,DeonHeyns/Metrics.NET,ntent-ad/Metrics.NET,Recognos/Metrics.NET,etishor/Metrics.NET | Samples/Metrics.StupidBenchmarks/Program.cs | Samples/Metrics.StupidBenchmarks/Program.cs |
using System;
using Metrics.Core;
using Metrics.Utils;
namespace Metrics.StupidBenchmarks
{
class Program
{
static void Main(string[] args)
{
Clock.TestClock clock = new Clock.TestClock();
Timer timer = new TimerMetric(SamplingType.FavourRecent, clock);
//Counter counter = new CounterMetric();
//Meter meter = new MeterMetric(clock);
for (int i = 1; i < 8; i++)
{
//TestMeter(clock, meter, i);
//TestCounter(counter, i);
TestTimer(clock, timer, i);
}
Console.WriteLine("done");
Console.ReadKey();
}
private static void TestMeter(Clock.TestClock clock, Meter meter, int threadCount)
{
var meterResult = Benchmark.Run((i, l) => { meter.Mark(i); clock.Advance(TimeUnit.Milliseconds, l); },
iterations: 50000, threadCount: threadCount);
Console.WriteLine("{0}\t{1}", threadCount, meterResult.PerSecond);
}
private static void TestCounter(Counter counter, int threadCount)
{
var counterResult = Benchmark.Run((i, l) => counter.Increment(l), iterations: 100000, threadCount: threadCount);
Console.WriteLine("{0}\t{1}", threadCount, counterResult.PerSecond);
}
private static void TestTimer(Clock.TestClock clock, Timer timer, int threadCount)
{
var timerResult = Benchmark.Run((i, l) => { using (timer.NewContext()) { clock.Advance(TimeUnit.Milliseconds, l); } },
iterations: 100000, threadCount: threadCount);
Console.WriteLine("{0}\t{1}", threadCount, timerResult.PerSecond);
}
}
}
|
using System;
using Metrics.Core;
using Metrics.Utils;
namespace Metrics.StupidBenchmarks
{
class Program
{
static void Main(string[] args)
{
Clock.TestClock clock = new Clock.TestClock();
Timer timer = new TimerMetric(SamplingType.FavourRecent, clock);
Counter counter = new CounterMetric();
Meter meter = new MeterMetric(clock);
for (int i = 1; i < 8; i++)
{
//TestMeter(clock, meter, i);
//TestCounter(counter, i);
TestTimer(clock, timer, i);
}
Console.WriteLine("done");
Console.ReadKey();
}
private static void TestMeter(Clock.TestClock clock, Meter meter, int threadCount)
{
var meterResult = Benchmark.Run((i, l) => { meter.Mark(i); clock.Advance(TimeUnit.Milliseconds, l); },
iterations: 50000, threadCount: threadCount);
Console.WriteLine("{0}\t{1}", threadCount, meterResult.PerSecond);
}
private static void TestCounter(Counter counter, int threadCount)
{
var counterResult = Benchmark.Run((i, l) => counter.Increment(l), iterations: 100000, threadCount: threadCount);
Console.WriteLine("{0}\t{1}", threadCount, counterResult.PerSecond);
}
private static void TestTimer(Clock.TestClock clock, Timer timer, int threadCount)
{
var timerResult = Benchmark.Run((i, l) => { using (timer.NewContext()) { clock.Advance(TimeUnit.Milliseconds, l); } },
iterations: 100000, threadCount: threadCount);
Console.WriteLine("{0}\t{1}", threadCount, timerResult.PerSecond);
}
}
}
| apache-2.0 | C# |
abc7576081256a57369266fc04fb8b4be30383b1 | add Telerik.JustMock.MSTest2.Tests.InternalBits to InternalsVisible in Telerik.JustMock | telerik/JustMockLite | Telerik.JustMock/Properties/AssemblyInfo.cs | Telerik.JustMock/Properties/AssemblyInfo.cs | /*
JustMock Lite
Copyright © 2010-2015 Telerik AD
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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[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("3ee4c43f-15f9-4a98-b6c9-39f6a4ff3e73")]
[assembly: InternalsVisibleTo("Telerik.JustMock.Tests.InternalBits, PublicKey=0024000004800000940000000602000000240000525341310004000001000100e5acf216ee062f37022a13fe7bed4d8689102a99e8765d51cf85cb6c6d3619943c37f49ee920f931a71fe6f66780d088bb035f0b7faaea46638a5ad3790c75a2793b5e97cc8fb59b6eab749149637ffdf89087f130abc55a0098783ff21a3551470da33fa5a9921c02552b1376f4a2aec2bceab2dba750ba884545e251670eb4")]
[assembly: InternalsVisibleTo("Telerik.JustMock.Tests.InternalBits.NET4.5, PublicKey=0024000004800000940000000602000000240000525341310004000001000100e5acf216ee062f37022a13fe7bed4d8689102a99e8765d51cf85cb6c6d3619943c37f49ee920f931a71fe6f66780d088bb035f0b7faaea46638a5ad3790c75a2793b5e97cc8fb59b6eab749149637ffdf89087f130abc55a0098783ff21a3551470da33fa5a9921c02552b1376f4a2aec2bceab2dba750ba884545e251670eb4")]
[assembly: InternalsVisibleTo("Telerik.JustMock.MSTest2.Tests.InternalBits, PublicKey=0024000004800000940000000602000000240000525341310004000001000100e5acf216ee062f37022a13fe7bed4d8689102a99e8765d51cf85cb6c6d3619943c37f49ee920f931a71fe6f66780d088bb035f0b7faaea46638a5ad3790c75a2793b5e97cc8fb59b6eab749149637ffdf89087f130abc55a0098783ff21a3551470da33fa5a9921c02552b1376f4a2aec2bceab2dba750ba884545e251670eb4")]
| /*
JustMock Lite
Copyright © 2010-2015 Telerik AD
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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[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("3ee4c43f-15f9-4a98-b6c9-39f6a4ff3e73")]
[assembly: InternalsVisibleTo("Telerik.JustMock.Tests.InternalBits, PublicKey=0024000004800000940000000602000000240000525341310004000001000100e5acf216ee062f37022a13fe7bed4d8689102a99e8765d51cf85cb6c6d3619943c37f49ee920f931a71fe6f66780d088bb035f0b7faaea46638a5ad3790c75a2793b5e97cc8fb59b6eab749149637ffdf89087f130abc55a0098783ff21a3551470da33fa5a9921c02552b1376f4a2aec2bceab2dba750ba884545e251670eb4")]
[assembly: InternalsVisibleTo("Telerik.JustMock.Tests.InternalBits.NET4.5, PublicKey=0024000004800000940000000602000000240000525341310004000001000100e5acf216ee062f37022a13fe7bed4d8689102a99e8765d51cf85cb6c6d3619943c37f49ee920f931a71fe6f66780d088bb035f0b7faaea46638a5ad3790c75a2793b5e97cc8fb59b6eab749149637ffdf89087f130abc55a0098783ff21a3551470da33fa5a9921c02552b1376f4a2aec2bceab2dba750ba884545e251670eb4")]
| apache-2.0 | C# |
09a8e56158171fb0e2d361f19ba6948f13409578 | Update AdamBertram.cs | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/AdamBertram.cs | src/Firehose.Web/Authors/AdamBertram.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class AdamBertram : IAmAMicrosoftMVP
{
public string FirstName => "Adam";
public string LastName => "Bertram";
public string ShortBioOrTagLine => "Automation Engineer, writer, trainer, Microsoft MVP, fiercely independent, laid back guy that loves sharing.";
public string StateOrRegion => "Evansville, IN";
public string EmailAddress => string.Empty;
public string TwitterHandle => "adbertram";
public string GravatarHash => "f21b5adac336b3678098de870efcf994";
public string GitHubHandle => "adbertram";
public GeoPosition Position => new GeoPosition(37.996239,-87.54378);
public Uri WebSite => new Uri("https://www.adamtheautomator.com");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://www.adamtheautomator.com/feed/"); }
}
public bool Filter(SyndicationItem item)
{
return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell"));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class AdamBertram : IAmAMicrosoftMVP
{
public string FirstName => "Adam";
public string LastName => "Bertram";
public string ShortBioOrTagLine => "Automation Engineer, writer, trainer, Microsoft MVP, fiercely independent, laid back guy that loves sharing.";
public string StateOrRegion => "Evansville, IN";
public string EmailAddress => string.Empty;
public string TwitterHandle => "adbertram";
public string GravatarHash => "f21b5adac336b3678098de870efcf994";
public string GitHubHandle => "adbertram";
public GeoPosition Position => new GeoPosition(37.996239,-87.54378);
public Uri WebSite => new Uri("https://www.adamtheautomator.com");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://www.adamtheautomator.com/feed/"); }
}
}
}
| mit | C# |
6bd08897cecddd2bc23b566f1d9999c0b3e935e3 | Fix NH-2513 (SetMaxResults issue with DB2400Dialect) | nhibernate/nhibernate-core,alobakov/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,alobakov/nhibernate-core,nkreipke/nhibernate-core,ngbrown/nhibernate-core,ManufacturingIntelligence/nhibernate-core,alobakov/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nhibernate/nhibernate-core,livioc/nhibernate-core,fredericDelaporte/nhibernate-core,ngbrown/nhibernate-core,ngbrown/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,gliljas/nhibernate-core,nkreipke/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,hazzik/nhibernate-core,livioc/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core,RogerKratz/nhibernate-core,livioc/nhibernate-core,hazzik/nhibernate-core,fredericDelaporte/nhibernate-core,nkreipke/nhibernate-core,gliljas/nhibernate-core,hazzik/nhibernate-core,fredericDelaporte/nhibernate-core | src/NHibernate/Dialect/DB2400Dialect.cs | src/NHibernate/Dialect/DB2400Dialect.cs | using NHibernate.Cfg;
using NHibernate.SqlCommand;
namespace NHibernate.Dialect
{
/// <summary>
/// An SQL dialect for DB2 on iSeries OS/400.
/// </summary>
/// <remarks>
/// The DB2400Dialect defaults the following configuration properties:
/// <list type="table">
/// <listheader>
/// <term>Property</term>
/// <description>Default Value</description>
/// </listheader>
/// <item>
/// <term>connection.driver_class</term>
/// <description><see cref="NHibernate.Driver.DB2400Driver" /></description>
/// </item>
/// </list>
/// </remarks>
public class DB2400Dialect : DB2Dialect
{
public DB2400Dialect()
{
DefaultProperties[Environment.ConnectionDriver] = "NHibernate.Driver.DB2400Driver";
}
public override bool SupportsSequences
{
get { return false; }
}
public override string IdentitySelectString
{
get { return "select identity_val_local() from sysibm.sysdummy1"; }
}
public override bool SupportsLimit
{
get { return true; }
}
public override bool SupportsLimitOffset
{
get { return false; }
}
public override SqlString GetLimitString(SqlString querySqlString, int offset, int limit, int? offsetParameterIndex, int? limitParameterIndex)
{
// override the base-class's implementation that uses limit parameters
return GetLimitString(querySqlString, offset, limit);
}
public override SqlString GetLimitString(SqlString querySqlString, int offset, int limit)
{
return new SqlStringBuilder(querySqlString)
.Add(" fetch first ")
.Add(limit.ToString())
.Add(" rows only ")
.ToSqlString();
}
public override bool UseMaxForLimit
{
get { return true; }
}
public override bool SupportsVariableLimit
{
get { return false; }
}
}
} | using NHibernate.Cfg;
using NHibernate.SqlCommand;
namespace NHibernate.Dialect
{
/// <summary>
/// An SQL dialect for DB2 on iSeries OS/400.
/// </summary>
/// <remarks>
/// The DB2400Dialect defaults the following configuration properties:
/// <list type="table">
/// <listheader>
/// <term>Property</term>
/// <description>Default Value</description>
/// </listheader>
/// <item>
/// <term>connection.driver_class</term>
/// <description><see cref="NHibernate.Driver.DB2400Driver" /></description>
/// </item>
/// </list>
/// </remarks>
public class DB2400Dialect : DB2Dialect
{
public DB2400Dialect()
{
DefaultProperties[Environment.ConnectionDriver] = "NHibernate.Driver.DB2400Driver";
}
public override bool SupportsSequences
{
get { return false; }
}
public override string IdentitySelectString
{
get { return "select identity_val_local() from sysibm.sysdummy1"; }
}
public override bool SupportsLimit
{
get { return true; }
}
public override bool SupportsLimitOffset
{
get { return false; }
}
public override SqlString GetLimitString(SqlString querySqlString, int offset, int limit)
{
return new SqlStringBuilder(querySqlString)
.Add(" fetch first ")
.Add(limit.ToString())
.Add(" rows only ")
.ToSqlString();
}
public override bool UseMaxForLimit
{
get { return true; }
}
public override bool SupportsVariableLimit
{
get { return false; }
}
}
} | lgpl-2.1 | C# |
f61383995d0a20aa25098c6df01ff20bd7bdd851 | change color of footer links | kreeben/resin,kreeben/resin | src/Sir.HttpServer/Views/_Layout.cshtml | src/Sir.HttpServer/Views/_Layout.cshtml | <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
</head>
<body>
<style>
a {
text-decoration: none;
color: orangered;
}
a.result-link {
color: mediumblue;
}
a.result-link:visited {
color: purple;
}
input[type=text] {
width: 300px;
}
textarea {
width: 300px;
height: 150px;
}
footer {
padding-top: 10px;
border-top: 1px solid black;
}
footer span{
padding-top: 10px;
}
footer a {
text-decoration: none;
color: black;
}
</style>
<a href="/"><h1>Did you go go?</h1></a>
<p>No cookies. No javascript. No tracking. Just web search.</p>
<div>
@RenderBody()
</div>
<footer>
<div>Hosted on: 12 cores, 32 GB RAM, 1 TB storage</div>
<div><a href="https://github.com/kreeben/resin">Source code is on GitHub</a>.</div>
</footer>
</body>
</html> | <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
</head>
<body>
<style>
a {
text-decoration: none;
color: orangered;
}
a.result-link {
color: mediumblue;
}
a.result-link:visited {
color: purple;
}
input[type=text] {
width: 300px;
}
textarea {
width: 300px;
height: 150px;
}
footer {
padding-top: 10px;
border-top: 1px solid black;
}
footer span{
padding-top: 10px;
}
</style>
<a href="/"><h1>Did you go go?</h1></a>
<p>No cookies. No javascript. No tracking. Just web search.</p>
<div>
@RenderBody()
</div>
<footer>
<div>Hosted on: 12 cores, 32 GB RAM, 1 TB storage</div>
<div><a href="https://github.com/kreeben/resin">Source code on GitHub</a></div>
</footer>
</body>
</html> | mit | C# |
de5cfcf6efd091c238f80781edb2fd78621a99ee | Tweak wait form display when loading table document | electroly/sqlnotebook,electroly/sqlnotebook,electroly/sqlnotebook | src/SqlNotebook/TableDocumentControl.cs | src/SqlNotebook/TableDocumentControl.cs | using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using SqlNotebook.Properties;
using SqlNotebookScript;
using SqlNotebookScript.Utils;
namespace SqlNotebook;
public partial class TableDocumentControl : UserControl, IDocumentControl, IDocumentControlOpenNotification {
private readonly NotebookManager _manager;
private readonly string _tableName;
private readonly DataGridView _grid;
private string _query;
public TableDocumentControl(NotebookManager manager, string tableName) {
InitializeComponent();
_manager = manager;
_tableName = tableName;
_toolStrip.SetMenuAppearance();
_grid = DataGridViewUtil.NewDataGridView();
_grid.Dock = DockStyle.Fill;
_tablePanel.Controls.Add(_grid);
Ui ui = new(this, false);
ui.Init(_scriptBtn, Resources.script_go, Resources.script_go32);
}
public void OnOpen() {
using var simpleDataTable = WaitForm.GoWithCancel(TopLevelControl, "Table", "Reading table...", out var success, cancel => {
using var status = WaitStatus.StartStatic(_tableName);
cancel.Register(() => _manager.Notebook.BeginUserCancel());
try {
return _manager.Notebook.Query($"SELECT * FROM {_tableName.DoubleQuote()} LIMIT 1000");
} finally {
_manager.Notebook.EndUserCancel();
}
});
if (!success) {
throw new OperationCanceledException();
}
var dt = new DataTable();
foreach (var col in simpleDataTable.Columns) {
dt.Columns.Add(col);
}
foreach (var row in simpleDataTable.Rows) {
var dtRow = dt.NewRow();
dtRow.ItemArray = row;
dt.Rows.Add(dtRow);
}
_grid.DataSource = dt;
_grid.AutoSizeColumns(this.Scaled(500));
_query = $"SELECT\r\n{string.Join(",\r\n", simpleDataTable.Columns.Select(x => " " + x.DoubleQuote()))}\r\nFROM {_tableName.DoubleQuote()}\r\nLIMIT 1000;\r\n";
}
// IDocumentControl
string IDocumentControl.ItemName { get; set; }
public void Save() { }
private void ScriptBtn_Click(object sender, EventArgs e) {
var name = _manager.NewScript();
_manager.SetItemData(name, _query);
_manager.OpenItem(new NotebookItem(NotebookItemType.Script, name));
}
}
| using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using SqlNotebook.Properties;
using SqlNotebookScript.Utils;
namespace SqlNotebook;
public partial class TableDocumentControl : UserControl, IDocumentControl, IDocumentControlOpenNotification {
private readonly NotebookManager _manager;
private readonly string _tableName;
private readonly DataGridView _grid;
private string _query;
public TableDocumentControl(NotebookManager manager, string tableName) {
InitializeComponent();
_manager = manager;
_tableName = tableName;
_toolStrip.SetMenuAppearance();
_grid = DataGridViewUtil.NewDataGridView();
_grid.Dock = DockStyle.Fill;
_tablePanel.Controls.Add(_grid);
Ui ui = new(this, false);
ui.Init(_scriptBtn, Resources.script_go, Resources.script_go32);
}
public void OnOpen() {
using var simpleDataTable = WaitForm.GoWithCancel(TopLevelControl, "Table", "Reading table...\r\n" + _tableName, out var success, cancel => {
cancel.Register(() => _manager.Notebook.BeginUserCancel());
try {
return _manager.Notebook.Query($"SELECT * FROM {_tableName.DoubleQuote()} LIMIT 1000");
} finally {
_manager.Notebook.EndUserCancel();
}
});
if (!success) {
throw new OperationCanceledException();
}
var dt = new DataTable();
foreach (var col in simpleDataTable.Columns) {
dt.Columns.Add(col);
}
foreach (var row in simpleDataTable.Rows) {
var dtRow = dt.NewRow();
dtRow.ItemArray = row;
dt.Rows.Add(dtRow);
}
_grid.DataSource = dt;
_grid.AutoSizeColumns(this.Scaled(500));
_query = $"SELECT\r\n{string.Join(",\r\n", simpleDataTable.Columns.Select(x => " " + x.DoubleQuote()))}\r\nFROM {_tableName.DoubleQuote()}\r\nLIMIT 1000;\r\n";
}
// IDocumentControl
string IDocumentControl.ItemName { get; set; }
public void Save() { }
private void ScriptBtn_Click(object sender, EventArgs e) {
var name = _manager.NewScript();
_manager.SetItemData(name, _query);
_manager.OpenItem(new NotebookItem(NotebookItemType.Script, name));
}
}
| mit | C# |
1eafce66b628b86c31a1b7a5d53a0caafa4f4cac | Maintain same message type when echoing back | tewarid/NetTools,tewarid/net-tools | WebSocketSharpServerTool/ServiceBehavior.cs | WebSocketSharpServerTool/ServiceBehavior.cs | using WebSocketSharp;
using WebSocketSharp.Server;
namespace WebSocketServerTool
{
class ServiceBehavior : WebSocketBehavior
{
protected override void OnMessage(MessageEventArgs e)
{
if (e.IsBinary)
base.Send(e.RawData);
else
base.Send(e.Data);
}
protected override void OnClose(CloseEventArgs e)
{
}
}
}
| using WebSocketSharp;
using WebSocketSharp.Server;
namespace WebSocketServerTool
{
class ServiceBehavior : WebSocketBehavior
{
protected override void OnMessage(MessageEventArgs e)
{
base.Send(e.RawData);
}
protected override void OnClose(CloseEventArgs e)
{
}
}
}
| mit | C# |
b2a188150498bab8d915dd8624bf3feb49ba42db | Add Serialization test category to aid CI configuration. | sitofabi/duplicati,mnaiman/duplicati,mnaiman/duplicati,duplicati/duplicati,duplicati/duplicati,sitofabi/duplicati,sitofabi/duplicati,duplicati/duplicati,sitofabi/duplicati,duplicati/duplicati,duplicati/duplicati,mnaiman/duplicati,mnaiman/duplicati,mnaiman/duplicati,sitofabi/duplicati | Duplicati/UnitTest/ResultFormatSerializerProviderTest.cs | Duplicati/UnitTest/ResultFormatSerializerProviderTest.cs | using Duplicati.Library.Modules.Builtin;
using Duplicati.Library.Modules.Builtin.ResultSerialization;
using NUnit.Framework;
namespace Duplicati.UnitTest
{
[TestFixture]
public class ResultFormatSerializerProviderTest
{
[Test]
[Category("Serialization")]
public void TestGetSerializerGivenDuplicatiReturnsDuplicatiSerializer()
{
IResultFormatSerializer serializer = ResultFormatSerializerProvider.GetSerializer(ResultExportFormat.Duplicati);
Assert.AreEqual(typeof(DuplicatiFormatSerializer), serializer.GetType());
}
[Test]
[Category("Serialization")]
public void TestGetSerializerGivenJsonReturnsJsonSerializer()
{
IResultFormatSerializer serializer = ResultFormatSerializerProvider.GetSerializer(ResultExportFormat.Json);
Assert.AreEqual(typeof(JsonFormatSerializer), serializer.GetType());
}
}
}
| using Duplicati.Library.Modules.Builtin;
using Duplicati.Library.Modules.Builtin.ResultSerialization;
using NUnit.Framework;
namespace Duplicati.UnitTest
{
[TestFixture]
public class ResultFormatSerializerProviderTest
{
[Test]
public void TestGetSerializerGivenDuplicatiReturnsDuplicatiSerializer()
{
IResultFormatSerializer serializer = ResultFormatSerializerProvider.GetSerializer(ResultExportFormat.Duplicati);
Assert.AreEqual(typeof(DuplicatiFormatSerializer), serializer.GetType());
}
[Test]
public void TestGetSerializerGivenJsonReturnsJsonSerializer()
{
IResultFormatSerializer serializer = ResultFormatSerializerProvider.GetSerializer(ResultExportFormat.Json);
Assert.AreEqual(typeof(JsonFormatSerializer), serializer.GetType());
}
}
}
| lgpl-2.1 | C# |
79fb6eaa4073f0cac9b715ed23bf62c7d74a7ceb | Detach VideoView on disappearing (iOS) | mike-rowley/XamarinMediaManager,martijn00/XamarinMediaManager,martijn00/XamarinMediaManager,mike-rowley/XamarinMediaManager | MediaManager/Platforms/Ios/Video/PlayerViewController.cs | MediaManager/Platforms/Ios/Video/PlayerViewController.cs | using AVKit;
namespace MediaManager.Platforms.Ios.Video
{
public class PlayerViewController : AVPlayerViewController
{
protected MediaManagerImplementation MediaManager => CrossMediaManager.Apple;
public override void ViewWillDisappear(bool animated)
{
base.ViewWillDisappear(animated);
if (MediaManager.MediaPlayer.VideoView == View.Superview)
MediaManager.MediaPlayer.VideoView = null;
Player = null;
}
}
}
| using AVKit;
namespace MediaManager.Platforms.Ios.Video
{
public class PlayerViewController : AVPlayerViewController
{
public override void ViewWillDisappear(bool animated)
{
base.ViewWillDisappear(animated);
Player = null;
}
}
}
| mit | C# |
0d68da5b5855a2a3993c006a8cda052acfe676f6 | fix step name | peppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework | osu.Framework.Tests/Visual/Clocks/TestSceneStopwatchClock.cs | osu.Framework.Tests/Visual/Clocks/TestSceneStopwatchClock.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Audio.Track;
using osu.Framework.Timing;
namespace osu.Framework.Tests.Visual.Clocks
{
public class TestSceneStopwatchClock : TestSceneClock
{
private TrackVirtual trackVirtual;
private StopwatchClock stopwatchClock;
[Test]
public void TestStopwatchClock()
{
AddStep("Create Stopwatch Clock", () =>
{
AddClock(stopwatchClock = new StopwatchClock());
stopwatchClock.Start();
});
AddWaitStep("Wait for time to pass", 5);
AddStep("Adjust rate", () => stopwatchClock.Rate = 2.0f);
AddStep("Stop and reset", () =>
{
stopwatchClock.Stop();
stopwatchClock.Reset();
});
AddAssert("Current time is 0", () => stopwatchClock.CurrentTime == 0);
}
[Test]
public void TestTrackVirtual()
{
double? stoppedTime = null;
AddStep("Create TrackVirtual", () =>
{
AddClock(trackVirtual = new TrackVirtual(60000));
trackVirtual.Start();
});
AddWaitStep("Wait for time to pass", 5);
AddStep("Adjust rate", () =>
{
trackVirtual.Tempo.Value = 2.0f;
trackVirtual.Frequency.Value = 2.0f;
trackVirtual.OnStateChanged();
});
AddStep("Pause", () =>
{
trackVirtual.Stop();
stoppedTime = trackVirtual.CurrentTime;
});
AddStep("Seek current time", () => trackVirtual.Seek(trackVirtual.CurrentTime));
AddAssert("Current time has not changed", () => stoppedTime == trackVirtual.CurrentTime);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Audio.Track;
using osu.Framework.Timing;
namespace osu.Framework.Tests.Visual.Clocks
{
public class TestSceneStopwatchClock : TestSceneClock
{
private TrackVirtual trackVirtual;
private StopwatchClock stopwatchClock;
[Test]
public void TestStopwatchClock()
{
AddStep("Create Stopwatch Clock", () =>
{
AddClock(stopwatchClock = new StopwatchClock());
stopwatchClock.Start();
});
AddWaitStep("Wait for time to pass", 5);
AddStep("Adjust rate", () => stopwatchClock.Rate = 2.0f);
AddStep("Stop and reset", () =>
{
stopwatchClock.Stop();
stopwatchClock.Reset();
});
AddAssert("Current time is 0", () => stopwatchClock.CurrentTime == 0);
}
[Test]
public void TestTrackVirtual()
{
double? stoppedTime = null;
AddStep("Decouple clock", () =>
{
AddClock(trackVirtual = new TrackVirtual(60000));
trackVirtual.Start();
});
AddWaitStep("Wait for time to pass", 5);
AddStep("Adjust rate", () =>
{
trackVirtual.Tempo.Value = 2.0f;
trackVirtual.Frequency.Value = 2.0f;
trackVirtual.OnStateChanged();
});
AddStep("Pause", () =>
{
trackVirtual.Stop();
stoppedTime = trackVirtual.CurrentTime;
});
AddStep("Seek current time", () => trackVirtual.Seek(trackVirtual.CurrentTime));
AddAssert("Current time has not changed", () => stoppedTime == trackVirtual.CurrentTime);
}
}
}
| mit | C# |
40322c0f8b408dda058458ea83dc2b6ccc92cd48 | Remove editorbrowsable attribute from Configure | IRlyDontKnow/FluentValidation,regisbsb/FluentValidation,mgmoody42/FluentValidation,deluxetiky/FluentValidation,olcayseker/FluentValidation,GDoronin/FluentValidation,cecilphillip/FluentValidation,glorylee/FluentValidation,ruisebastiao/FluentValidation,robv8r/FluentValidation | src/FluentValidation/Internal/IConfigurable.cs | src/FluentValidation/Internal/IConfigurable.cs | #region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
namespace FluentValidation.Internal {
using System;
using System.ComponentModel;
/// <summary>
/// Represents an object that is configurable.
/// </summary>
/// <typeparam name="TConfiguration">Type of object being configured</typeparam>
/// <typeparam name="TNext">Return type</typeparam>
public interface IConfigurable<TConfiguration, out TNext> {
/// <summary>
/// Configures the current object.
/// </summary>
/// <param name="configurator">Action to configure the object.</param>
/// <returns></returns>
TNext Configure(Action<TConfiguration> configurator);
}
} | #region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
namespace FluentValidation.Internal {
using System;
using System.ComponentModel;
/// <summary>
/// Represents an object that is configurable.
/// </summary>
/// <typeparam name="TConfiguration">Type of object being configured</typeparam>
/// <typeparam name="TNext">Return type</typeparam>
public interface IConfigurable<TConfiguration, out TNext> {
/// <summary>
/// Configures the current object.
/// </summary>
/// <param name="configurator">Action to configure the object.</param>
/// <returns></returns>
[EditorBrowsable(EditorBrowsableState.Never)]
TNext Configure(Action<TConfiguration> configurator);
}
} | apache-2.0 | C# |
cf76fd505808023a97ad7028e39353e3a4eef256 | Change version | marska/habitrpg-api-dotnet-client | src/HabitRPG.Client/Properties/AssemblyInfo.cs | src/HabitRPG.Client/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("HabitRPG.Client")]
[assembly: AssemblyDescription("Simple HabitRPG API Client Library.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mariusz Skarupiński")]
[assembly: AssemblyProduct("HabitRPG.Client")]
[assembly: AssemblyCopyright("Copyright © Mariusz Skarupiński 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("08640ace-5a58-4b8b-a279-56a73f5f5a05")]
// 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.2.0")]
[assembly: AssemblyFileVersion("1.0.2.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HabitRPG.Client")]
[assembly: AssemblyDescription("Simple HabitRPG API Client Library.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mariusz Skarupiński")]
[assembly: AssemblyProduct("HabitRPG.Client")]
[assembly: AssemblyCopyright("Copyright © Mariusz Skarupiński 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("08640ace-5a58-4b8b-a279-56a73f5f5a05")]
// 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.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| apache-2.0 | C# |
82d69da00f5bb127daef7692d34a2c53a021dda1 | add replaceNonAsciiToAscii() | yasokada/unity-151117-linemonitor-UI | Assets/MyStringUtil.cs | Assets/MyStringUtil.cs | using UnityEngine;
using System.Linq;
/*
* v0.2 2015/11/21
* - add replaceNonAsciiToAscii()
*/
namespace NS_MyStringUtil
{
public static class MyStringUtil {
public static string removeLine(string src, int numRemove)
{
string work = src;
for(int loop=0; loop < numRemove; loop++) {
int pos = work.IndexOf('\n');
work = work.Substring(pos+1);
}
return work;
}
public static string addToRingBuffer(string src, string addStr, int maxline)
{
string work = src + addStr;
int numline = work.Count( c => c == '\n') + 1;
int numRemove = numline - maxline;
work = removeLine(work, numRemove);
return work;
}
public static string replaceNonAsciiToAscii(string srcstr)
{
string work = srcstr;
bool hasNewLine = false;
if (srcstr.IndexOf ("\r") >= 0) {
hasNewLine = true;
}
if (srcstr.IndexOf ("\n") >= 0) {
hasNewLine = true;
}
work = work.Replace ("\r", "<CR>");
work = work.Replace ("\n", "<LF>");
if (hasNewLine) {
work = work + System.Environment.NewLine;
}
return work;
}
}
} | using UnityEngine;
using System.Linq;
namespace NS_MyStringUtil
{
public static class MyStringUtil {
public static string removeLine(string src, int numRemove)
{
string work = src;
for(int loop=0; loop < numRemove; loop++) {
int pos = work.IndexOf('\n');
work = work.Substring(pos+1);
}
return work;
}
public static string addToRingBuffer(string src, string addStr, int maxline)
{
string work = src + addStr;
int numline = work.Count( c => c == '\n') + 1;
int numRemove = numline - maxline;
work = removeLine(work, numRemove);
return work;
}
}
} | mit | C# |
a35a52daf544ef182a00c0a7326ce33f46e2959c | Add Try&Catch | FreyYa/KCVAutoUpdater | AutoUpdater/Program.cs | AutoUpdater/Program.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using AppSettings = AutoUpdater.Properties.Settings;
namespace AutoUpdater
{
class Program
{
static void Main(string[] args)
{
try
{
Updater AppUpdater = new Updater();
var MainFolder = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
Uri VerUri = new Uri(AppSettings.Default.KCVUpdateUrl);
Uri FileUri = new Uri(AppSettings.Default.NowVersion);
Console.Title = "제독업무도 바빠! 자동 업데이트 프로그램";
Assembly asm = Assembly.LoadFrom("KanColleViewer.exe");
AssemblyName NowAppName = asm.GetName();
Version NowVersion = NowAppName.Version;
AppUpdater.LoadVersion(VerUri.AbsoluteUri);
var Checkbool = AppUpdater.IsOnlineVersionGreater(NowVersion.ToString());
var OnlineVersion = AppUpdater.GetOnlineVersion(false);
Console.WriteLine("어플리케이션 경로: ");
Console.WriteLine(MainFolder.ToString());
Console.WriteLine();
Console.WriteLine("업데이트 버전파일 경로: ");
Console.WriteLine(VerUri.ToString());
Console.WriteLine();
Console.WriteLine("현재 칸코레뷰어 버전: " + NowVersion.ToString());
Console.WriteLine();
Console.WriteLine("최신 칸코레뷰어 버전: " + OnlineVersion.ToString());
Console.WriteLine();
Console.WriteLine("온라인버전이 더 높은가?: " + Checkbool.ToString());
Console.WriteLine();
int statusint = 0;
if (Checkbool)
statusint = AppUpdater.UpdateFile(FileUri.ToString(), NowVersion.ToString());
string status;
if (statusint == 1) status = "성공";
else if (statusint == -1) status = "실패";
else status = "없음";
Console.WriteLine("업데이트상태: " + status);
}
catch (Exception e)
{
Console.WriteLine("에러발생 : ");
Console.WriteLine(e.Message);
}
System.Console.ReadKey();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using AppSettings = AutoUpdater.Properties.Settings;
namespace AutoUpdater
{
class Program
{
static void Main(string[] args)
{
Updater AppUpdater = new Updater();
var MainFolder = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
Uri VerUri = new Uri( AppSettings.Default.KCVUpdateUrl);
Uri FileUri=new Uri(AppSettings.Default.NowVersion);
Console.Title = "제독업무도 바빠! 자동 업데이트 프로그램";
Assembly asm = Assembly.LoadFrom("KanColleViewer.exe");
AssemblyName NowAppName = asm.GetName();
Version NowVersion = NowAppName.Version;
AppUpdater.LoadVersion(VerUri.AbsoluteUri);
var Checkbool=AppUpdater.IsOnlineVersionGreater(NowVersion.ToString());
var OnlineVersion = AppUpdater.GetOnlineVersion(false);
Console.WriteLine("어플리케이션 경로: ");
Console.WriteLine(MainFolder.ToString());
Console.WriteLine();
Console.WriteLine("업데이트 버전파일 경로: ");
Console.WriteLine(VerUri.ToString());
Console.WriteLine();
Console.WriteLine("현재 칸코레뷰어 버전: " + NowVersion.ToString());
Console.WriteLine();
Console.WriteLine("최신 칸코레뷰어 버전: " + OnlineVersion.ToString());
Console.WriteLine();
Console.WriteLine("온라인버전이 더 높은가?: " + Checkbool.ToString());
Console.WriteLine();
int statusint=0;
if(Checkbool)
statusint = AppUpdater.UpdateFile(FileUri.ToString(),NowVersion.ToString());
string status;
if (statusint == 1) status = "성공";
else if (statusint == -1) status = "실패";
else status = "없음";
Console.WriteLine("업데이트상태: "+status);
System.Console.ReadKey();
}
}
}
| mit | C# |
66ff5029dc022979e38fc762540a6119c28670a8 | Print functionality updated. | aykanatm/ProjectMarkdown | ProjectMarkdown/Services/DocumentPrinter.cs | ProjectMarkdown/Services/DocumentPrinter.cs | using System.Windows.Forms;
using Spire.Pdf;
using PrintDialog = System.Windows.Forms.PrintDialog;
namespace ProjectMarkdown.Services
{
public class DocumentPrinter
{
public static void Print(string tempFilePath)
{
var pdfDocument = new PdfDocument();
pdfDocument.LoadFromFile(tempFilePath);
var printDialog = new PrintDialog
{
AllowPrintToFile = true,
AllowSomePages = true,
PrinterSettings =
{
MinimumPage = 1,
MaximumPage = pdfDocument.Pages.Count,
FromPage = 1,
ToPage = pdfDocument.Pages.Count
}
};
if (printDialog.ShowDialog() == DialogResult.OK)
{
pdfDocument.PrintFromPage = printDialog.PrinterSettings.FromPage;
pdfDocument.PrintToPage = printDialog.PrinterSettings.ToPage;
pdfDocument.PrinterName = printDialog.PrinterSettings.PrinterName;
var printDocument = pdfDocument.PrintDocument;
printDialog.Document = printDocument;
printDocument.Print();
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace ProjectMarkdown.Services
{
public class DocumentPrinter
{
public static void Print(string tempFilePath)
{
//var diaglog = new PrintDialog();
//var result = diaglog.ShowDialog();
//if (result != null)
//{
// if (result == true)
// {
// var printProcess = new Process();
// printProcess.StartInfo.FileName = tempFilePath;
// printProcess.StartInfo.Arguments = diaglog.PrintQueue.Name;
// printProcess.StartInfo.Verb = "Print";
// printProcess.StartInfo.CreateNoWindow = false;
// printProcess.Start();
// }
//}
ProcessStartInfo info = new ProcessStartInfo();
info.Verb = "print";
info.FileName = tempFilePath;
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
Process p = new Process();
p.StartInfo = info;
p.Start();
p.WaitForInputIdle();
Thread.Sleep(3000);
if (false == p.CloseMainWindow())
p.Kill();
}
}
}
| mit | C# |
491558261f4163f1f06e0b16f7cffe7a255e9af1 | remove unnecessary type-specification | ppy/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu,peppy/osu | osu.Game.Rulesets.Osu/Mods/OsuModPerfect.cs | osu.Game.Rulesets.Osu/Mods/OsuModPerfect.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using System.Linq;
using osu.Game.Rulesets.Mods;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModPerfect : ModPerfect
{
public override Type[] IncompatibleMods => base.IncompatibleMods.Concat(new[] { typeof(OsuModAutopilot) }).ToArray();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using System.Linq;
using osu.Game.Rulesets.Mods;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModPerfect : ModPerfect
{
public override Type[] IncompatibleMods => base.IncompatibleMods.Concat(new Type[] { typeof(OsuModAutopilot) }).ToArray();
}
}
| mit | C# |
05d64e63f8eca506ab034213b30a0e44ea72f709 | add name back to sample | nexbit/IdentityManager.MembershipReboot | source/Host/Config/MembershipRebootIdentityManagerFactory.cs | source/Host/Config/MembershipRebootIdentityManagerFactory.cs | using BrockAllen.MembershipReboot;
using BrockAllen.MembershipReboot.Ef;
using BrockAllen.MembershipReboot.Relational;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Thinktecture.IdentityManager;
using Thinktecture.IdentityManager.MembershipReboot;
namespace Thinktecture.IdentityManager.Host
{
public class MembershipRebootIdentityManagerFactory
{
string connString;
public MembershipRebootIdentityManagerFactory(string connString)
{
this.connString = connString;
}
public IIdentityManagerService Create()
{
var db = new CustomDatabase(connString);
var userRepo = new DbContextUserAccountRepository<CustomDatabase, CustomUser>(db);
userRepo.QueryFilter = RelationalUserAccountQuery<CustomUser>.Filter;
userRepo.QuerySort = RelationalUserAccountQuery<CustomUser>.Sort;
var userSvc = new UserAccountService<CustomUser>(MRConfig.config, userRepo);
var groupRepo = new DbContextGroupRepository<CustomDatabase, CustomGroup>(db);
var groupSvc = new GroupService<CustomGroup>(MRConfig.config.DefaultTenant, groupRepo);
MembershipRebootIdentityManagerService<CustomUser, CustomGroup> idMgr = null;
idMgr = new MembershipRebootIdentityManagerService<CustomUser, CustomGroup>(userSvc, userRepo, groupSvc, groupRepo, () =>
{
var meta = idMgr.GetStandardMetadata();
meta.UserMetadata.UpdateProperties =
meta.UserMetadata.UpdateProperties.Union(
new PropertyMetadata[] {
idMgr.GetMetadataForClaim(Constants.ClaimTypes.Name, "Name")
}
);
return Task.FromResult(meta);
});
return new DisposableIdentityManagerService(idMgr, db);
}
}
} | using BrockAllen.MembershipReboot;
using BrockAllen.MembershipReboot.Ef;
using BrockAllen.MembershipReboot.Relational;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Thinktecture.IdentityManager;
using Thinktecture.IdentityManager.MembershipReboot;
namespace Thinktecture.IdentityManager.Host
{
public class MembershipRebootIdentityManagerFactory
{
string connString;
public MembershipRebootIdentityManagerFactory(string connString)
{
this.connString = connString;
}
public IIdentityManagerService Create()
{
var db = new CustomDatabase(connString);
var userRepo = new DbContextUserAccountRepository<CustomDatabase, CustomUser>(db);
userRepo.QueryFilter = RelationalUserAccountQuery<CustomUser>.Filter;
userRepo.QuerySort = RelationalUserAccountQuery<CustomUser>.Sort;
var userSvc = new UserAccountService<CustomUser>(MRConfig.config, userRepo);
var groupRepo = new DbContextGroupRepository<CustomDatabase, CustomGroup>(db);
var groupSvc = new GroupService<CustomGroup>(MRConfig.config.DefaultTenant, groupRepo);
MembershipRebootIdentityManagerService<CustomUser, CustomGroup> idMgr = null;
idMgr = new MembershipRebootIdentityManagerService<CustomUser, CustomGroup>(userSvc, userRepo, groupSvc, groupRepo, () =>
{
var meta = idMgr.GetStandardMetadata();
meta.UserMetadata.UpdateProperties =
meta.UserMetadata.UpdateProperties.Union(
new PropertyMetadata[] {
//idMgr.GetMetadataForClaim(Constants.ClaimTypes.Name)
}
);
return Task.FromResult(meta);
});
return new DisposableIdentityManagerService(idMgr, db);
}
}
} | apache-2.0 | C# |
78efc6a430af1d1256f9c14d57c5f3c33d137109 | Copy basic Boogie parser stuff from Adam's DynamicAnalysis tool. Things are still broken. The type checker throws an exception when trying to resolve() | symbooglix/symbooglix,symbooglix/symbooglix,symbooglix/symbooglix | symbooglix/symbooglix/driver.cs | symbooglix/symbooglix/driver.cs | using System;
using Microsoft;
using System.Linq;
using Microsoft.Boogie;
using System.Diagnostics;
using System.Collections.Generic;
namespace symbooglix
{
public class driver
{
public static int Main(String[] args)
{
if (args.Length == 0) {
Console.WriteLine ("Pass boogie file as first arg!");
return 1;
}
Debug.Listeners.Add(new TextWriterTraceListener(Console.Error));
Program p = null;
var defines = new List<String> { "FILE_0" }; // WTF??
int errors = Parser.Parse (args[0], defines, out p);
if (errors != 0)
{
Console.WriteLine("Failed to parse");
return 1;
}
errors = p.Resolve();
if (errors != 0)
{
Console.WriteLine("Failed to resolve.");
return 1;
}
errors = p.Typecheck();
if (errors != 0)
{
Console.WriteLine("Failed to resolve.");
return 1;
}
IStateScheduler scheduler = new DFSStateScheduler();
PrintingExecutor e = new PrintingExecutor(p, scheduler);
// FIXME: Find a better way to choose entry point.
Microsoft.Boogie.Implementation entry = p.TopLevelDeclarations.OfType<Implementation>().FirstOrDefault();
return e.run(entry)? 1 : 0;
}
}
}
| using System;
using Microsoft;
using System.Linq;
using Microsoft.Boogie;
using System.Diagnostics;
namespace symbooglix
{
public class driver
{
public static int Main(String[] args)
{
if (args.Length == 0) {
Console.WriteLine ("Pass boogie file as first arg!");
return 1;
}
Debug.Listeners.Add(new TextWriterTraceListener(Console.Error));
//Microsoft.Boogie.Program p = null;
Program p = null;
System.Collections.Generic.List<string> defines = null;
int success = Parser.Parse (args[0], defines, out p);
if (success != 0)
{
Console.WriteLine("Failed to parse");
return 1;
}
IStateScheduler scheduler = new DFSStateScheduler();
PrintingExecutor e = new PrintingExecutor(p, scheduler);
// FIXME: Find a better way to choose entry point.
Microsoft.Boogie.Implementation entry = p.TopLevelDeclarations.OfType<Implementation>().FirstOrDefault();
return e.run(entry)? 1 : 0;
}
}
}
| bsd-2-clause | C# |
c21248376815feff137ca8fa010f3eb2ff0c32a8 | Fix car movement input in editor | android/games-samples,android/games-samples,android/games-samples,android/games-samples | trivialkart/trivialkart-unity/Assets/Scripts/Controller/Game/CarMove.cs | trivialkart/trivialkart-unity/Assets/Scripts/Controller/Game/CarMove.cs | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
/// <summary>
/// A component script for a specific car game object.
/// It controls movement of a specific car in the play mode.
/// CarMove script is added as a component to every car game object in the play mode.
/// </summary>
public class CarMove : MonoBehaviour
{
public GameObject tapToDriveText;
public CarName carName;
private Rigidbody2D _rigidbody2D;
private GameManager _gameManger;
private CarList.Car _carObj;
private Gas _gas;
private const float NoVelocity = 0.01f;
private void Start()
{
_gameManger = FindObjectOfType<GameManager>();
// Get the carObj corresponding to the car game object the script attached to.
_carObj = CarList.GetCarByName(carName);
_rigidbody2D = GetComponent<Rigidbody2D>();
_gas = transform.parent.gameObject.GetComponent<Gas>();
}
private void Update()
{
// Check for fresh touches and see if they touched the car.
for (int i = 0; i < Input.touchCount; ++i)
{
var touch = Input.GetTouch(i);
if (touch.phase == TouchPhase.Began)
{
Debug.Log("NCT_TOUCH 1");
ProcessTouch(touch.position);
}
}
// left mouse button
#if UNITY_EDITOR
if (Input.GetMouseButtonDown(0))
{
Debug.Log("NCT_TOUCH 2");
ProcessTouch(Input.mousePosition);
}
#endif
}
private void ProcessTouch(Vector2 touchPosition)
{
Ray touchRay = Camera.main.ScreenPointToRay(touchPosition);
RaycastHit2D touchHit = Physics2D.Raycast(touchRay.origin, touchRay.direction);
if (touchHit.rigidbody == _rigidbody2D)
{
if (_rigidbody2D.velocity.magnitude < NoVelocity &&
_gas.HasGas() && _gameManger.IsInPlayCanvas())
{
Drive();
}
}
}
private void Drive()
{
tapToDriveText.SetActive(false);
_rigidbody2D.AddForce(new Vector2(_carObj.Speed, 0));
}
} | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
/// <summary>
/// A component script for a specific car game object.
/// It controls movement of a specific car in the play mode.
/// CarMove script is added as a component to every car game object in the play mode.
/// </summary>
public class CarMove : MonoBehaviour
{
public GameObject tapToDriveText;
public CarName carName;
private Rigidbody2D _rigidbody2D;
private GameManager _gameManger;
private CarList.Car _carObj;
private Gas _gas;
private const float NoVelocity = 0.01f;
private void Start()
{
_gameManger = FindObjectOfType<GameManager>();
// Get the carObj corresponding to the car game object the script attached to.
_carObj = CarList.GetCarByName(carName);
_rigidbody2D = GetComponent<Rigidbody2D>();
_gas = transform.parent.gameObject.GetComponent<Gas>();
}
private void Update()
{
// Check for fresh touches and see if they touched the car.
for (int i = 0; i < Input.touchCount; ++i)
{
if (Input.GetTouch(i).phase == TouchPhase.Began)
{
Ray touchRay = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
RaycastHit2D touchHit = Physics2D.Raycast(touchRay.origin, touchRay.direction);
if (touchHit.rigidbody == _rigidbody2D)
{
if (_rigidbody2D.velocity.magnitude < NoVelocity &&
_gas.HasGas() && _gameManger.IsInPlayCanvas())
{
Drive();
}
}
}
}
}
private void Drive()
{
tapToDriveText.SetActive(false);
_rigidbody2D.AddForce(new Vector2(_carObj.Speed, 0));
}
} | apache-2.0 | C# |
f4b4e9511927ff53bec4ebb93217854517f0d398 | Bump to version 0.1.2. | FacilityApi/FacilityCSharp | SolutionInfo.cs | SolutionInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("0.1.2.0")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright 2016 Ed Ball")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
| using System.Reflection;
[assembly: AssemblyVersion("0.1.1.0")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright 2016 Ed Ball")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
| mit | C# |
73f1bd770e9d0cdf59a37ec4c49e50170afc7b4b | Remove cookie tomfoolery and just authorize | bretgourdie/stockfighter | StockFighter/GamemasterAPI.cs | StockFighter/GamemasterAPI.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
using StockFighter.Responses;
using StockFighter.Requests;
namespace StockFighter
{
/// <summary>
/// Wraps Gamemaster API functions.
/// </summary>
public class GamemasterAPI : AbstractAPI
{
/// <summary>
/// URL for interfacing with the Gamemaster API.
/// </summary>
protected override string url { get { return @"https://www.stockfighter.io/gm"; } }
/// <summary>
/// Authorization parameter name for GM API calls.
/// </summary>
protected override string authorizationParameterName { get { return @"api_key"; } }
/// <summary>
/// Initializes a dictionary of Gamemaster API commands and returns it.
/// </summary>
/// <returns>Returns an initialized dictionary of Gamemaster API commands.</returns>
protected override Dictionary<Type, string> getCommandDictionary()
{
var dict = new Dictionary<Type, string>
{
{typeof(StartedLevel), "/levels/{0}"}
};
return dict;
}
/// <summary>
/// Start the specified level.
/// </summary>
/// <param name="levelName">The name of the level to start.</param>
/// <returns>Returns information about the started level.</returns>
public StartedLevel StartLevel(string levelName)
{
var startedLevel = postResponse<StartedLevel>(null, ParameterType.Cookie, levelName);
if (startedLevel == null)
{
throw new ArgumentException("Unable to start the level.");
}
return startedLevel;
}
/// <summary>
/// Overridden to not add a parameter to the POST request.
/// </summary>
/// <param name="request">The RestRequest.</param>
/// <param name="requestFormat">Disregarded.</param>
/// <returns>Returns the original RestRequest.</returns>
protected override RestRequest setRequestFormat(RestRequest request, DataFormat requestFormat)
{
return request;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
using StockFighter.Responses;
using StockFighter.Requests;
namespace StockFighter
{
/// <summary>
/// Wraps Gamemaster API functions.
/// </summary>
public class GamemasterAPI : AbstractAPI
{
/// <summary>
/// URL for interfacing with the Gamemaster API.
/// </summary>
protected override string url { get { return @"https://www.stockfighter.io/gm"; } }
/// <summary>
/// Authorization parameter name for GM API calls.
/// </summary>
protected override string authorizationParameterName { get { return @" Cookie:api_key="; } }
/// <summary>
/// Initializes a dictionary of Gamemaster API commands and returns it.
/// </summary>
/// <returns>Returns an initialized dictionary of Gamemaster API commands.</returns>
protected override Dictionary<Type, string> getCommandDictionary()
{
var dict = new Dictionary<Type, string>
{
{typeof(StartedLevel), "/levels/{0}"}
};
return dict;
}
/// <summary>
/// Start the specified level.
/// </summary>
/// <param name="levelName">The name of the level to start.</param>
/// <returns>Returns information about the started level.</returns>
public StartedLevel StartLevel(string levelName)
{
var startedLevel = postResponse<StartedLevel>(null, ParameterType.Cookie, levelName);
if (startedLevel == null)
{
throw new ArgumentException("Unable to start the level.");
}
return startedLevel;
}
/// <summary>
/// Overridden to simplify the POST request.
/// </summary>
/// <param name="request">The RestRequest.</param>
/// <param name="authorizationKey">The authorization parameter name.</param>
/// <param name="authorizationValue">The authorization parameter value.</param>
/// <param name="authParameterType">Disregarded.</param>
/// <returns>Returns an authorized RestRequest.</returns>
protected override RestRequest authorizeRequest(RestRequest request, string authorizationKey, string authorizationValue, ParameterType authParameterType)
{
request.Resource += authorizationKey + authorizationValue;
return request;
}
/// <summary>
/// Overridden to not add a parameter to the POST request.
/// </summary>
/// <param name="request">The RestRequest.</param>
/// <param name="requestFormat">Disregarded.</param>
/// <returns>Returns the original RestRequest.</returns>
protected override RestRequest setRequestFormat(RestRequest request, DataFormat requestFormat)
{
return request;
}
}
}
| mit | C# |
a5dc07a6fa9144dc7b422d6c4c3cbeb93d6056bf | add boots and squeaky tratis | fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation | UnityProject/Assets/Scripts/Items/Traits/CommonTraits.cs | UnityProject/Assets/Scripts/Items/Traits/CommonTraits.cs |
using UnityEngine;
/// <summary>
/// Singleton, provides common ItemTraits with special purposes (such as components
/// used on many prefabs which automatically cause an object to have particular traits) so they can be easily used
/// in components without needing to be assigned in editor.
/// </summary>
[CreateAssetMenu(fileName = "CommonTraitsSingleton", menuName = "Singleton/Traits/CommonTraits")]
public class CommonTraits : SingletonScriptableObject<CommonTraits>
{
public ItemTrait ReagentContainer;
public ItemTrait CanisterFillable;
public ItemTrait Gun;
public ItemTrait Food;
public ItemTrait Mask;
public ItemTrait Wirecutter;
public ItemTrait Wrench;
public ItemTrait Emag;
public ItemTrait Crowbar;
public ItemTrait Screwdriver;
public ItemTrait NoSlip;
public ItemTrait Slippery;
public ItemTrait Multitool;
public ItemTrait SpillOnThrow;
public ItemTrait CanFillMop;
public ItemTrait Cultivator;
public ItemTrait Trowel;
public ItemTrait Bucket;
public ItemTrait MetalSheet;
public ItemTrait GlassSheet;
public ItemTrait PlasteelSheet;
public ItemTrait WoodenPlank;
public ItemTrait Cable;
public ItemTrait Welder;
public ItemTrait Shovel;
public ItemTrait Knife;
public ItemTrait Transforamble;
public ItemTrait Squeaky;
public ItemTrait Boots;
}
|
using UnityEngine;
/// <summary>
/// Singleton, provides common ItemTraits with special purposes (such as components
/// used on many prefabs which automatically cause an object to have particular traits) so they can be easily used
/// in components without needing to be assigned in editor.
/// </summary>
[CreateAssetMenu(fileName = "CommonTraitsSingleton", menuName = "Singleton/Traits/CommonTraits")]
public class CommonTraits : SingletonScriptableObject<CommonTraits>
{
public ItemTrait ReagentContainer;
public ItemTrait CanisterFillable;
public ItemTrait Gun;
public ItemTrait Food;
public ItemTrait Mask;
public ItemTrait Wirecutter;
public ItemTrait Wrench;
public ItemTrait Emag;
public ItemTrait Crowbar;
public ItemTrait Screwdriver;
public ItemTrait NoSlip;
public ItemTrait Slippery;
public ItemTrait Multitool;
public ItemTrait SpillOnThrow;
public ItemTrait CanFillMop;
public ItemTrait Cultivator;
public ItemTrait Trowel;
public ItemTrait Bucket;
public ItemTrait MetalSheet;
public ItemTrait GlassSheet;
public ItemTrait PlasteelSheet;
public ItemTrait WoodenPlank;
public ItemTrait Cable;
public ItemTrait Welder;
public ItemTrait Shovel;
public ItemTrait Knife;
public ItemTrait Transforamble;
}
| agpl-3.0 | C# |
6d650404c2fef2ab87020201ae4b4a83777249bc | Add json ignor to brave | generik0/Rik.CodeCamp | Src/Business/Rik.Codecamp.Entities/Brave.cs | Src/Business/Rik.Codecamp.Entities/Brave.cs | using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Dapper.FastCrud;
using Newtonsoft.Json;
using Smooth.IoC.Cqrs.Query;
using Smooth.IoC.Cqrs.Requests;
namespace Rik.Codecamp.Entities
{
public class Brave : IRequest, IQuery
{
[Key, DatabaseGeneratedDefaultValue]
public int Id { get; set; }
[ForeignKey("New")]
public int NewId { get; set; }
public New New { get; set; }
[ForeignKey("World")]
public int WorldId { get; set; }
public World World { get; set; }
[NotMapped, JsonIgnore]
public int Version { get; } = 0;
[NotMapped, JsonIgnore]
public Guid QueryId { get; } = Guid.NewGuid();
[NotMapped, JsonIgnore]
public Guid RequestId { get; } = Guid.NewGuid();
}
}
| using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Dapper.FastCrud;
using Smooth.IoC.Cqrs.Query;
using Smooth.IoC.Cqrs.Requests;
namespace Rik.Codecamp.Entities
{
public class Brave : IRequest, IQuery
{
[Key, DatabaseGeneratedDefaultValue]
public int Id { get; set; }
[ForeignKey("New")]
public int NewId { get; set; }
public New New { get; set; }
[ForeignKey("World")]
public int WorldId { get; set; }
public World World { get; set; }
[NotMapped]
public int Version { get; } = 0;
[NotMapped]
public Guid QueryId { get; } = Guid.NewGuid();
[NotMapped]
public Guid RequestId { get; } = Guid.NewGuid();
}
}
| mit | C# |
aec7a1ca61371f528b4c19ea39e47a5add359364 | Update ShellProgress.cs | tiksn/TIKSN-Framework | TIKSN.Framework.Core/Shell/ShellProgress.cs | TIKSN.Framework.Core/Shell/ShellProgress.cs | using ShellProgressBar;
using TIKSN.Progress;
namespace TIKSN.Shell
{
public class ShellProgress : DisposableProgress<OperationProgressReport>
{
private readonly int _accuracy;
private readonly ProgressBar _progressBar;
public ShellProgress(string message, int accuracy)
{
this._accuracy = accuracy;
var options = new ProgressBarOptions();
this._progressBar = new ProgressBar(this.EstimateTicks(100d), message, options);
}
private int EstimateTicks(double percentage) => (int)(percentage * this._accuracy);
protected override void OnReport(OperationProgressReport value)
{
base.OnReport(value);
this._progressBar.Message = $"{value.StatusDescription} {value.CurrentOperation}";
var updatedTicks = this.EstimateTicks(value.PercentComplete);
while (this._progressBar.CurrentTick < updatedTicks)
{
this._progressBar.Tick();
}
}
public override void Dispose() => this._progressBar.Dispose();
}
}
| using ShellProgressBar;
using TIKSN.Progress;
namespace TIKSN.Shell
{
public class ShellProgress : DisposableProgress<OperationProgressReport>
{
private readonly ProgressBar _progressBar;
private readonly int _accuracy;
public ShellProgress(string message, int accuracy)
{
_accuracy = accuracy;
var options = new ProgressBarOptions();
_progressBar = new ProgressBar(EstimateTicks(100d), message, options);
}
private int EstimateTicks(double percentage)
{
return (int)(percentage * _accuracy);
}
protected override void OnReport(OperationProgressReport value)
{
base.OnReport(value);
_progressBar.Message = $"{value.StatusDescription} {value.CurrentOperation}";
var updatedTicks = EstimateTicks(value.PercentComplete);
while (_progressBar.CurrentTick < updatedTicks)
{
_progressBar.Tick();
}
}
public override void Dispose()
{
_progressBar.Dispose();
}
}
} | mit | C# |
a0f9bd1ef84b66813de40520180e5ec5d608b26d | fix build break by reincluding empty method calls that were moved to macros.cs | xorware/android_build,knone1/platform_manifest,xorware/android_build,pranav01/platform_manifest,xorware/android_build,ND-3500/platform_manifest,xorware/android_build,see4ri/lolili,Hybrid-Power/startsync,RR-msm7x30/platform_manifest,fallouttester/platform_manifest,hagar006/platform_manifest,xorware/android_build | tools/droiddoc/templates/customization.cs | tools/droiddoc/templates/customization.cs | <?cs # This default template file is meant to be replaced. ?>
<?cs # Use the -templatedir arg to javadoc to set your own directory with a ?>
<?cs # replacement for this file in it. ?>
<?cs # appears at the top of every page ?><?cs
def:custom_masthead() ?>
<div id="header">
<div id="headerLeft">
<a href="<?cs var:toroot ?>index.html" tabindex="-1"><?cs var:page.title ?></a>
</div>
<div id="headerRight">
<?cs if:!online-pdk ?>
<?cs call:default_search_box() ?>
<?cs /if ?>
</div><!-- headerRight -->
</div><!-- header --><?cs
/def ?>
<?cs # appear at the bottom of every page ?>
<?cs def:custom_copyright() ?><?cs /def ?>
<?cs def:custom_cc_copyright() ?><?cs /def ?>
<?cs def:custom_footerlinks() ?><?cs /def ?>
<?cs def:custom_buildinfo() ?>Build <?cs var:page.build ?> - <?cs var:page.now ?><?cs /def ?>
<?cs # appears on the side of the page ?>
<?cs def:custom_left_nav() ?><?cs call:default_left_nav() ?><?cs /def ?>
<?cs def:default_search_box() ?><?cs /def ?>
<?cs def:default_left_nav() ?><?cs /def ?> | <?cs # This default template file is meant to be replaced. ?>
<?cs # Use the -templatedir arg to javadoc to set your own directory with a ?>
<?cs # replacement for this file in it. ?>
<?cs # appears at the top of every page ?><?cs
def:custom_masthead() ?>
<div id="header">
<div id="headerLeft">
<a href="<?cs var:toroot ?>index.html" tabindex="-1"><?cs var:page.title ?></a>
</div>
<div id="headerRight">
<?cs if:!online-pdk ?>
<?cs call:default_search_box() ?>
<?cs /if ?>
</div><!-- headerRight -->
</div><!-- header --><?cs
/def ?>
<?cs # appear at the bottom of every page ?>
<?cs def:custom_copyright() ?><?cs /def ?>
<?cs def:custom_cc_copyright() ?><?cs /def ?>
<?cs def:custom_footerlinks() ?><?cs /def ?>
<?cs def:custom_buildinfo() ?>Build <?cs var:page.build ?> - <?cs var:page.now ?><?cs /def ?>
<?cs # appears on the side of the page ?>
<?cs def:custom_left_nav() ?><?cs call:default_left_nav() ?><?cs /def ?>
| apache-2.0 | C# |
eede4a9f7175a78739f5ae6ea54d85777077c995 | Fix alignment | DinoV/azure-sdk-tools,markcowl/azure-sdk-tools,markcowl/azure-sdk-tools,markcowl/azure-sdk-tools,DinoV/azure-sdk-tools,markcowl/azure-sdk-tools,DinoV/azure-sdk-tools,DinoV/azure-sdk-tools,markcowl/azure-sdk-tools,DinoV/azure-sdk-tools | WindowsAzurePowershell/src/Management.Utilities/Common/GlobalPathInfo.cs | WindowsAzurePowershell/src/Management.Utilities/Common/GlobalPathInfo.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.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Management.Utilities.Common
{
using System;
using System.IO;
using Microsoft.WindowsAzure.Management.Utilities.Properties;
public class GlobalPathInfo
{
public string PublishSettingsFile { get; private set; }
public string SubscriptionsDataFile { get; private set; }
public string ServiceConfigurationFile { get; private set; }
public string EnvironmentsFile { get; private set; }
public static readonly string AzureAppDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
Resources.AzureDirectoryName);
/// <summary>
/// Path to the global settings directory used by GlobalSettingsManager.
/// </summary>
private static string _globalSettingsDirectory;
/// <summary>
/// Gets a path to the global settings directory, which defaults to
/// AzureSdkAppDir. This can be set internally for the purpose of
/// testing.
/// </summary>
public static string GlobalSettingsDirectory
{
get { return _globalSettingsDirectory ?? AzureAppDir; }
set { _globalSettingsDirectory = value; }
}
public string AzureDirectory { get; private set; }
public GlobalPathInfo(string rootPath)
: this(rootPath, null)
{
}
public GlobalPathInfo(string rootPath, string subscriptionsDataFile)
{
PublishSettingsFile = Path.Combine(rootPath, Resources.PublishSettingsFileName);
SubscriptionsDataFile = subscriptionsDataFile ?? Path.Combine(rootPath, Resources.SubscriptionDataFileName);
ServiceConfigurationFile = Path.Combine(rootPath, Resources.ConfigurationFileName);
EnvironmentsFile = Path.Combine(rootPath, Resources.EnvironmentsFileName);
AzureDirectory = rootPath;
}
}
} | // ----------------------------------------------------------------------------------
//
// 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.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Management.Utilities.Common
{
using System;
using System.IO;
using Microsoft.WindowsAzure.Management.Utilities.Properties;
public class GlobalPathInfo
{
public string PublishSettingsFile { get; private set; }
public string SubscriptionsDataFile { get; private set; }
public string ServiceConfigurationFile { get; private set; }
public string EnvironmentsFile { get; private set; }
public static readonly string AzureAppDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
Resources.AzureDirectoryName);
/// <summary>
/// Path to the global settings directory used by GlobalSettingsManager.
/// </summary>
private static string _globalSettingsDirectory;
/// <summary>
/// Gets a path to the global settings directory, which defaults to
/// AzureSdkAppDir. This can be set internally for the purpose of
/// testing.
/// </summary>
public static string GlobalSettingsDirectory
{
get { return _globalSettingsDirectory ?? AzureAppDir; }
set { _globalSettingsDirectory = value; }
}
public string AzureDirectory { get; private set; }
public GlobalPathInfo(string rootPath)
: this(rootPath, null)
{
}
public GlobalPathInfo(string rootPath, string subscriptionsDataFile)
{
PublishSettingsFile = Path.Combine(rootPath, Resources.PublishSettingsFileName);
SubscriptionsDataFile = subscriptionsDataFile ?? Path.Combine(rootPath, Resources.SubscriptionDataFileName);
ServiceConfigurationFile = Path.Combine(rootPath, Resources.ConfigurationFileName);
EnvironmentsFile = Path.Combine(rootPath, Resources.EnvironmentsFileName);
AzureDirectory = rootPath;
}
}
} | apache-2.0 | C# |
4deea279efe4730cc78ff05e78aec64fa795d7c0 | refactor to call SyncIfNeeded without cookie | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | unity/EditorPlugin/RiderPackageInterop.cs | unity/EditorPlugin/RiderPackageInterop.cs | using System;
using System.Linq;
using System.Reflection;
using JetBrains.Diagnostics;
namespace JetBrains.Rider.Unity.Editor
{
public static class RiderPackageInterop
{
private static readonly ILog ourLogger = Log.GetLog("RiderPackageInterop");
public static Assembly GetAssembly()
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var riderPackageAssembly = assemblies
.FirstOrDefault(assembly => assembly.GetName().Name.Equals("Unity.Rider.Editor"));
if (riderPackageAssembly == null)
{
ourLogger.Verbose("Could not find Unity.Rider.Editor assembly in current AppDomain");
}
return riderPackageAssembly;
}
/// <summary>
/// This calls SyncIfNeeded in Rider package
/// </summary>
public static void SyncSolution()
{
if (!TrySyncIfNeeded(true))
UnityUtils.SyncSolution();
}
public static bool IsUnityCompatibleWithRiderPackage()
{
#if UNITY_2019_2
return true;
#else
return false;
#endif
}
private static bool TrySyncIfNeeded(bool checkProjectFiles)
{
if (!IsUnityCompatibleWithRiderPackage())
return false;
try
{
var riderPackageAssembly = GetAssembly();
if (riderPackageAssembly == null)
{
ourLogger.Error("EditorPlugin assembly is null.");
return false;
}
var riderScriptEditorType = riderPackageAssembly.GetType("Packages.Rider.Editor.RiderScriptEditor");
if (riderScriptEditorType == null)
{
ourLogger.Warn("riderScriptEditorType is null.");
return false;
}
var syncIfNeededMethod = riderScriptEditorType.GetMethod("SyncIfNeeded", BindingFlags.Static | BindingFlags.Public); // Rider package prior to 3.0.13 doesn't have it
if (syncIfNeededMethod == null)
{
ourLogger.Info("syncIfNeededMethod is null.");
return false;
}
syncIfNeededMethod.Invoke(null, new object[] { checkProjectFiles });
}
catch (Exception e)
{
ourLogger.Error(e);
return false;
}
return true;
}
}
} | using System;
using System.Linq;
using System.Reflection;
using JetBrains.Diagnostics;
namespace JetBrains.Rider.Unity.Editor
{
public static class RiderPackageInterop
{
private static readonly ILog ourLogger = Log.GetLog("RiderPackageInterop");
public static Assembly GetAssembly()
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var riderPackageAssembly = assemblies
.FirstOrDefault(assembly => assembly.GetName().Name.Equals("Unity.Rider.Editor"));
if (riderPackageAssembly == null)
{
ourLogger.Verbose("Could not find Unity.Rider.Editor assembly in current AppDomain");
}
return riderPackageAssembly;
}
/// <summary>
/// This calls SyncIfNeeded in Rider package
/// </summary>
public static void SyncSolution()
{
TrySetCheckProjectFiles(true);
try
{
UnityUtils.SyncSolution();
}
finally
{
TrySetCheckProjectFiles(false);
}
}
public static bool IsUnityCompatibleWithRiderPackage()
{
#if UNITY_2019_2
return true;
#else
return false;
#endif
}
private static void TrySetCheckProjectFiles(bool checkProjectFiles)
{
if (!IsUnityCompatibleWithRiderPackage())
return;
try
{
var riderPackageAssembly = GetAssembly();
if (riderPackageAssembly == null)
{
ourLogger.Error("EditorPlugin assembly is null.");
return;
}
var editorPluginCookieType = riderPackageAssembly.GetType("Packages.Rider.Editor.ProjectGeneration.EditorPluginCookie");
if (editorPluginCookieType == null)
{
ourLogger.Warn("editorPluginCookieType is null."); // Rider package prior to 3.0.13 doesn't have it
return;
}
var baseType = editorPluginCookieType.BaseType;
if (baseType == null)
{
ourLogger.Error("editorPluginCookieType.BaseType is null.");
return;
}
var instance = baseType.GetProperty("instance");
if (instance == null)
{
ourLogger.Error("instance of EditorPluginCookieType is null.");
return;
}
var instanceVal = instance.GetValue(null, new object[] { });
var checkProjectFilesField = editorPluginCookieType.GetField("checkProjectFiles");
if (checkProjectFilesField == null)
{
ourLogger.Error("checkProjectFilesField is null.");
return;
}
checkProjectFilesField.SetValue(instanceVal, checkProjectFiles);
}
catch (Exception e)
{
ourLogger.Error(e);
}
}
}
} | apache-2.0 | C# |
714513fab9a38a84bb3e223f03ca96205461fa4c | Remove old commented-out code. | mcneel/RhinoCycles | RenderEngine.UploadData.cs | RenderEngine.UploadData.cs | /**
Copyright 2014-2016 Robert McNeel and Associates
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**/
namespace RhinoCyclesCore
{
partial class RenderEngine
{
/// <summary>
/// Main entry point for uploading data to Cycles.
/// </summary>
protected bool UploadData()
{
if (CancelRender) return false;
Database.UploadRenderSettingsChanges();
if (CancelRender) return false;
// linear workflow changes
Database.UploadLinearWorkflowChanges();
if (CancelRender) return false;
// gamma changes
Database.UploadGammaChanges();
if (CancelRender) return false;
// environment changes
Database.UploadEnvironmentChanges();
if (CancelRender) return false;
// transforms on objects, no geometry changes
Database.UploadDynamicObjectTransforms();
if (CancelRender) return false;
// viewport changes
Database.UploadCameraChanges();
if (CancelRender) return false;
// new shaders we've got
Database.UploadShaderChanges();
if (CancelRender) return false;
// light changes
Database.UploadLightChanges();
if (CancelRender) return false;
// mesh changes (new ones, updated ones)
Database.UploadMeshChanges();
if (CancelRender) return false;
// shader changes on objects (replacement)
Database.UploadObjectShaderChanges();
if (CancelRender) return false;
// object changes (new ones, deleted ones)
Database.UploadObjectChanges();
if (CancelRender) return false;
// done, now clear out our change queue stuff so we're ready for the next time around :)
Database.ResetChangeQueue();
if (CancelRender) return false;
return true;
}
}
}
| /**
Copyright 2014-2016 Robert McNeel and Associates
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**/
namespace RhinoCyclesCore
{
partial class RenderEngine
{
/// <summary>
/// Main entry point for uploading data to Cycles.
/// </summary>
protected bool UploadData()
{
if (CancelRender) return false;
Database.UploadRenderSettingsChanges();
// adding the locking guard makes viewport updates
// on changes much blockier. For now disabling, even
// though http://mcneel.myjetbrains.com/youtrack/issue/RH-31968
// may happen. @todo figure out a better way to solve
//if (!Session.Scene.TryLock()) return false;
if (CancelRender) return false;
// linear workflow changes
Database.UploadLinearWorkflowChanges();
if (CancelRender) return false;
// gamma changes
Database.UploadGammaChanges();
if (CancelRender) return false;
// environment changes
Database.UploadEnvironmentChanges();
if (CancelRender) return false;
// transforms on objects, no geometry changes
Database.UploadDynamicObjectTransforms();
if (CancelRender) return false;
// viewport changes
Database.UploadCameraChanges();
if (CancelRender) return false;
// new shaders we've got
Database.UploadShaderChanges();
if (CancelRender) return false;
// light changes
Database.UploadLightChanges();
if (CancelRender) return false;
// mesh changes (new ones, updated ones)
Database.UploadMeshChanges();
if (CancelRender) return false;
// shader changes on objects (replacement)
Database.UploadObjectShaderChanges();
if (CancelRender) return false;
// object changes (new ones, deleted ones)
Database.UploadObjectChanges();
if (CancelRender) return false;
// done, now clear out our change queue stuff so we're ready for the next time around :)
Database.ResetChangeQueue();
if (CancelRender) return false;
//Session.Scene.Unlock();
return true;
}
}
}
| apache-2.0 | C# |
68dc03d18bb04eb0364188c124def2b81553c144 | Document DocumentPrinter | lambdacasserole/sulfide | Sulfide/DocumentPrinter.cs | Sulfide/DocumentPrinter.cs | using System;
using System.Windows.Documents;
using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Highlighting;
namespace Sulfide
{
/// <summary>
/// Contains useful static methods for preparing <see cref="TextEditor"/> documents for printing.
/// </summary>
public static class DocumentPrinter
{
/// <summary>
/// Produces a <see cref="FlowDocument"/> from a <see cref="TextEditor"/> instance.
/// </summary>
/// <param name="editor"></param>
/// <returns></returns>
public static FlowDocument CreateFlowDocumentForEditor(TextEditor editor)
{
var highlighter = editor.TextArea.GetService(typeof (IHighlighter)) as IHighlighter;
var doc = new FlowDocument(ConvertTextDocumentToBlock(editor.Document, highlighter))
{
FontFamily = editor.FontFamily,
FontSize = editor.FontSize
};
return doc;
}
/// <summary>
/// Produces a highlighted code block from a <see cref="TextDocument"/> instance.
/// </summary>
/// <param name="document">The document to produce the block from.</param>
/// <param name="highlighter">The highlighter to use.</param>
/// <returns></returns>
public static Block ConvertTextDocumentToBlock(TextDocument document, IHighlighter highlighter)
{
if (document == null)
{
throw new ArgumentNullException(nameof(document));
}
var paragraph = new Paragraph();
foreach (var line in document.Lines)
{
var lineNumber = line.LineNumber;
var inlineBuilder = new HighlightedInlineBuilder(document.GetText(line));
if (highlighter != null)
{
var highlightedLine = highlighter.HighlightLine(lineNumber);
var lineStartOffset = line.Offset;
foreach (var section in highlightedLine.Sections)
{
inlineBuilder.SetHighlighting(section.Offset - lineStartOffset, section.Length, section.Color);
}
}
paragraph.Inlines.AddRange(inlineBuilder.CreateRuns());
paragraph.Inlines.Add(new LineBreak());
}
return paragraph;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Documents;
using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Highlighting;
namespace Sulfide
{
public static class DocumentPrinter
{
public static FlowDocument CreateFlowDocumentForEditor(TextEditor editor)
{
IHighlighter highlighter = editor.TextArea.GetService(typeof(IHighlighter)) as IHighlighter;
FlowDocument doc = new FlowDocument(ConvertTextDocumentToBlock(editor.Document, highlighter));
doc.FontFamily = editor.FontFamily;
doc.FontSize = editor.FontSize;
return doc;
}
public static Block ConvertTextDocumentToBlock(TextDocument document, IHighlighter highlighter)
{
if (document == null)
throw new ArgumentNullException("document");
Paragraph p = new Paragraph();
foreach (DocumentLine line in document.Lines)
{
int lineNumber = line.LineNumber;
HighlightedInlineBuilder inlineBuilder = new HighlightedInlineBuilder(document.GetText(line));
if (highlighter != null)
{
HighlightedLine highlightedLine = highlighter.HighlightLine(lineNumber);
int lineStartOffset = line.Offset;
foreach (HighlightedSection section in highlightedLine.Sections)
inlineBuilder.SetHighlighting(section.Offset - lineStartOffset, section.Length, section.Color);
}
p.Inlines.AddRange(inlineBuilder.CreateRuns());
p.Inlines.Add(new LineBreak());
}
return p;
}
}
}
| mit | C# |
4ba9597ccbf433abc31739dcce8165547d4871b1 | Add link to PDF Download to make it more discoverable | icsharpcode/SharpDevelopReporting | samples/WebAppMvc/WebAppMvc/Views/Home/Index.cshtml | samples/WebAppMvc/WebAppMvc/Views/Home/Index.cshtml | @{
ViewBag.Title = "Home Page";
}
<h2>Demo Start Page</h2>
@Html.ActionLink("Download PDF","ContributorsList") | @{
ViewBag.Title = "Home Page";
}
<h2>Demo Start Page</h2>
| mit | C# |
ee6abe4d9fb87f5aa3d006e69aa89e245ce1c628 | Update binder to use the property api | kswoll/WootzJs,x335/WootzJs,kswoll/WootzJs,kswoll/WootzJs,x335/WootzJs,x335/WootzJs | WootzJs.Mvc/Views/Binders/TextBoxBinders.cs | WootzJs.Mvc/Views/Binders/TextBoxBinders.cs | #region License
//-----------------------------------------------------------------------
// <copyright>
// The MIT License (MIT)
//
// Copyright (c) 2014 Kirk S Woll
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
#endregion
using System;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.WootzJs;
using WootzJs.Mvc.Models;
namespace WootzJs.Mvc.Views.Binders
{
public static class TextBoxBinders
{
public static void BindTextBox<TModel, TValue>(this Bindings<TModel> bindings, TextBox textBox, Expression<Func<TModel, TValue>> property) where TModel : Model<TModel>
{
var model = bindings.Model;
var prop = model.GetProperty(property);
Action updateText = () => textBox.Text = (string)Convert.ChangeType(prop.Value, typeof(string));
updateText();
textBox.Changed += () => prop.Value = Convert.ChangeType(textBox.Text, prop.PropertyInfo.PropertyType);
prop.Changed += updateText;
prop.Validated += validations =>
{
var application = textBox.ViewContext.ControllerContext.Application;
application.NotifyOnValidatedControl(textBox, validations);
};
}
}
} | #region License
//-----------------------------------------------------------------------
// <copyright>
// The MIT License (MIT)
//
// Copyright (c) 2014 Kirk S Woll
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
#endregion
using System;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.WootzJs;
using WootzJs.Mvc.Models;
namespace WootzJs.Mvc.Views.Binders
{
public static class TextBoxBinders
{
public static void BindTextBox<TModel, TValue>(this Bindings<TModel> bindings, TextBox textBox, Expression<Func<TModel, TValue>> property) where TModel : Model<TModel>
{
var getter = property.Compile();
var setter = property.GetPropertyInfo();
var model = bindings.Model;
Action updateText = () => textBox.Text = (string)Convert.ChangeType(getter(model), typeof(string));
updateText();
textBox.Changed += () => setter.SetValue(model, null);
var prop = model.GetProperty(property);
prop.Changed += updateText;
prop.Validated += validations =>
{
var application = textBox.ViewContext.ControllerContext.Application;
application.NotifyOnValidatedControl(textBox, validations);
};
}
}
} | mit | C# |
2205bc87403ae6f4677e19cc8b4151602e77ba3b | Update Program.cs | knave2000/ACMReports | ACMReports/Program.cs | ACMReports/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ACMReports
{
static class Program
{
/// <summary>
/// Main initial application point
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ACMReports
{
static class Program
{
/// <summary>
/// Главная точка входа для приложения.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| mit | C# |
cb6162c7f94862f1f7d5502fa895181858d3de49 | Set the function's name in the object literal. | jmatysczak/DotNETPOCs,jmatysczak/DotNETPOCs | AjaxMinAST/Program.cs | AjaxMinAST/Program.cs | using System;
using System.IO;
using Microsoft.Ajax.Utilities;
namespace AjaxMinAST {
class Program {
static void Main(string[] args) {
var input = File.ReadAllText("input.js");
Console.WriteLine("--- Raw ---");
Console.WriteLine(input);
Console.WriteLine("\r\n");
Console.WriteLine("--- Minified ---");
Console.WriteLine(new Minifier().MinifyJavaScript(input));
Console.WriteLine("\r\n");
Console.WriteLine("--- AST ---");
var parser = new JSParser();
parser.CompilerError += (_, ea) => Console.WriteLine(ea.Error);
var functions = parser.Parse(input);
var functionContext = parser.Parse("var functionContext = {};");
new ObjectLiteralVisitor(functions).Visit(functionContext);
OutputVisitor.Apply(Console.Out, functionContext, new CodeSettings() { MinifyCode = false, OutputMode = OutputMode.MultipleLines });
}
}
class ObjectLiteralVisitor : TreeVisitor {
Block functions;
public ObjectLiteralVisitor(Block functions) {
this.functions = functions;
}
public override void Visit(ObjectLiteral node) {
base.Visit(node);
foreach(var function in this.functions.Children) {
node.Properties.Insert(node.Properties.Count, new ObjectLiteralProperty(node.Context) {
Name = new ObjectLiteralField((function as FunctionObject).Binding.Name, PrimitiveType.String, node.Context),
Value = function
});
}
}
}
}
| using System;
using System.IO;
using Microsoft.Ajax.Utilities;
namespace AjaxMinAST {
class Program {
static void Main(string[] args) {
var input = File.ReadAllText("input.js");
Console.WriteLine("--- Raw ---");
Console.WriteLine(input);
Console.WriteLine("\r\n");
Console.WriteLine("--- Minified ---");
Console.WriteLine(new Minifier().MinifyJavaScript(input));
Console.WriteLine("\r\n");
Console.WriteLine("--- AST ---");
var parser = new JSParser();
parser.CompilerError += (_, ea) => Console.WriteLine(ea.Error);
var functions = parser.Parse(input);
var functionContext = parser.Parse("var functionContext = {};");
new ObjectLiteralVisitor(functions).Visit(functionContext);
OutputVisitor.Apply(Console.Out, functionContext, new CodeSettings() { MinifyCode = false, OutputMode = OutputMode.MultipleLines });
}
}
class ObjectLiteralVisitor : TreeVisitor {
Block functions;
public ObjectLiteralVisitor(Block functions) {
this.functions = functions;
}
public override void Visit(ObjectLiteral node) {
base.Visit(node);
foreach(var function in this.functions.Children) {
node.Properties.Insert(node.Properties.Count, new ObjectLiteralProperty(node.Context) {
Name = new ObjectLiteralField("Name", PrimitiveType.String, node.Context),
Value = function
});
}
}
}
}
| unlicense | C# |
bd3ad4427aa433c42dc2d7cc677f2142c3e61d26 | add method destroyWhenGameover | endlessz/Flappy-Cube | Assets/Scripts/Obstacle.cs | Assets/Scripts/Obstacle.cs | using UnityEngine;
using System.Collections;
public class Obstacle : MonoBehaviour {
// Update is called once per frame
void Update () {
destroyWhenOutOfScreen();
destroyWhenGameover();
}
private void destroyWhenOutOfScreen(){
Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
//When obstacle out of screen
if (screenPosition.x < -1){
Destroy(gameObject);
}
}
private void destroyWhenGameover(){
if (GameManager.instance.currentState == GameStates.GAMEOVER) {
Destroy (gameObject, 1.5f);
}
}
}
| using UnityEngine;
using System.Collections;
public class Obstacle : MonoBehaviour {
// Update is called once per frame
void Update () {
destroyWhenOutOfScreen ();
}
private void destroyWhenOutOfScreen(){
Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
//When obstacle out of screen
if (screenPosition.x < -1){
Destroy(gameObject);
}
}
}
| mit | C# |
d89f98b02d2b36a526d2a911656ca59aeb298d0f | debug output for Delete task | socialdotcom/bounce,sreal/bounce,refractalize/bounce,socialdotcom/bounce,refractalize/bounce,socialdotcom/bounce,socialdotcom/bounce,refractalize/bounce,sreal/bounce,sreal/bounce | Bounce.Framework/Delete.cs | Bounce.Framework/Delete.cs | using System.IO;
namespace Bounce.Framework {
public class Delete : Task {
[Dependency]
public Task<string> Path;
private IDirectoryUtils DirectoryUtils;
public Delete() {
DirectoryUtils = new DirectoryUtils();
}
public override void Build(IBounce bounce) {
foreach (var file in Directory.GetFiles(".", Path.Value))
{
bounce.Log.Debug("deleting file: `{0}'", file);
File.Delete(file);
}
foreach (var directory in Directory.GetDirectories(".", Path.Value))
{
bounce.Log.Debug("deleting directory: `{0}'", directory);
DirectoryUtils.DeleteDirectory(directory);
}
}
}
} | using System.IO;
namespace Bounce.Framework {
public class Delete : Task {
[Dependency]
public Task<string> Path;
private IDirectoryUtils DirectoryUtils;
public Delete() {
DirectoryUtils = new DirectoryUtils();
}
public override void Build() {
foreach (var file in Directory.GetFiles(".", Path.Value))
{
File.Delete(file);
}
foreach (var directory in Directory.GetDirectories(".", Path.Value))
{
DirectoryUtils.DeleteDirectory(directory);
}
}
}
} | bsd-2-clause | C# |
3155335a4f87b36dd3818921d5682065b9eb1e84 | Add *fixed header* scaffolded MDL page | peterblazejewicz/mdl-app-layouts,peterblazejewicz/mdl-app-layouts | AppLayouts/src/Views/Shared/_Layout.cshtml | AppLayouts/src/Views/Shared/_Layout.cshtml | <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - AppLayouts</title>
<!-- Page styles -->
<environment names="Development">
<link href='//fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en' rel='stylesheet' type='text/css'>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<link rel="stylesheet" href="~/lib/material-design-lite/material.css">
<link rel="stylesheet" href="~/css/site.css">
</environment>
<environment names="Staging,Production">
<link href='//fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en' rel='stylesheet' type='text/css'>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<link rel="stylesheet" href="https://storage.googleapis.com/code.getmdl.io/1.0.4/material.min.css" asp-fallback-href="~/lib/material-design-lite/material.min.css" asp-fallback-test-class="hidden" asp-fallback-test-property="visibility" asp-fallback-test-value="hidden" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
</environment>
@RenderSection("styles", required: false)
</head>
<body>
<!-- Always shows a header, even in smaller screens. -->
<div class="mdl-layout mdl-js-layout mdl-layout--fixed-header">
<header class="mdl-layout__header">
<div class="mdl-layout__header-row">
<!-- Title -->
<span class="mdl-layout-title">Title</span>
<!-- Add spacer, to align navigation to the right -->
<div class="mdl-layout-spacer"></div>
<!-- Navigation. We hide it in small screens. -->
<nav class="mdl-navigation mdl-layout--large-screen-only">
<a class="mdl-navigation__link" href="">Link</a>
<a class="mdl-navigation__link" href="">Link</a>
<a class="mdl-navigation__link" href="">Link</a>
<a class="mdl-navigation__link" href="">Link</a>
</nav>
</div>
</header>
<div class="mdl-layout__drawer">
<span class="mdl-layout-title">Title</span>
<nav class="mdl-navigation">
<a class="mdl-navigation__link" href="">Link</a>
<a class="mdl-navigation__link" href="">Link</a>
<a class="mdl-navigation__link" href="">Link</a>
<a class="mdl-navigation__link" href="">Link</a>
</nav>
</div>
<main class="mdl-layout__content">
<div class="page-content">
<!-- Your content goes here -->
@RenderBody()
</div>
</main>
</div>
<environment names="Development">
<script src="~/material-design-lite/material.js"></script>
<script src="~/js/site.js"></script>
</environment>
<environment names="Staging,Production">
<script src="https://storage.googleapis.com/code.getmdl.io/1.0.4/material.min.js" asp-fallback-src="~/material-design-lite/material.min.js" asp-fallback-test="window.MaterialButton"></script>
<script src="~/js/site.min.js" asp-append-version="true"></script>
</environment>
@RenderSection("scripts", required: false)
</body>
</html>
| <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - AppLayouts</title>
@RenderSection("styles", required: false)
</head>
<body>
<mdl-drawer-panel id="drawerPanel">
<div class="nav" drawer>
<!-- Nav Content -->
</div>
<mdl-header-panel class="main" main mode="waterfall">
<!-- Main Toolbar -->
<mdl-toolbar>
<mdl-icon-button icon="menu" mdl-drawer-toggle></mdl-icon-button>
</mdl-toolbar>
<!-- Main Content -->
<div class="content">
@RenderBody()
</div>
</mdl-header-panel>
</mdl-drawer-panel>
@RenderSection("scripts", required: false)
</body>
</html>
| unlicense | C# |
c537ef6875bef67b5da8df0705dce19b2c0638cd | Update DataGameSession.cs | dimmpixeye/Unity3dTools | Assets/[1]Source/Common/DataGameSession.cs | Assets/[1]Source/Common/DataGameSession.cs | using UnityEngine;
namespace Homebrew
{
[CreateAssetMenu(fileName = "DataGameSession", menuName = "Actors/Data/DataGameSession")]
public class DataGameSession : DataGame, IKernel
{
}
}
| using UnityEngine;
namespace Homebrew
{
[CreateAssetMenu(fileName = "DataGameSession", menuName = "Actors/Data/DataGameSession")]
public class DataGameSession : DataGame
{
}
} | mit | C# |
8d89ef3e64e4e82aaa32443d100a33ee0015e473 | implement the hello world sample from electron - access to the node.js process object | ElectronNET/Electron.NET,ElectronNET/Electron.NET,ElectronNET/Electron.NET,ElectronNET/Electron.NET,ElectronNET/Electron.NET | ElectronNET.WebApp/Views/Home/Index.cshtml | ElectronNET.WebApp/Views/Home/Index.cshtml | <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Home</title>
</head>
<body>
<h3>Hello from ASP.NET Core MVC!</h3>
We are using node
<script>document.write(process.versions.node)</script>,
Chrome
<script>document.write(process.versions.chrome)</script>,
and Electron
<script>document.write(process.versions.electron)</script>.
<br /><br />
<input type="button" value="Call Notification" onclick="location.href='@Url.Action("SayHello", "Home")'" />
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Home</title>
</head>
<body>
<h3>Hello from ASP.NET Core MVC!</h3>
<br /><br />
<input type="button" value="Call Notification" onclick="location.href='@Url.Action("SayHello", "Home")'" />
</body>
</html>
| mit | C# |
08c8905a81f9197fda3f30866a7eb75814186ca0 | Make sure the xml returns correct rotor data | It423/enigma-simulator,wrightg42/enigma-simulator | Enigma/EnigmaUtilities/Data/XML/ReadXML.cs | Enigma/EnigmaUtilities/Data/XML/ReadXML.cs | // ReadXML.cs
// <copyright file="ReadXML.cs"> This code is protected under the MIT License. </copyright>
using System.Xml.Linq;
namespace EnigmaUtilities.Data.XML
{
/// <summary>
/// A static class used for reading xml data about components.
/// </summary>
public static class ReadXML
{
/// <summary>
/// Converts an instance of the <see cref="XElement "/> class to a <see cref="ReflectorData" /> instance.
/// </summary>
/// <param name="x"> The <see cref="XElement" /> instance. </param>
/// <returns> The equivalent reflector data from the xml element. </returns>
public static ReflectorData ToReflectorData(this XElement x)
{
// Check validity
if (!CheckXML.ValidReflectorXML(x))
{
// Not valid so return nothing
return null;
}
// Convert the x element into reflector data
string name = x.Attribute("Name").Value;
string wiring = x.Attribute("Wiring").Value.ToLower();
return new ReflectorData(name, wiring);
}
/// <summary>
/// Converts an instance of the <see cref="XElement "/> class to a <see cref="RotorData" /> instance.
/// </summary>
/// <param name="x"> The <see cref="XElement" /> instance. </param>
/// <returns> The equivalent rotor data from the xml element. </returns>
public static RotorData ToRotorData(this XElement x)
{
// Check validity
if (!CheckXML.ValidRotorXML(x))
{
// Not valid so return nothing
return null;
}
// Convert the x element into rotor data
string name = x.Attribute("Name").Value;
string wiring = x.Attribute("Wiring").Value.ToLower();
string turningNotches = x.Attribute("TurningNotches").Value.ToLower();
return new RotorData(name, wiring, turningNotches);
}
}
}
| // ReadXML.cs
// <copyright file="ReadXML.cs"> This code is protected under the MIT License. </copyright>
using System.Xml.Linq;
namespace EnigmaUtilities.Data.XML
{
/// <summary>
/// A static class used for reading xml data about components.
/// </summary>
public static class ReadXML
{
/// <summary>
/// Converts an instance of the <see cref="XElement "/> class to a <see cref="ReflectorData" /> instance.
/// </summary>
/// <param name="x"> The <see cref="XElement" /> instance. </param>
/// <returns> The equivalent reflector data from the xml element. </returns>
public static ReflectorData ToReflectorData(this XElement x)
{
// Check validity
if (!CheckXML.ValidReflectorXML(x))
{
// Not valid so return nothing
return null;
}
// Convert the x element into reflector data
string name = x.Attribute("Name").Value;
string wiring = x.Attribute("Wiring").Value;
return new ReflectorData(name, wiring);
}
/// <summary>
/// Converts an instance of the <see cref="XElement "/> class to a <see cref="RotorData" /> instance.
/// </summary>
/// <param name="x"> The <see cref="XElement" /> instance. </param>
/// <returns> The equivalent rotor data from the xml element. </returns>
public static RotorData ToRotorData(this XElement x)
{
// Check validity
if (!CheckXML.ValidRotorXML(x))
{
// Not valid so return nothing
return null;
}
// Convert the x element into rotor data
string name = x.Attribute("Name").Value;
string wiring = x.Attribute("Wiring").Value;
string turningNotches = x.Attribute("TurningNotches").Value;
return new RotorData(name, wiring, turningNotches);
}
}
}
| mit | C# |
4b55b7b4be7df7f459330b5261236bf70198e51a | Set the default route of the site to be /Home/Index | jhenriquez/ironbank | IronBank/IronBank/App_Start/RouteConfig.cs | IronBank/IronBank/App_Start/RouteConfig.cs | using System.Web.Mvc;
using System.Web.Routing;
[assembly: WebActivatorEx.PostApplicationStartMethod(typeof(IronBank.App_Start.RouteConfig), "RegisterRoutes")]
namespace IronBank.App_Start
{
public class RouteConfig
{
public static void RegisterRoutes()
{
RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
RouteTable.Routes.MapRoute(
name: "DefaultWebIndex",
url: "",
defaults: new { controller = "Home", action = "Index" }
);
RouteTable.Routes.MapRoute(
name: "DefaultWeb",
url: "{controller}/{action}/{id}",
defaults: new { id = UrlParameter.Optional }
);
}
}
} | using System.Web.Mvc;
using System.Web.Routing;
[assembly: WebActivatorEx.PostApplicationStartMethod(typeof(IronBank.App_Start.RouteConfig), "RegisterRoutes")]
namespace IronBank.App_Start
{
public class RouteConfig
{
public static void RegisterRoutes()
{
RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
RouteTable.Routes.MapRoute(
name: "DefaultWeb",
url: "{controller}/{action}/{id}",
defaults: new { id = UrlParameter.Optional }
);
}
}
} | mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.