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
d8b0146e4164eaf6d2a2e5c01d7b9ee921716235
add default config values for editing
stdscatchemall/BotVentic,firestack/BotVentic,Ianchandler1990/BotVentic,3ventic/BotVentic
BotVentic/BotVentic/Json/Config.cs
BotVentic/BotVentic/Json/Config.cs
using Newtonsoft.Json; namespace BotVentic.Json { class Config { [JsonProperty("email")] public string Email { get; set; } [JsonProperty("password")] public string Password { get; set; } [JsonProperty("editthreshold")] public int EditThreshold { get; set; } = 1; [JsonProperty("editmax")] public int EditMax { get; set; } = 10; } }
using Newtonsoft.Json; namespace BotVentic.Json { class Config { [JsonProperty("email")] public string Email { get; set; } [JsonProperty("password")] public string Password { get; set; } [JsonProperty("editthreshold")] public int EditThreshold { get; set; } [JsonProperty("editmax")] public int EditMax { get; set; } } }
mit
C#
55c8ff5b377332596fc3c63f847070b6cfbe00a2
Remove unuse testcase.
eternnoir/NLogging
src/NLogging.Test/LoggingTest.cs
src/NLogging.Test/LoggingTest.cs
using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using NLogging; using NLogging.Exceptions; namespace NLogging.Test { [TestFixture] class LoggingTest { [Test] public void TestGetLogger() { ILogger logger1 = Logging.Instance.GetLogger("TestGetLogger"); ILogger logger2 = Logging.Instance.GetLogger("TestGetLogger"); Assert.AreSame(logger1, logger2); } [Test] public void TestGetDifLogger() { ILogger logger1 = Logging.Instance.GetLogger("TestGetDifLogger"); ILogger logger2 = Logging.Instance.GetLogger("TestGetDifLogger2"); Assert.AreNotSame(logger1, logger2); } } }
using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using NLogging; using NLogging.Exceptions; namespace NLogging.Test { [TestFixture] class LoggingTest { [Test] public void TestGetLogger() { ILogger logger1 = Logging.Instance.GetLogger("TestGetLogger"); ILogger logger2 = Logging.Instance.GetLogger("TestGetLogger"); Assert.AreSame(logger1, logger2); } [Test] public void TestGetDifLogger() { ILogger logger1 = Logging.Instance.GetLogger("TestGetDifLogger"); ILogger logger2 = Logging.Instance.GetLogger("TestGetDifLogger2"); Assert.AreNotSame(logger1, logger2); } [Test] public void TestLoggerNameDuplicateException() { ILogger logger1 = Logging.Instance.GetLogger("LoggerName1"); ILogger logger2 = new Logger("LoggerName1"); try { Logging.Instance.AddLogger(logger2); Assert.True(false); } catch (LoggerNameDuplicateException ex) { System.Console.WriteLine(ex.ToString()); Assert.True(true); } } } }
mit
C#
4c09b9401f910e643a7a0c6f50b53f30a4e6a364
fix for GA
autumn009/TanoCSharpSamples
Chap37/ParameterlessStructConstructors/ParameterlessStructConstructors/Program.cs
Chap37/ParameterlessStructConstructors/ParameterlessStructConstructors/Program.cs
using System; A a = new A(); a.Sub(); struct A { internal void Sub() { Console.WriteLine("Hello, World!"); } public A() { Console.WriteLine("Constructed!"); } }
A a = new A(); a.Sub(); struct A { internal void Sub() { Console.WriteLine("Hello, World!"); } public A() { Console.WriteLine("Constructed!"); } }
mit
C#
c28186561dcd56f44a785094172e539fed4d914f
Use a fix that's closer to the Mongo 2.0 driver's way of doing things
RightpointLabs/Pourcast,RightpointLabs/Pourcast,RightpointLabs/Pourcast,RightpointLabs/Pourcast,RightpointLabs/Pourcast
RightpointLabs.Pourcast.Infrastructure/Persistence/Repositories/UserRepository.cs
RightpointLabs.Pourcast.Infrastructure/Persistence/Repositories/UserRepository.cs
using System; namespace RightpointLabs.Pourcast.Infrastructure.Persistence.Repositories { using System.Collections.Generic; using System.Linq; using RightpointLabs.Pourcast.Domain.Models; using RightpointLabs.Pourcast.Domain.Repositories; using RightpointLabs.Pourcast.Infrastructure.Persistence.Collections; public class UserRepository : EntityRepository<User>, IUserRepository { public UserRepository(UserCollectionDefinition userCollectionDefinition) : base(userCollectionDefinition) { } public User GetByUsername(string username) { // TODO: Update to Mongo 2.0 so we can drop the .ToList() and push the work to Mongo return Queryable.ToList().SingleOrDefault(x => x.Username.Equals(username, StringComparison.InvariantCultureIgnoreCase)); } public IEnumerable<User> GetUsersInRole(string id) { return Queryable.Where(x => x.RoleIds.Contains(id)); } } }
using System; namespace RightpointLabs.Pourcast.Infrastructure.Persistence.Repositories { using System.Collections.Generic; using System.Linq; using RightpointLabs.Pourcast.Domain.Models; using RightpointLabs.Pourcast.Domain.Repositories; using RightpointLabs.Pourcast.Infrastructure.Persistence.Collections; public class UserRepository : EntityRepository<User>, IUserRepository { public UserRepository(UserCollectionDefinition userCollectionDefinition) : base(userCollectionDefinition) { } public User GetByUsername(string username) { // TODO: use a Regex so we can drop the ToList() and push the work to Mongo return Queryable.ToList().SingleOrDefault(x => string.Equals(x.Username, username, StringComparison.InvariantCultureIgnoreCase)); } public IEnumerable<User> GetUsersInRole(string id) { return Queryable.Where(x => x.RoleIds.Contains(id)); } } }
mit
C#
0617ebb7bab693e9c132937e95183f4544fd6f02
Update Program.cs
tmmtsmith/MongoDB,tmmtsmith/MongoDB,tmmtsmith/MongoDB
MongoStart/MongoStart/Program.cs
MongoStart/MongoStart/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace MongoStart { static class Program { /// class connection, migrate - .ignore /// <summary> /// The main entry point for the application. /// </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.Windows.Forms; namespace MongoStart { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
mit
C#
75eef93b477a800128410382ffed4cb8ea79caba
simplify implements inpc
Fody/PropertyChanged
PropertyChanged.Fody/NotifyInterfaceFinder.cs
PropertyChanged.Fody/NotifyInterfaceFinder.cs
using System.Collections.Generic; using Mono.Cecil; public partial class ModuleWeaver { Dictionary<string, bool> typesImplementingINotify = new Dictionary<string, bool>(); public bool HierarchyImplementsINotify(TypeReference typeReference) { var fullName = typeReference.FullName; if (typesImplementingINotify.TryGetValue(fullName, out var implementsINotify)) { return implementsINotify; } TypeDefinition typeDefinition; if (typeReference.IsDefinition) { typeDefinition = (TypeDefinition)typeReference; } else { typeDefinition = Resolve(typeReference); } foreach (var interfaceImplementation in typeDefinition.Interfaces) { if (interfaceImplementation.InterfaceType.Name == "INotifyPropertyChanged") { typesImplementingINotify[fullName] = true; return true; } } var baseType = typeDefinition.BaseType; if (baseType == null) { typesImplementingINotify[fullName] = false; return false; } var baseTypeImplementsINotify = HierarchyImplementsINotify(baseType); typesImplementingINotify[fullName] = baseTypeImplementsINotify; return baseTypeImplementsINotify; } public static bool IsPropertyChangedEventHandler(TypeReference typeReference) { return typeReference.FullName == "System.ComponentModel.PropertyChangedEventHandler" || typeReference.FullName == "Windows.UI.Xaml.Data.PropertyChangedEventHandler" || typeReference.FullName == "System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable`1<Windows.UI.Xaml.Data.PropertyChangedEventHandler>"; } }
using System.Collections.Generic; using System.Linq; using Mono.Cecil; public partial class ModuleWeaver { Dictionary<string, bool> typeReferencesImplementingINotify = new Dictionary<string, bool>(); public bool HierarchyImplementsINotify(TypeReference typeReference) { var fullName = typeReference.FullName; if (typeReferencesImplementingINotify.TryGetValue(fullName, out var implementsINotify)) { return implementsINotify; } TypeDefinition typeDefinition; if (typeReference.IsDefinition) { typeDefinition = (TypeDefinition) typeReference; } else { typeDefinition = Resolve(typeReference); } if (HasPropertyChangedEvent(typeDefinition)) { typeReferencesImplementingINotify[fullName] = true; return true; } if (HasPropertyChangedField(typeDefinition)) { typeReferencesImplementingINotify[fullName] = true; return true; } var baseType = typeDefinition.BaseType; if (baseType == null) { typeReferencesImplementingINotify[fullName] = false; return false; } var baseTypeImplementsINotify = HierarchyImplementsINotify(baseType); typeReferencesImplementingINotify[fullName] = baseTypeImplementsINotify; return baseTypeImplementsINotify; } public static bool HasPropertyChangedEvent(TypeDefinition typeDefinition) { return typeDefinition.Events.Any(IsPropertyChangedEvent); } public static bool IsPropertyChangedEvent(EventDefinition eventDefinition) { return IsNamedPropertyChanged(eventDefinition) && IsPropertyChangedEventHandler(eventDefinition.EventType); } static bool IsNamedPropertyChanged(EventDefinition eventDefinition) { return eventDefinition.Name == "PropertyChanged" || eventDefinition.Name == "System.ComponentModel.INotifyPropertyChanged.PropertyChanged" || eventDefinition.Name == "Windows.UI.Xaml.Data.PropertyChanged"; } public static bool IsPropertyChangedEventHandler(TypeReference typeReference) { return typeReference.FullName == "System.ComponentModel.PropertyChangedEventHandler" || typeReference.FullName == "Windows.UI.Xaml.Data.PropertyChangedEventHandler" || typeReference.FullName == "System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable`1<Windows.UI.Xaml.Data.PropertyChangedEventHandler>"; } static bool HasPropertyChangedField(TypeDefinition typeDefinition) { foreach (var fieldType in typeDefinition.Fields.Select(x => x.FieldType)) { if (fieldType.FullName == "Microsoft.FSharp.Control.FSharpEvent`2<System.ComponentModel.PropertyChangedEventHandler,System.ComponentModel.PropertyChangedEventArgs>") { return true; } if (fieldType.FullName == "Microsoft.FSharp.Control.FSharpEvent`2<Windows.UI.Xaml.Data.PropertyChangedEventHandler,Windows.UI.Xaml.Data.PropertyChangedEventArgs>") { return true; } } return false; } }
mit
C#
481cdaebe8bb9763fcfc3660b066c1a9936263f1
Update NoDbRepositoryOptions.cs
tiksn/TIKSN-Framework
TIKSN.Core/Data/NoDB/NoDbRepositoryOptions.cs
TIKSN.Core/Data/NoDB/NoDbRepositoryOptions.cs
namespace TIKSN.Data.NoDB { public class NoDbRepositoryOptions { public string ProjectId { get; set; } } public class NoDbRepositoryOptions<T> : NoDbRepositoryOptions { } }
namespace TIKSN.Data.NoDB { public class NoDbRepositoryOptions { public string ProjectId { get; set; } } public class NoDbRepositoryOptions<T> : NoDbRepositoryOptions { } }
mit
C#
814f80b2733216fb7c3ae57b453530de75cd06bd
Set TupleElementNamesAttribute to LESSTHAN_NET40
theraot/Theraot
Framework.Core/System/Runtime/CompilerServices/TupleElementNamesAttribute.net40.cs
Framework.Core/System/Runtime/CompilerServices/TupleElementNamesAttribute.net40.cs
#if LESSTHAN_NET40 // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace System.Runtime.CompilerServices { /// <summary> /// Indicates that the use of <see cref="ValueTuple"/> on a member is meant to be treated as a tuple with element names. /// </summary> [CLSCompliant(false)] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Event)] public sealed class TupleElementNamesAttribute : Attribute { private readonly string[] _transformNames; /// <summary> /// Initializes a new instance of the <see cref="TupleElementNamesAttribute"/> class. /// </summary> /// <param name="transformNames"> /// Specifies, in a pre-order depth-first traversal of a type's /// construction, which <see cref="ValueType"/> occurrences are /// meant to carry element names. /// </param> /// <remarks> /// This constructor is meant to be used on types that contain an /// instantiation of <see cref="ValueType"/> that contains /// element names. For instance, if <c>C</c> is a generic type with /// two type parameters, then a use of the constructed type <c>C{<see cref="System.ValueTuple{T1, T2}"/>, <see cref="System.ValueTuple{T1, T2, T3}"/></c> might be intended to /// treat the first type argument as a tuple with element names and the /// second as a tuple without element names. In which case, the /// appropriate attribute specification should use a /// <c>transformNames</c> value of <c>{ "name1", "name2", null, null, /// null }</c>. /// </remarks> public TupleElementNamesAttribute(string[] transformNames) { _transformNames = transformNames ?? throw new ArgumentNullException(nameof(transformNames)); } /// <summary> /// Specifies, in a pre-order depth-first traversal of a type's /// construction, which <see cref="ValueTuple"/> elements are /// meant to carry element names. /// </summary> public IList<string> TransformNames => _transformNames; } } #endif
#if NET20 || NET30 || NET35 || NETSTANDARD1_0 || NETSTANDARD1_1 || NETSTANDARD1_2 || NETSTANDARD1_3 || NETSTANDARD1_4 // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace System.Runtime.CompilerServices { /// <summary> /// Indicates that the use of <see cref="ValueTuple"/> on a member is meant to be treated as a tuple with element names. /// </summary> [CLSCompliant(false)] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Event)] public sealed class TupleElementNamesAttribute : Attribute { private readonly string[] _transformNames; /// <summary> /// Initializes a new instance of the <see cref="TupleElementNamesAttribute"/> class. /// </summary> /// <param name="transformNames"> /// Specifies, in a pre-order depth-first traversal of a type's /// construction, which <see cref="ValueType"/> occurrences are /// meant to carry element names. /// </param> /// <remarks> /// This constructor is meant to be used on types that contain an /// instantiation of <see cref="ValueType"/> that contains /// element names. For instance, if <c>C</c> is a generic type with /// two type parameters, then a use of the constructed type <c>C{<see cref="System.ValueTuple{T1, T2}"/>, <see cref="System.ValueTuple{T1, T2, T3}"/></c> might be intended to /// treat the first type argument as a tuple with element names and the /// second as a tuple without element names. In which case, the /// appropriate attribute specification should use a /// <c>transformNames</c> value of <c>{ "name1", "name2", null, null, /// null }</c>. /// </remarks> public TupleElementNamesAttribute(string[] transformNames) { _transformNames = transformNames ?? throw new ArgumentNullException(nameof(transformNames)); } /// <summary> /// Specifies, in a pre-order depth-first traversal of a type's /// construction, which <see cref="ValueTuple"/> elements are /// meant to carry element names. /// </summary> public IList<string> TransformNames => _transformNames; } } #endif
mit
C#
9156671b8e9a04906b7cd130a59083aee15516ad
Make Moq act the same as expected of the real thing (and make some test data public)
BenPhegan/NuGet.Extensions
NuGet.Extensions.Tests/ReferenceAnalysers/ProjectReferenceTestData.cs
NuGet.Extensions.Tests/ReferenceAnalysers/ProjectReferenceTestData.cs
using System.Collections.Generic; using System.IO; using Moq; using NuGet.Extensions.MSBuild; using NuGet.Extensions.Tests.Mocks; namespace NuGet.Extensions.Tests.ReferenceAnalysers { public class ProjectReferenceTestData { public const string AssemblyInPackageRepository = "Assembly11.dll"; public const string AnotherAssemblyInPackageRepository = "Assembly21.dll"; public const string PackageInRepository = "Test1"; public static Mock<IVsProject> ConstructMockProject(IReference[] references = null, string outputAssembly = null) { var project = new Mock<IVsProject>(); project.Setup(proj => proj.GetBinaryReferences()).Returns(references ?? new IReference[0]); outputAssembly = outputAssembly ?? "randomAssemblyName" + Path.GetTempFileName(); project.SetupGet(p => p.AssemblyName).Returns(outputAssembly); return project; } public static Mock<IReference> ConstructMockDependency(string includeName = null, string includeVersion = null) { includeName = includeName ?? AssemblyInPackageRepository; var dependency = new Mock<IReference>(); dependency.SetupGet(d => d.IncludeName).Returns(includeName); dependency.SetupGet(d => d.IncludeVersion).Returns(includeVersion ?? "0.0.0.0"); dependency.Setup(d => d.IsForAssembly(includeName)).Returns(true); string anydependencyHintpath = includeName; dependency.Setup(d => d.TryGetHintPath(out anydependencyHintpath)).Returns(true); return dependency; } public static MockPackageRepository CreateMockRepository() { var mockRepo = new MockPackageRepository(); mockRepo.AddPackage(PackageUtility.CreatePackage(PackageInRepository, isLatest: true, assemblyReferences: new List<string> { AssemblyInPackageRepository, "Assembly12.dll" }, dependencies: new List<PackageDependency>())); mockRepo.AddPackage(PackageUtility.CreatePackage("Test2", isLatest: true, assemblyReferences: new List<string> { AnotherAssemblyInPackageRepository, "Assembly22.dll" }, dependencies: new List<PackageDependency> { new PackageDependency(PackageInRepository) })); return mockRepo; } } }
using System.Collections.Generic; using System.IO; using Moq; using NuGet.Extensions.MSBuild; using NuGet.Extensions.Tests.Mocks; namespace NuGet.Extensions.Tests.ReferenceAnalysers { public class ProjectReferenceTestData { private const string AssemblyInPackageRepository = "Assembly11.dll"; public const string PackageInRepository = "Test1"; public static Mock<IVsProject> ConstructMockProject(IReference[] references = null, string outputAssembly = null) { var project = new Mock<IVsProject>(); project.Setup(proj => proj.GetBinaryReferences()).Returns(references ?? new IReference[0]); outputAssembly = outputAssembly ?? "randomAssemblyName" + Path.GetTempFileName(); project.SetupGet(p => p.AssemblyName).Returns(outputAssembly); return project; } public static Mock<IReference> ConstructMockDependency(string includeName = null, string includeVersion = null) { includeName = includeName ?? AssemblyInPackageRepository; var dependency = new Mock<IReference>(); dependency.SetupGet(d => d.IncludeName).Returns(includeName); dependency.SetupGet(d => d.IncludeVersion).Returns(includeVersion ?? "0.0.0.0"); dependency.Setup(d => d.IsForAssembly(It.IsAny<string>())).Returns(true); string anydependencyHintpath = includeName; dependency.Setup(d => d.TryGetHintPath(out anydependencyHintpath)).Returns(true); return dependency; } public static MockPackageRepository CreateMockRepository() { var mockRepo = new MockPackageRepository(); mockRepo.AddPackage(PackageUtility.CreatePackage(PackageInRepository, isLatest: true, assemblyReferences: new List<string> { AssemblyInPackageRepository, "Assembly12.dll" }, dependencies: new List<PackageDependency>())); mockRepo.AddPackage(PackageUtility.CreatePackage("Test2", isLatest: true, assemblyReferences: new List<string> { "Assembly21.dll", "Assembly22.dll" }, dependencies: new List<PackageDependency> { new PackageDependency(PackageInRepository) })); return mockRepo; } } }
mit
C#
32ffd860960bb8c2429163767cb11df9d5cf98f8
add viewmodellocator missing view key.
h82258652/UwpMasterDetailViewSample
UwpMasterDetailViewSample/UwpMasterDetailViewSample/ViewModels/ViewModelLocator.cs
UwpMasterDetailViewSample/UwpMasterDetailViewSample/ViewModels/ViewModelLocator.cs
using GalaSoft.MvvmLight.Views; using Microsoft.Practices.ServiceLocation; using Microsoft.Practices.Unity; using UwpMasterDetailViewSample.Views; namespace UwpMasterDetailViewSample.ViewModels { public class ViewModelLocator { public const string AboutViewKey = "About"; public const string CommentViewKey = "Comment"; public const string DetailViewKey = "Detail"; public const string MasterViewKey = "Master"; public const string NoDetailViewKey = "NoDetail"; static ViewModelLocator() { var serviceLocator = new UnityServiceLocator(ConfigureUnityContainer()); ServiceLocator.SetLocatorProvider(() => serviceLocator); } public DetailViewModel Detail => ServiceLocator.Current.GetInstance<DetailViewModel>(); public MasterViewModel Master => ServiceLocator.Current.GetInstance<MasterViewModel>(); private static IUnityContainer ConfigureUnityContainer() { var unityContainer = new UnityContainer(); unityContainer.RegisterInstance(CreateNavigationService()); unityContainer.RegisterType<MasterViewModel>(); unityContainer.RegisterType<DetailViewModel>(); return unityContainer; } private static INavigationService CreateNavigationService() { var navigationService = new Services.NavigationService(); navigationService.Configure(MasterViewKey, typeof(MasterView)); navigationService.Configure(DetailViewKey, typeof(DetailView)); navigationService.Configure(AboutViewKey, typeof(AboutView)); navigationService.Configure(CommentViewKey, typeof(CommentView)); navigationService.Configure(NoDetailViewKey, typeof(NoDetailView)); return navigationService; } } }
using GalaSoft.MvvmLight.Views; using Microsoft.Practices.ServiceLocation; using Microsoft.Practices.Unity; using UwpMasterDetailViewSample.Views; namespace UwpMasterDetailViewSample.ViewModels { public class ViewModelLocator { public const string DetailViewKey = "Detail"; static ViewModelLocator() { var serviceLocator = new UnityServiceLocator(ConfigureUnityContainer()); ServiceLocator.SetLocatorProvider(() => serviceLocator); } public DetailViewModel Detail => ServiceLocator.Current.GetInstance<DetailViewModel>(); public MasterViewModel Master => ServiceLocator.Current.GetInstance<MasterViewModel>(); private static IUnityContainer ConfigureUnityContainer() { var unityContainer = new UnityContainer(); unityContainer.RegisterInstance(CreateNavigationService()); unityContainer.RegisterType<MasterViewModel>(); unityContainer.RegisterType<DetailViewModel>(); return unityContainer; } private static INavigationService CreateNavigationService() { var navigationService = new Services.NavigationService(); navigationService.Configure(DetailViewKey, typeof(DetailView)); return navigationService; } } }
apache-2.0
C#
261f6b8c55a99f54516d3545228913669a21d700
Update MicrogameNumber.cs
plrusek/NitoriWare,Barleytree/NitoriWare,uulltt/NitoriWare,NitorInc/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare
Assets/Scripts/Animation/MicrogameNumber.cs
Assets/Scripts/Animation/MicrogameNumber.cs
using UnityEngine; using System.Collections; public class MicrogameNumber : MonoBehaviour { public TextMesh text; void Start () { } void Update () { } public void increaseNumber() { if (text.text == "999") return; short number = short.Parse(text.text) + 1; text.text = number < 10 ? "00" + number.ToString() : number < 100 ? "0" + number.ToString() : number.ToString(); } }
using UnityEngine; using System.Collections; public class MicrogameNumber : MonoBehaviour { public TextMesh text; void Start () { } void Update () { } public void increaseNumber() { if (text.text == "999") return; int number = int.Parse(text.text) + 1; if (number < 10) text.text = "00" + number.ToString(); else if (number < 100) text.text = "0" + number.ToString(); else text.text = number.ToString(); } }
mit
C#
4bc06e8efbe130e1259b90925cf6a67cd18a27cf
Set TransientMessage.RequireAuthentication to true
beebotte/bbt_dotnet
Beebotte.API.Server.Net/TransientMessage.cs
Beebotte.API.Server.Net/TransientMessage.cs
using System; using System.Runtime.Serialization; using System.Text.RegularExpressions; namespace Beebotte.API.Server.Net { [DataContract] internal class TransientMessage : WriteMessageBase { #region Fields private string _serializedMessage; #endregion #region ctor internal TransientMessage(string channel, string resource, object data, int timestamp) { Channel = channel; Resource = resource; Data = data; TimeStamp = timestamp > 0 ? timestamp : 0; } #endregion #region Properties [DataMember(EmitDefaultValue = true, IsRequired = true, Name = "data", Order = 1)] internal object Data { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false, Name = "ts", Order = 2)] internal int TimeStamp { get; set; } internal string Channel { get; set; } internal string Resource { get; set; } internal override string Uri { get { return String.Format("{0}/{1}/{2}", OperationUri.Publish.GetOperationUri(), Channel, Resource); } } internal override bool RequireAuthentication { get { return true; } } internal override string SerializedContent { get { if (String.IsNullOrEmpty(_serializedMessage)) { _serializedMessage = JsonHelper.JsonSerialize(this); } return _serializedMessage; } } #endregion #region Methods internal override bool ValidateSchema() { return Utilities.ValidateChannelFormat(Channel) && Utilities.ValidateResourceFormat(Resource); } #endregion } }
using System; using System.Runtime.Serialization; using System.Text.RegularExpressions; namespace Beebotte.API.Server.Net { [DataContract] internal class TransientMessage : WriteMessageBase { #region Fields private string _serializedMessage; #endregion #region ctor internal TransientMessage(string channel, string resource, object data, int timestamp) { Channel = channel; Resource = resource; Data = data; TimeStamp = timestamp > 0 ? timestamp : 0; } #endregion #region Properties [DataMember(EmitDefaultValue = true, IsRequired = true, Name = "data", Order = 1)] internal object Data { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false, Name = "ts", Order = 2)] internal int TimeStamp { get; set; } internal string Channel { get; set; } internal string Resource { get; set; } internal override string Uri { get { return String.Format("{0}/{1}/{2}", OperationUri.Publish.GetOperationUri(), Channel, Resource); } } internal override bool RequireAuthentication { get { return false; } } internal override string SerializedContent { get { if (String.IsNullOrEmpty(_serializedMessage)) { _serializedMessage = JsonHelper.JsonSerialize(this); } return _serializedMessage; } } #endregion #region Methods internal override bool ValidateSchema() { return Utilities.ValidateChannelFormat(Channel) && Utilities.ValidateResourceFormat(Resource); } #endregion } }
mit
C#
016f4ba1cbc75b22ba08a97bf9c66052ea34e2ec
Edit it
jogibear9988/websocket-sharp,jogibear9988/websocket-sharp,2Toad/websocket-sharp,2Toad/websocket-sharp,jogibear9988/websocket-sharp,sta/websocket-sharp,2Toad/websocket-sharp,2Toad/websocket-sharp,sta/websocket-sharp,sta/websocket-sharp,sta/websocket-sharp,jogibear9988/websocket-sharp
websocket-sharp/ErrorEventArgs.cs
websocket-sharp/ErrorEventArgs.cs
#region License /* * ErrorEventArgs.cs * * The MIT License * * Copyright (c) 2012-2016 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Contributors /* * Contributors: * - Frank Razenberg <frank@zzattack.org> */ #endregion using System; namespace WebSocketSharp { /// <summary> /// Represents the event data for the <see cref="WebSocket.OnError"/> event. /// </summary> /// <remarks> /// <para> /// That event occurs when the <see cref="WebSocket"/> gets an error. /// </para> /// <para> /// If you would like to get the error message, you should access /// the <see cref="ErrorEventArgs.Message"/> property. /// </para> /// <para> /// And if the error is due to an exception, you can get it by accessing /// the <see cref="ErrorEventArgs.Exception"/> property. /// </para> /// </remarks> public class ErrorEventArgs : EventArgs { #region Private Fields private Exception _exception; private string _message; #endregion #region Internal Constructors internal ErrorEventArgs (string message) : this (message, null) { } internal ErrorEventArgs (string message, Exception exception) { _message = message; _exception = exception; } #endregion #region Public Properties /// <summary> /// Gets the exception that caused the error. /// </summary> /// <value> /// An <see cref="System.Exception"/> instance that represents the cause of /// the error if it is due to an exception; otherwise, <see langword="null"/>. /// </value> public Exception Exception { get { return _exception; } } /// <summary> /// Gets the error message. /// </summary> /// <value> /// A <see cref="string"/> that represents the error message. /// </value> public string Message { get { return _message; } } #endregion } }
#region License /* * ErrorEventArgs.cs * * The MIT License * * Copyright (c) 2012-2016 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Contributors /* * Contributors: * - Frank Razenberg <frank@zzattack.org> */ #endregion using System; namespace WebSocketSharp { /// <summary> /// Represents the event data for the <see cref="WebSocket.OnError"/> event. /// </summary> /// <remarks> /// <para> /// That event occurs when the <see cref="WebSocket"/> gets an error. /// </para> /// <para> /// If you would like to get the error message, you should access /// the <see cref="ErrorEventArgs.Message"/> property. /// </para> /// <para> /// And if the error is due to an exception, you can get it by accessing /// the <see cref="ErrorEventArgs.Exception"/> property. /// </para> /// </remarks> public class ErrorEventArgs : EventArgs { #region Private Fields private Exception _exception; private string _message; #endregion #region Internal Constructors internal ErrorEventArgs (string message) : this (message, null) { } internal ErrorEventArgs (string message, Exception exception) { _message = message; _exception = exception; } #endregion #region Public Properties /// <summary> /// Gets the exception that caused the error. /// </summary> /// <value> /// An <see cref="System.Exception"/> instance that represents the cause of /// the error, or <see langword="null"/> if it is not due to an exception. /// </value> public Exception Exception { get { return _exception; } } /// <summary> /// Gets the error message. /// </summary> /// <value> /// A <see cref="string"/> that represents the error message. /// </value> public string Message { get { return _message; } } #endregion } }
mit
C#
1babb05fc7ee51aef25d53468ae7b2d1129a485e
add OsuMarkdownInlineCode
NeoAdonis/osu,UselessToucan/osu,peppy/osu-new,UselessToucan/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,ppy/osu,smoogipoo/osu
osu.Game/Graphics/Containers/Markdown/OsuMarkdownTextFlowContainer.cs
osu.Game/Graphics/Containers/Markdown/OsuMarkdownTextFlowContainer.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 Markdig.Syntax.Inlines; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers.Markdown; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Game.Overlays; namespace osu.Game.Graphics.Containers.Markdown { public class OsuMarkdownTextFlowContainer : MarkdownTextFlowContainer { [Resolved] private OverlayColourProvider colourProvider { get; set; } protected override void AddLinkText(string text, LinkInline linkInline) => AddDrawable(new OsuMarkdownLinkText(text, linkInline)); // TODO : Add background (colour B6) and change font to monospace protected override void AddCodeInLine(CodeInline codeInline) => AddText(codeInline.Content, t => { t.Colour = colourProvider.Light1; }); protected override SpriteText CreateEmphasisedSpriteText(bool bold, bool italic) => CreateSpriteText().With(t => t.Font = t.Font.With(weight: bold ? FontWeight.Bold : FontWeight.Regular, italics: italic)); private class OsuMarkdownInlineCode : Container { [Resolved] private IMarkdownTextComponent parentTextComponent { get; set; } public string Text; [BackgroundDependencyLoader] private void load(OverlayColourProvider colourProvider) { AutoSizeAxes = Axes.Both; Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = colourProvider.Background6, }, parentTextComponent.CreateSpriteText().With(t => { t.Colour = colourProvider.Light1; t.Text = Text; }), }; } } } }
// 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 Markdig.Syntax.Inlines; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers.Markdown; using osu.Framework.Graphics.Sprites; using osu.Game.Overlays; namespace osu.Game.Graphics.Containers.Markdown { public class OsuMarkdownTextFlowContainer : MarkdownTextFlowContainer { [Resolved] private OverlayColourProvider colourProvider { get; set; } protected override void AddLinkText(string text, LinkInline linkInline) => AddDrawable(new OsuMarkdownLinkText(text, linkInline)); // TODO : Add background (colour B6) and change font to monospace protected override void AddCodeInLine(CodeInline codeInline) => AddText(codeInline.Content, t => { t.Colour = colourProvider.Light1; }); protected override SpriteText CreateEmphasisedSpriteText(bool bold, bool italic) => CreateSpriteText().With(t => t.Font = t.Font.With(weight: bold ? FontWeight.Bold : FontWeight.Regular, italics: italic)); } }
mit
C#
8bf9ae8faedba47a7a2f873a2a1dbd1260928d37
Update Entity.cs
carlos-vicente/Playgrounf,carlos-vicente/Playground,carlos-vicente/Playground
Playground.Domain/Model/Entity.cs
Playground.Domain/Model/Entity.cs
using System; namespace Playground.Domain.Model { public abstract class Entity : IEquatable<Entity> { public Guid Id { get; private set; } protected Entity(Guid id) { Id = id; } public bool Equals(Entity other) { if (other == null) return false; return ReferenceEquals(this, other) || Id.Equals(other.Id); } public override bool Equals(object obj) { return Equals(obj as Entity); } public override int GetHashCode() { return Id.GetHashCode(); } } }
using System; namespace Playground.Domain.Model { public abstract class Entity : IEquatable<Entity> { public Guid Id { get; } protected Entity(Guid id) { Id = id; } public bool Equals(Entity other) { if (other == null) return false; return ReferenceEquals(this, other) || Id.Equals(other.Id); } public override bool Equals(object obj) { return Equals(obj as Entity); } public override int GetHashCode() { return Id.GetHashCode(); } } }
mit
C#
6f8219fcad7553c93cfeba21fba1c4a1b2d44eee
Remove dead wood
ceddlyburge/canoe-polo-league-organiser-backend
CanoePoloLeagueOrganiser/GamesNotPlayedBetweenFirstAndLast.cs
CanoePoloLeagueOrganiser/GamesNotPlayedBetweenFirstAndLast.cs
using System; using System.Collections.Generic; using static System.Diagnostics.Contracts.Contract; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace CanoePoloLeagueOrganiser { public class GamesNotPlayedBetweenFirstAndLast { GameList GameList { get; set; } public uint Calculate(GameList gameList) { Requires(gameList != null); GameList = gameList; return (uint)GameList.Teams.Sum(team => GamesNotPlayedBetweenFirstAndLastByTeam(team.Name)); } uint GamesNotPlayedBetweenFirstAndLastByTeam(string team) => new GamesNotPlayedBetweenFirstAndLastByTeam(GameList.Games, team).Calculate(); } }
using System; using System.Collections.Generic; using static System.Diagnostics.Contracts.Contract; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace CanoePoloLeagueOrganiser { public class GamesNotPlayedBetweenFirstAndLast { GameList GameList { get; set; } public uint Calculate(GameList gameList) { Requires(gameList != null); GameList = gameList; return (uint)GameList.Teams.Sum(team => GamesNotPlayedBetweenFirstAndLastByTeam(team.Name)); } //IEnumerable<string> Teams => // HomeTeams // .Concat(AwayTeams) // .Distinct(); uint GamesNotPlayedBetweenFirstAndLastByTeam(string team) => new GamesNotPlayedBetweenFirstAndLastByTeam(GameList.Games, team).Calculate(); //IEnumerable<string> HomeTeams => // GameList.Select(game => game.HomeTeam.Name); //IEnumerable<string> AwayTeams => // GameList.Select(game => game.AwayTeam.Name); } }
mit
C#
a09260ab41b46c0c2a43b6207ce8a26ae9be21bd
Add pictures count of category
SoftwareFans/AstroPhotoGallery,SoftwareFans/AstroPhotoGallery,SoftwareFans/AstroPhotoGallery
AstroPhotoGallery/AstroPhotoGallery/Views/Home/ListCategories.cshtml
AstroPhotoGallery/AstroPhotoGallery/Views/Home/ListCategories.cshtml
@model PagedList.IPagedList<AstroPhotoGallery.Models.Category> @using PagedList.Mvc; @using System.Linq; @{ ViewBag.Title = "List"; } <link href="~/Content/PagedList.css" rel="stylesheet" /> <div class="container"> <h2 class="text-center">Browse by categories</h2> <br/> @foreach (var category in Model) { <div class="col-sm-4"> <div class="thumbnail "> @if (category.Pictures.Any(p => p.CategoryId == category.Id)) { <img src="@Url.Content(category.Pictures.Where(p => p.CategoryId == category.Id).FirstOrDefault().ImagePath)" style="height:190px;width:350px"> } else { <img src="~/Content/images/default-gallery-image.jpg" style="height:190px;width:350px" /> } <div class="caption text-center "> <h4> @Html.ActionLink(string.Format($"{category.Name}({category.Pictures.Count})"), "ListPictures", "Home", new { @categoryId = category.Id }, null) </h4> </div> </div> </div> } </div> Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount @Html.PagedListPager(Model, page => Url.Action("ListCategories", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
@model PagedList.IPagedList<AstroPhotoGallery.Models.Category> @using PagedList.Mvc; @using System.Linq; @{ ViewBag.Title = "List"; } <link href="~/Content/PagedList.css" rel="stylesheet" /> <div class="container"> <h2 class="text-center">Browse by categories</h2> <br/> @foreach (var category in Model) { <div class="col-sm-4"> <div class="thumbnail "> @if (category.Pictures.Any(p => p.CategoryId == category.Id)) { <img src="@Url.Content(category.Pictures.Where(p => p.CategoryId == category.Id).FirstOrDefault().ImagePath)" style="height:190px;width:350px"> } else { <img src="~/Content/images/default-gallery-image.jpg" style="height:190px;width:350px" /> } <div class="caption text-center "> <h4> @Html.ActionLink(string.Format($"{category.Name}"), "ListPictures", "Home", new { @categoryId = category.Id }, null) </h4> </div> </div> </div> } </div> Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount @Html.PagedListPager(Model, page => Url.Action("ListCategories", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
mit
C#
03c6e989be2835d4f143a19577e040962b912781
Comment fix
vvolkgang/XUTSample.Twitter
Evolve2016Twitter/TwitterUiTest.cs
Evolve2016Twitter/TwitterUiTest.cs
using NUnit.Framework; using System; using Xamarin.UITest.Android; using System.Reflection; using System.IO; using Xamarin.UITest; using Xamarin.UITest.Queries; using System.Linq; using Evolve2016Twitter; namespace Evolve2016Twitter.UITest { [TestFixture] public class TwitterUiTest : BaseTestFixture { private const string _username = "CHAMGE_ME"; private const string _password = "CHANGE_ME"; private readonly string _tweet = $"@XamarinHQ #TweetCeption from device {DeviceId} in #TestCloud. Check #DementedVice and @vvolkgang for results!"; private static string DeviceId => Environment.GetEnvironmentVariable("XTC_DEVICE_INDEX") ?? "1"; [Test] public void Login_and_tweet() { //LOGIN _app.WaitTapWait(_queries.LoginInFirstViewButton, "Given I'm in the initial view", _queries.Username, "When I tap Login button, I'm presented with the Login view"); _app.WaitAndEnterText(_queries.Username, _username, "After I insert my Username, I can see the username field filled"); _app.WaitAndEnterText(_queries.Password, _password, "After I insert my Password, I can see the password field filled"); _app.TapAndWait(_queries.LoginButton, _queries.OkButton, "When I tap the Login button, I can see the Logged in view"); _app.Tap(_queries.OkButton); //NOTE(avfe) this is the "Twitter would like to use your location" dialog _app.Screenshot("After I login, I can see the twitter timeline"); //TWEET _app.TapAndWait(_queries.CreateNewTweet, _queries.TweetBox, "After I tap the Whats Happening box, I can see the tweet composer"); _app.EnterText(_queries.TweetBox, _tweet ); _app.Screenshot("After I insert my tweet, I can see the composer view filled"); _app.TapAndWait(_queries.SendTweetButton, _queries.CreateNewTweet, "When I tap Tweet button, I'm back to the timeline"); } } }
using NUnit.Framework; using System; using Xamarin.UITest.Android; using System.Reflection; using System.IO; using Xamarin.UITest; using Xamarin.UITest.Queries; using System.Linq; using Evolve2016Twitter; namespace Evolve2016Twitter.UITest { [TestFixture] public class TwitterUiTest : BaseTestFixture { private const string _username = "CHAMGE_ME"; private const string _password = "CHANGE_ME"; private readonly string _tweet = $"@XamarinHQ #TweetCeption from device {DeviceId} in #TestCloud. Check #DementedVice and @vvolkgang for results!"; private static string DeviceId => Environment.GetEnvironmentVariable("XTC_DEVICE_INDEX") ?? "1"; [Test] public void Login_and_tweet() { //LOGIN _app.WaitTapWait(_queries.LoginInFirstViewButton, "Given I'm in the initial view", _queries.Username, "When I tap Login button, I'm presented with the Login view"); _app.WaitAndEnterText(_queries.Username, _username, "After I insert my Username, I can see the username field filled"); _app.WaitAndEnterText(_queries.Password, _password, "After I insert my Password, I can see the password field filled"); _app.TapAndWait(_queries.LoginButton, _queries.OkButton, "When I tap the Login button, I can see the Logged in view"); _app.Tap(_queries.OkButton); //NOTE(alison) this is the "Twitter would like to use your location" dialog _app.Screenshot("After I login, I can see the twitter timeline"); //TWEET _app.TapAndWait(_queries.CreateNewTweet, _queries.TweetBox, "After I tap the Whats Happening box, I can see the tweet composer"); _app.EnterText(_queries.TweetBox, _tweet ); _app.Screenshot("After I insert my tweet, I can see the composer view filled"); _app.TapAndWait(_queries.SendTweetButton, _queries.CreateNewTweet, "When I tap Tweet button, I'm back to the timeline"); } } }
mit
C#
735986c41c1b9dfda00d7e861a1fa86948819be0
Update CharacterControllerExample.cs
HiddenMonk/Unity3DCustomCharacterControllerCapsuleCollisionDetection
Assets/CapsuleCharacterCollision/CharacterControllerExample/CharacterControllerExample.cs
Assets/CapsuleCharacterCollision/CharacterControllerExample/CharacterControllerExample.cs
using System; using UnityEngine; namespace CapsuleCharacterCollisionDetection { public class CharacterControllerExample : PlayerRigidbody //We inherit PlayerRigidbody so that we can easily connect with its subUpdater. You can handle this any way you want though. { public float walkSpeed = 10f; public float airSpeed = .6f; public float jumpForce = 10f; public float gravity = 20f; void Start() { autoUpdate = false; } void Update() { //For framerate independent movement, forces like gravity must be used with ForceMode.Force or Acceleration, at least from my testing. //Likewise, jumping must be used with ForceMode.Impulse or VelocityChange. Jump(); //Should probably be put inside DoMovementForces for framerate independent accuracy. Gravity(); //Should be fine in here since its a constant force. //We call it here to ensure our mouselook script is ran after we moved to avoid jitter UpdateRigidbody(); } //Since our walking is dependent on our grounding, we need to run our walk code within the rigidbody substep loop for framerate independence. //Otherwise we will walk with the normal speed, then our subloop would detect that we are actually now in the air, but we would still be using the normal speed. //If we wanted our gravity to stop when grounded, I think we would also need to put it in here, use as ForceMode.Impulse and multiply by the deltaTime for framerate independence. protected override void DoMovementForces(float deltaTime) { Walk(deltaTime); } void Walk(float deltaTime) { Vector3 inputDirection = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical")).normalized; if(inputDirection != Vector3.zero) { float speed = (isGrounded) ? walkSpeed * 10f : airSpeed * 10f; AddRelativeForce((inputDirection * speed) * deltaTime, ForceMode.Impulse); //We set it as ForceMode.Impulse since we are multiplying it with deltaTime ourselves within the subUpdater loop } } void Jump() { if(isGrounded && Input.GetKeyDown(KeyCode.Space)) { AddRelativeForce(Vector3.up * jumpForce, ForceMode.Impulse); } } void Gravity() { AddRelativeForce(Vector3.down * gravity, ForceMode.Force); } } }
using System; using UnityEngine; namespace CapsuleCharacterCollisionDetection { public class CharacterControllerExample : PlayerRigidbody //We inherit PlayerRigidbody so that we can easily connect with its subUpdater. You can handle this any way you want though. { public float walkSpeed = 10f; public float airSpeed = .6f; public float jumpForce = 10f; public float gravity = 20f; void Start() { autoUpdate = false; } void Update() { //For framerate independent movement, forces like gravity must be used with ForceMode.Force or Acceleration, at least from my testing. //Likewise, jumping must be used with ForceMode.Impulse or VelocityChange. Jump(); Gravity(); //We call it here to ensure our mouselook script is ran after we moved to avoid jitter UpdateRigidbody(); } //Since our walking is dependent on our grounding, we need to run our walk code within the rigidbody substep loop for framerate independence. //Otherwise we will walk with the normal speed, then our subloop would detect that we are actually now in the air, but we would still be using the normal speed. //If we wanted our gravity to stop when grounded, I think we would also need to put it in here, use as ForceMode.Impulse and multiply by the deltaTime for framerate independence. protected override void DoMovementForces(float deltaTime) { Walk(deltaTime); } void Walk(float deltaTime) { Vector3 inputDirection = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical")).normalized; if(inputDirection != Vector3.zero) { float speed = (isGrounded) ? walkSpeed * 10f : airSpeed * 10f; AddRelativeForce((inputDirection * speed) * deltaTime, ForceMode.Impulse); //We set it as ForceMode.Impulse since we are multiplying it with deltaTime ourselves within the subUpdater loop } } void Jump() { if(isGrounded && Input.GetKeyDown(KeyCode.Space)) { AddRelativeForce(Vector3.up * jumpForce, ForceMode.Impulse); } } void Gravity() { AddRelativeForce(Vector3.down * gravity, ForceMode.Force); } } }
mit
C#
7d9f648a0982687d90ab0c4ff56093dca3000427
Add new argument check
dsbenghe/Novell.Directory.Ldap.NETStandard,dsbenghe/Novell.Directory.Ldap.NETStandard
src/Novell.Directory.Ldap.NETStandard/Utilclass/StringExtensions.cs
src/Novell.Directory.Ldap.NETStandard/Utilclass/StringExtensions.cs
using System; namespace Novell.Directory.Ldap.Utilclass { public static class StringExtensions { /// <summary> /// Replaces string.Substring(offset).StartsWith(value) and avoids memory allocations /// </summary> public static bool StartsWithStringAtOffset(this string baseString, string value, int offset) { if (value == null) throw new ArgumentNullException(nameof(value)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (offset > baseString.Length) throw new ArgumentOutOfRangeException(nameof(offset), "offset cannot be larger than length of string"); if (offset + value.Length > baseString.Length) { return false; } for (int i = 0; i < value.Length; i++) { if (baseString[offset + i] != value[i]) return false; } return true; } } }
using System; namespace Novell.Directory.Ldap.Utilclass { public static class StringExtensions { /// <summary> /// Replaces string.Substring(offset).StartsWith(value) and avoids memory allocations /// </summary> public static bool StartsWithStringAtOffset(this string baseString, string value, int offset) { if (value == null) throw new ArgumentNullException(nameof(value)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (offset + value.Length > baseString.Length) { return false; } for (int i = 0; i < value.Length; i++) { if (baseString[offset + i] != value[i]) return false; } return true; } } }
mit
C#
6fbe4a25977a3aaaf2332c5125576744a18f6275
Allow SampleRate setting for any resource type
hudl/HudlFfmpeg
Hudl.Ffmpeg/Settings/SampleRate.cs
Hudl.Ffmpeg/Settings/SampleRate.cs
using System; using Hudl.FFmpeg.Attributes; using Hudl.FFmpeg.Enums; using Hudl.FFmpeg.Resources.BaseTypes; using Hudl.FFmpeg.Settings.Attributes; using Hudl.FFmpeg.Settings.BaseTypes; using Hudl.FFmpeg.Settings.Interfaces; namespace Hudl.FFmpeg.Settings { [ForStream(Type = typeof(AudioStream))] [Setting(Name = "ar", ResourceType = SettingsCollectionResourceType.Any)] public class SampleRate : ISetting { public SampleRate(double rate) { if (rate <= 0) { throw new ArgumentException("Sample rate must be greater than zero."); } Rate = rate; } [SettingParameter] [Validate(LogicalOperators.GreaterThan, 0)] public double Rate { get; set; } } }
using System; using Hudl.FFmpeg.Attributes; using Hudl.FFmpeg.Enums; using Hudl.FFmpeg.Resources.BaseTypes; using Hudl.FFmpeg.Settings.Attributes; using Hudl.FFmpeg.Settings.BaseTypes; using Hudl.FFmpeg.Settings.Interfaces; namespace Hudl.FFmpeg.Settings { [ForStream(Type = typeof(AudioStream))] [Setting(Name = "ar")] public class SampleRate : ISetting { public SampleRate(double rate) { if (rate <= 0) { throw new ArgumentException("Sample rate must be greater than zero."); } Rate = rate; } [SettingParameter] [Validate(LogicalOperators.GreaterThan, 0)] public double Rate { get; set; } } }
apache-2.0
C#
1a50a65a2678ad8ea0a2fc9aa2d3c00a6c3c4fe4
Add default log levels for FileLoggingConfiguration
tgstation/tgstation-server,Cyberboss/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server
src/Tgstation.Server.Host/Configuration/FileLoggingConfiguration.cs
src/Tgstation.Server.Host/Configuration/FileLoggingConfiguration.cs
using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Tgstation.Server.Host.Configuration { /// <summary> /// File logging configuration options /// </summary> sealed class FileLoggingConfiguration { /// <summary> /// The key for the <see cref="Microsoft.Extensions.Configuration.IConfigurationSection"/> the <see cref="FileLoggingConfiguration"/> resides in /// </summary> public const string Section = "FileLogging"; /// <summary> /// Default value for <see cref="LogLevel"/> /// </summary> const LogLevel DefaultLogLevel = LogLevel.Debug; /// <summary> /// Default value for <see cref="MicrosoftLogLevel"/> /// </summary> const LogLevel DefaultMicrosoftLogLevel = LogLevel.Warning; /// <summary> /// Where log files are stored /// </summary> public string Directory { get; set; } /// <summary> /// If file logging is disabled /// </summary> public bool Disable { get; set; } /// <summary> /// The <see cref="string"/>ified minimum <see cref="Microsoft.Extensions.Logging.LogLevel"/> to display in logs /// </summary> [JsonConverter(typeof(StringEnumConverter))] public LogLevel LogLevel { get; set; } = DefaultLogLevel; /// <summary> /// The <see cref="string"/>ified minimum <see cref="Microsoft.Extensions.Logging.LogLevel"/> to display in logs for Microsoft library sources /// </summary> [JsonConverter(typeof(StringEnumConverter))] public LogLevel MicrosoftLogLevel { get; set; } = DefaultMicrosoftLogLevel; } }
using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Tgstation.Server.Host.Configuration { /// <summary> /// File logging configuration options /// </summary> sealed class FileLoggingConfiguration { /// <summary> /// The key for the <see cref="Microsoft.Extensions.Configuration.IConfigurationSection"/> the <see cref="FileLoggingConfiguration"/> resides in /// </summary> public const string Section = "FileLogging"; /// <summary> /// Where log files are stored /// </summary> public string Directory { get; set; } /// <summary> /// If file logging is disabled /// </summary> public bool Disable { get; set; } /// <summary> /// The <see cref="string"/>ified minimum <see cref="Microsoft.Extensions.Logging.LogLevel"/> to display in logs /// </summary> [JsonConverter(typeof(StringEnumConverter))] public LogLevel LogLevel { get; set; } /// <summary> /// The <see cref="string"/>ified minimum <see cref="Microsoft.Extensions.Logging.LogLevel"/> to display in logs for Microsoft library sources /// </summary> [JsonConverter(typeof(StringEnumConverter))] public LogLevel MicrosoftLogLevel { get; set; } } }
agpl-3.0
C#
1e1c954faae8f97cd8d8c1104372ad14f192f1b9
Update test methods for DbContextFactory
aliencube/Entity-Context-Library,aliencube/Entity-Context-Library,aliencube/Entity-Context-Library
SourceCodes/Tests/EntityContextLibrary.Tests/DbContextFactoryTest.cs
SourceCodes/Tests/EntityContextLibrary.Tests/DbContextFactoryTest.cs
using System; using Aliencube.EntityContextLibrary.Interfaces; using FluentAssertions; using NUnit.Framework; namespace Aliencube.EntityContextLibrary.Tests { /// <summary> /// This represents the test entity for the <see cref="DbContextFactory{TContext}" /> class. /// </summary> [TestFixture] public class DbContextFactoryTest { private IDbContextFactory _factory; /// <summary> /// Initialises all resources for tests. /// </summary> [SetUp] public void Init() { AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Directory.GetCurrentDirectory()); this._factory = new DbContextFactory<ProductContext>(); } /// <summary> /// Release all resources after tests. /// </summary> [TearDown] public void Cleanup() { if (this._factory != null) { this._factory.Dispose(); } } /// <summary> /// Tests whether the context factory returns DbContext with given type or not. /// </summary> /// <param name="expectedType"> /// The expected type. /// </param> [Test] [TestCase(typeof(ProductContext))] public void ContextFactory_Should_Return_Context_Of_Given_Type(Type expectedType) { var context = this._factory.Context; context.Should().NotBeNull(); context.Should().BeOfType(expectedType); } } }
using System; using Aliencube.EntityContextLibrary.Interfaces; using FluentAssertions; using NUnit.Framework; namespace Aliencube.EntityContextLibrary.Tests { [TestFixture] public class DbContextFactoryTest { private IDbContextFactory _factory; [SetUp] public void Init() { AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Directory.GetCurrentDirectory()); this._factory = new DbContextFactory<ProductContext>(); } [TearDown] public void Cleanup() { if (this._factory != null) { this._factory.Dispose(); } } [Test] [TestCase(typeof(ProductContext))] public void GetContext_GivenDetails_ReturnContext(Type expectedType) { var context = this._factory.Context; context.Should().NotBeNull(); context.Should().BeOfType(expectedType); } } }
mit
C#
7047bf4f6b30f6eadaca2588468db298fa2ac8e3
Update assembly attributes
andrevdm/ttree
TTree/Properties/AssemblyInfo.cs
TTree/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System; // 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( "TTree" )] [assembly: AssemblyDescription( "C# T-Tree implementation" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Andre Van Der Merwe" )] [assembly: AssemblyProduct( "TTree" )] [assembly: AssemblyCopyright( "Public domain" )] [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 )] [assembly: CLSCompliant(true)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "8704a11e-4278-43ae-a054-8743d972b30c" )] // 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.*" )] [assembly: AssemblyFileVersion( "1.0.0.0" )]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System; // 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( "TTree" )] [assembly: AssemblyDescription( "C# T-Tree implementation" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Andre Van Der Merwe" )] [assembly: AssemblyProduct( "TTree" )] [assembly: AssemblyCopyright( "Public domain" )] [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 )] [assembly: CLSCompliant(true)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "8704a11e-4278-43ae-a054-8743d972b30c" )] // 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.*.*" )] [assembly: AssemblyFileVersion( "1.0.0.0" )]
mit
C#
f1412c21ac8bbdd4cdc3ea083e729ef576319153
Fix the build
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.AspNet.Mvc.Razor/Compilation/CompilationOptionsProviderExtension.cs
src/Microsoft.AspNet.Mvc.Razor/Compilation/CompilationOptionsProviderExtension.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.Dnx.Compilation; using Microsoft.Dnx.Compilation.CSharp; using Microsoft.Extensions.PlatformAbstractions; namespace Microsoft.AspNet.Mvc.Razor.Compilation { /// <summary> /// Extension methods for <see cref="ICompilerOptionsProvider"/>. /// </summary> public static class CompilationOptionsProviderExtension { /// <summary> /// Parses the <see cref="ICompilerOptions"/> for the current executing application and returns a /// <see cref="CompilationSettings"/> used for Roslyn compilation. /// </summary> /// <param name="compilerOptionsProvider"> /// A <see cref="ICompilerOptionsProvider"/> that reads compiler options. /// </param> /// <param name="applicationEnvironment"> /// The <see cref="IApplicationEnvironment"/> for the executing application. /// </param> /// <returns>The <see cref="CompilationSettings"/> for the current application.</returns> public static CompilationSettings GetCompilationSettings( this ICompilerOptionsProvider compilerOptionsProvider, IApplicationEnvironment applicationEnvironment) { if (compilerOptionsProvider == null) { throw new ArgumentNullException(nameof(compilerOptionsProvider)); } if (applicationEnvironment == null) { throw new ArgumentNullException(nameof(applicationEnvironment)); } return compilerOptionsProvider.GetCompilerOptions(applicationEnvironment.ApplicationName, applicationEnvironment.RuntimeFramework, applicationEnvironment.Configuration) .ToCompilationSettings(applicationEnvironment.RuntimeFramework, applicationEnvironment.ApplicationBasePath); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.Dnx.Compilation; using Microsoft.Dnx.Compilation.CSharp; using Microsoft.Extensions.PlatformAbstractions; namespace Microsoft.AspNet.Mvc.Razor.Compilation { /// <summary> /// Extension methods for <see cref="ICompilerOptionsProvider"/>. /// </summary> public static class CompilationOptionsProviderExtension { /// <summary> /// Parses the <see cref="ICompilerOptions"/> for the current executing application and returns a /// <see cref="CompilationSettings"/> used for Roslyn compilation. /// </summary> /// <param name="compilerOptionsProvider"> /// A <see cref="ICompilerOptionsProvider"/> that reads compiler options. /// </param> /// <param name="applicationEnvironment"> /// The <see cref="IApplicationEnvironment"/> for the executing application. /// </param> /// <returns>The <see cref="CompilationSettings"/> for the current application.</returns> public static CompilationSettings GetCompilationSettings( this ICompilerOptionsProvider compilerOptionsProvider, IApplicationEnvironment applicationEnvironment) { if (compilerOptionsProvider == null) { throw new ArgumentNullException(nameof(compilerOptionsProvider)); } if (applicationEnvironment == null) { throw new ArgumentNullException(nameof(applicationEnvironment)); } return compilerOptionsProvider.GetCompilerOptions(applicationEnvironment.ApplicationName, applicationEnvironment.RuntimeFramework, applicationEnvironment.Configuration) .ToCompilationSettings(applicationEnvironment.RuntimeFramework); } } }
apache-2.0
C#
327d46ebbd28c618e09945ac6a390b8527abed5c
Fix bug
mhertis/Orleankka,yevhen/Orleankka,OrleansContrib/Orleankka,pkese/Orleankka,yevhen/Orleankka,OrleansContrib/Orleankka,pkese/Orleankka,mhertis/Orleankka
Source/Orleankka.Runtime/Actor.cs
Source/Orleankka.Runtime/Actor.cs
using System; using System.Threading.Tasks; namespace Orleankka { using Core; using Behaviors; using Services; using Utility; public abstract class Actor { ActorRef self; protected Actor() { Behavior = ActorBehavior.Null(this); } protected Actor(string id, IActorRuntime runtime, Dispatcher dispatcher = null) : this() { Requires.NotNull(runtime, nameof(runtime)); Requires.NotNullOrWhitespace(id, nameof(id)); Runtime = runtime; Dispatcher = dispatcher ?? ActorType.Dispatcher(GetType()); Path = GetType().ToActorPath(id); } internal virtual void Initialize(IActorHost host, ActorPath path, IActorRuntime runtime, Dispatcher dispatcher) { Path = path; Runtime = runtime; Dispatcher = Dispatcher ?? dispatcher; Host = host; } public string Id => Path.Id; internal IActorHost Host {get; private set;} public ActorPath Path {get; private set;} public IActorRuntime Runtime {get; private set;} public ActorBehavior Behavior {get; private set;} public Dispatcher Dispatcher {get; private set;} public IActorSystem System => Runtime.System; public IActivationService Activation => Runtime.Activation; public IReminderService Reminders => Runtime.Reminders; public ITimerService Timers => Runtime.Timers; public ActorRef Self => self ?? (self = System.ActorOf(Path)); public virtual Task OnActivate() => Behavior.HandleActivate(); public virtual Task OnDeactivate() => Behavior.HandleDeactivate(); public virtual Task<object> OnReceive(object message) => Behavior.HandleReceive(message); public virtual Task OnReminder(string id) => Behavior.HandleReminder(id); public async Task<TResult> Dispatch<TResult>(object message, Func<object, Task<object>> fallback = null) => (TResult)await Dispatch(message, fallback); public Task<object> Dispatch(object message, Func<object, Task<object>> fallback = null) { Requires.NotNull(message, nameof(message)); return Dispatcher.Dispatch(this, message, fallback); } } }
using System; using System.Threading.Tasks; namespace Orleankka { using Core; using Behaviors; using Services; using Utility; public abstract class Actor { ActorRef self; protected Actor() { Behavior = ActorBehavior.Null(this); } protected Actor(string id, IActorRuntime runtime, Dispatcher dispatcher = null) : this() { Requires.NotNull(runtime, nameof(runtime)); Requires.NotNullOrWhitespace(id, nameof(id)); Runtime = runtime; Dispatcher = dispatcher ?? ActorType.Dispatcher(GetType()); Path = runtime.GetType().ToActorPath(id); } internal virtual void Initialize(IActorHost host, ActorPath path, IActorRuntime runtime, Dispatcher dispatcher) { Path = path; Runtime = runtime; Dispatcher = Dispatcher ?? dispatcher; Host = host; } public string Id => Path.Id; internal IActorHost Host {get; private set;} public ActorPath Path {get; private set;} public IActorRuntime Runtime {get; private set;} public ActorBehavior Behavior {get; private set;} public Dispatcher Dispatcher {get; private set;} public IActorSystem System => Runtime.System; public IActivationService Activation => Runtime.Activation; public IReminderService Reminders => Runtime.Reminders; public ITimerService Timers => Runtime.Timers; public ActorRef Self => self ?? (self = System.ActorOf(Path)); public virtual Task OnActivate() => Behavior.HandleActivate(); public virtual Task OnDeactivate() => Behavior.HandleDeactivate(); public virtual Task<object> OnReceive(object message) => Behavior.HandleReceive(message); public virtual Task OnReminder(string id) => Behavior.HandleReminder(id); public async Task<TResult> Dispatch<TResult>(object message, Func<object, Task<object>> fallback = null) => (TResult)await Dispatch(message, fallback); public Task<object> Dispatch(object message, Func<object, Task<object>> fallback = null) { Requires.NotNull(message, nameof(message)); return Dispatcher.Dispatch(this, message, fallback); } } }
apache-2.0
C#
9f189f837a07c612051d3bcce8d98fd7f7811241
Implement ShapeBatcher
Vtek/Pulsar
Src/Pulsar/Graphics/ShapeBatch.cs
Src/Pulsar/Graphics/ShapeBatch.cs
using System; using SFML.Graphics; using Pulsar.Helpers; namespace Pulsar.Graphics { /// <summary> /// Shape batcher. /// </summary> public class ShapeBatch : GraphicsBatch { /// <summary> /// The _rectangle. /// </summary> private readonly RectangleShape _rectangle = new RectangleShape(); /// <summary> /// Initializes a new instance of the <see cref="Pulsar.Graphics.ShapeBatch"/> class. /// </summary> /// <param name="renderTarget">Render target.</param> public ShapeBatch(RenderTarget renderTarget) : base(renderTarget) { } /// <summary> /// Draws the rectangle. /// </summary> /// <param name="rectangle">Rectangle.</param> /// <param name="position">Position.</param> /// <param name="fillColor">Fill color.</param> /// <param name="borderColor">Border color.</param> /// <param name="rotation">Rotation.</param> /// <param name="origin">Origin.</param> /// <param name="scale">Scale.</param> public void DrawRectangle(Rectangle rectangle, Vector position, Color fillColor, Color borderColor, float rotation, Vector origin, float scale) { var p = _rectangle.Position; p.X = position.X; p.Y = position.X; _rectangle.Position = p; var fc = _rectangle.FillColor; fc.A = fillColor.A; fc.B = fillColor.B; fc.G = fillColor.G; fc.R = fillColor.R; _rectangle.FillColor = fc; var oc = _rectangle.OutlineColor; oc.A = fillColor.A; oc.B = fillColor.B; oc.G = fillColor.G; oc.R = fillColor.R; _rectangle.FillColor = oc; _rectangle.Rotation = MathHelper.ToDegrees(rotation); var o = _rectangle.Origin; o.X = origin.X; o.Y = origin.Y; _rectangle.Origin = o; var s = _rectangle.Scale; s.X = scale; s.Y = scale; _rectangle.Scale = s; RenderTarget.Draw(_rectangle); } /// <summary> /// Draws rectangle. /// </summary> /// <param name="rectangle">Rectangle.</param> /// <param name="position">Position.</param> /// <param name="fillColor">Fill color.</param> /// <param name="borderColor">Border color.</param> public void DrawRectangle(Rectangle rectangle, Vector position, Color fillColor, Color borderColor) { DrawRectangle (rectangle, position, fillColor, borderColor, 0, Vector.Zero, 0); } } }
using System; using SFML.Graphics; //TODO complete implementation for ShapeBatcher namespace Pulsar.Graphics { /// <summary> /// Shape batcher. /// </summary> public class ShapeBatch : GraphicsBatch { /// <summary> /// The _rectangle. /// </summary> private readonly RectangleShape _rectangle = new RectangleShape(); /// <summary> /// The _circle. /// </summary> private readonly CircleShape _circle = new CircleShape(); /// <summary> /// Initializes a new instance of the <see cref="Pulsar.Graphics.ShapeBatch"/> class. /// </summary> /// <param name="renderTarget">Render target.</param> public ShapeBatch(RenderTarget renderTarget) : base(renderTarget) { } } }
mit
C#
85a443783755a52cc2d46581644180a264339a2d
Fix editor custom FadeOut causing overlapping issues by removing existing FadeOut
peppy/osu,ppy/osu,2yangk23/osu,EVAST9919/osu,peppy/osu-new,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,johnneijzen/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,johnneijzen/osu,ppy/osu,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu,EVAST9919/osu,NeoAdonis/osu,peppy/osu,2yangk23/osu,peppy/osu
osu.Game.Rulesets.Osu/Edit/DrawableOsuEditRuleset.cs
osu.Game.Rulesets.Osu/Edit/DrawableOsuEditRuleset.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.Collections.Generic; using System.Linq; using osu.Framework.Graphics; using osu.Game.Beatmaps; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.UI; using osu.Game.Rulesets.UI; using osuTK; namespace osu.Game.Rulesets.Osu.Edit { public class DrawableOsuEditRuleset : DrawableOsuRuleset { /// <summary> /// Hit objects are intentionally made to fade out at a constant slower rate than in gameplay. /// This allows a mapper to gain better historical context and use recent hitobjects as reference / snap points. /// </summary> private const double editor_hit_object_fade_out_extension = 500; public DrawableOsuEditRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods) : base(ruleset, beatmap, mods) { } public override DrawableHitObject<OsuHitObject> CreateDrawableRepresentation(OsuHitObject h) => base.CreateDrawableRepresentation(h)?.With(d => d.ApplyCustomUpdateState += updateState); private void updateState(DrawableHitObject hitObject, ArmedState state) { switch (state) { case ArmedState.Miss: // Get the existing fade out transform var existing = hitObject.Transforms.LastOrDefault(t => t.TargetMember == nameof(Alpha)); if (existing == null) return; hitObject.RemoveTransform(existing); using (hitObject.BeginAbsoluteSequence(existing.StartTime)) hitObject.FadeOut(editor_hit_object_fade_out_extension).Expire(); break; } } protected override Playfield CreatePlayfield() => new OsuPlayfieldNoCursor(); public override PlayfieldAdjustmentContainer CreatePlayfieldAdjustmentContainer() => new OsuPlayfieldAdjustmentContainer { Size = Vector2.One }; private class OsuPlayfieldNoCursor : OsuPlayfield { protected override GameplayCursorContainer CreateCursor() => null; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Framework.Graphics; using osu.Game.Beatmaps; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.UI; using osu.Game.Rulesets.UI; using osuTK; namespace osu.Game.Rulesets.Osu.Edit { public class DrawableOsuEditRuleset : DrawableOsuRuleset { /// <summary> /// Hit objects are intentionally made to fade out at a constant slower rate than in gameplay. /// This allows a mapper to gain better historical context and use recent hitobjects as reference / snap points. /// </summary> private const double editor_hit_object_fade_out_extension = 500; public DrawableOsuEditRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods) : base(ruleset, beatmap, mods) { } public override DrawableHitObject<OsuHitObject> CreateDrawableRepresentation(OsuHitObject h) => base.CreateDrawableRepresentation(h)?.With(d => d.ApplyCustomUpdateState += updateState); private void updateState(DrawableHitObject hitObject, ArmedState state) { switch (state) { case ArmedState.Miss: // Get the existing fade out transform var existing = hitObject.Transforms.LastOrDefault(t => t.TargetMember == nameof(Alpha)); if (existing == null) return; using (hitObject.BeginAbsoluteSequence(existing.StartTime)) hitObject.FadeOut(editor_hit_object_fade_out_extension).Expire(); break; } } protected override Playfield CreatePlayfield() => new OsuPlayfieldNoCursor(); public override PlayfieldAdjustmentContainer CreatePlayfieldAdjustmentContainer() => new OsuPlayfieldAdjustmentContainer { Size = Vector2.One }; private class OsuPlayfieldNoCursor : OsuPlayfield { protected override GameplayCursorContainer CreateCursor() => null; } } }
mit
C#
98b12383af4e3986294be3cd73b39febb79e15d5
Check we have a message as well when checking the flashmessage view model
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerApprenticeshipsService.Web/Views/Shared/_SuccessMessage.cshtml
src/SFA.DAS.EmployerApprenticeshipsService.Web/Views/Shared/_SuccessMessage.cshtml
@using SFA.DAS.EmployerApprenticeshipsService.Web @using SFA.DAS.EmployerApprenticeshipsService.Web.Models @model dynamic @{ var viewModel = Model as OrchestratorResponse; } @if (!string.IsNullOrEmpty(viewModel?.FlashMessage?.Message)) { <div class="grid-row"> <div class="column-full"> <div class="@viewModel.FlashMessage.SeverityCssClass"> @if (!string.IsNullOrWhiteSpace(viewModel.FlashMessage.Headline)) { <h1 class="bold-large">@viewModel.FlashMessage.Headline</h1> } @if (!string.IsNullOrEmpty(viewModel.FlashMessage.Message)) { <p>@viewModel.FlashMessage.Message</p> } @if (!string.IsNullOrEmpty(viewModel.FlashMessage.SubMessage)) { <p>@viewModel.FlashMessage.SubMessage</p> } </div> </div> </div> }
@using SFA.DAS.EmployerApprenticeshipsService.Web @using SFA.DAS.EmployerApprenticeshipsService.Web.Models @model dynamic @{ var viewModel = Model as OrchestratorResponse; } @if (viewModel?.FlashMessage != null) { <div class="grid-row"> <div class="column-full"> <div class="@viewModel.FlashMessage.SeverityCssClass"> @if (!string.IsNullOrWhiteSpace(viewModel.FlashMessage.Headline)) { <h1 class="bold-large">@viewModel.FlashMessage.Headline</h1> } @if (!string.IsNullOrEmpty(viewModel.FlashMessage.Message)) { <p>@viewModel.FlashMessage.Message</p> } @if (!string.IsNullOrEmpty(viewModel.FlashMessage.SubMessage)) { <p>@viewModel.FlashMessage.SubMessage</p> } </div> </div> </div> }
mit
C#
80170d5e758ac5cf9259a0078e0c65179c8dd747
Remove --indexed flag from Generate-Tilemap, use IsIndexed property from tilemap format instead
Prof9/PixelPet
PixelPet/CLI/Commands/GenerateTilemapCmd.cs
PixelPet/CLI/Commands/GenerateTilemapCmd.cs
using LibPixelPet; using System; using System.Drawing; namespace PixelPet.CLI.Commands { internal class GenerateTilemapCmd : CliCommand { public GenerateTilemapCmd() : base("Generate-Tilemap", new Parameter(true, new ParameterValue("format")), new Parameter("no-reduce", "nr", false), new Parameter("x", "x", false, new ParameterValue("pixels", "0")), new Parameter("y", "y", false, new ParameterValue("pixels", "0")), new Parameter("width", "w", false, new ParameterValue("pixels", "-1")), new Parameter("height", "h", false, new ParameterValue("pixels", "-1")) ) { } public override void Run(Workbench workbench, ILogger logger) { string fmtName = FindUnnamedParameter(0).Values[0].Value; bool noReduce = FindNamedParameter("--no-reduce").IsPresent; int x = FindNamedParameter("--x").Values[0].ToInt32(); int y = FindNamedParameter("--y").Values[0].ToInt32(); int w = FindNamedParameter("--width").Values[0].ToInt32(); int h = FindNamedParameter("--height").Values[0].ToInt32(); if (!(TilemapFormat.GetFormat(fmtName) is TilemapFormat fmt)) { logger?.Log("Unknown tilemap format \"" + fmtName + "\".", LogLevel.Error); return; } int beforeCount = workbench.Tilemap.Count; using (Bitmap bmp = workbench.GetCroppedBitmap(x, y, w, h, logger)) { if (fmt.IsIndexed) { workbench.Tilemap.AddBitmapIndexed(bmp, workbench.Tileset, workbench.PaletteSet, fmt, !noReduce); } else { workbench.Tilemap.AddBitmap(bmp, workbench.Tileset, fmt, !noReduce); } } workbench.TilemapFormat = fmt; int addedCount = workbench.Tilemap.Count - beforeCount; logger?.Log("Generated " + addedCount + " tilemap entries."); } } }
using LibPixelPet; using System; using System.Drawing; namespace PixelPet.CLI.Commands { internal class GenerateTilemapCmd : CliCommand { public GenerateTilemapCmd() : base("Generate-Tilemap", new Parameter(true, new ParameterValue("format")), new Parameter("no-reduce", "nr", false), new Parameter("indexed", "i", false), new Parameter("x", "x", false, new ParameterValue("pixels", "0")), new Parameter("y", "y", false, new ParameterValue("pixels", "0")), new Parameter("width", "w", false, new ParameterValue("pixels", "-1")), new Parameter("height", "h", false, new ParameterValue("pixels", "-1")) ) { } public override void Run(Workbench workbench, ILogger logger) { string fmtName = FindUnnamedParameter(0).Values[0].Value; bool noReduce = FindNamedParameter("--no-reduce").IsPresent; bool indexed = FindNamedParameter("--indexed").IsPresent; int x = FindNamedParameter("--x").Values[0].ToInt32(); int y = FindNamedParameter("--y").Values[0].ToInt32(); int w = FindNamedParameter("--width").Values[0].ToInt32(); int h = FindNamedParameter("--height").Values[0].ToInt32(); if (!(TilemapFormat.GetFormat(fmtName) is TilemapFormat fmt)) { logger?.Log("Unknown tilemap format \"" + fmtName + "\".", LogLevel.Error); return; } int beforeCount = workbench.Tilemap.Count; using (Bitmap bmp = workbench.GetCroppedBitmap(x, y, w, h, logger)) { if (indexed) { workbench.Tilemap.AddBitmapIndexed(bmp, workbench.Tileset, workbench.PaletteSet, fmt, !noReduce); } else { workbench.Tilemap.AddBitmap(bmp, workbench.Tileset, fmt, !noReduce); } } workbench.TilemapFormat = fmt; int addedCount = workbench.Tilemap.Count - beforeCount; logger?.Log("Generated " + addedCount + " tilemap entries."); } } }
mit
C#
ea63d1625d02c6dc514474bdf56230dd01effad2
Update AssemblyVersion to 1.5.0
alexguirre/RAGENativeUI,alexguirre/RAGENativeUI
Source/Properties/AssemblyInfo.cs
Source/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("RAGENativeUI")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RAGENativeUI")] [assembly: AssemblyCopyright("Copyright 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("f3e16ed9-dbf7-4e7b-b04b-9b24b11891d3")] [assembly: AssemblyVersion("1.5.0.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("RAGENativeUI")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RAGENativeUI")] [assembly: AssemblyCopyright("Copyright 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("f3e16ed9-dbf7-4e7b-b04b-9b24b11891d3")] [assembly: AssemblyVersion("1.4.1.0")]
mit
C#
234718d862ab95cabfafa34d1b6c4dadb88cde49
Disable debug
Simie/PrecisionEngineering
Src/PrecisionEngineering/Debug.cs
Src/PrecisionEngineering/Debug.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ColossalFramework.Plugins; using UE=UnityEngine; namespace PrecisionEngineering { static class Debug { public const bool Enabled = false; private const string Prefix = "[PrecisionEngineering] "; public static void Log(string str) { var message = Prefix + str; DebugOutputPanel.AddMessage(PluginManager.MessageType.Message, message); UE.Debug.Log(message); } public static void LogWarning(string str) { DebugOutputPanel.AddMessage(PluginManager.MessageType.Warning, Prefix + str); UE.Debug.LogWarning(str); } public static void LogError(string str) { DebugOutputPanel.AddMessage(PluginManager.MessageType.Error, Prefix + str); UE.Debug.LogError(str); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ColossalFramework.Plugins; using UE=UnityEngine; namespace PrecisionEngineering { static class Debug { public const bool Enabled = true; private const string Prefix = "[PrecisionEngineering] "; public static void Log(string str) { var message = Prefix + str; DebugOutputPanel.AddMessage(PluginManager.MessageType.Message, message); UE.Debug.Log(message); } public static void LogWarning(string str) { DebugOutputPanel.AddMessage(PluginManager.MessageType.Warning, Prefix + str); UE.Debug.LogWarning(str); } public static void LogError(string str) { DebugOutputPanel.AddMessage(PluginManager.MessageType.Error, Prefix + str); UE.Debug.LogError(str); } } }
mit
C#
6fa9818b34d451c40869cf3e0d87ba52f19c5e70
Order by workshop id
earalov/Skylines-VehicleConverter
VehicleConverter/Config/Config.cs
VehicleConverter/Config/Config.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using VehicleConverter.OptionsFramework; namespace VehicleConverter.Config { public class Config : IModOptions { public Config() { Underground = new TrainItems(Trains.GetItems(TrainCategory.Underground).OrderBy(i => i.WorkshopId).ToList()); SBahn = new TrainItems(Trains.GetItems(TrainCategory.SBahn).OrderBy(i => i.WorkshopId).ToList()); Trams = new TrainItems(Trains.GetItems(TrainCategory.Tram).OrderBy(i => i.WorkshopId).ToList()); Pantograph = new TrainItems(Trains.GetItems(TrainCategory.Pantograph).OrderBy(i => i.WorkshopId).ToList()); TramStations = new StationItems(Stations.GetItems(StationCategory.Tram).OrderBy(i => i.WorkshopId).ToList()); OldStations = new StationItems(Stations.GetItems(StationCategory.Old).OrderBy(i => i.WorkshopId).ToList()); ModernStations = new StationItems(Stations.GetItems(StationCategory.Modern).OrderBy(i => i.WorkshopId).ToList()); } [XmlElement("version")] public int Version { get; set; } [XmlElement("underground-trains-to-metro")] public TrainItems Underground { get; private set; } [XmlElement("s-bahn-trains-to-metro")] public TrainItems SBahn { get; private set; } [XmlElement("pantograph-trains-to-metro")] public TrainItems Pantograph { get; private set; } [XmlElement("tram-trains-to-tram")] public TrainItems Trams { get; private set; } [XmlElement("tram-train-stations-to-metro-station")] public StationItems TramStations { get; private set; } [XmlElement("old-stations-to-metro-station")] public StationItems OldStations { get; private set; } [XmlElement("modern-stations-to-metro-station")] public StationItems ModernStations { get; private set; } [XmlIgnore] public string FileName => "CSL-TrainConverter-Config.xml"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using VehicleConverter.OptionsFramework; namespace VehicleConverter.Config { public class Config : IModOptions { public Config() { Underground = new TrainItems(Trains.GetItems(TrainCategory.Underground).ToList()); SBahn = new TrainItems(Trains.GetItems(TrainCategory.SBahn).ToList()); Trams = new TrainItems(Trains.GetItems(TrainCategory.Tram).ToList()); Pantograph = new TrainItems(Trains.GetItems(TrainCategory.Pantograph).ToList()); TramStations = new StationItems(Stations.GetItems(StationCategory.Tram).ToList()); OldStations = new StationItems(Stations.GetItems(StationCategory.Old).ToList()); ModernStations = new StationItems(Stations.GetItems(StationCategory.Modern).ToList()); } [XmlElement("version")] public int Version { get; set; } [XmlElement("underground-trains-to-metro")] public TrainItems Underground { get; private set; } [XmlElement("s-bahn-trains-to-metro")] public TrainItems SBahn { get; private set; } [XmlElement("pantograph-trains-to-metro")] public TrainItems Pantograph { get; private set; } [XmlElement("tram-trains-to-tram")] public TrainItems Trams { get; private set; } [XmlElement("tram-train-stations-to-metro-station")] public StationItems TramStations { get; private set; } [XmlElement("old-stations-to-metro-station")] public StationItems OldStations { get; private set; } [XmlElement("modern-stations-to-metro-station")] public StationItems ModernStations { get; private set; } [XmlIgnore] public string FileName => "CSL-TrainConverter-Config.xml"; } }
mit
C#
bff44108a6f135f059dc080cc90826b894fff53c
Update KeyProvider.cs
accessrichard/sqleditor.net
SqlEditor/Models/Cryptography/KeyProvider.cs
SqlEditor/Models/Cryptography/KeyProvider.cs
namespace SqlEditor.Models.Cryptography { using System.Security.Cryptography; using System.Text; /// <summary> /// The cryptographic secret key available for the /// duration of the app pool. /// </summary> public class KeyProvider { /// <summary> /// Backing field for the cryptographic secret key. /// </summary> private static byte[] secretKey; /// <summary> /// Gets a cryptographic secret key. /// </summary> public static byte[] SecretKey { get { if (secretKey != null) { return secretKey; } using (var aes = new AesCryptoServiceProvider()) { secretKey = aes.Key; } return secretKey; } } /// <summary> /// Gets a user specific secret key based off of the /// user specified partial key and the application generated secret key. /// </summary> /// <param name="userKey">The secret key that is generated by the client/user.</param> /// <returns>A combination key based of a user key and the application key.</returns> public static byte[] GetUserSpecificSecretKey(string userKey) { var key = SecretKey; var userKeyEncoded = Encoding.UTF8.GetBytes(userKey); for (var i = 0; i < SecretKey.Length / 2 && i < userKeyEncoded.Length; i++) { key[i] = userKeyEncoded[i]; } return key; } } }
namespace SqlEditor.Models.Cryptography { using System.Security.Cryptography; using System.Text; /// <summary> /// The cryptographic secret key available for the /// duration of the app pool. /// </summary> public class KeyProvider { /// <summary> /// Backing field for the cryptographic secret key. /// </summary> private static byte[] secretKey; /// <summary> /// Gets a cryptographic secret key. /// </summary> public static byte[] GetSecretKey { get { if (secretKey != null) { return secretKey; } using (var aes = new AesCryptoServiceProvider()) { secretKey = aes.Key; } return secretKey; } } /// <summary> /// Gets a user specific secret key based off of the /// user specified partial key and the application generated secret key. /// </summary> /// <param name="userKey">The secret key that is generated by the client/user.</param> /// <returns>A combination key based of a user key and the application key.</returns> public static byte[] GetUserSpecificSecretKey(string userKey) { var key = GetSecretKey; var userKeyEncoded = Encoding.UTF8.GetBytes(userKey); for (var i = 0; i < GetSecretKey.Length / 2 && i < userKeyEncoded.Length; i++) { key[i] = userKeyEncoded[i]; } return key; } } }
mit
C#
24d3f5c126bc92013e7164da51aaf406f8923a2a
Simplify the Expression<Func<>> specimen building
zvirja/AutoFixture,sergeyshushlyapin/AutoFixture,sbrockway/AutoFixture,sbrockway/AutoFixture,dcastro/AutoFixture,AutoFixture/AutoFixture,adamchester/AutoFixture,sean-gilliam/AutoFixture,adamchester/AutoFixture,Pvlerick/AutoFixture,sergeyshushlyapin/AutoFixture,dcastro/AutoFixture
Src/AutoFixture/LambdaExpressionGenerator.cs
Src/AutoFixture/LambdaExpressionGenerator.cs
namespace Ploeh.AutoFixture { using System; using System.Linq; using System.Linq.Expressions; using Kernel; public class LambdaExpressionGenerator : ISpecimenBuilder { public object Create(object request, ISpecimenContext context) { var requestType = request as Type; if (requestType == null) { return new NoSpecimen(); } if (requestType.BaseType != typeof(LambdaExpression)) { return new NoSpecimen(); } var delegateType = requestType.GetGenericArguments().Single(); var genericArguments = delegateType.GetGenericArguments().Select(Expression.Parameter).ToList(); if (delegateType.Name.StartsWith("Action")) { return Expression.Lambda(Expression.Empty(), genericArguments); } var body = genericArguments.Last(); var parameters = genericArguments.Except(new[] { body }); return Expression.Lambda(body, parameters); } } }
namespace Ploeh.AutoFixture { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Kernel; public class LambdaExpressionGenerator : ISpecimenBuilder { public object Create(object request, ISpecimenContext context) { var requestType = request as Type; if (requestType == null) { return new NoSpecimen(); } if (requestType.BaseType != typeof(LambdaExpression)) { return new NoSpecimen(); } var delegateType = requestType.GetGenericArguments().Single(); var genericArguments = delegateType.GetGenericArguments().Select(Expression.Parameter).ToList(); if (delegateType.Name.StartsWith( "Action")) { return Expression.Lambda(Expression.Empty(), genericArguments); } var body = genericArguments.Last(); var parameters = new List<ParameterExpression>(); if (genericArguments.Count > 1) { parameters = genericArguments.Take(genericArguments.Count - 1).ToList(); } return Expression.Lambda(body, parameters); } } }
mit
C#
bd71b4d909d84c4644c2e006d7256de41e56ef3d
Enhance log interception
samcragg/Crest,samcragg/Crest,samcragg/Crest
test/Host.UnitTests/FakeLogger.cs
test/Host.UnitTests/FakeLogger.cs
namespace Host.UnitTests { using System; using System.Threading; using Crest.Host.Logging; using Crest.Host.Logging.LogProviders; using NSubstitute; internal static class FakeLogger { private static readonly object LockObject = new object(); [ThreadStatic] private static LogLevel level; [ThreadStatic] private static string message; internal static void InterceptLogger() { Logger logger = (logLevel, messageFunc, exception, formatParameters) => { level = logLevel; message = messageFunc == null ? string.Empty : LogMessageFormatter.SimulateStructuredLogging(messageFunc, formatParameters)(); return true; }; LogProvider.SetCurrentLogProvider(Substitute.For<ILogProvider>()); LogProvider.CurrentLogProvider.GetLogger(null) .ReturnsForAnyArgs(logger); } internal static LogInfo MonitorLogging() { var disposableLock = new LogInfo(); level = default; message = null; return disposableLock; } internal class LogInfo : IDisposable { public LogInfo() { Monitor.Enter(LockObject); } public LogLevel LogLevel => level; public string Message => message; public void Dispose() { Monitor.Exit(LockObject); } } } }
namespace Host.UnitTests { using System; using System.Threading; using Crest.Host.Logging; using NSubstitute; internal static class FakeLogger { private static readonly object LockObject = new object(); private static LogLevel level; private static string message; internal static void InterceptLogger() { Logger logger = (logLevel, messageFunc, exception, formatParameters) => { level = logLevel; message = messageFunc?.Invoke(); return true; }; LogProvider.SetCurrentLogProvider(Substitute.For<ILogProvider>()); LogProvider.CurrentLogProvider.GetLogger(null) .ReturnsForAnyArgs(logger); } internal static LogInfo MonitorLogging() { var disposableLock = new LogInfo(); level = default; message = null; return disposableLock; } internal class LogInfo : IDisposable { public LogInfo() { Monitor.Enter(LockObject); } public LogLevel LogLevel => level; public string Message => message; public void Dispose() { Monitor.Exit(LockObject); } } } }
mit
C#
1995aa110aa2e1ae78bce598dcfbb500c1a9bbef
fix crash on this again :shrug:
Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns
TCC.Core/Parsing/Messages/S_NPCGUILD_LIST.cs
TCC.Core/Parsing/Messages/S_NPCGUILD_LIST.cs
using System; using System.Collections.Generic; using TCC.Data; using TCC.TeraCommon.Game.Messages; using TCC.TeraCommon.Game.Services; namespace TCC.Parsing.Messages { public class S_NPCGUILD_LIST : ParsedMessage { public Dictionary<int, int> NpcGuildList { get; } public ulong UserId { get; } public S_NPCGUILD_LIST(TeraMessageReader reader) : base(reader) { NpcGuildList = new Dictionary<int, int>(); try { var count = reader.ReadUInt16(); if (count == 0) return; var offset = reader.ReadUInt16(); UserId = reader.ReadUInt64(); reader.BaseStream.Position = offset - 4; for (var i = 0; i < count; i++) { var curr = reader.ReadUInt16(); var next = reader.ReadUInt16(); var region = reader.ReadInt32(); var faction = reader.ReadInt32(); var rank = reader.ReadInt32(); var reputation = reader.ReadInt32(); var credits = reader.ReadInt32(); NpcGuildList[faction] = credits; if (next == 0) return; reader.BaseStream.Position = next - 4; } } catch (Exception e) { Log.F($"[{nameof(S_NPCGUILD_LIST)}] Failed to parse packet. \nContent:\n{StringUtils.ByteArrayToString(Payload.Array)}\nException:\n{e.Message}\n{e.StackTrace}"); WindowManager.FloatingButton.NotifyExtended("Warning", "A non-fatal error occured. More detailed info has been written to error.log. Please report this to the developer on Discord or Github.", NotificationType.Warning, 10000); } } } }
using System; using System.Collections.Generic; using TCC.Data; using TCC.TeraCommon.Game.Messages; using TCC.TeraCommon.Game.Services; namespace TCC.Parsing.Messages { public class S_NPCGUILD_LIST : ParsedMessage { public Dictionary<int, int> NpcGuildList { get; } public ulong UserId { get; } public S_NPCGUILD_LIST(TeraMessageReader reader) : base(reader) { NpcGuildList = new Dictionary<int, int>(); var count = reader.ReadUInt16(); if (count == 0) return; try { var offset = reader.ReadUInt16(); UserId = reader.ReadUInt64(); reader.BaseStream.Position = offset - 4; for (var i = 0; i < count; i++) { var curr = reader.ReadUInt16(); var next = reader.ReadUInt16(); var region = reader.ReadInt32(); var faction = reader.ReadInt32(); var rank = reader.ReadInt32(); var reputation = reader.ReadInt32(); var credits = reader.ReadInt32(); NpcGuildList[faction] = credits; if (next == 0) return; reader.BaseStream.Position = next - 4; } } catch(Exception e) { Log.F($"[{nameof(S_NPCGUILD_LIST)}] Failed to parse packet. \nContent:\n{StringUtils.ByteArrayToString(Payload.Array)}\nException:\n{e.Message}\n{e.StackTrace}"); WindowManager.FloatingButton.NotifyExtended("Warning", "A non-fatal error occured. More detailed info has been written to error.log. Please report this to the developer on Discord or Github.", NotificationType.Warning, 10000); } } } }
mit
C#
16ea01291eec546c3e36b1c10d0bb348f4406d9a
Create tile vertices
EightBitBoy/EcoRealms
Assets/Scripts/Map/MapPresenter.cs
Assets/Scripts/Map/MapPresenter.cs
using UnityEngine; using System.Collections; namespace ecorealms.map { public class MapPresenter : MonoBehaviour { private int sizeX; private int sizeY; private GameObject rootObject; private Transform root; public Mesh mesh; public Material material; private Tile[] tiles; public void Setup(int sizeX, int sizeY) { this.sizeX = sizeX; this.sizeY = sizeY; InitializeData(); } private void InitializeData() { tiles = new Tile[sizeX * sizeY]; rootObject = new GameObject("MapRoot"); rootObject.AddComponent<MeshFilter>().mesh = mesh; rootObject.AddComponent<MeshRenderer>().material = material; root = rootObject.transform; StartCoroutine(DelayedFunction()); //TODO do something awesome } private void GenerateMap() { int tileIndex = 0; for(int x = 0; x < sizeX; x++) { for(int y = 0; y < sizeY; y++) { tiles[tileIndex] = new Tile(x, y); tileIndex++; } } } private IEnumerator DelayedFunction() { //TDOD do something yield return new WaitForSeconds(0.5f); } } public class Tile { private Vector3[] vertices; public Tile(int x, int y) { vertices = new Vector3[4]; vertices[0] = new Vector3((float)(x + 0), 0.0f, (float)(y + 0)); vertices[1] = new Vector3((float)(x + 0), 0.0f, (float)(y + 1)); vertices[2] = new Vector3((float)(x + 1), 0.0f, (float)(y + 1)); vertices[3] = new Vector3((float)(x + 1), 0.0f, (float)(y + 0)); } } }
using UnityEngine; using System.Collections; namespace ecorealms.map { public class MapPresenter : MonoBehaviour { private int sizeX; private int sizeY; private GameObject rootObject; private Transform root; public Mesh mesh; public Material material; private Tile[] tiles; public void Setup(int sizeX, int sizeY) { this.sizeX = sizeX; this.sizeY = sizeY; InitializeData(); } private void InitializeData() { tiles = new Tile[sizeX * sizeY]; rootObject = new GameObject("MapRoot"); rootObject.AddComponent<MeshFilter>().mesh = mesh; rootObject.AddComponent<MeshRenderer>().material = material; root = rootObject.transform; StartCoroutine(DelayedFunction()); //TODO do something awesome } private void GenerateMap() { for(int x = 0; x < sizeX; x++) { for(int y = 0; y < sizeY; y++) { CreateQuad(x, y); } } } private IEnumerator DelayedFunction() { //TDOD do something yield return new WaitForSeconds(0.5f); } private void CreateQuad(int x, int y) { //Vector3.one; } } public class Tile { private Vector3[] vertices; } }
apache-2.0
C#
cd867fda414c933e19d33f3bd5252ddcfc2ab72c
Update LayerMetadataWelder.cs (#1174)
stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,petedavis/Orchard2,xkproject/Orchard2,xkproject/Orchard2,petedavis/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,OrchardCMS/Brochard
src/OrchardCore.Modules/OrchardCore.Layers/Drivers/LayerMetadataWelder.cs
src/OrchardCore.Modules/OrchardCore.Layers/Drivers/LayerMetadataWelder.cs
using System; using System.Threading.Tasks; using Microsoft.Extensions.Localization; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Display.ContentDisplay; using OrchardCore.DisplayManagement.Handlers; using OrchardCore.DisplayManagement.Views; using OrchardCore.Layers.Models; using OrchardCore.Layers.Services; using OrchardCore.Layers.ViewModels; namespace OrchardCore.Layers.Drivers { public class LayerMetadataWelder : ContentDisplayDriver { private readonly ILayerService _layerService; private readonly IStringLocalizer<LayerMetadataWelder> S; public LayerMetadataWelder(ILayerService layerService, IStringLocalizer<LayerMetadataWelder> stringLocalizer) { _layerService = layerService; S = stringLocalizer; } protected override void BuildPrefix(ContentItem model, string htmlFieldPrefix) { Prefix = "LayerMetadata"; } public override async Task<IDisplayResult> EditAsync(ContentItem model, BuildEditorContext context) { var layerMetadata = model.As<LayerMetadata>(); if (layerMetadata == null) { layerMetadata = new LayerMetadata(); // Are we loading an editor that requires layer metadata? if (await context.Updater.TryUpdateModelAsync(layerMetadata, Prefix, m => m.Zone, m => m.Position) && !String.IsNullOrEmpty(layerMetadata.Zone)) { model.Weld(layerMetadata); } else { return null; } } return Shape<LayerMetadataEditViewModel>("LayerMetadata_Edit", async shape => { shape.LayerMetadata = layerMetadata; shape.Layers = (await _layerService.GetLayersAsync()).Layers; }) .Location("Content:before"); } public override async Task<IDisplayResult> UpdateAsync(ContentItem model, UpdateEditorContext context) { var viewModel = new LayerMetadataEditViewModel(); await context.Updater.TryUpdateModelAsync(viewModel, Prefix); if (String.IsNullOrEmpty(viewModel.LayerMetadata.Zone)) { context.Updater.ModelState.AddModelError("LayerMetadata.Zone", S["Zone is missing"]); } if (context.Updater.ModelState.IsValid) { model.Apply(viewModel.LayerMetadata); } return await EditAsync(model, context); } } }
using System; using System.Threading.Tasks; using Microsoft.Extensions.Localization; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Display.ContentDisplay; using OrchardCore.DisplayManagement.Handlers; using OrchardCore.DisplayManagement.Views; using OrchardCore.Layers.Models; using OrchardCore.Layers.Services; using OrchardCore.Layers.ViewModels; namespace OrchardCore.Layers.Drivers { public class LayerMetadataWelder : ContentDisplayDriver { private readonly ILayerService _layerService; private readonly IStringLocalizer<LayerMetadataWelder> S; public LayerMetadataWelder(ILayerService layerService, IStringLocalizer<LayerMetadataWelder> stringLocalizer) { _layerService = layerService; S = stringLocalizer; } protected override void BuildPrefix(ContentItem model, string htmlFieldPrefix) { Prefix = "LayerMetadata"; } public override async Task<IDisplayResult> EditAsync(ContentItem model, BuildEditorContext context) { var layerMetadata = model.As<LayerMetadata>(); if (layerMetadata == null) { layerMetadata = new LayerMetadata(); // Are we loading an editor that requires layer metadata? if (await context.Updater.TryUpdateModelAsync(layerMetadata, "LayerMetadata", m => m.Zone, m => m.Position) && !String.IsNullOrEmpty(layerMetadata.Zone)) { model.Weld(layerMetadata); } else { return null; } } return Shape<LayerMetadataEditViewModel>("LayerMetadata_Edit", async shape => { shape.LayerMetadata = layerMetadata; shape.Layers = (await _layerService.GetLayersAsync()).Layers; }) .Location("Content:before"); } public override async Task<IDisplayResult> UpdateAsync(ContentItem model, UpdateEditorContext context) { var viewModel = new LayerMetadataEditViewModel(); await context.Updater.TryUpdateModelAsync(viewModel, Prefix); if (String.IsNullOrEmpty(viewModel.LayerMetadata.Zone)) { context.Updater.ModelState.AddModelError("LayerMetadata.Zone", S["Zone is missing"]); } if (context.Updater.ModelState.IsValid) { model.Apply(viewModel.LayerMetadata); } return await EditAsync(model, context); } } }
bsd-3-clause
C#
8eadcb3e9bdc10d8aaaa4ddc8ef557132a945383
Update InsertingAColumn.cs
aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET
Examples/CSharp/RowsColumns/InsertingAndDeleting/InsertingAColumn.cs
Examples/CSharp/RowsColumns/InsertingAndDeleting/InsertingAColumn.cs
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.RowsColumns.InsertingAndDeleting { public class InsertingAColumn { public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Creating a file stream containing the Excel file to be opened FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open); //Instantiating a Workbook object //Opening the Excel file through the file stream Workbook workbook = new Workbook(fstream); //Accessing the first worksheet in the Excel file Worksheet worksheet = workbook.Worksheets[0]; //Inserting a column into the worksheet at 2nd position worksheet.Cells.InsertColumn(1); //Saving the modified Excel file workbook.Save(dataDir + "output.out.xls"); //Closing the file stream to free all resources fstream.Close(); //End:1 } } }
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.RowsColumns.InsertingAndDeleting { public class InsertingAColumn { public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Creating a file stream containing the Excel file to be opened FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open); //Instantiating a Workbook object //Opening the Excel file through the file stream Workbook workbook = new Workbook(fstream); //Accessing the first worksheet in the Excel file Worksheet worksheet = workbook.Worksheets[0]; //Inserting a column into the worksheet at 2nd position worksheet.Cells.InsertColumn(1); //Saving the modified Excel file workbook.Save(dataDir + "output.out.xls"); //Closing the file stream to free all resources fstream.Close(); } } }
mit
C#
17aef8cba7526d4b0d01fcb54e553771beab21c7
Remove unused usings
smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework
SampleGame.Android/MainActivity.cs
SampleGame.Android/MainActivity.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using Android.App; using Android.OS; using Android.Content.PM; using Android.Views; namespace SampleGame.Android { [Activity(Label = "SampleGame", ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, MainLauncher = true, Theme = "@android:style/Theme.NoTitleBar")] public class MainActivity : Activity { private SampleGameView sampleGameView; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Window.AddFlags(WindowManagerFlags.Fullscreen); Window.AddFlags(WindowManagerFlags.KeepScreenOn); SetContentView(sampleGameView = new SampleGameView(this)); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using Android.App; using Android.OS; using Android.Content.PM; using Android.Views; using System; using Android.Runtime; using Android.Content.Res; namespace SampleGame.Android { [Activity(Label = "SampleGame", ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, MainLauncher = true, Theme = "@android:style/Theme.NoTitleBar")] public class MainActivity : Activity { private SampleGameView sampleGameView; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Window.AddFlags(WindowManagerFlags.Fullscreen); Window.AddFlags(WindowManagerFlags.KeepScreenOn); SetContentView(sampleGameView = new SampleGameView(this)); } } }
mit
C#
3ed3e7a23354821673a2992f6241b4486fb5d642
Update AssemblyInfo.cs
jakejgordon/versioned-rest-api,jakejgordon/versioned-rest-api
VersionedRestApi/Properties/AssemblyInfo.cs
VersionedRestApi/Properties/AssemblyInfo.cs
#region LICENSE // The MIT License (MIT) // // Copyright (c) 2015 Jake Gordon // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #endregion 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("VersionedRestApi")] [assembly: AssemblyDescription(@"VersionedRestApi provides a simple but powerful attribute called 'ApiRoute' that lets you annotate your Web API actions with versions (or version ranges). Versioning is handled via the URI (as opposed to query string parameter, header, or body parameter). See GitHub project readme for more details: https://github.com/RIDGIDSoftwareSolutions/versioned-rest-api")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("RIDGID Software Solutions")] [assembly: AssemblyProduct("VersionedRestApi")] [assembly: AssemblyCopyright("Copyright © RIDGID Software Solutions 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b7141b36-36dd-49be-b02d-4da4dac9e618")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.1")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("VersionedRestApi.Tests")]
#region LICENSE // The MIT License (MIT) // // Copyright (c) 2015 Jake Gordon // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #endregion 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("VersionedRestApi")] [assembly: AssemblyDescription(@"VersionedRestApi provides a simple but powerful attribute called 'ApiRoute' that lets you annotate your Web API actions with versions (or version ranges). Versioning is handled via the URI (as opposed to query string parameter, header, or body parameter). See GitHub project readme for more details: https://github.com/jakejgordon/versioned-rest-api")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("jakejgordon")] [assembly: AssemblyProduct("VersionedRestApi")] [assembly: AssemblyCopyright("Copyright © jakejgordon 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b7141b36-36dd-49be-b02d-4da4dac9e618")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.1")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("VersionedRestApi.Tests")]
mit
C#
c102afd85f6d56a2f1c7bdeaecb694bf372cb2b5
Remove unused code
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Extensions/StringExtensions.cs
WalletWasabi/Extensions/StringExtensions.cs
namespace System { public static class StringExtensions { /// <summary> /// Removes one leading occurrence of the specified string /// </summary> public static string TrimStart(this string me, string trimString, StringComparison comparisonType) { if (me.StartsWith(trimString, comparisonType)) { return me[trimString.Length..]; } return me; } /// <summary> /// Removes one trailing occurrence of the specified string /// </summary> public static string TrimEnd(this string me, string trimString, StringComparison comparisonType) { if (me.EndsWith(trimString, comparisonType)) { return me.Substring(0, me.Length - trimString.Length); } return me; } /// <summary> /// Returns true if the string contains leading or trailing whitespace, otherwise returns false. /// </summary> public static bool IsTrimmable(this string me) { if (me.Length == 0) { return false; } return char.IsWhiteSpace(me[0]) || char.IsWhiteSpace(me[^1]); } } }
namespace System { public static class StringExtensions { public static bool Equals(this string source, string value, StringComparison comparisonType, bool trimmed) { if (comparisonType == StringComparison.Ordinal) { if (trimmed) { return string.CompareOrdinal(source.Trim(), value.Trim()) == 0; } return string.CompareOrdinal(source, value) == 0; } if (trimmed) { return source.Trim().Equals(value.Trim(), comparisonType); } return source.Equals(value, comparisonType); } public static bool Contains(this string source, string toCheck, StringComparison comp) { return source.IndexOf(toCheck, comp) >= 0; } public static string[] Split(this string me, string separator, StringSplitOptions options = StringSplitOptions.None) { return me.Split(separator.ToCharArray(), options); } /// <summary> /// Removes one leading and trailing occurrence of the specified string /// </summary> public static string Trim(this string me, string trimString, StringComparison comparisonType) { return me.TrimStart(trimString, comparisonType).TrimEnd(trimString, comparisonType); } /// <summary> /// Removes one leading occurrence of the specified string /// </summary> public static string TrimStart(this string me, string trimString, StringComparison comparisonType) { if (me.StartsWith(trimString, comparisonType)) { return me[trimString.Length..]; } return me; } /// <summary> /// Removes one trailing occurrence of the specified string /// </summary> public static string TrimEnd(this string me, string trimString, StringComparison comparisonType) { if (me.EndsWith(trimString, comparisonType)) { return me.Substring(0, me.Length - trimString.Length); } return me; } /// <summary> /// Returns true if the string contains leading or trailing whitespace, otherwise returns false. /// </summary> public static bool IsTrimmable(this string me) { if (me.Length == 0) { return false; } return char.IsWhiteSpace(me[0]) || char.IsWhiteSpace(me[^1]); } } }
mit
C#
0a55c6f09c05b0f152684b4d33368a3572b0b0ed
Update QuoteRepository.cs
ScarletKuro/NadekoBot,Midnight-Myth/Mitternacht-NEW,shikhir-arora/NadekoBot,Youngsie1997/NadekoBot,WoodenGlaze/NadekoBot,gfrewqpoiu/NadekoBot,Nielk1/NadekoBot,halitalf/NadekoMods,PravEF/EFNadekoBot,ShadowNoire/NadekoBot,Midnight-Myth/Mitternacht-NEW,Taknok/NadekoBot,powered-by-moe/MikuBot,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,miraai/NadekoBot,Blacnova/NadekoBot
src/NadekoBot/Services/Database/Repositories/Impl/QuoteRepository.cs
src/NadekoBot/Services/Database/Repositories/Impl/QuoteRepository.cs
using NadekoBot.Services.Database.Models; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace NadekoBot.Services.Database.Repositories.Impl { public class QuoteRepository : Repository<Quote>, IQuoteRepository { public QuoteRepository(DbContext context) : base(context) { } public IEnumerable<Quote> GetAllQuotesByKeyword(ulong guildId, string keyword) => _set.Where(q => q.GuildId == guildId && q.Keyword == keyword); public IEnumerable<Quote> GetGroup(ulong guildId, int skip, int take) => _set.Where(q=>q.GuildId == guildId).OrderBy(q => q.Keyword).Skip(skip).Take(take).ToList(); public Task<Quote> GetRandomQuoteByKeywordAsync(ulong guildId, string keyword) { var rng = new NadekoRandom(); return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rng.Next()).FirstOrDefaultAsync(); } public Task<Quote> SearchQuoteKeywordTextAsync(ulong guildId, string keyword, string text) { var rngk = new NadekoRandom(); lowertext = text.ToLowerInvariant(); uppertext = text.ToUpperInvariant(); return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword && (q.Text.Contains(text) || q.Text.Contains(lowertext) || q.Text.Contains(uppertext))).OrderBy(q => rngk.Next()).FirstOrDefaultAsync(); } } }
using NadekoBot.Services.Database.Models; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace NadekoBot.Services.Database.Repositories.Impl { public class QuoteRepository : Repository<Quote>, IQuoteRepository { public QuoteRepository(DbContext context) : base(context) { } public IEnumerable<Quote> GetAllQuotesByKeyword(ulong guildId, string keyword) => _set.Where(q => q.GuildId == guildId && q.Keyword == keyword); public IEnumerable<Quote> GetGroup(ulong guildId, int skip, int take) => _set.Where(q=>q.GuildId == guildId).OrderBy(q => q.Keyword).Skip(skip).Take(take).ToList(); public Task<Quote> GetRandomQuoteByKeywordAsync(ulong guildId, string keyword) { var rng = new NadekoRandom(); return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rng.Next()).FirstOrDefaultAsync(); } public Task<Quote> SearchQuoteKeywordTextAsync(ulong guildId, string keyword, string text) { var rngk = new NadekoRandom(); lowertext = text.ToLowerInvariant(); uppertext = text.ToUpperInvariant(); return _set.Where(q => q.Text.Contains(text) || q.Text.Contains(lowertext) || q.Text.Contains(uppertext) && q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rngk.Next()).FirstOrDefaultAsync(); } } }
mit
C#
2acd61350fc39d62108eda77ae70492a0faa9ae0
Add RuntimeFeature detection for default interface method (#11940)
poizan42/coreclr,mmitche/coreclr,JosephTremoulet/coreclr,JosephTremoulet/coreclr,krk/coreclr,krk/coreclr,ruben-ayrapetyan/coreclr,ruben-ayrapetyan/coreclr,yizhang82/coreclr,wtgodbe/coreclr,wtgodbe/coreclr,poizan42/coreclr,yizhang82/coreclr,krk/coreclr,mmitche/coreclr,wtgodbe/coreclr,mmitche/coreclr,ruben-ayrapetyan/coreclr,yizhang82/coreclr,wtgodbe/coreclr,mmitche/coreclr,mmitche/coreclr,ruben-ayrapetyan/coreclr,poizan42/coreclr,yizhang82/coreclr,krk/coreclr,yizhang82/coreclr,cshung/coreclr,krk/coreclr,cshung/coreclr,cshung/coreclr,mmitche/coreclr,poizan42/coreclr,cshung/coreclr,cshung/coreclr,cshung/coreclr,ruben-ayrapetyan/coreclr,JosephTremoulet/coreclr,ruben-ayrapetyan/coreclr,JosephTremoulet/coreclr,yizhang82/coreclr,JosephTremoulet/coreclr,wtgodbe/coreclr,wtgodbe/coreclr,JosephTremoulet/coreclr,poizan42/coreclr,krk/coreclr,poizan42/coreclr
src/mscorlib/shared/System/Runtime/CompilerServices/RuntimeFeature.cs
src/mscorlib/shared/System/Runtime/CompilerServices/RuntimeFeature.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.CompilerServices { public static class RuntimeFeature { /// <summary> /// Name of the Portable PDB feature. /// </summary> public const string PortablePdb = nameof(PortablePdb); /// Indicates that this version of runtime supports default interface method implementations. /// </summary> public const string DefaultImplementationsOfInterfaces = nameof(DefaultImplementationsOfInterfaces); /// <summary> /// Checks whether a certain feature is supported by the Runtime. /// </summary> public static bool IsSupported(string feature) { switch (feature) { case PortablePdb: case DefaultImplementationsOfInterfaces: return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.CompilerServices { public static class RuntimeFeature { /// <summary> /// Name of the Portable PDB feature. /// </summary> public const string PortablePdb = nameof(PortablePdb); /// <summary> /// Checks whether a certain feature is supported by the Runtime. /// </summary> public static bool IsSupported(string feature) { // Features should be added as public const string fields in the same class. // Example: public const string FeatureName = nameof(FeatureName); switch (feature) { case nameof(PortablePdb): return true; } return false; } } }
mit
C#
551ca247394bb3fe0288d41df4fddd131ff16a16
Fix something
temdisponivel/TheJungleTriad
Assets/Code/Enviroment.cs
Assets/Code/Enviroment.cs
using UnityEngine; using System.Collections; /// <summary> /// Class that holds usefull information for building a enviroment. /// </summary> public class Enviroment : MonoBehaviour { public Player.State _targetState = Player.State.Bird; [Header("Enviroment localization")] public GameObject _startOfEnviromentObj = null; public GameObject _endOfEnviromentObj = null; [Header("Barriers")] public GameObject _barrier = null; public GameObject[] _barriersPosition = null; public int _minBarrierCount = 1; public Vector2 StartOfEnviroment {get { return this.transform.position + this._startOfEnviromentObj.transform.position; } } public Vector2 EndOfEnviroment {get { return this.transform.position + this._endOfEnviromentObj.transform.position; } } public void Start() { float barrierCount = Random.Range (this._minBarrierCount, this._barriersPosition.Length); for (int i = 0; i < barrierCount; i++) { int index = (int) Random.Range (0, this._barriersPosition.Length); GameObject b = (GameObject)GameObject.Instantiate (this._barrier, this._barriersPosition [index].transform.position, this._barriersPosition [index].transform.rotation); b.transform.parent = this.transform; } } public void Update() { if (GameManager.Instance.CurrentCamera.WorldToViewportPoint(this._endOfEnviromentObj.transform.position).x < 0) { EnviromentBuilder.Instance.BuildNext (); GameObject.Destroy(this.gameObject); } } public void MoveStartTo(Vector2 position) { this.transform.position = new Vector2() { x = ((Vector2)this._startOfEnviromentObj.transform.position - position).x, y = 0 }; } public void OnTriggerEnter2D(Collider2D coll) { if (coll.gameObject.tag == "Player") { if (Player.Instance._currentState != this._targetState) { GameManager.Instance.GameOver (); } } } }
using UnityEngine; using System.Collections; /// <summary> /// Class that holds usefull information for building a enviroment. /// </summary> public class Enviroment : MonoBehaviour { public Player.State _targetState = Player.State.Bird; [Header("Enviroment localization")] public GameObject _startOfEnviromentObj = null; public GameObject _endOfEnviromentObj = null; [Header("Barriers")] public GameObject _barrier = null; public GameObject[] _barriersPosition = null; public int _minBarrierCount = 1; public Vector2 StartOfEnviroment {get { return this.transform.position + this._startOfEnviromentObj.transform.position; } } public Vector2 EndOfEnviroment {get { return this.transform.position + this._endOfEnviromentObj.transform.position; } } public void Start() { float barrierCount = Random.Range (this._minBarrierCount, this._barriersPosition.Length); for (int i = 0; i < barrierCount; i++) { int index = (int) Random.Range (0, this._barriersPosition.Length); GameObject b = (GameObject)GameObject.Instantiate (this._barrier, this._barriersPosition [index].transform.position, this._barriersPosition [index].transform.rotation); b.transform.parent = this.transform; } } public void Update() { if (GameManager.Instance.CurrentCamera.WorldToViewportPoint(this._endOfEnviromentObj.transform.position).x < 0) { EnviromentBuilder.Instance.BuildNext (); GameObject.Destroy(this.gameObject); } } public void MoveStartTo(Vector2 position) { } public void OnTriggerEnter2D(Collider2D coll) { if (coll.gameObject.tag == "Player") { if (Player.Instance._currentState != this._targetState) { GameManager.Instance.GameOver (); } } } }
mit
C#
5821ae0f78f21c4052fe7fb2c75b825b16b216e5
remove wrong using directive
dnauck/License.Manager,dnauck/License.Manager
src/License.Manager.Core/Persistence/ProductAllPropertiesIndex.cs
src/License.Manager.Core/Persistence/ProductAllPropertiesIndex.cs
using System.Linq; using License.Manager.Core.Model; using Raven.Abstractions.Indexing; using Raven.Client.Indexes; namespace License.Manager.Persistence { public class ProductAllPropertiesIndex : AbstractIndexCreationTask<Product, ProductAllPropertiesIndex.Result> { public class Result { public string Query { get; set; } } public ProductAllPropertiesIndex() { Map = products => from product in products select new { Query = AsDocument(product).Select(x => x.Value) }; Index(x => x.Query, FieldIndexing.Analyzed); } } }
using System.Linq; using License.Manager.Core.Model; using License.Manager.Models; using Raven.Abstractions.Indexing; using Raven.Client.Indexes; namespace License.Manager.Persistence { public class ProductAllPropertiesIndex : AbstractIndexCreationTask<Product, ProductAllPropertiesIndex.Result> { public class Result { public string Query { get; set; } } public ProductAllPropertiesIndex() { Map = products => from product in products select new { Query = AsDocument(product).Select(x => x.Value) }; Index(x => x.Query, FieldIndexing.Analyzed); } } }
mit
C#
02c77efcfc567f19df97c2179af7e960ee27022a
Add method `GetInvocationList` in `Delegate` class
AndreyZM/Bridge,AndreyZM/Bridge,bridgedotnet/Bridge,bridgedotnet/Bridge,bridgedotnet/Bridge,AndreyZM/Bridge,bridgedotnet/Bridge,AndreyZM/Bridge
Bridge/System/Delegate.cs
Bridge/System/Delegate.cs
using System.Reflection; namespace System { [Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)] [Bridge.External] [Bridge.IgnoreCast] [Bridge.Name("Function")] public class Delegate { public extern int Length { [Bridge.Template("{this}.length")] get; } protected extern Delegate(object target, string method); protected extern Delegate(Type target, string method); protected extern Delegate(); public virtual extern object Apply(object thisArg); public virtual extern object Apply(); public virtual extern object Apply(object thisArg, Array args); public virtual extern object Call(object thisArg, params object[] args); public virtual extern object Call(object thisArg); public virtual extern object Call(); [Bridge.Template("Bridge.fn.combine({0}, {1})")] public static extern Delegate Combine(Delegate a, Delegate b); [Bridge.Template("Bridge.fn.remove({0}, {1})")] public static extern Delegate Remove(Delegate source, Delegate value); [Bridge.Template("Bridge.staticEquals({a}, {b})")] public static extern bool operator ==(Delegate a, Delegate b); [Bridge.Template("!Bridge.staticEquals({a}, {b})")] public static extern bool operator !=(Delegate a, Delegate b); [Bridge.Template("Bridge.Reflection.createDelegate({method}, {firstArgument})")] public static extern Delegate CreateDelegate(Type type, object firstArgument, MethodInfo method); [Bridge.Template("Bridge.fn.getInvocationList({this})")] public extern Delegate[] GetInvocationList(); } [Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)] [Bridge.External] [Bridge.IgnoreCast] [Bridge.Name("Function")] public class MulticastDelegate : Delegate { protected extern MulticastDelegate(); protected extern MulticastDelegate(object target, string method); protected extern MulticastDelegate(Type target, string method); [Bridge.Template("Bridge.staticEquals({a}, {b})")] public static extern bool operator ==(MulticastDelegate a, MulticastDelegate b); [Bridge.Template("!Bridge.staticEquals({a}, {b})")] public static extern bool operator !=(MulticastDelegate a, MulticastDelegate b); } }
using System.Reflection; namespace System { [Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)] [Bridge.External] [Bridge.IgnoreCast] [Bridge.Name("Function")] public class Delegate { public extern int Length { [Bridge.Template("{this}.length")] get; } protected extern Delegate(object target, string method); protected extern Delegate(Type target, string method); protected extern Delegate(); public virtual extern object Apply(object thisArg); public virtual extern object Apply(); public virtual extern object Apply(object thisArg, Array args); public virtual extern object Call(object thisArg, params object[] args); public virtual extern object Call(object thisArg); public virtual extern object Call(); [Bridge.Template("Bridge.fn.combine({0}, {1})")] public static extern Delegate Combine(Delegate a, Delegate b); [Bridge.Template("Bridge.fn.remove({0}, {1})")] public static extern Delegate Remove(Delegate source, Delegate value); [Bridge.Template("Bridge.staticEquals({a}, {b})")] public static extern bool operator ==(Delegate a, Delegate b); [Bridge.Template("!Bridge.staticEquals({a}, {b})")] public static extern bool operator !=(Delegate a, Delegate b); [Bridge.Template("Bridge.Reflection.createDelegate({method}, {firstArgument})")] public static extern Delegate CreateDelegate(Type type, object firstArgument, MethodInfo method); } [Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)] [Bridge.External] [Bridge.IgnoreCast] [Bridge.Name("Function")] public class MulticastDelegate : Delegate { protected extern MulticastDelegate(); protected extern MulticastDelegate(object target, string method); protected extern MulticastDelegate(Type target, string method); [Bridge.Template("Bridge.staticEquals({a}, {b})")] public static extern bool operator ==(MulticastDelegate a, MulticastDelegate b); [Bridge.Template("!Bridge.staticEquals({a}, {b})")] public static extern bool operator !=(MulticastDelegate a, MulticastDelegate b); [Bridge.Template("Bridge.fn.getInvocationList({this})")] public extern Delegate[] GetInvocationList(); } }
apache-2.0
C#
9ee0e2821f584919106760eac6db97b29beeb3c4
Update SingleEntryCurrencyConversionCompositionStrategy.cs
tiksn/TIKSN-Framework
TIKSN.Core/Finance/SingleEntryCurrencyConversionCompositionStrategy.cs
TIKSN.Core/Finance/SingleEntryCurrencyConversionCompositionStrategy.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using TIKSN.Finance.Helpers; namespace TIKSN.Finance { public class SingleEntryCurrencyConversionCompositionStrategy : ICurrencyConversionCompositionStrategy { public async Task<Money> ConvertCurrencyAsync(Money baseMoney, IEnumerable<ICurrencyConverter> converters, CurrencyInfo counterCurrency, DateTimeOffset asOn, CancellationToken cancellationToken) { var filteredConverters = await CurrencyHelper.FilterConvertersAsync(converters, baseMoney.Currency, counterCurrency, asOn, cancellationToken).ConfigureAwait(false); var converter = filteredConverters.Single(); return await converter.ConvertCurrencyAsync(baseMoney, counterCurrency, asOn, cancellationToken).ConfigureAwait(false); } public async Task<decimal> GetExchangeRateAsync(IEnumerable<ICurrencyConverter> converters, CurrencyPair pair, DateTimeOffset asOn, CancellationToken cancellationToken) { var filteredConverters = await CurrencyHelper.FilterConvertersAsync(converters, pair, asOn, cancellationToken).ConfigureAwait(false); var converter = filteredConverters.Single(); return await converter.GetExchangeRateAsync(pair, asOn, cancellationToken).ConfigureAwait(false); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using TIKSN.Finance.Helpers; namespace TIKSN.Finance { public class SingleEntryCurrencyConversionCompositionStrategy : ICurrencyConversionCompositionStrategy { public async Task<Money> ConvertCurrencyAsync(Money baseMoney, IEnumerable<ICurrencyConverter> converters, CurrencyInfo counterCurrency, DateTimeOffset asOn, CancellationToken cancellationToken) { var filteredConverters = await CurrencyHelper.FilterConverters(converters, baseMoney.Currency, counterCurrency, asOn, cancellationToken); var converter = filteredConverters.Single(); return await converter.ConvertCurrencyAsync(baseMoney, counterCurrency, asOn, cancellationToken); } public async Task<decimal> GetExchangeRateAsync(IEnumerable<ICurrencyConverter> converters, CurrencyPair pair, DateTimeOffset asOn, CancellationToken cancellationToken) { var filteredConverters = await CurrencyHelper.FilterConverters(converters, pair, asOn, cancellationToken); var converter = filteredConverters.Single(); return await converter.GetExchangeRateAsync(pair, asOn, cancellationToken); } } }
mit
C#
677b205153f4443efb9e794299d8b4c387acbbff
Fix pack failure caused by thumbnail creation error for unsupported video format
semenenkov/fig-leaf
FigLeaf.Core/Thumbnail.cs
FigLeaf.Core/Thumbnail.cs
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; namespace FigLeaf.Core { public class Thumbnail { private readonly int _size; private readonly List<string> _videoExts; public Thumbnail(Settings settings) { if (!settings.EnableThumbnails) throw new ApplicationException("Trying to create thumbnail generator for disabled thumbnails option"); _size = settings.ThumbnailSize; _videoExts = settings.VideoExtensions; } public string GetThumbnailFileName(string source, out bool isVideo) { string ext = Path.GetExtension(source); if (!string.IsNullOrEmpty(ext) && ext.StartsWith(".")) ext = ext.Substring(1).ToLower(); isVideo = _videoExts.Any(ve => string.Equals(ve, ext, StringComparison.OrdinalIgnoreCase)); if (!isVideo && !IsSupportedPhotoFormat(ext)) return null; return string.Format("{0}.jpg", Path.GetFileName(source)); } public bool MakeForPhoto(string source, string target) { try { using (var image = Image.FromFile(source)) { int w = image.Width > image.Height ? _size : _size * image.Width / image.Height; int h = image.Height > image.Width ? _size : _size * image.Height / image.Width; using (Image thumb = image.GetThumbnailImage(w, h, () => false, IntPtr.Zero)) thumb.Save(target, ImageFormat.Jpeg); return true; } } catch { // may be thrown for bad image or not supported format return false; } } public bool MakeForVideo(string source, string target) { var ffMpeg = new NReco.VideoConverter.FFMpegConverter(); string tmpFile = target + ".tmp"; try { ffMpeg.GetVideoThumbnail(source, tmpFile); bool result = MakeForPhoto(tmpFile, target); File.Delete(tmpFile); return result; } catch { // may be thrown for bad image or not supported format return false; } } private bool IsSupportedPhotoFormat(string ext) { return ext == "bmp" || ext == "gif" || ext == "jpg" || ext == "jpeg" || ext == "png" || ext == "tiff"; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; namespace FigLeaf.Core { public class Thumbnail { private readonly int _size; private readonly List<string> _videoExts; public Thumbnail(Settings settings) { if (!settings.EnableThumbnails) throw new ApplicationException("Trying to create thumbnail generator for disabled thumbnails option"); _size = settings.ThumbnailSize; _videoExts = settings.VideoExtensions; } public string GetThumbnailFileName(string source, out bool isVideo) { string ext = Path.GetExtension(source); if (!string.IsNullOrEmpty(ext) && ext.StartsWith(".")) ext = ext.Substring(1).ToLower(); isVideo = _videoExts.Any(ve => string.Equals(ve, ext, StringComparison.OrdinalIgnoreCase)); if (!isVideo && !IsSupportedPhotoFormat(ext)) return null; return string.Format("{0}.jpg", Path.GetFileName(source)); } public bool MakeForPhoto(string source, string target) { try { using (var image = Image.FromFile(source)) { int w = image.Width > image.Height ? _size : _size * image.Width / image.Height; int h = image.Height > image.Width ? _size : _size * image.Height / image.Width; using (Image thumb = image.GetThumbnailImage(w, h, () => false, IntPtr.Zero)) thumb.Save(target, ImageFormat.Jpeg); return true; } } catch { // may be thrown for bad image or not supported format return false; } } public bool MakeForVideo(string source, string target) { var ffMpeg = new NReco.VideoConverter.FFMpegConverter(); string tmpFile = target + ".tmp"; ffMpeg.GetVideoThumbnail(source, tmpFile); bool result = MakeForPhoto(tmpFile, target); File.Delete(tmpFile); return result; } private bool IsSupportedPhotoFormat(string ext) { return ext == "bmp" || ext == "gif" || ext == "jpg" || ext == "jpeg" || ext == "png" || ext == "tiff"; } } }
mit
C#
c54784701afef6112e5140fd714813b11ef7cdab
Tweak to comment
svermeulen/Unity3dAsyncAwaitUtil
UnityProject/Assets/Plugins/AsyncAwaitUtil/Source/AwaitExtensions.cs
UnityProject/Assets/Plugins/AsyncAwaitUtil/Source/AwaitExtensions.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading.Tasks; using UnityEngine; public static class AwaitExtensions { public static TaskAwaiter<int> GetAwaiter(this Process process) { var tcs = new TaskCompletionSource<int>(); process.EnableRaisingEvents = true; process.Exited += (s, e) => tcs.TrySetResult(process.ExitCode); if (process.HasExited) { tcs.TrySetResult(process.ExitCode); } return tcs.Task.GetAwaiter(); } // Any time you call an async method from sync code, you can either use this wrapper // method or you can define your own `async void` method that performs the await // on the given Task public static async void WrapErrors(this Task task) { await task; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading.Tasks; using UnityEngine; public static class AwaitExtensions { public static TaskAwaiter<int> GetAwaiter(this Process process) { var tcs = new TaskCompletionSource<int>(); process.EnableRaisingEvents = true; process.Exited += (s, e) => tcs.TrySetResult(process.ExitCode); if (process.HasExited) { tcs.TrySetResult(process.ExitCode); } return tcs.Task.GetAwaiter(); } // Any time you call an async method from sync code, you should call this method // as well, otherwise any exceptions that occur inside the async code will not be // received by Unity. (Unity only observes errors for async methods that have return type void) public static async void WrapErrors(this Task task) { await task; } }
mit
C#
472ddbe28c4c652b15a3bfb9b94dbd6422f24aae
fix typo
DigDes/SoapCore
src/SoapCore.Tests/Serialization/Models.Xml/ComplexLegacyModel.cs
src/SoapCore.Tests/Serialization/Models.Xml/ComplexLegacyModel.cs
using System.ServiceModel; using System.Xml.Schema; using System.Xml.Serialization; namespace SoapCore.Tests.Serialization.Models.Xml { [MessageContract(WrapperName = "getLinks", WrapperNamespace = "http://xmlelement-namespace/", IsWrapped = true)] public class ComplexLegacyModel { [MessageBodyMember(Namespace = "http://xmlelement-namespace/", Order = 0)] [XmlElement("unqualified", Form = XmlSchemaForm.Unqualified)] public string[] UnqualifiedItems { get; set; } [MessageBodyMember(Namespace = "http://xmlelement-namespace/", Order = 1)] [XmlElement("qualified")] public string[] QualifiedItems { get; set; } } }
using System.ServiceModel; using System.Xml.Schema; using System.Xml.Serialization; namespace SoapCore.Tests.Serialization.Models.Xml { [MessageContract(WrapperName = "getLinks", WrapperNamespace = "http://xmlelement-namespace/", IsWrapped = true)] public class ComplexLegacyModel { [MessageBodyMember(Namespace = "http://xmlelement-namespace/", Order = 0)] [XmlElement("qualified", Form = XmlSchemaForm.Unqualified)] public string[] QualifiedItems { get; set; } [MessageBodyMember(Namespace = "http://xmlelement-namespace/", Order = 0)] [XmlElement("unqualified")] public string[] UnqualifiedItems { get; set; } } }
mit
C#
c625c929e5974f0b544758eb72a422a4cbf2def2
Update button text to match new terminology
ppy/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu,peppy/osu
osu.Game/Overlays/Settings/Sections/DebugSettings/GeneralSettings.cs
osu.Game/Overlays/Settings/Sections/DebugSettings/GeneralSettings.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Configuration; using osu.Framework.Graphics; using osu.Framework.Localisation; using osu.Framework.Screens; using osu.Game.Localisation; using osu.Game.Screens; using osu.Game.Screens.Import; using osu.Game.Screens.Utility; namespace osu.Game.Overlays.Settings.Sections.DebugSettings { public class GeneralSettings : SettingsSubsection { protected override LocalisableString Header => DebugSettingsStrings.GeneralHeader; [BackgroundDependencyLoader(true)] private void load(FrameworkDebugConfigManager config, FrameworkConfigManager frameworkConfig, IPerformFromScreenRunner performer) { Children = new Drawable[] { new SettingsCheckbox { LabelText = DebugSettingsStrings.ShowLogOverlay, Current = frameworkConfig.GetBindable<bool>(FrameworkSetting.ShowLogOverlay) }, new SettingsCheckbox { LabelText = DebugSettingsStrings.BypassFrontToBackPass, Current = config.GetBindable<bool>(DebugSetting.BypassFrontToBackPass) }, new SettingsButton { Text = DebugSettingsStrings.ImportFiles, Action = () => performer?.PerformFromScreen(menu => menu.Push(new FileImportScreen())) }, new SettingsButton { Text = @"Run latency certifier", Action = () => performer?.PerformFromScreen(menu => menu.Push(new LatencyCertifierScreen())) } }; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Configuration; using osu.Framework.Graphics; using osu.Framework.Localisation; using osu.Framework.Screens; using osu.Game.Localisation; using osu.Game.Screens; using osu.Game.Screens.Import; using osu.Game.Screens.Utility; namespace osu.Game.Overlays.Settings.Sections.DebugSettings { public class GeneralSettings : SettingsSubsection { protected override LocalisableString Header => DebugSettingsStrings.GeneralHeader; [BackgroundDependencyLoader(true)] private void load(FrameworkDebugConfigManager config, FrameworkConfigManager frameworkConfig, IPerformFromScreenRunner performer) { Children = new Drawable[] { new SettingsCheckbox { LabelText = DebugSettingsStrings.ShowLogOverlay, Current = frameworkConfig.GetBindable<bool>(FrameworkSetting.ShowLogOverlay) }, new SettingsCheckbox { LabelText = DebugSettingsStrings.BypassFrontToBackPass, Current = config.GetBindable<bool>(DebugSetting.BypassFrontToBackPass) }, new SettingsButton { Text = DebugSettingsStrings.ImportFiles, Action = () => performer?.PerformFromScreen(menu => menu.Push(new FileImportScreen())) }, new SettingsButton { Text = @"Run latency comparer", Action = () => performer?.PerformFromScreen(menu => menu.Push(new LatencyCertifierScreen())) } }; } } }
mit
C#
a7982d583c99a5bd7b3b54099edfac224a6d2344
Change version to 0.5
DataGenSoftware/DataGen.Extensions
DataGen.Extensions/DataGen.Extensions.Shared/Common/AssemblyInfo.Common.cs
DataGen.Extensions/DataGen.Extensions.Shared/Common/AssemblyInfo.Common.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("DataGen.Extensions")] [assembly: AssemblyDescription(".NET types extensions")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DataGen.Extensions")] [assembly: AssemblyCopyright("Copyright © Karol Habczyk")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.5.*")] [assembly: AssemblyFileVersion("0.5.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DataGen.Extensions")] [assembly: AssemblyDescription(".NET types extensions")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DataGen.Extensions")] [assembly: AssemblyCopyright("Copyright © Karol Habczyk")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.4.0.0")] [assembly: AssemblyFileVersion("0.4.0.0")]
mit
C#
8658fc9287e99e437134d2278af66bec9f273ea3
fix bootstrap pagination demo.
kpi-ua/X.PagedList,ernado-x/X.PagedList,ernado-x/X.PagedList,dncuug/X.PagedList,kpi-ua/X.PagedList
examples/X.PagedList.Mvc.Example.Core/Views/Bootstrap41/Index.cshtml
examples/X.PagedList.Mvc.Example.Core/Views/Bootstrap41/Index.cshtml
@{ Layout = "~/Views/Shared/_Layout-41.cshtml"; ViewBag.Title = "Product Listing"; } @using X.PagedList.Mvc.Core; @*import this so we get our HTML Helper*@ @using X.PagedList; @*import this so we can cast our list to IPagedList (only necessary because ViewBag is dynamic)*@ <!-- import the included stylesheet for some (very basic) default styling --> <link href="/Content/PagedList.css" rel="stylesheet" type="text/css" /> <!-- loop through each of your products and display it however you want. we're just printing the name here --> <section class="mt-4"> <h2>List of Products</h2> <ul> @foreach (var name in ViewBag.Names) { <li>@name</li> } </ul> </section> <!-- output a paging control that lets the user navigation to the previous page, next page, etc --> @Html.PagedListPager((IPagedList)ViewBag.Names, page => Url.Action("Index", new { page }), new X.PagedList.Mvc.Common.PagedListRenderOptionsBase { PageClasses = new string[] { "page-link" }, UlElementClasses = new string[] { "pagination" }, LiElementClasses = new string[] { "page-item" }, DisplayItemSliceAndTotal = true, })
@{ Layout = "~/Views/Shared/_Layout-41.cshtml"; ViewBag.Title = "Product Listing"; } @using X.PagedList.Mvc.Core; @*import this so we get our HTML Helper*@ @using X.PagedList; @*import this so we can cast our list to IPagedList (only necessary because ViewBag is dynamic)*@ <!-- import the included stylesheet for some (very basic) default styling --> <link href="/Content/PagedList.css" rel="stylesheet" type="text/css" /> <!-- loop through each of your products and display it however you want. we're just printing the name here --> <section class="mt-4"> <h2>List of Products</h2> <ul> @foreach (var name in ViewBag.Names) { <li>@name</li> } </ul> </section> <!-- output a paging control that lets the user navigation to the previous page, next page, etc --> @Html.PagedListPager((IPagedList)ViewBag.Names, page => Url.Action("Index", new { page }), new X.PagedList.Mvc.Common.PagedListRenderOptionsBase { DisplayItemSliceAndTotal = true, })
mit
C#
c215c9c350002bd42b4d317390ab2624dc92e61a
Update SettingFontColor.cs
asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET
Examples/CSharp/Formatting/DealingWithFontSettings/SettingFontColor.cs
Examples/CSharp/Formatting/DealingWithFontSettings/SettingFontColor.cs
using System.IO; using Aspose.Cells; using System.Drawing; namespace Aspose.Cells.Examples.Formatting.DealingWithFontSettings { public class SettingFontColor { public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); //Instantiating a Workbook object Workbook workbook = new Workbook(); //Adding a new worksheet to the Excel object int i = workbook.Worksheets.Add(); //Obtaining the reference of the newly added worksheet by passing its sheet index Worksheet worksheet = workbook.Worksheets[i]; //Accessing the "A1" cell from the worksheet Aspose.Cells.Cell cell = worksheet.Cells["A1"]; //Adding some value to the "A1" cell cell.PutValue("Hello Aspose!"); //Obtaining the style of the cell Style style = cell.GetStyle(); //Setting the font color to blue style.Font.Color = Color.Blue; //Applying the style to the cell cell.SetStyle(style); //Saving the Excel file workbook.Save(dataDir + "book1.out.xls", SaveFormat.Excel97To2003); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; using System.Drawing; namespace Aspose.Cells.Examples.Formatting.DealingWithFontSettings { public class SettingFontColor { public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); //Instantiating a Workbook object Workbook workbook = new Workbook(); //Adding a new worksheet to the Excel object int i = workbook.Worksheets.Add(); //Obtaining the reference of the newly added worksheet by passing its sheet index Worksheet worksheet = workbook.Worksheets[i]; //Accessing the "A1" cell from the worksheet Aspose.Cells.Cell cell = worksheet.Cells["A1"]; //Adding some value to the "A1" cell cell.PutValue("Hello Aspose!"); //Obtaining the style of the cell Style style = cell.GetStyle(); //Setting the font color to blue style.Font.Color = Color.Blue; //Applying the style to the cell cell.SetStyle(style); //Saving the Excel file workbook.Save(dataDir + "book1.out.xls", SaveFormat.Excel97To2003); } } }
mit
C#
d20b82423f2ecbf62e00e0fa28d81cc42b7f8f4c
Optimize RecordHeader ToBytes
markmeeus/MarcelloDB
MarcelloDB/Records/RecordHeader.cs
MarcelloDB/Records/RecordHeader.cs
using System; using MarcelloDB.Serialization; namespace MarcelloDB.Records { internal class RecordHeader { const int BYTE_SIZE = sizeof(byte) + (2 * sizeof(Int32)); //Address is not stored internal byte Type { get; set; } internal long Address { get; set; } internal Int32 DataSize { get; set; } internal Int32 AllocatedDataSize { get; set; } internal Int32 TotalRecordSize { get{ return ByteSize + AllocatedDataSize; } } static internal int ByteSize { get { return BYTE_SIZE; } } private RecordHeader(){} //construction only allowed from factory methods internal byte[] AsBytes() { var bytes = new byte[ByteSize]; var writer = new BufferWriter(bytes); writer .WriteByte(this.Type) .WriteInt32(this.DataSize) .WriteInt32(this.AllocatedDataSize); return writer.GetTrimmedBuffer(); } #region factory methods internal static RecordHeader New (){ return new RecordHeader();} internal static RecordHeader FromBytes(Int64 address, byte[] bytes) { var reader = new BufferReader(bytes); var recordHeader = new RecordHeader(); recordHeader.Address = address; recordHeader.Type = reader.ReadByte(); recordHeader.DataSize = reader.ReadInt32(); recordHeader.AllocatedDataSize = reader.ReadInt32(); return recordHeader; } #endregion } }
using System; using MarcelloDB.Serialization; namespace MarcelloDB.Records { internal class RecordHeader { const int BYTE_SIZE = sizeof(byte) + (3 * sizeof(Int32)); //Address is not stored internal byte Type { get; set; } internal long Address { get; set; } internal Int32 DataSize { get; set; } internal Int32 AllocatedDataSize { get; set; } internal Int32 TotalRecordSize { get{ return ByteSize + AllocatedDataSize; } } static internal int ByteSize { get { return BYTE_SIZE; } } private RecordHeader(){} //construction only allowed from factory methods internal byte[] AsBytes() { var bytes = new byte[ByteSize]; var writer = new BufferWriter(bytes); writer .WriteByte(this.Type) .WriteInt32(this.DataSize) .WriteInt32(this.AllocatedDataSize); return writer.GetTrimmedBuffer(); } #region factory methods internal static RecordHeader New (){ return new RecordHeader();} internal static RecordHeader FromBytes(Int64 address, byte[] bytes) { var reader = new BufferReader(bytes); var recordHeader = new RecordHeader(); recordHeader.Address = address; recordHeader.Type = reader.ReadByte(); recordHeader.DataSize = reader.ReadInt32(); recordHeader.AllocatedDataSize = reader.ReadInt32(); return recordHeader; } #endregion } }
mit
C#
5f04cfe44758ebda8d5d14b27f8955f88308bd2d
Fix temp folder in cleanup button and add submit queue folder
Sitecore/Sitecore-Instance-Manager,sergeyshushlyapin/Sitecore-Instance-Manager,Brad-Christie/Sitecore-Instance-Manager,dsolovay/Sitecore-Instance-Manager
src/SIM.Tool.Windows/MainWindowComponents/CleanupInstanceButton.cs
src/SIM.Tool.Windows/MainWindowComponents/CleanupInstanceButton.cs
namespace SIM.Tool.Windows.MainWindowComponents { using System.IO; using System.Linq; using System.Windows; using Sitecore.Diagnostics.Base; using Sitecore.Diagnostics.Base.Annotations; using SIM.Instances; using SIM.Tool.Base; using SIM.Tool.Base.Plugins; public class CleanupInstanceButton : IMainWindowButton { [UsedImplicitly] public CleanupInstanceButton() { } public bool IsEnabled(Window mainWindow, Instance instance) { return instance != null; } public void OnClick(Window mainWindow, Instance instance) { if (instance.State != InstanceState.Stopped) { WindowHelper.ShowMessage("Stop the instance first"); return; } WindowHelper.LongRunningTask(() => DoWork(instance), "Cleaning up", mainWindow); } private void DoWork(Instance instance) { Assert.ArgumentNotNull(instance, nameof(instance)); while (instance.ProcessIds.Any()) { if (instance.State != InstanceState.Stopped) { MessageBox.Show("Stop the instance first"); } } var tempFolder = instance.TempFolderPath; if (!string.IsNullOrEmpty(tempFolder) && Directory.Exists(tempFolder)) { foreach (var dir in Directory.GetDirectories(tempFolder)) { Directory.Delete(dir, true); } foreach (var file in Directory.GetFiles(tempFolder)) { if (file.EndsWith("dictionary.dat")) { continue; } File.Delete(file); } } var folders = new[] { instance.LogsFolderPath, Path.Combine(instance.WebRootPath, "App_Data/MediaCache"), Path.Combine(instance.DataFolderPath, "ViewState"), Path.Combine(instance.DataFolderPath, "Diagnostics"), Path.Combine(instance.DataFolderPath, "Submit Queue"), }; foreach (var folder in folders) { if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) { continue; } Directory.Delete(folder, true); Directory.CreateDirectory(folder); } } } }
namespace SIM.Tool.Windows.MainWindowComponents { using System.IO; using System.Linq; using System.Windows; using Sitecore.Diagnostics.Base; using Sitecore.Diagnostics.Base.Annotations; using SIM.Instances; using SIM.Tool.Base; using SIM.Tool.Base.Plugins; public class CleanupInstanceButton : IMainWindowButton { [UsedImplicitly] public CleanupInstanceButton() { } public bool IsEnabled(Window mainWindow, Instance instance) { return instance != null; } public void OnClick(Window mainWindow, Instance instance) { if (instance.State != InstanceState.Stopped) { WindowHelper.ShowMessage("Stop the instance first"); return; } WindowHelper.LongRunningTask(() => DoWork(instance), "Cleaning up", mainWindow); } private void DoWork(Instance instance) { Assert.ArgumentNotNull(instance, nameof(instance)); while (instance.ProcessIds.Any()) { if (instance.State != InstanceState.Stopped) { MessageBox.Show("Stop the instance first"); } } var tempFolder = instance.TempFolderPath; if (!string.IsNullOrEmpty(tempFolder) && Directory.Exists(tempFolder)) { foreach (var dir in Directory.GetDirectories(tempFolder)) { Directory.Delete(dir, true); } foreach (var file in Directory.GetFiles(tempFolder)) { if (file.EndsWith("dictionary.data")) { continue; } File.Delete(file); } } var folders = new[] { instance.LogsFolderPath, Path.Combine(instance.WebRootPath, "App_Data/MediaCache"), Path.Combine(instance.DataFolderPath, "ViewState"), Path.Combine(instance.DataFolderPath, "Diagnostics"), }; foreach (var folder in folders) { if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) { continue; } Directory.Delete(folder, true); Directory.CreateDirectory(folder); } } } }
mit
C#
9eaecba44d0e697320d51f9470214c45da427e74
Add image for a hovered state in image button
k-t/SharpHaven
MonoHaven.Client/UI/ImageButton.cs
MonoHaven.Client/UI/ImageButton.cs
using System; using System.Drawing; using MonoHaven.Graphics; using MonoHaven.Utils; using OpenTK.Input; namespace MonoHaven.UI { public class ImageButton : Widget { private bool isPressed; public ImageButton(Widget parent) : base(parent) { IsFocusable = true; } public event EventHandler Clicked; public Drawable Image { get; set; } public Drawable PressedImage { get; set; } public Drawable HoveredImage { get; set; } protected override void OnDraw(DrawingContext dc) { Drawable image = null; if (isPressed && PressedImage != null) image = PressedImage; else if (IsHovered && HoveredImage != null) image = HoveredImage; else image = Image; if (image != null) dc.Draw(image, 0, 0); } protected override void OnMouseButtonDown(MouseButtonEventArgs e) { Host.GrabMouse(this); isPressed = true; } protected override void OnMouseButtonUp(MouseButtonEventArgs e) { Host.ReleaseMouse(); isPressed = false; // button released outside of borders? var p = PointToWidget(e.Position); if (Rectangle.FromLTRB(0, 0, Width, Height).Contains(p)) Clicked.Raise(this, EventArgs.Empty); } } }
using System; using System.Drawing; using MonoHaven.Graphics; using MonoHaven.Utils; using OpenTK.Input; namespace MonoHaven.UI { public class ImageButton : Widget { private bool isPressed; public ImageButton(Widget parent) : base(parent) { IsFocusable = true; } public event EventHandler Clicked; public Drawable Image { get; set; } public Drawable PressedImage { get; set; } protected override void OnDraw(DrawingContext dc) { var tex = isPressed ? PressedImage : Image; if (tex != null) dc.Draw(tex, 0, 0); } protected override void OnMouseButtonDown(MouseButtonEventArgs e) { Host.GrabMouse(this); isPressed = true; } protected override void OnMouseButtonUp(MouseButtonEventArgs e) { Host.ReleaseMouse(); isPressed = false; // button released outside of borders? var p = PointToWidget(e.Position); if (Rectangle.FromLTRB(0, 0, Width, Height).Contains(p)) Clicked.Raise(this, EventArgs.Empty); } } }
mit
C#
443dca831b3c0696172fc6089fe504087b5a0c34
comment removed
MaderaJan/INPTP01
INPTP_AppForFixing/Entity/Boss.cs
INPTP_AppForFixing/Entity/Boss.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace INPTP_AppForFixing { public class Boss : Employee { private const int MONTHS_OF_YEAR = 12; private HashSet<Employee> employees; private Department department; public double PerEmplSalaryBonus { get; set; } public Boss(Department department) { employees = new HashSet<Employee>(); this.department = department; } public void InsertEmpl(Employee empl) { employees.Add(empl); } public void PurgeEmpl(Employee empl) { employees.Remove(empl); } public bool HasEmployee(Employee empl) { return employees.Contains(empl); } public ISet<Employee> GetEmployees() { return new HashSet<Employee>(employees); } public int EmployeeCount { get { return employees.Count; } } // calculate base year salary + subemployee bonus public override double CalcYearlySalaryCZK() { return (base.CalcYearlySalaryCZK() + (EmployeeCount * PerEmplSalaryBonus * MONTHS_OF_YEAR)); } public override double CalcYearlyIncome() { return MonthlySalaryCZK * MONTHS_OF_YEAR * (1 - taxRate) + (MONTHS_OF_YEAR * (EmployeeCount * PerEmplSalaryBonus * (1 - taxRate))); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace INPTP_AppForFixing { public class Boss : Employee { private const int MONTHS_OF_YEAR = 12; private HashSet<Employee> employees; private Department department; public double PerEmplSalaryBonus { get; set; } public Boss(Department department) { employees = new HashSet<Employee>(); this.department = department; } public void InsertEmpl(Employee empl) { employees.Add(empl); } public void PurgeEmpl(Employee empl) { employees.Remove(empl); } public bool HasEmployee(Employee empl) { return employees.Contains(empl); } public ISet<Employee> GetEmployees() { return new HashSet<Employee>(employees); } public int EmployeeCount { get { return employees.Count; } } // calculate base year salary + subemployee bonus public override double CalcYearlySalaryCZK() { return (base.CalcYearlySalaryCZK() + (EmployeeCount * PerEmplSalaryBonus * MONTHS_OF_YEAR)); } public override double CalcYearlyIncome() { //return CalcYearlySalaryCZK() * (1 - taxRate); return MonthlySalaryCZK * MONTHS_OF_YEAR * (1 - taxRate) + (MONTHS_OF_YEAR * (EmployeeCount * PerEmplSalaryBonus * (1 - taxRate))); } } }
unlicense
C#
9eb6f2de1ef5b8d76ec9eb551c2af492091ab2b8
Update BaseViewModel.cs
jamesmontemagno/MyShoppe
MyShop/ViewModels/BaseViewModel.cs
MyShop/ViewModels/BaseViewModel.cs
using System; using System.ComponentModel; using System.Collections.Generic; using System.Runtime.CompilerServices; using Xamarin.Forms; namespace MyShop { public class BaseViewModel : INotifyPropertyChanged { protected Page page; public BaseViewModel (Page page) { this.page = page; } private string title = string.Empty; public const string TitlePropertyName = "Title"; /// <summary> /// Gets or sets the "Title" property /// </summary> /// <value>The title.</value> public string Title { get { return title; } set { SetProperty (ref title, value);} } private string subTitle = string.Empty; /// <summary> /// Gets or sets the "Subtitle" property /// </summary> public const string SubtitlePropertyName = "Subtitle"; public string Subtitle { get { return subTitle; } set { SetProperty (ref subTitle, value);} } private string icon = null; /// <summary> /// Gets or sets the "Icon" of the viewmodel /// </summary> public const string IconPropertyName = "Icon"; public string Icon { get { return icon; } set { SetProperty (ref icon, value);} } private bool isBusy; /// <summary> /// Gets or sets if the view is busy. /// </summary> public const string IsBusyPropertyName = "IsBusy"; public bool IsBusy { get { return isBusy; } set { SetProperty (ref isBusy, value);} } private bool canLoadMore = true; /// <summary> /// Gets or sets if we can load more. /// </summary> public const string CanLoadMorePropertyName = "CanLoadMore"; public bool CanLoadMore { get { return canLoadMore; } set { SetProperty (ref canLoadMore, value);} } protected void SetProperty<T>( ref T backingStore, T value, [CallerMemberName]string propertyName = "", Action onChanged = null) { if (EqualityComparer<T>.Default.Equals(backingStore, value)) return; backingStore = value; onChanged?.Invoke(); OnPropertyChanged(propertyName); } #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; #endregion public void OnPropertyChanged([CallerMemberName]string propertyName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs (propertyName)); } }
using System; using System.ComponentModel; using System.Collections.Generic; using System.Runtime.CompilerServices; using Xamarin.Forms; namespace MyShop { public class BaseViewModel : INotifyPropertyChanged { protected Page page; public BaseViewModel (Page page) { this.page = page; } private string title = string.Empty; public const string TitlePropertyName = "Title"; /// <summary> /// Gets or sets the "Title" property /// </summary> /// <value>The title.</value> public string Title { get { return title; } set { SetProperty (ref title, value);} } private string subTitle = string.Empty; /// <summary> /// Gets or sets the "Subtitle" property /// </summary> public const string SubtitlePropertyName = "Subtitle"; public string Subtitle { get { return subTitle; } set { SetProperty (ref subTitle, value);} } private string icon = null; /// <summary> /// Gets or sets the "Icon" of the viewmodel /// </summary> public const string IconPropertyName = "Icon"; public string Icon { get { return icon; } set { SetProperty (ref icon, value);} } private bool isBusy; /// <summary> /// Gets or sets if the view is busy. /// </summary> public const string IsBusyPropertyName = "IsBusy"; public bool IsBusy { get { return isBusy; } set { SetProperty (ref isBusy, value);} } private bool canLoadMore = true; /// <summary> /// Gets or sets if we can load more. /// </summary> public const string CanLoadMorePropertyName = "CanLoadMore"; public bool CanLoadMore { get { return canLoadMore; } set { SetProperty (ref canLoadMore, value);} } protected void SetProperty<T>( ref T backingStore, T value, [CallerMemberName]string propertyName = "", Action onChanged = null) { if (EqualityComparer<T>.Default.Equals(backingStore, value)) return; backingStore = value; onChanged?.Invoke(); OnPropertyChanged(propertyName); } #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; #endregion public void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs (propertyName)); } }
mit
C#
a8bc2636fcce20ff1c8f243112311d756dc21f0e
change default IBinarySerializer.
tangxuehua/equeue,tangxuehua/equeue,Aaron-Liu/equeue,geffzhang/equeue,Aaron-Liu/equeue,geffzhang/equeue,tangxuehua/equeue
src/EQueue/Configurations/ConfigurationExtensions.cs
src/EQueue/Configurations/ConfigurationExtensions.cs
using ECommon.Configurations; using ECommon.IoC; using ECommon.Scheduling; using ECommon.Serializing; using EQueue.Broker; using EQueue.Clients.Consumers; using EQueue.Clients.Producers; namespace EQueue.Configurations { public static class ConfigurationExtensions { public static Configuration RegisterEQueueComponents(this Configuration configuration) { ObjectContainer.Register<IBinarySerializer, DefaultBinarySerializer>(); ObjectContainer.Register<IScheduleService, ScheduleService>(); ObjectContainer.Register<IAllocateMessageQueueStrategy, AverageAllocateMessageQueueStrategy>(); ObjectContainer.Register<IQueueSelector, QueueHashSelector>(); ObjectContainer.Register<IOffsetStore, InMemoryOffsetStore>(); ObjectContainer.Register<IMessageStore, InMemoryMessageStore>(); ObjectContainer.Register<IMessageService, MessageService>(); return configuration; } } }
using ECommon.Configurations; using ECommon.IoC; using ECommon.Scheduling; using ECommon.Serializing; using EQueue.Broker; using EQueue.Clients.Consumers; using EQueue.Clients.Producers; namespace EQueue.Configurations { public static class ConfigurationExtensions { public static Configuration RegisterEQueueComponents(this Configuration configuration) { ObjectContainer.Register<IBinarySerializer, JsonBasedBinarySerializer>(); ObjectContainer.Register<IScheduleService, ScheduleService>(); ObjectContainer.Register<IAllocateMessageQueueStrategy, AverageAllocateMessageQueueStrategy>(); ObjectContainer.Register<IQueueSelector, QueueHashSelector>(); ObjectContainer.Register<IOffsetStore, InMemoryOffsetStore>(); ObjectContainer.Register<IMessageStore, InMemoryMessageStore>(); ObjectContainer.Register<IMessageService, MessageService>(); return configuration; } } }
mit
C#
901659ec12f3e592ba22996058aedba7cbdd812f
Change source code as Nintendo updates SplatNet (bug fix).
mntone/SplatoonClient,mntone/SplatoonClient
Mntone.SplatoonClient/Mntone.SplatoonClient/SplatoonContextFactory.cs
Mntone.SplatoonClient/Mntone.SplatoonClient/SplatoonContextFactory.cs
using System.Threading.Tasks; using Mntone.NintendoNetworkHelper; using Mntone.SplatoonClient.Internal; namespace Mntone.SplatoonClient { public static class SplatoonContextFactory { public static async Task<SplatoonContext> GetContextAsync(string username, string password) { var authorizer = new NintendoNetworkAuthorizer(); var requestToken = await authorizer.GetRequestTokenAsync(SplatoonConstantValues.AUTH_FORWARD_URI).ConfigureAwait(false); var accessToken = await authorizer.Authorize(requestToken, new AuthenticationToken(username, password), SplatoonHelper.GetSessionValue).ConfigureAwait(false); authorizer.Dispose(); return new SplatoonContext(accessToken); } } }
using System.Threading.Tasks; using Mntone.NintendoNetworkHelper; using Mntone.SplatoonClient.Internal; namespace Mntone.SplatoonClient { public static class SplatoonContextFactory { public static async Task<SplatoonContext> GetContextAsync(string username, string password) { var authorizer = new NintendoNetworkAuthorizer(); var requestToken = await authorizer.GetRequestTokenAsync(SplatoonConstantValues.AUTH_FORWARD_URI).ConfigureAwait(false); var accessToken = await authorizer.Authorize(requestToken, new AuthenticationToken(username, password), SplatoonHelper.GetSessionValue).ConfigureAwait(false); var requestToken2 = await authorizer.GetRequestTokenAsync(SplatoonConstantValues.AUTH_FORWARD_URI).ConfigureAwait(false); var accessToken2 = await authorizer.Authorize(requestToken2, new AuthenticationToken(username, password), SplatoonHelper.GetSessionValue).ConfigureAwait(false); authorizer.Dispose(); return new SplatoonContext(accessToken2); } } }
mit
C#
d220ee2d3b9cc828bbb9c40543bd66bde6b212f1
Set title for settings detail page.
Azure-Samples/MyDriving,Azure-Samples/MyDriving,Azure-Samples/MyDriving
XamarinApp/MyTrips/MyTrips.iOS/Screens/SettingsDetailViewController.cs
XamarinApp/MyTrips/MyTrips.iOS/Screens/SettingsDetailViewController.cs
// This file has been autogenerated from a class added in the UI designer. using System; using System.Collections.Generic; using Foundation; using UIKit; using MyTrips.Model; namespace MyTrips.iOS { public partial class SettingsDetailViewController : UIViewController { public Setting Setting { get; set; } public SettingsDetailViewController (IntPtr handle) : base (handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); NavigationItem.Title = Setting.Name; settingsDetailTableView.Source = new SettingsDetailTableViewSource(Setting); } } public class SettingsDetailTableViewSource : UITableViewSource { Setting setting; public SettingsDetailTableViewSource(Setting setting) { this.setting = setting; } public override string TitleForHeader(UITableView tableView, nint section) { return setting.Name; } public override void WillDisplayHeaderView(UITableView tableView, UIView headerView, nint section) { var header = headerView as UITableViewHeaderFooterView; header.TextLabel.TextColor = "5C5C5C".ToUIColor(); header.TextLabel.Font = UIFont.FromName("AvenirNext-Medium", 16); header.TextLabel.Text = TitleForHeader(tableView, section); } public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { setting.Value = setting.PossibleValues[indexPath.Row]; var cells = tableView.VisibleCells; int i = 0; foreach (var cell in cells) { var value = setting.PossibleValues[i]; if (setting.Value != value) { cell.Accessory = UITableViewCellAccessory.None; } else { cell.Accessory = UITableViewCellAccessory.Checkmark; } i++; } } public override nint RowsInSection(UITableView tableview, nint section) { return setting.PossibleValues.Count; } public override nint NumberOfSections(UITableView tableView) { return 1; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { var cell = tableView.DequeueReusableCell("SETTING__DETAIL_VALUE_CELL") as SettingDetailTableViewCell; cell.Name = setting.PossibleValues[indexPath.Row]; cell.Accessory = UITableViewCellAccessory.None; if (cell.Name == setting.Value) cell.Accessory = UITableViewCellAccessory.Checkmark; return cell; } } }
// This file has been autogenerated from a class added in the UI designer. using System; using System.Collections.Generic; using Foundation; using UIKit; using MyTrips.Model; namespace MyTrips.iOS { public partial class SettingsDetailViewController : UIViewController { public Setting Setting { get; set; } public SettingsDetailViewController (IntPtr handle) : base (handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); settingsDetailTableView.Source = new SettingsDetailTableViewSource(Setting); } } public class SettingsDetailTableViewSource : UITableViewSource { Setting setting; public SettingsDetailTableViewSource(Setting setting) { this.setting = setting; } public override string TitleForHeader(UITableView tableView, nint section) { return setting.Name; } public override void WillDisplayHeaderView(UITableView tableView, UIView headerView, nint section) { var header = headerView as UITableViewHeaderFooterView; header.TextLabel.TextColor = "5C5C5C".ToUIColor(); header.TextLabel.Font = UIFont.FromName("AvenirNext-Medium", 16); header.TextLabel.Text = TitleForHeader(tableView, section); } public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { setting.Value = setting.PossibleValues[indexPath.Row]; var cells = tableView.VisibleCells; int i = 0; foreach (var cell in cells) { var value = setting.PossibleValues[i]; if (setting.Value != value) { cell.Accessory = UITableViewCellAccessory.None; } else { cell.Accessory = UITableViewCellAccessory.Checkmark; } i++; } } public override nint RowsInSection(UITableView tableview, nint section) { return setting.PossibleValues.Count; } public override nint NumberOfSections(UITableView tableView) { return 1; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { var cell = tableView.DequeueReusableCell("SETTING__DETAIL_VALUE_CELL") as SettingDetailTableViewCell; cell.Name = setting.PossibleValues[indexPath.Row]; cell.Accessory = UITableViewCellAccessory.None; if (cell.Name == setting.Value) cell.Accessory = UITableViewCellAccessory.Checkmark; return cell; } } }
mit
C#
7c2a1db0737a20fe7b61c4b4f457fd54c3fc77ec
create container if not exist
ravjotsingh9/DBLike
DBLike/Server/BlobAccess/Blob.cs
DBLike/Server/BlobAccess/Blob.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; namespace Server.BlobAccess { public class Blob { /// <summary> /// Get client's container in the Blob /// </summary> /// <param name="blobClient">use BlobConn to get blobClient</param> /// <param name="clientContainerName">This should be the ID of the User</param> /// <returns></returns> public CloudBlobContainer getClientContainer(CloudBlobClient blobClient,string clientContainerName) { //Get a reference to a container and create container for first time use user CloudBlobContainer container = blobClient.GetContainerReference(clientContainerName); container.CreateIfNotExists(); return container; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; namespace Server.BlobAccess { public class Blob { /// <summary> /// Get client's container in the Blob /// </summary> /// <param name="blobClient">use BlobConn to get blobClient</param> /// <param name="clientContainerName">This should be the ID of the User</param> /// <returns></returns> public CloudBlobContainer getClientContainer(CloudBlobClient blobClient,string clientContainerName) { //Get a reference to a container CloudBlobContainer container = blobClient.GetContainerReference(clientContainerName); return container; } } }
apache-2.0
C#
a640d33ca00a213138bfa2619b003be3bc1a16e7
add defaults
Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen
Dashen/DashboardConfiguration.cs
Dashen/DashboardConfiguration.cs
using System; namespace Dashen { public class DashboardConfiguration { public Uri ListenOn { get; set; } public string ApplicationName { get; set; } public string ApplicationVersion { get; set; } public DashboardConfiguration() { ListenOn = new Uri("http://localhost:8080"); ApplicationName = "Dashboard"; ApplicationVersion = "1.0.0.0"; } } }
using System; namespace Dashen { public class DashboardConfiguration { public Uri ListenOn { get; set; } public string ApplicationName { get; set; } public string ApplicationVersion { get; set; } } }
lgpl-2.1
C#
1cc1462032e8ca19f6d1f8432c75b159779085a0
Simplify LoggerExtensions
mrahhal/MR.AspNetCore.Jobs,mrahhal/MR.AspNetCore.Jobs
src/MR.AspNetCore.Jobs.SqlServer/LoggerExtensions.cs
src/MR.AspNetCore.Jobs.SqlServer/LoggerExtensions.cs
using System; using Microsoft.Extensions.Logging; namespace MR.AspNetCore.Jobs { internal static class LoggerExtensions { private static Action<ILogger, Exception> _collectingExpiredEntities = LoggerMessage.Define( LogLevel.Debug, 1, "Collecting expired entities."); private static Action<ILogger, Exception> _installing = LoggerMessage.Define( LogLevel.Debug, 1, "Installing Jobs SQL objects..."); private static Action<ILogger, Exception> _installingError = LoggerMessage.Define( LogLevel.Warning, 2, "Exception occurred during automatic migration. Retrying..."); private static Action<ILogger, Exception> _installingSuccess = LoggerMessage.Define( LogLevel.Debug, 3, "Jobs SQL objects installed."); public static void CollectingExpiredEntities(this ILogger logger) { _collectingExpiredEntities(logger, null); } public static void Installing(this ILogger logger) { _installing(logger, null); } public static void InstallingError(this ILogger logger, Exception ex) { _installingError(logger, ex); } public static void InstallingSuccess(this ILogger logger) { _installingSuccess(logger, null); } } }
using System; using Microsoft.Extensions.Logging; namespace MR.AspNetCore.Jobs { internal static class LoggerExtensions { private static Action<ILogger, Exception> _collectingExpiredEntities; private static Action<ILogger, Exception> _installing; private static Action<ILogger, Exception> _installingError; private static Action<ILogger, Exception> _installingSuccess; static LoggerExtensions() { _collectingExpiredEntities = LoggerMessage.Define( LogLevel.Debug, 1, "Collecting expired entities."); _installing = LoggerMessage.Define( LogLevel.Debug, 1, "Installing Jobs SQL objects..."); _installingError = LoggerMessage.Define( LogLevel.Warning, 2, "Exception occurred during automatic migration. Retrying..."); _installingSuccess = LoggerMessage.Define( LogLevel.Debug, 3, "Jobs SQL objects installed."); } public static void CollectingExpiredEntities(this ILogger logger) { _collectingExpiredEntities(logger, null); } public static void Installing(this ILogger logger) { _installing(logger, null); } public static void InstallingError(this ILogger logger, Exception ex) { _installingError(logger, ex); } public static void InstallingSuccess(this ILogger logger) { _installingSuccess(logger, null); } } }
mit
C#
16714b0df95b117beb67207ad10ee37df9b955c0
Update BradleyWyatt.cs
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/BradleyWyatt.cs
src/Firehose.Web/Authors/BradleyWyatt.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 BradleyWyatt : IAmACommunityMember { public string FirstName => "Bradley"; public string LastName => "Wyatt"; public string ShortBioOrTagLine => "Microsoft MVP, author of The Lazy Administrator, Co-Organizer of the Chicago PowerShell Conference, & Chicago PowerShell Users Group"; public string StateOrRegion => "Geneva, IL, USA"; public string EmailAddress => "brad@thelazyadministrator.com"; public string TwitterHandle => "bwya77"; public string GitHubHandle => "bwya77"; public string GravatarHash => "c4eaa00e143c7abb1362dc9a8a48da09"; public GeoPosition Position => new GeoPosition(41.887212,-88.302487); public Uri WebSite => new Uri("https://www.thelazyadministrator.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.thelazyadministrator.com/feed/"); } } } }
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 BradleyWyatt : IAmACommunityMember { public string FirstName => "Bradley"; public string LastName => "Wyatt"; public string ShortBioOrTagLine => "Microsoft MVP, author of The Lazy Administrator, Co-Organizer of the Chicago PowerShell Conference, & Chicago PowerShell Users Group"; public string StateOrRegion => "Geneva, IL, USA"; public string EmailAddress => "brad@thelazyadministrator.com"; public string TwitterHandle => "bwya77"; public string GitHubHandle => "bwya77"; public string GravatarHash => "c4eaa00e143c7abb1362dc9a8a48da09"; public GeoPosition Position => new GeoPosition(41.887212,-88.302487); public Uri WebSite => new Uri("https://www.thelazyadministrator.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.thelazyadministrator.com/feed/"); } } } }
mit
C#
24e256f364e4a2133b03dbe9b0a3ee0069eb77b9
Disable ObjectTests.Write test (#38101)
ericstj/corefx,shimingsg/corefx,ViktorHofer/corefx,ViktorHofer/corefx,shimingsg/corefx,wtgodbe/corefx,wtgodbe/corefx,ericstj/corefx,shimingsg/corefx,wtgodbe/corefx,wtgodbe/corefx,ericstj/corefx,BrennanConroy/corefx,BrennanConroy/corefx,shimingsg/corefx,wtgodbe/corefx,ericstj/corefx,ViktorHofer/corefx,BrennanConroy/corefx,shimingsg/corefx,wtgodbe/corefx,wtgodbe/corefx,ViktorHofer/corefx,ericstj/corefx,ViktorHofer/corefx,ericstj/corefx,ViktorHofer/corefx,ViktorHofer/corefx,ericstj/corefx,shimingsg/corefx,shimingsg/corefx
src/System.Text.Json/tests/Serialization/Object.WriteTests.cs
src/System.Text.Json/tests/Serialization/Object.WriteTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Text.Json.Serialization.Tests { public static partial class ObjectTests { [Fact] public static void VerifyTypeFail() { Assert.Throws<ArgumentException>(() => JsonSerializer.ToString(1, typeof(string))); } [ActiveIssue(38092)] [Theory] [MemberData(nameof(WriteSuccessCases))] public static void Write(ITestClass testObj) { string json; { testObj.Initialize(); testObj.Verify(); json = JsonSerializer.ToString(testObj, testObj.GetType()); } { ITestClass obj = (ITestClass)JsonSerializer.Parse(json, testObj.GetType()); obj.Verify(); } } public static IEnumerable<object[]> WriteSuccessCases { get { return TestData.WriteSuccessCases; } } [Fact] public static void WriteObjectAsObject() { var obj = new ObjectObject { Object = new object() }; string json = JsonSerializer.ToString(obj); Assert.Equal(@"{""Object"":{}}", json); } public class ObjectObject { public object Object { get; set; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Text.Json.Serialization.Tests { public static partial class ObjectTests { [Fact] public static void VerifyTypeFail() { Assert.Throws<ArgumentException>(() => JsonSerializer.ToString(1, typeof(string))); } [Theory] [MemberData(nameof(WriteSuccessCases))] public static void Write(ITestClass testObj) { string json; { testObj.Initialize(); testObj.Verify(); json = JsonSerializer.ToString(testObj, testObj.GetType()); } { ITestClass obj = (ITestClass)JsonSerializer.Parse(json, testObj.GetType()); obj.Verify(); } } public static IEnumerable<object[]> WriteSuccessCases { get { return TestData.WriteSuccessCases; } } [Fact] public static void WriteObjectAsObject() { var obj = new ObjectObject { Object = new object() }; string json = JsonSerializer.ToString(obj); Assert.Equal(@"{""Object"":{}}", json); } public class ObjectObject { public object Object { get; set; } } } }
mit
C#
77f691251c7f5bec43571a0ba0c3a568aee4deff
Allow to replace a liquid filter (#5043)
xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,petedavis/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,xkproject/Orchard2,petedavis/Orchard2,petedavis/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2
src/OrchardCore/OrchardCore.Liquid.Abstractions/ServiceExtensions.cs
src/OrchardCore/OrchardCore.Liquid.Abstractions/ServiceExtensions.cs
using Microsoft.Extensions.DependencyInjection; namespace OrchardCore.Liquid { public static class ServiceCollectionExtensions { public static IServiceCollection AddLiquidFilter<T>(this IServiceCollection services, string name) where T : class, ILiquidFilter { services.Configure<LiquidOptions>(options => options.FilterRegistrations[name] = typeof(T)); services.AddScoped<T>(); return services; } } }
using Microsoft.Extensions.DependencyInjection; namespace OrchardCore.Liquid { public static class ServiceCollectionExtensions { public static IServiceCollection AddLiquidFilter<T>(this IServiceCollection services, string name) where T : class, ILiquidFilter { services.Configure<LiquidOptions>(options => options.FilterRegistrations.Add(name, typeof(T))); services.AddScoped<T>(); return services; } } }
bsd-3-clause
C#
8e39c51ab21f99e4c27652ee827f7b45137b642a
Check that it can work with nullables too.
ManufacturingIntelligence/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,nkreipke/nhibernate-core,ngbrown/nhibernate-core,livioc/nhibernate-core,gliljas/nhibernate-core,hazzik/nhibernate-core,hazzik/nhibernate-core,RogerKratz/nhibernate-core,alobakov/nhibernate-core,fredericDelaporte/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,livioc/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,lnu/nhibernate-core,alobakov/nhibernate-core,ngbrown/nhibernate-core,fredericDelaporte/nhibernate-core,nkreipke/nhibernate-core,livioc/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,nkreipke/nhibernate-core,alobakov/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core,lnu/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nhibernate/nhibernate-core,ManufacturingIntelligence/nhibernate-core,ngbrown/nhibernate-core,RogerKratz/nhibernate-core
src/NHibernate.Test/NHSpecificTest/NH1119/Fixture.cs
src/NHibernate.Test/NHSpecificTest/NH1119/Fixture.cs
using System; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH1119 { [TestFixture] public class Fixture : BugTestCase { public override string BugNumber { get { return "NH1119"; } } [Test] public void SelectMinFromEmptyTable() { using (ISession s = OpenSession()) { DateTime dt = s.CreateQuery("select max(tc.DateTimeProperty) from TestClass tc").UniqueResult<DateTime>(); Assert.AreEqual(default(DateTime), dt); DateTime? dtn = s.CreateQuery("select max(tc.DateTimeProperty) from TestClass tc").UniqueResult<DateTime?>(); Assert.IsFalse(dtn.HasValue); } } } }
using System; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH1119 { [TestFixture] public class Fixture : BugTestCase { public override string BugNumber { get { return "NH1119"; } } [Test] public void SelectMinFromEmptyTable() { using (ISession s = OpenSession()) { DateTime dt = s.CreateQuery("select max(tc.DateTimeProperty) from TestClass tc").UniqueResult<DateTime>(); Assert.AreEqual(default(DateTime), dt); } } } }
lgpl-2.1
C#
4e86b5dea18b597853a2bd0025ae967aa784b004
Use longer BusyExecIdle test timeout to avoid CI failures
mikkelbu/nunit,NikolayPianikov/nunit,OmicronPersei/nunit,JustinRChou/nunit,OmicronPersei/nunit,appel1/nunit,appel1/nunit,mjedrzejek/nunit,nunit/nunit,NikolayPianikov/nunit,nunit/nunit,mjedrzejek/nunit,JustinRChou/nunit,mikkelbu/nunit
src/NUnitFramework/tests/Internal/TestWorkerTests.cs
src/NUnitFramework/tests/Internal/TestWorkerTests.cs
// *********************************************************************** // Copyright (c) 2014 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** #if PARALLEL using System.Text; using System.Threading; using NUnit.TestUtilities; namespace NUnit.Framework.Internal.Execution { public class TestWorkerTests { private WorkItemQueue _queue; private TestWorker _worker; [SetUp] public void SetUp() { #if APARTMENT_STATE _queue = new WorkItemQueue("TestQ", true, ApartmentState.MTA); #else _queue = new WorkItemQueue("TestQ", true); #endif _worker = new TestWorker(_queue, "TestQ_Worker"); } [TearDown] public void TearDown() { _queue.Stop(); } [Test] public void BusyExecuteIdleEventsCalledInSequence() { StringBuilder sb = new StringBuilder(); FakeWorkItem work = Fakes.GetWorkItem(this, "FakeMethod"); _worker.Busy += (s, ea) => { sb.Append("Busy"); }; work.Executed += (s, ea) => { sb.Append("Exec"); }; _worker.Idle += (s, ea) => { sb.Append ("Idle"); }; _queue.Enqueue(work); _worker.Start(); _queue.Start(); Assert.That(() => sb.ToString(), Is.EqualTo("BusyExecIdle").After( delayInMilliseconds: 10000, pollingInterval: 200)); } private void FakeMethod() { } } } #endif
// *********************************************************************** // Copyright (c) 2014 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** #if PARALLEL using System.Text; using System.Threading; using NUnit.TestUtilities; namespace NUnit.Framework.Internal.Execution { public class TestWorkerTests { private WorkItemQueue _queue; private TestWorker _worker; [SetUp] public void SetUp() { #if APARTMENT_STATE _queue = new WorkItemQueue("TestQ", true, ApartmentState.MTA); #else _queue = new WorkItemQueue("TestQ", true); #endif _worker = new TestWorker(_queue, "TestQ_Worker"); } [TearDown] public void TearDown() { _queue.Stop(); } [Test] public void BusyExecuteIdleEventsCalledInSequence() { StringBuilder sb = new StringBuilder(); FakeWorkItem work = Fakes.GetWorkItem(this, "FakeMethod"); _worker.Busy += (s, ea) => { sb.Append("Busy"); }; work.Executed += (s, ea) => { sb.Append("Exec"); }; _worker.Idle += (s, ea) => { sb.Append ("Idle"); }; _queue.Enqueue(work); _worker.Start(); _queue.Start(); Assert.That(() => sb.ToString(), Is.EqualTo("BusyExecIdle").After(200)); } private void FakeMethod() { } } } #endif
mit
C#
a6f51664796bf8b6b93d26aaf9aa9b318fa1a1fb
Use milliseconds for unix time conversions
poxet/InfluxDB.Net,poxet/InfluxDB.Net,ziyasal/InfluxDB.Net,ziyasal/InfluxDB.Net,jamesholcomb/InfluxDB.Net,jamesholcomb/InfluxDB.Net
InfluxDB.Net/ObjectExtensions.cs
InfluxDB.Net/ObjectExtensions.cs
using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System; using System.Text; namespace InfluxDB.Net { public static class ObjectExtensions { private static DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); public static string ToJson(this object @object) { return JsonConvert.SerializeObject(@object); } public static T ReadAs<T>(this InfluxDbApiResponse response) { var @object = JsonConvert.DeserializeObject<T>(response.Body); return @object; } /// <summary>Converts from unix time in milliseconds.</summary> /// <param name="unixTimeInMillis">The unix time in millis.</param> /// <returns></returns> public static DateTime FromUnixTime(this long unixTimeInMillis) { return _epoch.AddMilliseconds(unixTimeInMillis); } /// <summary>Converts to unix time in milliseconds.</summary> /// <param name="date">The date.</param> /// <returns>The number of elapsed milliseconds</returns> public static long ToUnixTime(this DateTime date) { return Convert.ToInt64((date - _epoch).TotalMilliseconds); } public static string NextPrintableString(this Random r, int length) { var data = new byte[length]; for (int i = 0; i < data.Length; i++) { // Only printable UTF-8 // and no backslashes for now // https://github.com/influxdb/influxdb/issues/3070 do { data[i] = (byte)r.Next(32, 127); } while (data[i] == 92); } var encoding = new UTF8Encoding(); return encoding.GetString(data, 0, length); } } }
using Newtonsoft.Json; using System; using System.Text; namespace InfluxDB.Net { public static class ObjectExtensions { private static DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); public static string ToJson(this object @object) { return JsonConvert.SerializeObject(@object); } public static T ReadAs<T>(this InfluxDbApiResponse response) { var @object = JsonConvert.DeserializeObject<T>(response.Body); return @object; } public static DateTime FromUnixTime(this long unixTime) { return _epoch.AddSeconds(unixTime); } public static long ToUnixTime(this DateTime date) { return Convert.ToInt64((date - _epoch).TotalSeconds); } public static string NextPrintableString(this Random r, int length) { var data = new byte[length]; for (int i = 0; i < data.Length; i++) { // Only printable UTF-8 // and no backslashes for now // https://github.com/influxdb/influxdb/issues/3070 do { data[i] = (byte)r.Next(32, 127); } while (data[i] == 92); } var encoding = new UTF8Encoding(); return encoding.GetString(data, 0, length); } } }
unlicense
C#
061d4188abba7d2d9c29af87ebbec6f78b0c2ad8
Add diagnostics to web app
lmno/cupster,lmno/cupster,lmno/cupster
webstats/Modules/Bootstrapper.cs
webstats/Modules/Bootstrapper.cs
/* * Created by SharpDevelop. * User: Lars Magnus * Date: 14.06.2014 * Time: 23:23 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Configuration; using System.Diagnostics; using System.IO; using Nancy; using Nancy.Bootstrapper; using Nancy.Diagnostics; using Nancy.TinyIoc; using SubmittedData; namespace Modules { /// <summary> /// Description of Bootstrapper. /// </summary> public class Bootstrapper : DefaultNancyBootstrapper { protected override void ConfigureApplicationContainer(TinyIoCContainer container) { string dataPath = ConfigurationManager.AppSettings["DataPath"].ToString(); string tournamentFile = ConfigurationManager.AppSettings["TournamentFile"].ToString(); string resultsFile = ConfigurationManager.AppSettings["ResultsFile"].ToString(); // Register our app dependency as a normal singletons var tournament = new Tournament(); tournament.Load(Path.Combine(dataPath, tournamentFile)); container.Register<ITournament, Tournament>(tournament); var bets = new SubmittedBets(); bets.TournamentFile = tournamentFile; bets.ActualResultsFile = resultsFile; bets.LoadAll(dataPath); container.Register<ISubmittedBets, SubmittedBets>(bets); var results = new Results(); results.Load(Path.Combine(dataPath, resultsFile)); container.Register<IResults, Results>(results); } protected override DiagnosticsConfiguration DiagnosticsConfiguration { get { return new DiagnosticsConfiguration { Password = @"kokko-bada-futu" }; } } #if DEBUG protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { StaticConfiguration.DisableErrorTraces = false; } #endif } }
/* * Created by SharpDevelop. * User: Lars Magnus * Date: 14.06.2014 * Time: 23:23 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Configuration; using System.IO; using Nancy; using Nancy.TinyIoc; using SubmittedData; namespace Modules { /// <summary> /// Description of Bootstrapper. /// </summary> public class Bootstrapper : DefaultNancyBootstrapper { protected override void ConfigureApplicationContainer(TinyIoCContainer container) { string dataPath = ConfigurationManager.AppSettings["DataPath"].ToString(); string tournamentFile = ConfigurationManager.AppSettings["TournamentFile"].ToString(); string resultsFile = ConfigurationManager.AppSettings["ResultsFile"].ToString(); // Register our app dependency as a normal singletons var tournament = new Tournament(); tournament.Load(Path.Combine(dataPath, tournamentFile)); container.Register<ITournament, Tournament>(tournament); var bets = new SubmittedBets(); bets.TournamentFile = tournamentFile; bets.ActualResultsFile = resultsFile; bets.LoadAll(dataPath); container.Register<ISubmittedBets, SubmittedBets>(bets); var results = new Results(); results.Load(Path.Combine(dataPath, resultsFile)); container.Register<IResults, Results>(results); } } }
mit
C#
3c0b74bdd1d0ac169018f914d9bd5c3b1519beb9
fix formatting
mm999/OrigoDB
src/OrigoDB.Core.UnitTests/ModelTests.cs
src/OrigoDB.Core.UnitTests/ModelTests.cs
using NUnit.Framework; namespace OrigoDB.Core.Test { [TestFixture] public class ModelTests { [Test] public void RevisionIsIncrementedWithEachCommand() { var config = EngineConfiguration.Create().ForIsolatedTest(); var target = Db.For<TestModel>(config); Assert.AreEqual(0, target.Revision); target.AddCustomer("Homer"); Assert.AreEqual(1, target.Revision); } } }
using NUnit.Framework; namespace OrigoDB.Core.Test { [TestFixture] public class ModelTests { [Test] public void RevisionIsIncrementedWithEachCommand() { var config = EngineConfiguration.Create().ForIsolatedTest(); var target = Db.For<TestModel>(config); Assert.AreEqual(0, target.Revision); target.AddCustomer("Homer"); Assert.AreEqual(1, target.Revision); } } }
mit
C#
cd9c8a3d5683e7c1381bed7978f27ded524cb7e1
Fix a test failure It is not repeatable to modify the request headers in place One integration test failed with "An item with the same key has already been added" due to this
danbadge/SevenDigital.Api.Wrapper,luiseduardohdbackup/SevenDigital.Api.Wrapper,bnathyuw/SevenDigital.Api.Wrapper,bettiolo/SevenDigital.Api.Wrapper,minkaotic/SevenDigital.Api.Wrapper,danhaller/SevenDigital.Api.Wrapper,gregsochanik/SevenDigital.Api.Wrapper,AnthonySteele/SevenDigital.Api.Wrapper,emashliles/SevenDigital.Api.Wrapper
src/SevenDigital.Api.Wrapper/EndpointResolution/RequestHandlers/AllRequestHandler.cs
src/SevenDigital.Api.Wrapper/EndpointResolution/RequestHandlers/AllRequestHandler.cs
using System; using System.Collections.Generic; using SevenDigital.Api.Wrapper.EndpointResolution.OAuth; using SevenDigital.Api.Wrapper.Http; namespace SevenDigital.Api.Wrapper.EndpointResolution.RequestHandlers { public class AllRequestHandler : RequestHandler { private readonly IOAuthCredentials _oAuthCredentials; public AllRequestHandler(IApiUri apiUri, IOAuthCredentials oAuthCredentials) : base(apiUri) { _oAuthCredentials = oAuthCredentials; } public override bool HandlesMethod(HttpMethod method) { return true; } public override Response HitEndpoint(RequestData requestData) { var request = BuildRequest(requestData); return HttpClient.Send(request); } private Request BuildRequest(RequestData requestData) { var headers = new Dictionary<string, string>(requestData.Headers); var apiRequest = MakeApiRequest(requestData); var fullUrl = apiRequest.AbsoluteUrl; if (!requestData.RequiresSignature) { if (HttpMethodHelpers.HasParams(requestData.HttpMethod)) { apiRequest.Parameters.Add("oauth_consumer_key", _oAuthCredentials.ConsumerKey); } else { headers.Add("Authorization", "oauth_consumer_key=" + _oAuthCredentials.ConsumerKey); } } if (HttpMethodHelpers.HasParams(requestData.HttpMethod) && (apiRequest.Parameters.Count > 0)) { fullUrl += "?" + apiRequest.Parameters.ToQueryString(); } if (requestData.RequiresSignature) { var oauthHeader = BuildOAuthHeader(requestData, fullUrl, apiRequest.Parameters); headers.Add("Authorization", oauthHeader); } string requestBody; if (HttpMethodHelpers.HasBody(requestData.HttpMethod)) { requestBody = apiRequest.Parameters.ToQueryString(); } else { requestBody = string.Empty; } return new Request(requestData.HttpMethod, fullUrl, headers, requestBody); } private string BuildOAuthHeader(RequestData requestData, string fullUrl, IDictionary<string, string> parameters) { var authHeaderGenerator = new OAuthHeaderGenerator(_oAuthCredentials); var oAuthHeaderData = new OAuthHeaderData { Url = fullUrl, HttpMethod = requestData.HttpMethod, UserToken = requestData.UserToken, TokenSecret = requestData.TokenSecret, RequestParameters = parameters }; return authHeaderGenerator.GenerateOAuthSignatureHeader(oAuthHeaderData); } public override string GetDebugUri(RequestData requestData) { return BuildRequest(requestData).Url; } } }
using System.Collections.Generic; using SevenDigital.Api.Wrapper.EndpointResolution.OAuth; using SevenDigital.Api.Wrapper.Http; namespace SevenDigital.Api.Wrapper.EndpointResolution.RequestHandlers { public class AllRequestHandler : RequestHandler { private readonly IOAuthCredentials _oAuthCredentials; public AllRequestHandler(IApiUri apiUri, IOAuthCredentials oAuthCredentials) : base(apiUri) { _oAuthCredentials = oAuthCredentials; } public override bool HandlesMethod(HttpMethod method) { return true; } public override Response HitEndpoint(RequestData requestData) { var request = BuildRequest(requestData); return HttpClient.Send(request); } private Request BuildRequest(RequestData requestData) { var apiRequest = MakeApiRequest(requestData); var fullUrl = apiRequest.AbsoluteUrl; if (!requestData.RequiresSignature) { if (HttpMethodHelpers.HasParams(requestData.HttpMethod)) { apiRequest.Parameters.Add("oauth_consumer_key", _oAuthCredentials.ConsumerKey); } else { requestData.Headers.Add("Authorization", "oauth_consumer_key=" + _oAuthCredentials.ConsumerKey); } } if (HttpMethodHelpers.HasParams(requestData.HttpMethod) && (apiRequest.Parameters.Count > 0)) { fullUrl += "?" + apiRequest.Parameters.ToQueryString(); } if (requestData.RequiresSignature) { var oauthHeader = BuildOAuthHeader(requestData, fullUrl, apiRequest.Parameters); requestData.Headers.Add("Authorization", oauthHeader); } string requestBody; if (HttpMethodHelpers.HasBody(requestData.HttpMethod)) { requestBody = apiRequest.Parameters.ToQueryString(); } else { requestBody = string.Empty; } return new Request(requestData.HttpMethod, fullUrl, requestData.Headers, requestBody); } private string BuildOAuthHeader(RequestData requestData, string fullUrl, IDictionary<string, string> parameters) { var authHeaderGenerator = new OAuthHeaderGenerator(_oAuthCredentials); var oAuthHeaderData = new OAuthHeaderData { Url = fullUrl, HttpMethod = requestData.HttpMethod, UserToken = requestData.UserToken, TokenSecret = requestData.TokenSecret, RequestParameters = parameters }; return authHeaderGenerator.GenerateOAuthSignatureHeader(oAuthHeaderData); } public override string GetDebugUri(RequestData requestData) { return BuildRequest(requestData).Url; } } }
mit
C#
9931ff46aedca01f3b941c1a5a329b1a7788f8ba
Solve build related issue
Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist
Trappist/src/Promact.Trappist.Core/Controllers/QuestionsController.cs
Trappist/src/Promact.Trappist.Core/Controllers/QuestionsController.cs
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> /// <returns></returns> [Route("single-multiple-question")] [HttpPost] public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion, singleMultipleAnswerQuestionOption); return Ok(); } } }
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [Route("single-multiple-question")] [HttpPost] /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion, singleMultipleAnswerQuestionOption); return Ok(); } } }
mit
C#
95c50b49d0e4ec6bca512103a16df1d9b2e9b69f
improve logs
MetacoSA/NBitcoin.Indexer,bijakatlykkex/NBitcoin.Indexer,NicolasDorier/NBitcoin.Indexer
NBitcoin.Indexer/IndexerTrace.cs
NBitcoin.Indexer/IndexerTrace.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBitcoin.Indexer { class IndexerTrace { static TraceSource _Trace = new TraceSource("NBitcoin.Indexer"); internal static void ErrorWhileImportingBlockToAzure(uint256 id, Exception ex) { _Trace.TraceEvent(TraceEventType.Error, 0, "Error while importing " + id + " in azure blob : " + Utils.ExceptionToString(ex)); } internal static void BlockAlreadyUploaded() { _Trace.TraceInformation("Block already uploaded"); } internal static void BlockUploaded(TimeSpan time, int bytes) { if(time.TotalSeconds == 0.0) time = TimeSpan.FromMilliseconds(10); double speed = ((double)bytes / 1024.0) / time.TotalSeconds; _Trace.TraceEvent(TraceEventType.Verbose, 0, "Block uploaded successfully (" + speed.ToString("0.00") + " KB/S)"); } internal static TraceCorrelation NewCorrelation(string activityName) { return new TraceCorrelation(_Trace, activityName); } internal static void StartingImportAt(DiskBlockPos lastPosition) { _Trace.TraceInformation("Starting import at position " + lastPosition); } internal static void PositionSaved(DiskBlockPos diskBlockPos) { _Trace.TraceInformation("New starting import position : " + diskBlockPos.ToString()); } internal static void BlockCount(int blockCount, bool verbose) { _Trace.TraceEvent((!verbose) ? TraceEventType.Information : TraceEventType.Verbose, 0, "Block count : " + blockCount); } internal static void TxCount(int txCount, bool verbose) { _Trace.TraceEvent((!verbose) ? TraceEventType.Information : TraceEventType.Verbose, 0, "Transaction count : " + txCount); } internal static void ErrorWhileImportingTxToAzure(IndexedTransaction[] transactions, Exception ex) { StringBuilder builder = new StringBuilder(); int i = 0; foreach(var tx in transactions) { builder.AppendLine("[ " + i + "] " + tx.PartitionKey + " " + tx.RowKey); i++; } _Trace.TraceEvent(TraceEventType.Error, 0, "Error while importing transactions (len:" + transactions.Length + ") : " + Utils.ExceptionToString(ex) + "\r\n" + builder.ToString()); } internal static void RetryWorked() { _Trace.TraceInformation("Retry worked"); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBitcoin.Indexer { class IndexerTrace { static TraceSource _Trace = new TraceSource("NBitcoin.Indexer"); internal static void ErrorWhileImportingBlockToAzure(uint256 id, Exception ex) { _Trace.TraceEvent(TraceEventType.Error, 0, "Error while importing " + id + " in azure blob : " + Utils.ExceptionToString(ex)); } internal static void BlockAlreadyUploaded() { _Trace.TraceInformation("Block already uploaded"); } internal static void BlockUploaded(TimeSpan time, int bytes) { if(time.TotalSeconds == 0.0) time = TimeSpan.FromMilliseconds(10); double speed = ((double)bytes / 1024.0) / time.TotalSeconds; _Trace.TraceEvent(TraceEventType.Verbose, 0, "Block uploaded successfully (" + speed.ToString("0.00") + " KB/S)"); } internal static TraceCorrelation NewCorrelation(string activityName) { return new TraceCorrelation(_Trace, activityName); } internal static void StartingImportAt(DiskBlockPos lastPosition) { _Trace.TraceInformation("Starting import at position " + lastPosition); } internal static void PositionSaved(DiskBlockPos diskBlockPos) { _Trace.TraceInformation("New starting import position : " + diskBlockPos.ToString()); } internal static void BlockCount(int blockCount, bool verbose) { _Trace.TraceEvent((!verbose) ? TraceEventType.Information : TraceEventType.Verbose, 0, "Block count : " + blockCount); } internal static void TxCount(int txCount, bool verbose) { _Trace.TraceEvent((!verbose) ? TraceEventType.Information : TraceEventType.Verbose, 0, "Transaction count : " + txCount); } internal static void ErrorWhileImportingTxToAzure(IndexedTransaction[] transactions, Exception ex) { StringBuilder builder = new StringBuilder(); int i = 0; foreach(var tx in transactions) { builder.AppendLine("[ " + i + "] " + tx.PartitionKey + " " + tx.RowKey); i++; } _Trace.TraceEvent(TraceEventType.Error, 0, "Error while importing transactions : " + Utils.ExceptionToString(ex)); } internal static void RetryWorked() { _Trace.TraceInformation("Retry worked"); } } }
mit
C#
ca4635cc3da2e64486da9cf049082853122c0dfd
Update assembly for NuGet
jehugaleahsa/NRest
NRest/Properties/AssemblyInfo.cs
NRest/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("NRest")] [assembly: AssemblyDescription("A simple REST client for making API calls using a fluent syntax.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Truncon")] [assembly: AssemblyProduct("NRest")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("ef25bcfd-d3d9-43d6-b3c0-9db02924b672")] [assembly: AssemblyVersion("0.0.0.15")] [assembly: AssemblyFileVersion("0.0.0.15")] [assembly: CLSCompliant(true)]
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("NRest")] [assembly: AssemblyDescription("Make REST API calls using a fluent syntax.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Truncon")] [assembly: AssemblyProduct("NRest")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("ef25bcfd-d3d9-43d6-b3c0-9db02924b672")] [assembly: AssemblyVersion("0.0.0.13")] [assembly: AssemblyFileVersion("0.0.0.13")] [assembly: CLSCompliant(true)]
unlicense
C#
6863e1f50495c5609698063fb736e7778e40cab8
Bump Assembly version number
Kerbas-ad-astra/KSPTrajectories
Plugin/Properties/AssemblyInfo.cs
Plugin/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("Trajectories")] [assembly: AssemblyDescription("A Kerbal Space Program mod to display atmospheric trajectories and more")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Trajectories")] [assembly: AssemblyCopyright("Copyright © 2016, Youen Toupin")] [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("38c16654-8d27-4a64-ba34-94645cecded4")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.6.6.0")] [assembly: AssemblyFileVersion("1.6.6.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("Trajectories")] [assembly: AssemblyDescription("A Kerbal Space Program mod to display atmospheric trajectories and more")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Trajectories")] [assembly: AssemblyCopyright("Copyright © 2016, Youen Toupin")] [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("38c16654-8d27-4a64-ba34-94645cecded4")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.6.5.0")] [assembly: AssemblyFileVersion("1.6.5.0")]
mit
C#
8aee4dc8e5055cb0a66cb80aa1ea0e2486f0b3fc
Simplify new test and reword
smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework
osu.Framework.Tests/Visual/Testing/TestSceneManualInputManagerTestScene.cs
osu.Framework.Tests/Visual/Testing/TestSceneManualInputManagerTestScene.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 NUnit.Framework; using osu.Framework.Input; using osu.Framework.Testing; using osu.Framework.Testing.Input; using osuTK; using osuTK.Input; namespace osu.Framework.Tests.Visual.Testing { public class TestSceneManualInputManagerTestScene : ManualInputManagerTestScene { protected override Vector2 InitialMousePosition => new Vector2(10f); [Test] public void TestResetInput() { AddStep("move mouse", () => InputManager.MoveMouseTo(Vector2.Zero)); AddStep("press mouse", () => InputManager.PressButton(MouseButton.Left)); AddStep("press key", () => InputManager.PressKey(Key.Z)); AddStep("press joystick", () => InputManager.PressJoystickButton(JoystickButton.Button1)); AddStep("reset input", ResetInput); AddAssert("mouse position reset", () => InputManager.CurrentState.Mouse.Position == InitialMousePosition); AddAssert("all input states released", () => !InputManager.CurrentState.Mouse.Buttons.HasAnyButtonPressed && !InputManager.CurrentState.Keyboard.Keys.HasAnyButtonPressed && !InputManager.CurrentState.Joystick.Buttons.HasAnyButtonPressed); } [Test] public void TestHoldLeftFromMaskedPosition() { TestCursor cursor = null; AddStep("retrieve cursor", () => cursor = (TestCursor)InputManager.ChildrenOfType<TestCursorContainer>().Single().ActiveCursor); AddStep("move mouse to screen zero", () => InputManager.MoveMouseTo(Vector2.Zero)); AddAssert("ensure cursor masked away", () => cursor.IsMaskedAway); AddStep("hold left button", () => InputManager.PressButton(MouseButton.Left)); AddAssert("cursor updated to hold", () => cursor.Left.IsPresent); AddStep("move mouse to content", () => InputManager.MoveMouseTo(Content)); AddAssert("cursor still holding", () => cursor.Left.IsPresent); } [Test] public void TestMousePositionSetToInitial() => AddAssert("mouse position set to initial", () => InputManager.CurrentState.Mouse.Position == InitialMousePosition); } }
// 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 NUnit.Framework; using osu.Framework.Input; using osu.Framework.Testing; using osu.Framework.Testing.Input; using osuTK; using osuTK.Input; namespace osu.Framework.Tests.Visual.Testing { public class TestSceneManualInputManagerTestScene : ManualInputManagerTestScene { protected override Vector2 InitialMousePosition => new Vector2(10f); [Test] public void TestResetInput() { AddStep("move mouse", () => InputManager.MoveMouseTo(Vector2.Zero)); AddStep("press mouse", () => InputManager.PressButton(MouseButton.Left)); AddStep("press key", () => InputManager.PressKey(Key.Z)); AddStep("press joystick", () => InputManager.PressJoystickButton(JoystickButton.Button1)); AddStep("reset input", ResetInput); AddAssert("mouse position reset", () => InputManager.CurrentState.Mouse.Position == InitialMousePosition); AddAssert("all input states released", () => !InputManager.CurrentState.Mouse.Buttons.HasAnyButtonPressed && !InputManager.CurrentState.Keyboard.Keys.HasAnyButtonPressed && !InputManager.CurrentState.Joystick.Buttons.HasAnyButtonPressed); } [Test] public void TestHoldLeftFromMaskedPosition() { TestCursor cursor = null; AddStep("retrieve cursor", () => cursor = (TestCursor)InputManager.ChildrenOfType<TestCursorContainer>().Single().ActiveCursor); AddStep("move mouse to screen zero", () => InputManager.MoveMouseTo(Vector2.Zero)); AddAssert("ensure cursor masked away", () => cursor.IsMaskedAway); AddStep("press buttons", () => { InputManager.PressButton(MouseButton.Left); InputManager.PressButton(MouseButton.Right); }); AddStep("move cursor to content", () => InputManager.MoveMouseTo(Content)); AddAssert("cursor button parts visible", () => cursor.Left.IsPresent && cursor.Right.IsPresent); } [Test] public void TestMousePositionSetToInitial() => AddAssert("mouse position set to initial", () => InputManager.CurrentState.Mouse.Position == InitialMousePosition); } }
mit
C#
358cc23d910a72bc5fe5a05afaa8c22f2188c2ef
Remove commented out Update method from PlayerController
compumike08/Roll-a-Ball
Assets/Scripts/PlayerController.cs
Assets/Scripts/PlayerController.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { public float speed; private Rigidbody rb; // Start is called during the first frame that this script is accessed during the game void Start () { rb = GetComponent<Rigidbody> (); } // FixedUpdate is called just before performing any physics calculations void FixedUpdate () { float moveHorizontal = Input.GetAxis ("Horizontal"); float moveVertical = Input.GetAxis ("Vertical"); Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical); rb.AddForce (movement * speed); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { public float speed; private Rigidbody rb; // Start is called during the first frame that this script is accessed during the game void Start () { rb = GetComponent<Rigidbody> (); } // Update is called before rendering a frame // void Update () // { // // } // FixedUpdate is called just before performing any physics calculations void FixedUpdate () { float moveHorizontal = Input.GetAxis ("Horizontal"); float moveVertical = Input.GetAxis ("Vertical"); Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical); rb.AddForce (movement * speed); } }
mit
C#
952b21edb673acb9922d272b2eca5b7caa3b33bd
Implement encoding
kappa7194/otp
Albireo.Otp.Library/Base32.cs
Albireo.Otp.Library/Base32.cs
namespace Albireo.Otp.Library { using System; using System.Diagnostics.Contracts; using System.Linq; using System.Text; internal static class Base32 { private static readonly char[] Alphabet = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7' }; internal static string Encode(byte[] input) { Contract.Requires<ArgumentException>(input != null); Contract.Ensures(Contract.Result<string>() != null); if (input.Length == 0) return string.Empty; var bits = input.Select(x => Convert.ToString(x, 2).PadLeft(8, '0')).Aggregate((x, y) => x + y); if (bits.Length % 5 != 0) bits += string.Concat(Enumerable.Repeat('0', 5 - bits.Length % 5)); var output = new StringBuilder(bits.Length / 5); for (int i = 0, j = bits.Length / 5; i < j; i++) output.Append(Alphabet[Convert.ToInt32(bits.Substring(5 * i, 5), 2)]); while (output.Length % 8 != 0) output.Append('='); return output.ToString(); } internal static byte[] Decode(string input) { throw new NotImplementedException(); } } }
namespace Albireo.Otp.Library { using System; internal static class Base32 { internal static string Encode(byte[] input) { throw new NotImplementedException(); } internal static byte[] Decode(string input) { throw new NotImplementedException(); } } }
mit
C#
25a8f2a233a026f86a1d8e15d445fdaefb53b540
Remove [AllowAnonymous] since added by default
VenusInterns/BlogTemplate,VenusInterns/BlogTemplate,VenusInterns/BlogTemplate
BlogTemplate/Pages/Post.cshtml.cs
BlogTemplate/Pages/Post.cshtml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.RazorPages; using BlogTemplate.Models; using Microsoft.AspNetCore.Mvc; using System.Xml; using System.Xml.Linq; using Microsoft.AspNetCore.Authorization; namespace BlogTemplate.Pages { public class PostModel : PageModel { private Blog _blog; private BlogDataStore _dataStore; public PostModel(Blog blog, BlogDataStore dataStore) { _blog = blog; _dataStore = dataStore; } [BindProperty] public Comment Comment { get; set; } public Post Post { get; set; } public void OnGet() { InitializePost(); } private void InitializePost() { string slug = RouteData.Values["slug"].ToString(); Post = _dataStore.GetPost(slug); if (Post == null) { RedirectToPage("/Index"); } } public IActionResult OnPostPublishComment() { string slug = RouteData.Values["slug"].ToString(); Post = _dataStore.GetPost(slug); if (Post == null) { RedirectToPage("/Index"); } else if (ModelState.IsValid) { Comment.IsPublic = true; Comment.UniqueId = Guid.NewGuid(); Post.Comments.Add(Comment); _dataStore.SavePost(Post); } return Page(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.RazorPages; using BlogTemplate.Models; using Microsoft.AspNetCore.Mvc; using System.Xml; using System.Xml.Linq; using Microsoft.AspNetCore.Authorization; namespace BlogTemplate.Pages { public class PostModel : PageModel { private Blog _blog; private BlogDataStore _dataStore; public PostModel(Blog blog, BlogDataStore dataStore) { _blog = blog; _dataStore = dataStore; } [BindProperty] public Comment Comment { get; set; } public Post Post { get; set; } [AllowAnonymous] public void OnGet() { InitializePost(); } private void InitializePost() { string slug = RouteData.Values["slug"].ToString(); Post = _dataStore.GetPost(slug); if (Post == null) { RedirectToPage("/Index"); } } [AllowAnonymous] public IActionResult OnPostPublishComment() { string slug = RouteData.Values["slug"].ToString(); Post = _dataStore.GetPost(slug); if (Post == null) { RedirectToPage("/Index"); } else if (ModelState.IsValid) { Comment.IsPublic = true; Comment.UniqueId = Guid.NewGuid(); Post.Comments.Add(Comment); _dataStore.SavePost(Post); } return Page(); } } }
mit
C#
5da24feb1789e6149a0505bea87465aeea100d1f
Add and remove the outline material when the outline should be shown
PearMed/Pear-Interaction-Engine
Scripts/EventListeners/Outline.cs
Scripts/EventListeners/Outline.cs
using System; using System.Collections; using System.Collections.Generic; using Pear.InteractionEngine.Events; using UnityEngine; namespace Pear.InteractionEngine.EventListeners { public class Outline : MonoBehaviour, IEventListener<RaycastHit?> { private const string LOG_TAG = "[Outline]"; // The value of the outline width when the outline is not showing private const float NoOutlineValue = 0f; // The name of the material private const string MaterialName = "__outlineMat__"; [Tooltip("Outline material")] public Material OutlineMaterialTemplate; // If true the outline will show // Will not show otherwise private static int counter = 0; private bool _showOutline = false; public bool ShowOutline { get { return _showOutline; } set { // If nothing changed return if (_showOutline == value) return; // Always remove any existing outline (brute force) RemoveOutline(); // If we're showing the outline add it if (value) AddOutline(); // Update the internal value _showOutline = value; } } private void Awake() { } public void ValueChanged(EventArgs<RaycastHit?> args) { ShowOutline = args.NewValue.HasValue; } private void AddOutline() { //Debug.Log(String.Format("{0} adding outline to {1}", LOG_TAG, name)); Renderer[] renderers = GetComponentsInChildren<Renderer>(); foreach (Renderer renderer in renderers) { Material outlineMaterial = Instantiate(OutlineMaterialTemplate); outlineMaterial.name = MaterialName; List<Material> materials = new List<Material>(renderer.sharedMaterials); materials.Add(outlineMaterial); renderer.sharedMaterials = materials.ToArray(); } } private void RemoveOutline() { //Debug.Log(String.Format("{0} removing outline from {1}", LOG_TAG, name)); Renderer[] renderers = GetComponentsInChildren<Renderer>(); foreach (Renderer renderer in renderers) { // Remove any outline materials List<Material> newMaterials = new List<Material>(renderer.sharedMaterials); newMaterials.RemoveAll(material => material.name.Contains(MaterialName)); renderer.sharedMaterials = newMaterials.ToArray(); } } } }
using System; using System.Collections; using System.Collections.Generic; using Pear.InteractionEngine.Events; using UnityEngine; namespace Pear.InteractionEngine.EventListeners { public class Outline : MonoBehaviour, IEventListener<RaycastHit?> { private const string LOG_TAG = "[Outline]"; // The value of the outline width when the outline is not showing private const float NoOutlineValue = 0f; [Tooltip("Outline material")] public Material OutlineMaterialTemplate; [Tooltip("The value of the outline width when the outline is showing")] public float HoveredOutlineValue = 0.2f; // The instance of the template private Material _outlineMaterial; // If true the outline will show // Will not show otherwise public bool ShowOutline { get { return _outlineMaterial != null && _outlineMaterial.GetFloat("_Outline") > 0; } set { if (_outlineMaterial == null) CreateOutlineMaterial(); if(_outlineMaterial != null) { float outlineValue = value ? HoveredOutlineValue : NoOutlineValue; _outlineMaterial.SetFloat("_Outline", outlineValue); } } } public void ValueChanged(EventArgs<RaycastHit?> args) { ShowOutline = args.NewValue.HasValue; } /// <summary> /// If this object has renderers on itself or in at least one of it's children /// create a new outline material and add it to each renderer /// </summary> private void CreateOutlineMaterial() { // If this object has renderers Get them Renderer[] renderers = GetComponentsInChildren<Renderer>(); // If there are no renderers we can't add the material if (renderers == null || renderers.Length == 0) { Debug.LogError(String.Format("{0} unable to create outline material for {1}. No renderers", LOG_TAG, name)); return; } // Create an instance of the outline material _outlineMaterial = Instantiate(OutlineMaterialTemplate); // Add the outline material to each renderer foreach (Renderer renderer in renderers) { List<Material> materials = new List<Material>(renderer.materials); materials.Add(_outlineMaterial); renderer.materials = materials.ToArray(); } } } }
mit
C#
58a73f809205c0d0ffeeddcc66758a2791fccd81
Set header correctly
mstrother/BmpListener
BmpListener/Bgp/BgpMessage.cs
BmpListener/Bgp/BgpMessage.cs
using System; using System.Linq; using Newtonsoft.Json; namespace BmpListener.Bgp { public abstract class BgpMessage { protected BgpMessage(ref ArraySegment<byte> data) { Header = new BgpHeader(data); var offset = data.Offset + 19; var count = Header.Length - 19; data = new ArraySegment<byte>(data.Array, offset, count); } [JsonIgnore] public BgpHeader Header { get; } public abstract void DecodeFromBytes(ArraySegment<byte> data); public static BgpMessage GetBgpMessage(ArraySegment<byte> data) { var msgType = (MessageType) data.ElementAt(18); switch (msgType) { case MessageType.Open: return new BgpOpenMessage(data); case MessageType.Update: return new BgpUpdateMessage(data); case MessageType.Notification: return new BgpNotification(data); case MessageType.Keepalive: throw new NotImplementedException(); case MessageType.RouteRefresh: throw new NotImplementedException(); default: throw new NotImplementedException(); } } } }
using System; using System.Linq; using Newtonsoft.Json; namespace BmpListener.Bgp { public abstract class BgpMessage { protected BgpMessage(ref ArraySegment<byte> data) { var bgpHeader = new BgpHeader(data); //Type = bgpHeader.Type; //Length = (int)bgpHeader.Length; var offset = data.Offset + 19; var count = bgpHeader.Length - 19; data = new ArraySegment<byte>(data.Array, offset, count); } [JsonIgnore] public BgpHeader Header { get; } public abstract void DecodeFromBytes(ArraySegment<byte> data); public static BgpMessage GetBgpMessage(ArraySegment<byte> data) { var msgType = (MessageType) data.ElementAt(18); switch (msgType) { case MessageType.Open: return new BgpOpenMessage(data); case MessageType.Update: return new BgpUpdateMessage(data); case MessageType.Notification: return new BgpNotification(data); case MessageType.Keepalive: throw new NotImplementedException(); case MessageType.RouteRefresh: throw new NotImplementedException(); default: throw new NotImplementedException(); } } } }
mit
C#
0d2e405c148440a4aec318fce4a3a2693141843d
reorder members
builttoroam/BuildIt,builttoroam/BuildIt
src/BuildIt.Forms/Samples/BuildIt.Forms.Sample.Android/MainActivity.cs
src/BuildIt.Forms/Samples/BuildIt.Forms.Sample.Android/MainActivity.cs
using Android.App; using Android.Content.PM; using Android.OS; using Android.Runtime; using Plugin.Permissions; namespace BuildIt.Forms.Sample.Droid { [Activity(Label = "BuildIt.Forms.Sample", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults) { PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults); base.OnRequestPermissionsResult(requestCode, permissions, grantResults); } protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; Plugin.CurrentActivity.CrossCurrentActivity.Current.Init(this, bundle); base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App()); } } }
using Android.App; using Android.Content.PM; using Android.OS; using Android.Runtime; using Plugin.Permissions; namespace BuildIt.Forms.Sample.Droid { [Activity(Label = "BuildIt.Forms.Sample", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; Plugin.CurrentActivity.CrossCurrentActivity.Current.Init(this, bundle); base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App()); } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults) { PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults); base.OnRequestPermissionsResult(requestCode, permissions, grantResults); } } }
mit
C#
d1dc15e72be7796223e0a882867fa0f7899faed3
Improve formatting of preprocessor regions
mmitche/codeformatter,BertTank/codeformatter,twsouthwick/codeformatter,rollie42/codeformatter,michaelcfanning/codeformatter,jaredpar/codeformatter,BradBarnich/codeformatter,dotnet/codeformatter,cbjugstad/codeformatter,mmitche/codeformatter,rainersigwald/codeformatter,twsouthwick/codeformatter,kharaone/codeformatter,david-mitchell/codeformatter,Maxwe11/codeformatter,shiftkey/Octokit.CodeFormatter,weltkante/codeformatter,srivatsn/codeformatter,jeremyabbott/codeformatter,hickford/codeformatter,shiftkey/codeformatter,dotnet/codeformatter
src/Microsoft.DotNet.CodeFormatting/Rules/IsFormattedFormattingRule.cs
src/Microsoft.DotNet.CodeFormatting/Rules/IsFormattedFormattingRule.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under MIT. See LICENSE in the project root for license information. using System; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.CSharp; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.DotNet.CodeFormatting.Rules { [Export(typeof(IFormattingRule))] internal sealed class IsFormattedFormattingRule : IFormattingRule { public async Task<Document> ProcessAsync(Document document, CancellationToken cancellationToken) { var newDocument = await Formatter.FormatAsync(document, cancellationToken: cancellationToken); // Roslyn formatter doesn't format code in #if false as it's considered as DisabledTextTrivia. Will be removed after the bug is fixed. // Doing that manually here var syntaxRoot = await newDocument.GetSyntaxRootAsync(cancellationToken) as CSharpSyntaxNode; var preprocessorNamesDefined = newDocument.Project.ParseOptions.PreprocessorSymbolNames; var preprocessorNamesToAdd = syntaxRoot.DescendantTrivia().Where(trivia => trivia.CSharpKind() == SyntaxKind.IfDirectiveTrivia) .SelectMany(trivia => trivia.GetStructure().DescendantNodes().OfType<IdentifierNameSyntax>()) .Select(identifier => identifier.Identifier.Text).Distinct().Where((name) => !preprocessorNamesDefined.Contains(name)); var newParseOptions = new CSharpParseOptions().WithPreprocessorSymbols(preprocessorNamesToAdd); var documentToProcess = newDocument.Project.WithParseOptions(newParseOptions).GetDocument(newDocument.Id); documentToProcess = await Formatter.FormatAsync(documentToProcess, cancellationToken: cancellationToken); return documentToProcess.Project.WithParseOptions(new CSharpParseOptions().WithPreprocessorSymbols(preprocessorNamesDefined)).GetDocument(documentToProcess.Id); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under MIT. See LICENSE in the project root for license information. using System; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.CSharp; using System.Linq; namespace Microsoft.DotNet.CodeFormatting.Rules { [Export(typeof(IFormattingRule))] internal sealed class IsFormattedFormattingRule : IFormattingRule { public async Task<Document> ProcessAsync(Document document, CancellationToken cancellationToken) { // Roslyn formatter doesn't format code in #if false as it's considered as DisabledTextTrivia. Will be removed after the bug is fixed. // Doing that manually here var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken) as CSharpSyntaxNode; var oldTrivia = syntaxRoot.DescendantTrivia().Where(trivia => trivia.CSharpKind() == SyntaxKind.DisabledTextTrivia); Func<SyntaxTrivia, SyntaxTrivia, SyntaxTrivia> replacementTrivia = (trivia, dummy) => { var levelToIndent = trivia.Token.Parent.Ancestors().Count(); var compilation = SyntaxFactory.ParseCompilationUnit(trivia.ToString()); var formattedTrivia = Formatter.Format(compilation.SyntaxTree.GetRoot(), document.Project.Solution.Workspace).GetText().ToString(); return SyntaxFactory.DisabledText(formattedTrivia); }; var newDocument = document.WithSyntaxRoot(syntaxRoot.ReplaceTrivia(oldTrivia, replacementTrivia)); return await Formatter.FormatAsync(newDocument, cancellationToken: cancellationToken); } } }
mit
C#
b9ede7bee92435ecc5bb78b802cc9201ae018c6f
Use DynamicApis.HttpGetAsync in vm
RSuter/NSwag,quails4Eva/NSwag,NSwag/NSwag,NSwag/NSwag,quails4Eva/NSwag,quails4Eva/NSwag,RSuter/NSwag,NSwag/NSwag,RSuter/NSwag,quails4Eva/NSwag,NSwag/NSwag,RSuter/NSwag,RSuter/NSwag
src/NSwagStudio/ViewModels/SwaggerGenerators/SwaggerInputViewModel.cs
src/NSwagStudio/ViewModels/SwaggerGenerators/SwaggerInputViewModel.cs
using System.Net; using System.Threading.Tasks; using System.Windows.Input; using MyToolkit.Command; using Newtonsoft.Json; using NJsonSchema.Infrastructure; using NSwag.Commands; namespace NSwagStudio.ViewModels.SwaggerGenerators { public class SwaggerInputViewModel : ViewModelBase { public SwaggerInputViewModel() { LoadSwaggerUrlCommand = new AsyncRelayCommand<string>(async url => await LoadSwaggerUrlAsync(url)); } public FromSwaggerCommand Command { get; set; } public ICommand LoadSwaggerUrlCommand { get; } public async Task LoadSwaggerUrlAsync(string url) { var json = string.Empty; await RunTaskAsync(async () => { json = await DynamicApis.HttpGetAsync(url); json = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented); }); Command.Swagger = json; } public async Task<string> GenerateSwaggerAsync() { return await RunTaskAsync(async () => { return await Task.Run(async () => { var document = await Command.RunAsync().ConfigureAwait(false); return document.ToJson(); }); }); } } }
using System.Net; using System.Threading.Tasks; using System.Windows.Input; using MyToolkit.Command; using Newtonsoft.Json; using NSwag.Commands; namespace NSwagStudio.ViewModels.SwaggerGenerators { public class SwaggerInputViewModel : ViewModelBase { public SwaggerInputViewModel() { LoadSwaggerUrlCommand = new AsyncRelayCommand<string>(async url => await LoadSwaggerUrlAsync(url)); } public FromSwaggerCommand Command { get; set; } public ICommand LoadSwaggerUrlCommand { get; } public async Task LoadSwaggerUrlAsync(string url) { var json = string.Empty; await RunTaskAsync(() => { using (var client = new WebClient()) json = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(client.DownloadString(url)), Formatting.Indented); }); Command.Swagger = json; } public async Task<string> GenerateSwaggerAsync() { return await RunTaskAsync(async () => { return await Task.Run(async () => { var document = await Command.RunAsync().ConfigureAwait(false); return document.ToJson(); }); }); } } }
mit
C#
d4609ef367a3b7ddf212b8b5424657f39e3faf87
Fix all violations of SA1127
tunnelvisionlabs/InheritanceMargin
Tvl.VisualStudio.InheritanceMargin/CSharpInheritanceTaggerProvider.cs
Tvl.VisualStudio.InheritanceMargin/CSharpInheritanceTaggerProvider.cs
namespace Tvl.VisualStudio.InheritanceMargin { using System.ComponentModel.Composition; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using IOutputWindowService = Tvl.VisualStudio.OutputWindow.Interfaces.IOutputWindowService; using TaskScheduler = System.Threading.Tasks.TaskScheduler; [Name("CSharp Inheritance Tagger Provider")] [TagType(typeof(IInheritanceTag))] [Export(typeof(ITaggerProvider))] [ContentType("CSharp")] internal class CSharpInheritanceTaggerProvider : ITaggerProvider { public CSharpInheritanceTaggerProvider() { TaskScheduler = TaskScheduler.Default; } ////[Import(PredefinedTaskSchedulers.BackgroundIntelliSense)] public TaskScheduler TaskScheduler { get; private set; } [Import] public ITextDocumentFactoryService TextDocumentFactoryService { get; private set; } [Import] public IOutputWindowService OutputWindowService { get; private set; } [Import] public SVsServiceProvider GlobalServiceProvider { get; private set; } public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag { if (buffer != null) return CSharpInheritanceTagger.CreateInstance(this, buffer) as ITagger<T>; return null; } } }
namespace Tvl.VisualStudio.InheritanceMargin { using System.ComponentModel.Composition; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using IOutputWindowService = Tvl.VisualStudio.OutputWindow.Interfaces.IOutputWindowService; using TaskScheduler = System.Threading.Tasks.TaskScheduler; [Name("CSharp Inheritance Tagger Provider")] [TagType(typeof(IInheritanceTag))] [Export(typeof(ITaggerProvider))] [ContentType("CSharp")] internal class CSharpInheritanceTaggerProvider : ITaggerProvider { public CSharpInheritanceTaggerProvider() { TaskScheduler = TaskScheduler.Default; } ////[Import(PredefinedTaskSchedulers.BackgroundIntelliSense)] public TaskScheduler TaskScheduler { get; private set; } [Import] public ITextDocumentFactoryService TextDocumentFactoryService { get; private set; } [Import] public IOutputWindowService OutputWindowService { get; private set; } [Import] public SVsServiceProvider GlobalServiceProvider { get; private set; } public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag { if (buffer != null) return CSharpInheritanceTagger.CreateInstance(this, buffer) as ITagger<T>; return null; } } }
mit
C#
cf5c6c924742abebfe4bcb203cee2ea15cc60f91
Add code sample
DaveSenn/Extend
.Src/Extend/System.Collections.Generic.IEnumerable[T]/IEnumerable[T].AnyAndNotNull.cs
.Src/Extend/System.Collections.Generic.IEnumerable[T]/IEnumerable[T].AnyAndNotNull.cs
#region Usings using System; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; #endregion namespace Extend { /// <summary> /// Class containing some extension methods for <see cref="IEnumerable{T}" />. /// </summary> // ReSharper disable once InconsistentNaming public static partial class IEnumerableTEx { /// <summary> /// Checks if the given IEnumerable is not null and contains some items. /// </summary> /// <example> /// <code> /// List&lt;String&gt; strings = null; /// Console.WriteLine( strings.AnyAndNotNull() ); // False /// strings = new List&lt;String&gt;(); /// Console.WriteLine( strings.AnyAndNotNull() ); // False /// strings.AddRange( "1", "2", "3" ); /// Console.WriteLine( strings.AnyAndNotNull() ); // True /// </code> /// </example> /// <typeparam name="T">The type of the items in the IEnumerable.</typeparam> /// <param name="enumerable">The IEnumerable to act on.</param> /// <returns>Returns true if the IEnumerable is not null or empty, otherwise false.</returns> [Pure] [PublicAPI] public static Boolean AnyAndNotNull<T>( [CanBeNull] [ItemCanBeNull] this IEnumerable<T> enumerable ) => enumerable != null && enumerable.Any(); /// <summary> /// Checks if the given IEnumerable is not null and contains some items /// which mates the given predicate. /// </summary> /// <exception cref="ArgumentNullException">The predicate can not be null.</exception> /// <typeparam name="T">The type of the items in the IEnumerable.</typeparam> /// <param name="enumerable">The IEnumerable to act on.</param> /// <param name="predicate">The predicate.</param> /// <returns>Returns true if the IEnumerable is not null or empty, otherwise false.</returns> [Pure] [PublicAPI] public static Boolean AnyAndNotNull<T>( [CanBeNull] [ItemCanBeNull] this IEnumerable<T> enumerable, [NotNull] Func<T, Boolean> predicate ) { predicate.ThrowIfNull( nameof( predicate ) ); return enumerable != null && enumerable.Any( predicate ); } } }
#region Usings using System; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; #endregion namespace Extend { /// <summary> /// Class containing some extension methods for <see cref="IEnumerable{T}" />. /// </summary> // ReSharper disable once InconsistentNaming public static partial class IEnumerableTEx { /// <summary> /// Checks if the given IEnumerable is not null and contains some items. /// </summary> /// <typeparam name="T">The type of the items in the IEnumerable.</typeparam> /// <param name="enumerable">The IEnumerable to act on.</param> /// <returns>Returns true if the IEnumerable is not null or empty, otherwise false.</returns> [Pure] [PublicAPI] public static Boolean AnyAndNotNull<T>( [CanBeNull] [ItemCanBeNull] this IEnumerable<T> enumerable ) => enumerable != null && enumerable.Any(); /// <summary> /// Checks if the given IEnumerable is not null and contains some items /// which mates the given predicate. /// </summary> /// <exception cref="ArgumentNullException">The predicate can not be null.</exception> /// <typeparam name="T">The type of the items in the IEnumerable.</typeparam> /// <param name="enumerable">The IEnumerable to act on.</param> /// <param name="predicate">The predicate.</param> /// <returns>Returns true if the IEnumerable is not null or empty, otherwise false.</returns> [Pure] [PublicAPI] public static Boolean AnyAndNotNull<T>( [CanBeNull] [ItemCanBeNull] this IEnumerable<T> enumerable, [NotNull] Func<T, Boolean> predicate ) { predicate.ThrowIfNull( nameof( predicate ) ); return enumerable != null && enumerable.Any( predicate ); } } }
mit
C#
21d217b9843bd11db6d8d33bf37b288de09cff5f
remove tabstop from spacer control (fixes #21)
misterhaan/MythClient
UI/Render/ContentsRendererBase.cs
UI/Render/ContentsRendererBase.cs
using System.Collections.Generic; using System.Windows.Forms; namespace au.Applications.MythClient.UI.Render { /// <summary> /// Common logic for contents renderers. /// </summary> /// <typeparam name="TItem"></typeparam> internal abstract class ContentsRendererBase<TItem> : RendererBase, IContentsRenderer<TItem> { /// <summary> /// Margin applied to each content item /// </summary> protected const int _margin = 5; /// <summary> /// Padding applied to each content item /// </summary> protected const int _padding = 7; /// <summary> /// Constructor /// </summary> /// <param name="control">Render target control</param> internal ContentsRendererBase(ScrollableControl control) : base(control) { } /// <inheritdoc /> public void Render(IReadOnlyCollection<TItem> items, TItem selectedItem) { Control.Controls.Clear(); foreach(TItem item in items) { bool selected = (object)item == (object)selectedItem; // casting to object because it doesn't recognize the two TItem types as the same Control itemControl = BuildItemControl(item, selected); Control.Controls.Add(itemControl); if(selected) Control.ScrollControlIntoView(itemControl); } // add an extra control to fix the scrolling problem Control.Controls.Add(new Control { Width = Control.Width - Control.Padding.Left - Control.Padding.Right - 1, Height = Control.Padding.Bottom + _margin + 1, TabStop = false }); } /// <summary> /// Build a control to represent the item /// </summary> /// <param name="item">Item control should represent</param> /// <param name="isSelected">Whether the control should appear selected</param> /// <returns>Control representing the item</returns> protected abstract Control BuildItemControl(TItem item, bool isSelected); } }
using System.Collections.Generic; using System.Windows.Forms; namespace au.Applications.MythClient.UI.Render { /// <summary> /// Common logic for contents renderers. /// </summary> /// <typeparam name="TItem"></typeparam> internal abstract class ContentsRendererBase<TItem> : RendererBase, IContentsRenderer<TItem> { /// <summary> /// Margin applied to each content item /// </summary> protected const int _margin = 5; /// <summary> /// Padding applied to each content item /// </summary> protected const int _padding = 7; /// <summary> /// Constructor /// </summary> /// <param name="control">Render target control</param> internal ContentsRendererBase(ScrollableControl control) : base(control) { } /// <inheritdoc /> public void Render(IReadOnlyCollection<TItem> items, TItem selectedItem) { Control.Controls.Clear(); foreach(TItem item in items) { bool selected = (object)item == (object)selectedItem; // casting to object because it doesn't recognize the two TItem types as the same Control itemControl = BuildItemControl(item, selected); Control.Controls.Add(itemControl); if(selected) Control.ScrollControlIntoView(itemControl); } // add an extra control to fix the scrolling problem Control.Controls.Add(new Control { Width = Control.Width - Control.Padding.Left - Control.Padding.Right - 1, Height = Control.Padding.Bottom + _margin + 1 }); } /// <summary> /// Build a control to represent the item /// </summary> /// <param name="item">Item control should represent</param> /// <param name="isSelected">Whether the control should appear selected</param> /// <returns>Control representing the item</returns> protected abstract Control BuildItemControl(TItem item, bool isSelected); } }
mit
C#
bfa75d92874c4c441691be268d81154094598186
Add convenience methods for timeslots
victoria92/university-program-generator,victoria92/university-program-generator
UniProgramGen/Helpers/TimeSlot.cs
UniProgramGen/Helpers/TimeSlot.cs
using System; namespace UniProgramGen.Helpers { public class TimeSlot { public const uint START_HOUR = 8; public const uint END_HOUR = 22; public const uint TOTAL_DAY_HOURS = END_HOUR - START_HOUR; public TimeSlot(DayOfWeek day, uint startHour, uint endHour) { validateHour(startHour); validateHour(endHour); if (startHour >= endHour) { throw new ArgumentException("Start hour has to be before end hour"); } Day = day; StartHour = startHour; EndHour = endHour; } public uint Duration() { return (uint)EndHour - StartHour; } public bool Overlaps(TimeSlot other) { return inSlot(other.StartHour) || inSlot(other.EndHour); } public bool Includes(TimeSlot other) { return other.StartHour >= StartHour && other.EndHour <= EndHour; } public DayOfWeek Day { get; private set; } public uint StartHour { get; private set; } public uint EndHour { get; private set; } private static void validateHour(uint hour) { if (hour < START_HOUR || hour > END_HOUR) { throw new ArgumentOutOfRangeException("Hour outside of working hours"); } } private bool inSlot(uint hour) { return hour > StartHour && hour < EndHour; } } }
using System; namespace UniProgramGen.Helpers { public class TimeSlot { public TimeSlot(DayOfWeek day, uint startHour, uint endHour) { Day = day; StartHour = startHour; EndHour = endHour; } public DayOfWeek Day { get; private set; } public uint StartHour { get; private set; } public uint EndHour { get; private set; } } }
bsd-2-clause
C#
38b4e2c282ea33d56afb8bfdbe19e1ae9ea7e92e
Use a single buffer for both channels.
jherby2k/AudioWorks
AudioWorks/Extensions/AudioWorks.Extensions.Flac/AudioStreamDecoder.cs
AudioWorks/Extensions/AudioWorks.Extensions.Flac/AudioStreamDecoder.cs
using JetBrains.Annotations; using System; using System.IO; using System.Runtime.InteropServices; namespace AudioWorks.Extensions.Flac { sealed class AudioStreamDecoder : AudioInfoStreamDecoder { float _divisor; [CanBeNull] int[] _buffer; [CanBeNull] public SampleCollection Samples { get; set; } internal AudioStreamDecoder([NotNull] Stream stream) : base(stream) { } public bool ProcessSingle() { return SafeNativeMethods.StreamDecoderProcessSingle(Handle); } protected override DecoderWriteStatus WriteCallback(IntPtr handle, ref Frame frame, IntPtr buffer, IntPtr userData) { // Initialize the divisor if (_divisor < 1) _divisor = (float) Math.Pow(2, frame.Header.BitsPerSample - 1); // Initialize the output buffer if (_buffer == null) _buffer = new int[frame.Header.BlockSize]; Samples = new SampleCollection((int)frame.Header.Channels, (int)frame.Header.BlockSize); for (var channelIndex = 0; channelIndex < frame.Header.Channels; channelIndex++) { // Copy the samples for each channel from unmanaged memory into the output buffer var channelPtr = Marshal.ReadIntPtr(buffer, channelIndex * Marshal.SizeOf(buffer)); Marshal.Copy(channelPtr, _buffer, 0, (int) frame.Header.BlockSize); // Convert to floating point values for (var frameIndex = 0; frameIndex < (int)frame.Header.BlockSize; frameIndex++) Samples[channelIndex][frameIndex] = _buffer[frameIndex] / _divisor; } return DecoderWriteStatus.Continue; } } }
using JetBrains.Annotations; using System; using System.IO; using System.Runtime.InteropServices; namespace AudioWorks.Extensions.Flac { sealed class AudioStreamDecoder : AudioInfoStreamDecoder { float _divisor; int[][] _managedBuffer; [CanBeNull] public SampleCollection Samples { get; set; } internal AudioStreamDecoder([NotNull] Stream stream) : base(stream) { } public bool ProcessSingle() { return SafeNativeMethods.StreamDecoderProcessSingle(Handle); } protected override DecoderWriteStatus WriteCallback(IntPtr handle, ref Frame frame, IntPtr buffer, IntPtr userData) { // Initialize the divisor: if (_divisor < 1) _divisor = (float) Math.Pow(2, frame.Header.BitsPerSample - 1); // Initialize the output buffer: if (_managedBuffer == null) { _managedBuffer = new int[frame.Header.Channels][]; for (var channelIndex = 0; channelIndex < frame.Header.Channels; channelIndex++) _managedBuffer[channelIndex] = new int[frame.Header.BlockSize]; } // Copy the samples from unmanaged memory into the output buffer: for (var channelIndex = 0; channelIndex < frame.Header.Channels; channelIndex++) { var channelPtr = Marshal.ReadIntPtr(buffer, channelIndex * Marshal.SizeOf(buffer)); Marshal.Copy(channelPtr, _managedBuffer[channelIndex], 0, (int) frame.Header.BlockSize); } Samples = new SampleCollection((int) frame.Header.Channels, (int) frame.Header.BlockSize); // Copy the output buffer into a new sample block, converting to floating point values: for (var channelIndex = 0; channelIndex < (int) frame.Header.Channels; channelIndex++) for (var frameIndex = 0; frameIndex < (int) frame.Header.BlockSize; frameIndex++) Samples[channelIndex][frameIndex] = _managedBuffer[channelIndex][frameIndex] / _divisor; return DecoderWriteStatus.Continue; } } }
agpl-3.0
C#
d6e0ece60d8b5bf041d5ee758fe64b47c7ebdb93
Fix typo in Branch.ToString
RyanLamansky/dotnet-webassembly
WebAssembly/Instructions/Branch.cs
WebAssembly/Instructions/Branch.cs
using System; using System.Linq; using System.Reflection.Emit; using WebAssembly.Runtime.Compilation; namespace WebAssembly.Instructions; /// <summary> /// Branch to a given label in an enclosing construct. /// </summary> public class Branch : Instruction { /// <summary> /// Always <see cref="OpCode.Branch"/>. /// </summary> public sealed override OpCode OpCode => OpCode.Branch; /// <summary> /// The number of ancestor blocks to climb; 0 is the immediate parent. /// </summary> public uint Index { get; set; } /// <summary> /// Creates a new <see cref="Branch"/> instance. /// </summary> public Branch() { } /// <summary> /// Creates a new <see cref="Branch"/> instance with the provided index. /// </summary> /// <param name="index">The number of ancestor blocks to climb; 0 is the immediate parent.</param> public Branch(uint index) { this.Index = index; } internal Branch(Reader reader) { if (reader == null) throw new ArgumentNullException(nameof(reader)); Index = reader.ReadVarUInt32(); } internal sealed override void WriteTo(Writer writer) { writer.Write((byte)OpCode.Branch); writer.WriteVar(this.Index); } /// <summary> /// Determines whether this instruction is identical to another. /// </summary> /// <param name="other">The instruction to compare against.</param> /// <returns>True if they have the same type and value, otherwise false.</returns> public override bool Equals(Instruction? other) => other is Branch instruction && instruction.Index == this.Index ; /// <summary> /// Returns a simple hash code based on the value of the instruction. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() => HashCode.Combine((int)this.OpCode, (int)this.Index); /// <summary> /// Provides a native representation of the instruction. /// </summary> /// <returns>A string representation of this instance.</returns> public override string ToString() => $"{base.ToString()} {Index}"; internal sealed override void Compile(CompilationContext context) { var blockType = context.Depth.ElementAt(checked((int)this.Index)); if (blockType.OpCode != OpCode.Loop && blockType.Type.TryToValueType(out var expectedType)) context.ValidateStack(this.OpCode, expectedType); context.Emit(OpCodes.Br, context.Labels[checked((uint)context.Depth.Count) - this.Index - 1]); //Mark the subsequent code within this block is unreachable context.MarkUnreachable(); } }
using System; using System.Linq; using System.Reflection.Emit; using WebAssembly.Runtime.Compilation; namespace WebAssembly.Instructions; /// <summary> /// Branch to a given label in an enclosing construct. /// </summary> public class Branch : Instruction { /// <summary> /// Always <see cref="OpCode.Branch"/>. /// </summary> public sealed override OpCode OpCode => OpCode.Branch; /// <summary> /// The number of ancestor blocks to climb; 0 is the immediate parent. /// </summary> public uint Index { get; set; } /// <summary> /// Creates a new <see cref="Branch"/> instance. /// </summary> public Branch() { } /// <summary> /// Creates a new <see cref="Branch"/> instance with the provided index. /// </summary> /// <param name="index">The number of ancestor blocks to climb; 0 is the immediate parent.</param> public Branch(uint index) { this.Index = index; } internal Branch(Reader reader) { if (reader == null) throw new ArgumentNullException(nameof(reader)); Index = reader.ReadVarUInt32(); } internal sealed override void WriteTo(Writer writer) { writer.Write((byte)OpCode.Branch); writer.WriteVar(this.Index); } /// <summary> /// Determines whether this instruction is identical to another. /// </summary> /// <param name="other">The instruction to compare against.</param> /// <returns>True if they have the same type and value, otherwise false.</returns> public override bool Equals(Instruction? other) => other is Branch instruction && instruction.Index == this.Index ; /// <summary> /// Returns a simple hash code based on the value of the instruction. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() => HashCode.Combine((int)this.OpCode, (int)this.Index); /// <summary> /// Provides a native representation of the instruction. /// </summary> /// <returns>A string representation of this instance.</returns> public override string ToString() => $"{base.ToString()} {Index})"; internal sealed override void Compile(CompilationContext context) { var blockType = context.Depth.ElementAt(checked((int)this.Index)); if (blockType.OpCode != OpCode.Loop && blockType.Type.TryToValueType(out var expectedType)) context.ValidateStack(this.OpCode, expectedType); context.Emit(OpCodes.Br, context.Labels[checked((uint)context.Depth.Count) - this.Index - 1]); //Mark the subsequent code within this block is unreachable context.MarkUnreachable(); } }
apache-2.0
C#
c07473031c3cc28f194643435b1079dccbde7b46
Update version
sys27/xFunc
SharedCode/SharedAssemblyInfo.cs
SharedCode/SharedAssemblyInfo.cs
using System.Reflection; using System.Resources; [assembly: AssemblyCopyright("Copyright 2012-2016 Dmitry Kischenko")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyVersion("3.3.0")] [assembly: AssemblyFileVersion("3.3.0")] [assembly: AssemblyInformationalVersion("3.3.0")] [assembly: NeutralResourcesLanguage("en")]
using System.Reflection; using System.Resources; [assembly: AssemblyCopyright("Copyright 2012-2016 Dmitry Kischenko")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyVersion("3.2.1")] [assembly: AssemblyFileVersion("3.2.1")] [assembly: AssemblyInformationalVersion("3.2.1")] [assembly: NeutralResourcesLanguage("en")]
mit
C#
d4157d17aed54526159c4acaa16bb5c3737abf17
Make libs target depend on externals
Redth/Cake.Android.Adb
build.cake
build.cake
#tool nuget:?package=NUnit.ConsoleRunner&version=3.6.0 var sln = "./Cake.Android.Adb.sln"; var nuspec = "./Cake.Android.Adb.nuspec"; var target = Argument ("target", "all"); var configuration = Argument ("configuration", "Release"); var NUGET_VERSION = Argument("nugetversion", "0.9999"); var SDK_URL_BASE = "https://dl.google.com/android/repository/tools_r{0}-{1}.zip"; var SDK_VERSION = "25.2.3"; Task ("externals") .WithCriteria (!FileExists ("./android-sdk/android-sdk.zip")) .Does (() => { var url = string.Format (SDK_URL_BASE, SDK_VERSION, "macosx"); if (IsRunningOnWindows ()) url = string.Format (SDK_URL_BASE, SDK_VERSION, "windows"); EnsureDirectoryExists ("./android-sdk/"); DownloadFile (url, "./android-sdk/android-sdk.zip"); Unzip ("./android-sdk/android-sdk.zip", "./android-sdk/"); // Install platform-tools so we get adb StartProcess ("./android-sdk/tools/bin/sdkmanager", new ProcessSettings { Arguments = "platform-tools" }); }); Task ("libs").IsDependentOn ("externals").Does (() => { NuGetRestore (sln); DotNetBuild (sln, c => c.Configuration = configuration); }); Task ("nuget").IsDependentOn ("libs").Does (() => { NuGetPack (nuspec, new NuGetPackSettings { Verbosity = NuGetVerbosity.Detailed, OutputDirectory = "./", Version = NUGET_VERSION, // NuGet messes up path on mac, so let's add ./ in front again BasePath = "././", }); }); Task("tests").IsDependentOn("libs").Does(() => { NUnit3("./**/bin/" + configuration + "/*.Tests.dll"); }); Task ("clean").Does (() => { CleanDirectories ("./**/bin"); CleanDirectories ("./**/obj"); CleanDirectories ("./**/Components"); CleanDirectories ("./**/tools"); CleanDirectories ("./android-sdk"); DeleteFiles ("./**/*.apk"); }); Task ("all").IsDependentOn("nuget").IsDependentOn ("tests"); RunTarget (target);
#tool nuget:?package=NUnit.ConsoleRunner&version=3.6.0 var sln = "./Cake.Android.Adb.sln"; var nuspec = "./Cake.Android.Adb.nuspec"; var target = Argument ("target", "all"); var configuration = Argument ("configuration", "Release"); var NUGET_VERSION = Argument("nugetversion", "0.9999"); var SDK_URL_BASE = "https://dl.google.com/android/repository/tools_r{0}-{1}.zip"; var SDK_VERSION = "25.2.3"; Task ("externals") .WithCriteria (!FileExists ("./android-sdk/android-sdk.zip")) .Does (() => { var url = string.Format (SDK_URL_BASE, SDK_VERSION, "macosx"); if (IsRunningOnWindows ()) url = string.Format (SDK_URL_BASE, SDK_VERSION, "windows"); EnsureDirectoryExists ("./android-sdk/"); DownloadFile (url, "./android-sdk/android-sdk.zip"); Unzip ("./android-sdk/android-sdk.zip", "./android-sdk/"); // Install platform-tools so we get adb StartProcess ("./android-sdk/tools/bin/sdkmanager", new ProcessSettings { Arguments = "platform-tools" }); }); Task ("libs").Does (() => { NuGetRestore (sln); DotNetBuild (sln, c => c.Configuration = configuration); }); Task ("nuget").IsDependentOn ("libs").Does (() => { NuGetPack (nuspec, new NuGetPackSettings { Verbosity = NuGetVerbosity.Detailed, OutputDirectory = "./", Version = NUGET_VERSION, // NuGet messes up path on mac, so let's add ./ in front again BasePath = "././", }); }); Task("tests").IsDependentOn("libs").Does(() => { NUnit3("./**/bin/" + configuration + "/*.Tests.dll"); }); Task ("clean").Does (() => { CleanDirectories ("./**/bin"); CleanDirectories ("./**/obj"); CleanDirectories ("./**/Components"); CleanDirectories ("./**/tools"); CleanDirectories ("./android-sdk"); DeleteFiles ("./**/*.apk"); }); Task ("all").IsDependentOn("nuget").IsDependentOn ("tests"); RunTarget (target);
mit
C#
c764ccafeb1f6bad8c8b4c14ac0b3c5d67f9367b
Update MergingCellsInWorksheet..cs
maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET
Examples/CSharp/Data/AddOn/Merging/MergingCellsInWorksheet..cs
Examples/CSharp/Data/AddOn/Merging/MergingCellsInWorksheet..cs
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Data.AddOn.Merging { public class MergingCellsInWorksheet { public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); //Create a Workbook. Workbook wbk = new Workbook(); //Create a Worksheet and get the first sheet. Worksheet worksheet = wbk.Worksheets[0]; //Create a Cells object ot fetch all the cells. Cells cells = worksheet.Cells; //Merge some Cells (C6:E7) into a single C6 Cell. cells.Merge(5, 2, 2, 3); //Input data into C6 Cell. worksheet.Cells[5, 2].PutValue("This is my value"); //Create a Style object to fetch the Style of C6 Cell. Style style = worksheet.Cells[5, 2].GetStyle(); //Create a Font object Font font = style.Font; //Set the name. font.Name = "Times New Roman"; //Set the font size. font.Size = 18; //Set the font color font.Color = System.Drawing.Color.Blue; //Bold the text font.IsBold = true; //Make it italic font.IsItalic = true; //Set the backgrond color of C6 Cell to Red style.ForegroundColor = System.Drawing.Color.Red; style.Pattern = BackgroundType.Solid; //Apply the Style to C6 Cell. cells[5, 2].SetStyle(style); //Save the Workbook. wbk.Save(dataDir + "mergingcells.out.xls"); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Data.AddOn.Merging { public class MergingCellsInWorksheet { public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); //Create a Workbook. Workbook wbk = new Workbook(); //Create a Worksheet and get the first sheet. Worksheet worksheet = wbk.Worksheets[0]; //Create a Cells object ot fetch all the cells. Cells cells = worksheet.Cells; //Merge some Cells (C6:E7) into a single C6 Cell. cells.Merge(5, 2, 2, 3); //Input data into C6 Cell. worksheet.Cells[5, 2].PutValue("This is my value"); //Create a Style object to fetch the Style of C6 Cell. Style style = worksheet.Cells[5, 2].GetStyle(); //Create a Font object Font font = style.Font; //Set the name. font.Name = "Times New Roman"; //Set the font size. font.Size = 18; //Set the font color font.Color = System.Drawing.Color.Blue; //Bold the text font.IsBold = true; //Make it italic font.IsItalic = true; //Set the backgrond color of C6 Cell to Red style.ForegroundColor = System.Drawing.Color.Red; style.Pattern = BackgroundType.Solid; //Apply the Style to C6 Cell. cells[5, 2].SetStyle(style); //Save the Workbook. wbk.Save(dataDir + "mergingcells.out.xls"); } } }
mit
C#
3da7efff7b4056123871b9aa8fdd21203bdc1c85
Add additional private methods to atexit (#224)
IronLanguages/ironpython3,IronLanguages/ironpython3,IronLanguages/ironpython3,IronLanguages/ironpython3,IronLanguages/ironpython3,IronLanguages/ironpython3
Src/IronPython.Modules/atexit.cs
Src/IronPython.Modules/atexit.cs
using System; using System.Collections.Generic; using Microsoft.Scripting; using IronPython.Runtime; using Microsoft.Scripting.Runtime; [assembly: PythonModule("atexit", typeof(IronPython.Modules.PythonAtExit))] namespace IronPython.Modules { [Documentation(@"allow programmer to define multiple exit functions to be executed upon normal program termination. Two public functions, register and unregister, are defined. ")] public static class PythonAtExit { [Documentation(@"register(func, *args, **kwargs) -> func Register a function to be executed upon normal program termination\n\ func - function to be called at exit args - optional arguments to pass to func kwargs - optional keyword arguments to pass to func func is returned to facilitate usage as a decorator.")] public static void register(object func, [ParamDictionary]IDictionary<object, object> kwargs, params object[] args) { // TODO: implement this } [Documentation(@"unregister(func) -> None Unregister an exit function which was previously registered using atexit.register func - function to be unregistered")] public static void unregister(object func) { // TODO: implement this } [Documentation(@"_clear() -> None Clear the list of previously registered exit functions.")] public static void _clear() { // TODO: implement this } [Documentation(@"_run_exitfuncs() -> None Run all registered exit functions.")] public static void _run_exitfuncs() { // TODO: implement this } [Documentation(@"_ncallbacks() -> int Return the number of registered exit functions.")] public static int _ncallbacks() { // TODO: implement this return 0; } } }
using System; using System.Collections.Generic; using Microsoft.Scripting; using IronPython.Runtime; [assembly: PythonModule("atexit", typeof(IronPython.Modules.PythonAtExit))] namespace IronPython.Modules { public static class PythonAtExit { public static void register(object func, [ParamDictionary]IDictionary<object, object> kwargs, params object[] args) { // TODO: implement this } public static void unregister(object func) { // TODO: implement this } public static void _clear() { // TODO: implement this } } }
apache-2.0
C#
a47d33cce0fb38b60ebd1923b5f4fd1cabc57d8b
Remove collision detector
EasyPeasyLemonSqueezy/MadCat
MadCat/NutEngine/EntityManager.cs
MadCat/NutEngine/EntityManager.cs
using System.Collections.Generic; namespace NutEngine { public class EntityManager { public List<Entity> Entities { get; } = new List<Entity>(); public void Update(float deltaTime) { foreach (var entity in Entities) { entity.Update(deltaTime); } Entities.RemoveAll( entity => { if (entity.Invalid) { entity.Cleanup(); return true; } return false; }); } public void Add(Entity entity) { Entities.Add(entity); } } }
using System.Collections.Generic; namespace NutEngine { public class EntityManager { public List<Entity> Entities { get; } = new List<Entity>(); public CollisionDetector Detector { get; } = new CollisionDetector(); public void Update(float deltaTime) { foreach (var entity in Entities) { entity.Update(deltaTime); } Detector.CheckCollisions(Entities); Entities.RemoveAll( entity => { if (entity.Invalid) { entity.Cleanup(); return true; } return false; }); } public void Add(Entity entity) { Entities.Add(entity); } } }
mit
C#