Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix to allow plugin to start up disabled as default
using System.Collections.Generic; using Wox.Plugin; namespace Wox.Infrastructure.UserSettings { public class PluginsSettings : BaseModel { public string PythonDirectory { get; set; } public Dictionary<string, Plugin> Plugins { get; set; } = new Dictionary<string, Plugin>(); public void UpdatePluginSettings(List<PluginMetadata> metadatas) { foreach (var metadata in metadatas) { if (Plugins.ContainsKey(metadata.ID)) { var settings = Plugins[metadata.ID]; if (settings.ActionKeywords?.Count > 0) { metadata.ActionKeywords = settings.ActionKeywords; metadata.ActionKeyword = settings.ActionKeywords[0]; } metadata.Disabled = settings.Disabled; } else { Plugins[metadata.ID] = new Plugin { ID = metadata.ID, Name = metadata.Name, ActionKeywords = metadata.ActionKeywords, Disabled = false }; } } } } public class Plugin { public string ID { get; set; } public string Name { get; set; } public List<string> ActionKeywords { get; set; } public bool Disabled { get; set; } } }
using System.Collections.Generic; using Wox.Plugin; namespace Wox.Infrastructure.UserSettings { public class PluginsSettings : BaseModel { public string PythonDirectory { get; set; } public Dictionary<string, Plugin> Plugins { get; set; } = new Dictionary<string, Plugin>(); public void UpdatePluginSettings(List<PluginMetadata> metadatas) { foreach (var metadata in metadatas) { if (Plugins.ContainsKey(metadata.ID)) { var settings = Plugins[metadata.ID]; if (settings.ActionKeywords?.Count > 0) { metadata.ActionKeywords = settings.ActionKeywords; metadata.ActionKeyword = settings.ActionKeywords[0]; } metadata.Disabled = settings.Disabled; } else { Plugins[metadata.ID] = new Plugin { ID = metadata.ID, Name = metadata.Name, ActionKeywords = metadata.ActionKeywords, Disabled = metadata.Disabled }; } } } } public class Plugin { public string ID { get; set; } public string Name { get; set; } public List<string> ActionKeywords { get; set; } public bool Disabled { get; set; } } }
Add OrderingDomainException when the order doesn't exist with id orderId
using Microsoft.EntityFrameworkCore; using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate; using Microsoft.eShopOnContainers.Services.Ordering.Domain.Seedwork; using System; using System.Threading.Tasks; namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Repositories { public class OrderRepository : IOrderRepository { private readonly OrderingContext _context; public IUnitOfWork UnitOfWork { get { return _context; } } public OrderRepository(OrderingContext context) { _context = context ?? throw new ArgumentNullException(nameof(context)); } public Order Add(Order order) { return _context.Orders.Add(order).Entity; } public async Task<Order> GetAsync(int orderId) { return await _context.Orders.FindAsync(orderId); } public void Update(Order order) { _context.Entry(order).State = EntityState.Modified; } } }
using Microsoft.EntityFrameworkCore; using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate; using Microsoft.eShopOnContainers.Services.Ordering.Domain.Seedwork; using Ordering.Domain.Exceptions; using System; using System.Threading.Tasks; namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Repositories { public class OrderRepository : IOrderRepository { private readonly OrderingContext _context; public IUnitOfWork UnitOfWork { get { return _context; } } public OrderRepository(OrderingContext context) { _context = context ?? throw new ArgumentNullException(nameof(context)); } public Order Add(Order order) { return _context.Orders.Add(order).Entity; } public async Task<Order> GetAsync(int orderId) { return await _context.Orders.FindAsync(orderId) ?? throw new OrderingDomainException($"Not able to get the order. Reason: no valid orderId: {orderId}"); } public void Update(Order order) { _context.Entry(order).State = EntityState.Modified; } } }
Check if tree is mirror. Improved logics.
using System; class Node { public Node(int val, Node left, Node right) { Value = val; Left = left; Right = right; } public int Value { get; private set; } public Node Left { get; private set; } public Node Right { get; private set; } } class Program{ static bool IsMirror(Node left, Node right) { if (left == null && right == null) { return true; } if (left == null && right != null || left != null && right == null) { return false; } return ((left.Value == right.Value) && IsMirror(left.Right, right.Left) && IsMirror(left.Left, right.Right)); } static void Main() { Node root = new Node(1, new Node(2, new Node(3, null, null), new Node(4, null, null)), new Node(2, new Node(4, null, null), new Node(3, null, null))); Node unroot = new Node(1, new Node(2, null, new Node(4, null, null)), new Node(2, null, new Node(4, null, null))); Console.WriteLine("First {0}", IsMirror(root.Left, root.Right)); Console.WriteLine("Second {0}", IsMirror(unroot.Left, unroot.Right)); } }
using System; class Node { public Node(int val, Node left, Node right) { Value = val; Left = left; Right = right; } public int Value { get; private set; } public Node Left { get; private set; } public Node Right { get; private set; } } class Program{ static bool IsMirror(Node left, Node right) { if (left == null || right == null) { return left == null && right == null; } return ((left.Value == right.Value) && IsMirror(left.Right, right.Left) && IsMirror(left.Left, right.Right)); } static void Main() { Node root = new Node(1, new Node(2, new Node(3, null, null), new Node(4, null, null)), new Node(2, new Node(4, null, null), new Node(3, null, null))); Node unroot = new Node(1, new Node(2, null, new Node(4, null, null)), new Node(2, null, new Node(4, null, null))); Console.WriteLine("First {0}", IsMirror(root.Left, root.Right)); Console.WriteLine("Second {0}", IsMirror(unroot.Left, unroot.Right)); } }
Update test for possible sizes
namespace CSharpMath.Xaml.Tests.NuGet { using Avalonia; using SkiaSharp; using Forms; public class Program { static string File(string platform, [System.Runtime.CompilerServices.CallerFilePath] string thisDir = "") => System.IO.Path.Combine(thisDir, "..", $"Test.{platform}.png"); [Xunit.Fact] public void TestImage() { global::Avalonia.Skia.SkiaPlatform.Initialize(); Xamarin.Forms.Device.PlatformServices = new Xamarin.Forms.Core.UnitTests.MockPlatformServices(); using (var forms = System.IO.File.OpenWrite(File(nameof(Forms)))) new Forms.MathView { LaTeX = "1" }.Painter.DrawAsStream()?.CopyTo(forms); using (var avalonia = System.IO.File.OpenWrite(File(nameof(Avalonia)))) new Avalonia.MathView { LaTeX = "1" }.Painter.DrawAsPng(avalonia); using (var forms = System.IO.File.OpenRead(File(nameof(Forms)))) Xunit.Assert.Equal(797, forms.Length); using (var avalonia = System.IO.File.OpenRead(File(nameof(Avalonia)))) Xunit.Assert.Equal(344, avalonia.Length); } } }
namespace CSharpMath.Xaml.Tests.NuGet { using Avalonia; using SkiaSharp; using Forms; public class Program { static string File(string platform, [System.Runtime.CompilerServices.CallerFilePath] string thisDir = "") => System.IO.Path.Combine(thisDir, "..", $"Test.{platform}.png"); [Xunit.Fact] public void TestImage() { global::Avalonia.Skia.SkiaPlatform.Initialize(); Xamarin.Forms.Device.PlatformServices = new Xamarin.Forms.Core.UnitTests.MockPlatformServices(); using (var forms = System.IO.File.OpenWrite(File(nameof(Forms)))) new Forms.MathView { LaTeX = "1" }.Painter.DrawAsStream()?.CopyTo(forms); using (var avalonia = System.IO.File.OpenWrite(File(nameof(Avalonia)))) new Avalonia.MathView { LaTeX = "1" }.Painter.DrawAsPng(avalonia); using (var forms = System.IO.File.OpenRead(File(nameof(Forms)))) Xunit.Assert.Contains(new[] { 344, 797 }, forms.Length); // 797 on Mac, 344 on Ubuntu using (var avalonia = System.IO.File.OpenRead(File(nameof(Avalonia)))) Xunit.Assert.Equal(344, avalonia.Length); } } }
Revert the hard coded name check for SBD incremental analyzer as unit test team has moved to IUnitTestingIncrementalAnalyzer
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal static partial class IIncrementalAnalyzerExtensions { public static BackgroundAnalysisScope GetOverriddenBackgroundAnalysisScope(this IIncrementalAnalyzer incrementalAnalyzer, OptionSet options, BackgroundAnalysisScope defaultBackgroundAnalysisScope) { // Unit testing analyzer has special semantics for analysis scope. if (incrementalAnalyzer is UnitTestingIncrementalAnalyzer unitTestingAnalyzer) { return unitTestingAnalyzer.GetBackgroundAnalysisScope(options); } // TODO: Remove the below if statement once SourceBasedTestDiscoveryIncrementalAnalyzer has been switched to UnitTestingIncrementalAnalyzer if (incrementalAnalyzer.GetType().FullName == "Microsoft.CodeAnalysis.UnitTesting.SourceBasedTestDiscovery.SourceBasedTestDiscoveryIncrementalAnalyzer") { return BackgroundAnalysisScope.FullSolution; } return defaultBackgroundAnalysisScope; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal static partial class IIncrementalAnalyzerExtensions { public static BackgroundAnalysisScope GetOverriddenBackgroundAnalysisScope(this IIncrementalAnalyzer incrementalAnalyzer, OptionSet options, BackgroundAnalysisScope defaultBackgroundAnalysisScope) { // Unit testing analyzer has special semantics for analysis scope. if (incrementalAnalyzer is UnitTestingIncrementalAnalyzer unitTestingAnalyzer) { return unitTestingAnalyzer.GetBackgroundAnalysisScope(options); } return defaultBackgroundAnalysisScope; } } }
Update Messages to correct location
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: System.Reflection.AssemblyInformationalVersion("1.2.0.c6b5bf2a")] [assembly: System.Reflection.AssemblyVersion("1.2.0")] [assembly: System.Reflection.AssemblyFileVersion("1.2.0")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: System.Reflection.AssemblyInformationalVersion("1.2.0.5b2eaa85")] [assembly: System.Reflection.AssemblyVersion("1.2.0")] [assembly: System.Reflection.AssemblyFileVersion("1.2.0")]
Fix catch spinners not being allowed for conversion
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Objects.Types; namespace osu.Game.Rulesets.Objects.Legacy.Catch { /// <summary> /// Legacy osu!catch Spinner-type, used for parsing Beatmaps. /// </summary> internal sealed class ConvertSpinner : HitObject, IHasEndTime, IHasCombo { public double EndTime { get; set; } public double Duration => EndTime - StartTime; public bool NewCombo { get; set; } public int ComboOffset { get; set; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Objects.Types; namespace osu.Game.Rulesets.Objects.Legacy.Catch { /// <summary> /// Legacy osu!catch Spinner-type, used for parsing Beatmaps. /// </summary> internal sealed class ConvertSpinner : HitObject, IHasEndTime, IHasXPosition, IHasCombo { public double EndTime { get; set; } public double Duration => EndTime - StartTime; public float X => 256; // Required for CatchBeatmapConverter public bool NewCombo { get; set; } public int ComboOffset { get; set; } } }
Disable unwanted lazy loading during query execution
namespace InfoCarrier.Core.Client.Query.Internal { using System; using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Query.Internal; public class InfoCarrierQueryContext : QueryContext { public InfoCarrierQueryContext( Func<IQueryBuffer> createQueryBuffer, ServerContext serverContext, IStateManager stateManager, IConcurrencyDetector concurrencyDetector) : base( createQueryBuffer, stateManager, concurrencyDetector) { this.ServerContext = serverContext; } public ServerContext ServerContext { get; } } }
namespace InfoCarrier.Core.Client.Query.Internal { using System; using Common; using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Query.Internal; public class InfoCarrierQueryContext : QueryContext { public InfoCarrierQueryContext( Func<IQueryBuffer> createQueryBuffer, ServerContext serverContext, IStateManager stateManager, IConcurrencyDetector concurrencyDetector) : base( createQueryBuffer, stateManager, concurrencyDetector) { this.ServerContext = serverContext; } public ServerContext ServerContext { get; } public override void StartTracking(object entity, EntityTrackingInfo entityTrackingInfo) { using (new PropertyLoadController(this.ServerContext.DataContext, enableLoading: false)) { base.StartTracking(entity, entityTrackingInfo); } } } }
Apply SqliteForeignKeyIndexConvention right after the ForeignKeyIndexConvetion.
using System; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; namespace SQLite.CodeFirst { public abstract class SqliteInitializerBase<TContext> : IDatabaseInitializer<TContext> where TContext : DbContext { protected readonly DbModelBuilder ModelBuilder; protected readonly string DatabaseFilePath; protected SqliteInitializerBase(string connectionString, DbModelBuilder modelBuilder) { DatabaseFilePath = SqliteConnectionStringParser.GetDataSource(connectionString); ModelBuilder = modelBuilder; // This convention will crash the SQLite Provider before "InitializeDatabase" gets called. // See https://github.com/msallin/SQLiteCodeFirst/issues/7 for details. modelBuilder.Conventions.Remove<TimestampAttributeConvention>(); } public virtual void InitializeDatabase(TContext context) { var model = ModelBuilder.Build(context.Database.Connection); using (var transaction = context.Database.BeginTransaction()) { try { var sqliteDatabaseCreator = new SqliteDatabaseCreator(context.Database, model); sqliteDatabaseCreator.Create(); transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } using (var transaction = context.Database.BeginTransaction()) { try { Seed(context); context.SaveChanges(); transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } } protected virtual void Seed(TContext context) { } } }
using System; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using SQLite.CodeFirst.Convention; namespace SQLite.CodeFirst { public abstract class SqliteInitializerBase<TContext> : IDatabaseInitializer<TContext> where TContext : DbContext { protected readonly DbModelBuilder ModelBuilder; protected readonly string DatabaseFilePath; protected SqliteInitializerBase(string connectionString, DbModelBuilder modelBuilder) { DatabaseFilePath = SqliteConnectionStringParser.GetDataSource(connectionString); ModelBuilder = modelBuilder; // This convention will crash the SQLite Provider before "InitializeDatabase" gets called. // See https://github.com/msallin/SQLiteCodeFirst/issues/7 for details. modelBuilder.Conventions.Remove<TimestampAttributeConvention>(); modelBuilder.Conventions.AddAfter<ForeignKeyIndexConvention>(new SqliteForeignKeyIndexConvention()); } public virtual void InitializeDatabase(TContext context) { var model = ModelBuilder.Build(context.Database.Connection); using (var transaction = context.Database.BeginTransaction()) { try { var sqliteDatabaseCreator = new SqliteDatabaseCreator(context.Database, model); sqliteDatabaseCreator.Create(); transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } using (var transaction = context.Database.BeginTransaction()) { try { Seed(context); context.SaveChanges(); transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } } protected virtual void Seed(TContext context) { } } }
Fix incorrect project file type description
using JetBrains.Annotations; using JetBrains.ProjectModel; using JetBrains.ReSharper.Plugins.Unity.UnityEditorIntegration; using JetBrains.ReSharper.Plugins.Yaml.ProjectModel; #nullable enable namespace JetBrains.ReSharper.Plugins.Unity.Yaml.ProjectModel { [ProjectFileTypeDefinition(Name)] public class MetaProjectFileType : YamlProjectFileType { public new const string Name = "Meta"; [UsedImplicitly] public new static MetaProjectFileType? Instance { get; private set; } public MetaProjectFileType() : base(Name, "Unity Yaml", new[] { UnityFileExtensions.MetaFileExtensionWithDot }) { } } }
using JetBrains.Annotations; using JetBrains.ProjectModel; using JetBrains.ReSharper.Plugins.Unity.UnityEditorIntegration; using JetBrains.ReSharper.Plugins.Yaml.ProjectModel; #nullable enable namespace JetBrains.ReSharper.Plugins.Unity.Yaml.ProjectModel { [ProjectFileTypeDefinition(Name)] public class MetaProjectFileType : YamlProjectFileType { public new const string Name = "Meta"; [UsedImplicitly] public new static MetaProjectFileType? Instance { get; private set; } public MetaProjectFileType() : base(Name, "Unity Meta File", new[] { UnityFileExtensions.MetaFileExtensionWithDot }) { } } }
Fix a typo in a view
using BroadbandSpeedStats.Database.Schema; using FluentMigrator; namespace BroadbandSpeedTests.Database.Migrations.Migrations { [Migration(20170228)] public class TodaysTestResultsView : Migration { public override void Up() { Execute.Sql($@" CREATE VIEW [{Views.TodaysTestResults.Name}] WITH SCHEMABINDING AS SELECT TOP 100 PERCENT [{Views.TodaysTestResults.Columns.Id}], [{Views.TodaysTestResults.Columns.Timestamp}], [{Views.TodaysTestResults.Columns.PingTime}], [{Views.TodaysTestResults.Columns.DownloadSpeed}], [{Views.TodaysTestResults.Columns.UploadSpeed}] FROM [dbo].[{Views.TodaysTestResults.SourceTable}] WHERE WHERE DATEDIFF(d, {Views.TodaysTestResults.Columns.Timestamp}, GETUTCDATE()) = 0 ORDER BY [{Views.TodaysTestResults.Columns.Timestamp}] DESC GO"); } public override void Down() { Execute.Sql($"DROP VIEW [{Views.TodaysTestResults.Name}]"); } } }
using BroadbandSpeedStats.Database.Schema; using FluentMigrator; namespace BroadbandSpeedTests.Database.Migrations.Migrations { [Migration(20170228)] public class TodaysTestResultsView : Migration { public override void Up() { Execute.Sql($@" CREATE VIEW [{Views.TodaysTestResults.Name}] WITH SCHEMABINDING AS SELECT TOP 100 PERCENT [{Views.TodaysTestResults.Columns.Id}], [{Views.TodaysTestResults.Columns.Timestamp}], [{Views.TodaysTestResults.Columns.PingTime}], [{Views.TodaysTestResults.Columns.DownloadSpeed}], [{Views.TodaysTestResults.Columns.UploadSpeed}] FROM [dbo].[{Views.TodaysTestResults.SourceTable}] WHERE DATEDIFF(d, {Views.TodaysTestResults.Columns.Timestamp}, GETUTCDATE()) = 0 ORDER BY [{Views.TodaysTestResults.Columns.Timestamp}] DESC GO"); } public override void Down() { Execute.Sql($"DROP VIEW [{Views.TodaysTestResults.Name}]"); } } }
Use local bound copy for `HiddenIssueTypes`
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Overlays; using osu.Game.Overlays.Settings; using osu.Game.Rulesets.Edit.Checks.Components; namespace osu.Game.Screens.Edit.Verify { internal class VisibilitySection : EditorRoundedScreenSettingsSection { [Resolved] private VerifyScreen verify { get; set; } private readonly IssueType[] configurableIssueTypes = { IssueType.Warning, IssueType.Error, IssueType.Negligible }; protected override string Header => "Visibility"; [BackgroundDependencyLoader] private void load(OverlayColourProvider colours) { foreach (IssueType issueType in configurableIssueTypes) { var checkbox = new SettingsCheckbox { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, LabelText = issueType.ToString() }; checkbox.Current.Default = !verify.HiddenIssueTypes.Contains(issueType); checkbox.Current.SetDefault(); checkbox.Current.BindValueChanged(state => { if (!state.NewValue) verify.HiddenIssueTypes.Add(issueType); else verify.HiddenIssueTypes.Remove(issueType); }); Flow.Add(checkbox); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Overlays; using osu.Game.Overlays.Settings; using osu.Game.Rulesets.Edit.Checks.Components; namespace osu.Game.Screens.Edit.Verify { internal class VisibilitySection : EditorRoundedScreenSettingsSection { [Resolved] private VerifyScreen verify { get; set; } private readonly IssueType[] configurableIssueTypes = { IssueType.Warning, IssueType.Error, IssueType.Negligible }; protected override string Header => "Visibility"; [BackgroundDependencyLoader] private void load(OverlayColourProvider colours) { var hiddenIssueTypes = verify.HiddenIssueTypes.GetBoundCopy(); foreach (IssueType issueType in configurableIssueTypes) { var checkbox = new SettingsCheckbox { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, LabelText = issueType.ToString() }; checkbox.Current.Default = !hiddenIssueTypes.Contains(issueType); checkbox.Current.SetDefault(); checkbox.Current.BindValueChanged(state => { if (!state.NewValue) hiddenIssueTypes.Add(issueType); else hiddenIssueTypes.Remove(issueType); }); Flow.Add(checkbox); } } } }
Revert "Added method to perform validity check for effect parameters"
namespace SoxSharp.Effects { public interface IBaseEffect { string Name { get; } bool IsValid(); string ToString(); } }
namespace SoxSharp.Effects { public interface IBaseEffect { string Name { get; } string ToString(); } }
Refactor plays/retries counting using osu events
using StreamCompanionTypes.DataTypes; using StreamCompanionTypes.Enums; using StreamCompanionTypes.Interfaces; using StreamCompanionTypes.Interfaces.Sources; namespace PlaysReplacements { public class PlaysReplacements : IPlugin, ITokensSource { private int Plays, Retrys; private Tokens.TokenSetter _tokenSetter; private string lastMapSearchString = ""; public string Description { get; } = ""; public string Name { get; } = nameof(PlaysReplacements); public string Author { get; } = "Piotrekol"; public string Url { get; } = ""; public string UpdateUrl { get; } = ""; public PlaysReplacements() { _tokenSetter = Tokens.CreateTokenSetter(Name); } public void CreateTokens(MapSearchResult map) { if (map.Action == OsuStatus.Playing) { if (lastMapSearchString == map.MapSearchString) Retrys++; else Plays++; lastMapSearchString = map.MapSearchString; } _tokenSetter("plays", Plays); _tokenSetter("retrys", Retrys); } } }
using StreamCompanionTypes.DataTypes; using StreamCompanionTypes.Enums; using StreamCompanionTypes.Interfaces; using StreamCompanionTypes.Interfaces.Sources; namespace PlaysReplacements { public class PlaysReplacements : IPlugin, ITokensSource { private int Plays, Retrys; private Tokens.TokenSetter _tokenSetter; public string Description { get; } = ""; public string Name { get; } = nameof(PlaysReplacements); public string Author { get; } = "Piotrekol"; public string Url { get; } = ""; public string UpdateUrl { get; } = ""; public PlaysReplacements() { _tokenSetter = Tokens.CreateTokenSetter(Name); UpdateTokens(); } public void CreateTokens(MapSearchResult map) { //ignore replays/spect if (map.Action != OsuStatus.Playing) return; switch (map.SearchArgs.EventType) { case OsuEventType.SceneChange: case OsuEventType.MapChange: Plays++; break; case OsuEventType.PlayChange: Retrys++; break; } UpdateTokens(); } private void UpdateTokens() { _tokenSetter("plays", Plays); _tokenSetter("retrys", Retrys); } } }
Clear all transforms of catcher trail sprite before returned to pool
// 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.Graphics; using osu.Framework.Graphics.Pooling; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osuTK; namespace osu.Game.Rulesets.Catch.UI { public class CatcherTrailSprite : PoolableDrawable { public Texture Texture { set => sprite.Texture = value; } private readonly Sprite sprite; public CatcherTrailSprite() { InternalChild = sprite = new Sprite { RelativeSizeAxes = Axes.Both }; Size = new Vector2(CatcherArea.CATCHER_SIZE); // Sets the origin roughly to the centre of the catcher's plate to allow for correct scaling. OriginPosition = new Vector2(0.5f, 0.06f) * CatcherArea.CATCHER_SIZE; } } }
// 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.Graphics; using osu.Framework.Graphics.Pooling; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osuTK; namespace osu.Game.Rulesets.Catch.UI { public class CatcherTrailSprite : PoolableDrawable { public Texture Texture { set => sprite.Texture = value; } private readonly Sprite sprite; public CatcherTrailSprite() { InternalChild = sprite = new Sprite { RelativeSizeAxes = Axes.Both }; Size = new Vector2(CatcherArea.CATCHER_SIZE); // Sets the origin roughly to the centre of the catcher's plate to allow for correct scaling. OriginPosition = new Vector2(0.5f, 0.06f) * CatcherArea.CATCHER_SIZE; } protected override void FreeAfterUse() { ClearTransforms(); base.FreeAfterUse(); } } }
Remove test on argument null exception message
using System; using FluentAssertions; using Microsoft.Practices.Unity; using Unity.Interception.Serilog.Tests.Support; using Xunit; namespace Unity.Interception.Serilog.Tests { public class NullTests { [Fact] public void NullMembersShouldThrow() { var container = new UnityContainer(); Action[] actions = { () => container.RegisterLoggedType<IDummy, Dummy>((InjectionMember[])null), () => container.RegisterLoggedType<IDummy, Dummy>("", (InjectionMember[])null), () => container.RegisterLoggedType<IDummy, Dummy>(new ContainerControlledLifetimeManager(), null), () => container.RegisterLoggedType<IDummy, Dummy>("", new ContainerControlledLifetimeManager(), null) }; foreach (var action in actions) { action.ShouldThrow<ArgumentNullException>().WithMessage("Value cannot be null.\nParameter name: first"); } } [Fact] public void NullContainerShouldThrow() { Action[] actions = { () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null), () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, ""), () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, new ContainerControlledLifetimeManager()), () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, "", new ContainerControlledLifetimeManager()) }; foreach (var action in actions) { action.ShouldThrow<ArgumentNullException>().WithMessage("Value cannot be null.\nParameter name: container"); } } } }
using System; using FluentAssertions; using Microsoft.Practices.Unity; using Unity.Interception.Serilog.Tests.Support; using Xunit; namespace Unity.Interception.Serilog.Tests { public class NullTests { [Fact] public void NullMembersShouldThrow() { var container = new UnityContainer(); Action[] actions = { () => container.RegisterLoggedType<IDummy, Dummy>((InjectionMember[])null), () => container.RegisterLoggedType<IDummy, Dummy>("", (InjectionMember[])null), () => container.RegisterLoggedType<IDummy, Dummy>(new ContainerControlledLifetimeManager(), null), () => container.RegisterLoggedType<IDummy, Dummy>("", new ContainerControlledLifetimeManager(), null) }; foreach (var action in actions) { action.ShouldThrow<ArgumentNullException>(); } } [Fact] public void NullContainerShouldThrow() { Action[] actions = { () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null), () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, ""), () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, new ContainerControlledLifetimeManager()), () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, "", new ContainerControlledLifetimeManager()) }; foreach (var action in actions) { action.ShouldThrow<ArgumentNullException>(); } } } }
Add option to install command
namespace SIM.Client.Commands { using CommandLine; using JetBrains.Annotations; using SIM.Core.Commands; public class InstallCommandFacade : InstallCommand { [UsedImplicitly] public InstallCommandFacade() { } [Option('n', "name", Required = true)] public override string Name { get; set; } [Option('s', "sqlPrefix", HelpText = "Logical names prefix of SQL databases, by default equals to instance name")] public override string SqlPrefix { get; set; } [Option('p', "product")] public override string Product { get; set; } [Option('v', "version")] public override string Version { get; set; } [Option('r', "revision")] public override string Revision { get; set; } [Option('a', "attach", HelpText = "Attach SQL databases, or just update ConnectionStrings.config", DefaultValue = AttachDatabasesDefault)] public override bool? AttachDatabases { get; set; } } }
namespace SIM.Client.Commands { using CommandLine; using JetBrains.Annotations; using SIM.Core.Commands; public class InstallCommandFacade : InstallCommand { [UsedImplicitly] public InstallCommandFacade() { } [Option('n', "name", Required = true)] public override string Name { get; set; } [Option('s', "sqlPrefix", HelpText = "Logical names prefix of SQL databases, by default equals to instance name")] public override string SqlPrefix { get; set; } [Option('p', "product")] public override string Product { get; set; } [Option('v', "version")] public override string Version { get; set; } [Option('r', "revision")] public override string Revision { get; set; } [Option('a', "attach", HelpText = "Attach SQL databases, or just update ConnectionStrings.config", DefaultValue = AttachDatabasesDefault)] public override bool? AttachDatabases { get; set; } [Option('u', "skipUnnecessaryFiles", HelpText = "Skip unnecessary files to speed up installation", DefaultValue = AttachDatabasesDefault)] public override bool? SkipUnnecessaryFiles { get; set; } } }
Add Nesting ServiceCollection Extension method overloads
using Microsoft.Extensions.DependencyInjection; using System; namespace THNETII.DependencyInjection.Nesting { public static class NestedServicesServiceCollectionExtensions { public static IServiceCollection AddNestedServices( this IServiceCollection rootServices, string key, Action<INestedServiceCollection> configureServices) { throw new NotImplementedException(); return rootServices; } } }
using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; namespace THNETII.DependencyInjection.Nesting { public static class NestedServicesServiceCollectionExtensions { public static IServiceCollection AddNestedServices( this IServiceCollection rootServices, string key, Action<INestedServiceCollection> configureServices) { return AddNestedServices<string>( rootServices, key, StringComparer.OrdinalIgnoreCase, configureServices ); } public static IServiceCollection AddNestedServices<T>( this IServiceCollection rootServices, string key, Action<INestedServiceCollection> configureServices) => AddNestedServices<T>(rootServices, key, StringComparer.OrdinalIgnoreCase, configureServices); public static IServiceCollection AddNestedServices<T>( this IServiceCollection rootServices, string key, IEqualityComparer<string> keyComparer, Action<INestedServiceCollection> configureServices) { throw new NotImplementedException(); return rootServices; } } }
Add Int.To(Int) Method, which allow to generate a sequence between two numbers.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ext.NET { class IntegerExtension { public static void Times(this int n, Action<int> action) { for (int i = 0; i < n; ++i) { action(i); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ext.NET { class IntegerExtension { public static void Times(this int n, Action<int> action) { for (int i = 0; i < n; ++i) { action(i); } } public static IEnumerable<int> To(this int n, int to) { if (n == to) { yield return n; } else if (to > n) { for (int i = n; i < to; ++i) yield return i; } else { for (int i = n; i > to; --i) yield return i; } } } }
Copy Updates Other Copy elements of the Same Type on the Same Page When Saving
@model Portal.CMS.Entities.Entities.Copy.Copy @using Portal.CMS.Web.Areas.Admin.Helpers; @{ Layout = ""; var isAdmin = UserHelper.IsAdmin; } <script type="text/javascript"> $(document).ready(function () { tinymce.init({ selector: '#copy-@(Model.CopyId).admin', inline: true, plugins: ['advlist autolink lists link image charmap anchor searchreplace visualblocks code fullscreen media table contextmenu paste'], toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image', setup:function(ed) { ed.on('change', function(e) { var dataParams = { "copyId": @Model.CopyId, "copyName": "@Model.CopyName", "copyBody": ed.getContent() }; $.ajax({data: dataParams, type: 'POST', cache: false, url: '/Admin/Copy/Inline'}); }); } }); }); </script> <div class="copy-wrapper"> @if (isAdmin) { <div class="box-title">@Model.CopyName</div> } <div id="copy-@Model.CopyId" class="@(UserHelper.IsAdmin ? "admin" : "") copy-block"> @Html.Raw(Model.CopyBody) </div> </div>
@model Portal.CMS.Entities.Entities.Copy.Copy @using Portal.CMS.Web.Areas.Admin.Helpers; @{ Layout = ""; var isAdmin = UserHelper.IsAdmin; } <script type="text/javascript"> $(document).ready(function () { tinymce.init({ selector: '.copy-@(Model.CopyId).admin', inline: true, plugins: ['advlist autolink lists link image charmap anchor searchreplace visualblocks code fullscreen media table contextmenu paste'], toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image', setup:function(ed) { ed.on('change', function(e) { var dataParams = { "copyId": @Model.CopyId, "copyName": "@Model.CopyName", "copyBody": ed.getContent() }; $.ajax({data: dataParams, type: 'POST', cache: false, url: '/Admin/Copy/Inline'}); $('.copy-@(Model.CopyId)').html(ed.getContent()); }); } }); }); </script> <div class="copy-wrapper"> @if (isAdmin) { <div class="box-title">@Model.CopyName</div> } <div class="@(UserHelper.IsAdmin ? "admin" : "") copy-@Model.CopyId copy-block"> @Html.Raw(Model.CopyBody) </div> </div>
Fix output path for nuget package.
#tool "nuget:?package=xunit.runner.console" var target = Argument("target", "Default"); var outputDir = "./bin"; Task("Default") .IsDependentOn("Xunit") .Does(() => { }); Task("Xunit") .IsDependentOn("Build") .Does(()=> { DotNetCoreTest("./src/FibonacciHeap.Tests/FibonacciHeap.Tests.csproj"); }); Task("Build") .IsDependentOn("NugetRestore") .Does(()=> { DotNetCoreMSBuild("FibonacciHeap.sln"); }); Task("NugetRestore") .IsDependentOn("Clean") .Does(()=> { DotNetCoreRestore(); }); Task("NugetPack") .IsDependentOn("Build") .Does(()=> { var settings = new DotNetCorePackSettings { Configuration = "Release", OutputDirectory = "../../nupkgs" }; DotNetCorePack("src/FibonacciHeap", settings); }); Task("Clean") .Does(()=> { CleanDirectories("**/bin/**"); CleanDirectories("**/obj/**"); CleanDirectories("nupkgs"); }); RunTarget(target);
#tool "nuget:?package=xunit.runner.console" var target = Argument("target", "Default"); var outputDir = "./bin"; Task("Default") .IsDependentOn("Xunit") .Does(() => { }); Task("Xunit") .IsDependentOn("Build") .Does(()=> { DotNetCoreTest("./src/FibonacciHeap.Tests/FibonacciHeap.Tests.csproj"); }); Task("Build") .IsDependentOn("NugetRestore") .Does(()=> { DotNetCoreMSBuild("FibonacciHeap.sln"); }); Task("NugetRestore") .IsDependentOn("Clean") .Does(()=> { DotNetCoreRestore(); }); Task("NugetPack") .IsDependentOn("Clean") .Does(()=> { var settings = new DotNetCorePackSettings { Configuration = "Release", OutputDirectory = "nupkgs" }; DotNetCorePack("src/FibonacciHeap", settings); }); Task("Clean") .Does(()=> { CleanDirectories("**/bin/**"); CleanDirectories("**/obj/**"); CleanDirectories("nupkgs"); }); RunTarget(target);
Change extension method default parameters to use constants
using Serilog.Configuration; using Serilog.Core; using Serilog.Events; using Serilog.Sinks.Graylog.Helpers; using Serilog.Sinks.Graylog.Transport; namespace Serilog.Sinks.Graylog { public static class LoggerConfigurationGrayLogExtensions { public static LoggerConfiguration Graylog(this LoggerSinkConfiguration loggerSinkConfiguration, GraylogSinkOptions options) { var sink = (ILogEventSink) new GraylogSink(options); return loggerSinkConfiguration.Sink(sink, options.MinimumLogEventLevel); } public static LoggerConfiguration Graylog(this LoggerSinkConfiguration loggerSinkConfiguration, string hostnameOrAddress, int port, TransportType transportType, LogEventLevel minimumLogEventLevel = LevelAlias.Minimum, MessageIdGeneratortype messageIdGeneratorType = GraylogSinkOptions.DefaultMessageGeneratorType, int shortMessageMaxLength = 500, int stackTraceDepth = 10, string facility = GraylogSinkOptions.DefaultFacility ) { var options = new GraylogSinkOptions { HostnameOrAdress = hostnameOrAddress, Port = port, TransportType = transportType, MinimumLogEventLevel = minimumLogEventLevel, MessageGeneratorType = messageIdGeneratorType, ShortMessageMaxLength = shortMessageMaxLength, StackTraceDepth = stackTraceDepth, Facility = facility }; return loggerSinkConfiguration.Graylog(options); } } }
using Serilog.Configuration; using Serilog.Core; using Serilog.Events; using Serilog.Sinks.Graylog.Helpers; using Serilog.Sinks.Graylog.Transport; namespace Serilog.Sinks.Graylog { public static class LoggerConfigurationGrayLogExtensions { public static LoggerConfiguration Graylog(this LoggerSinkConfiguration loggerSinkConfiguration, GraylogSinkOptions options) { var sink = (ILogEventSink) new GraylogSink(options); return loggerSinkConfiguration.Sink(sink, options.MinimumLogEventLevel); } public static LoggerConfiguration Graylog(this LoggerSinkConfiguration loggerSinkConfiguration, string hostnameOrAddress, int port, TransportType transportType, LogEventLevel minimumLogEventLevel = LevelAlias.Minimum, MessageIdGeneratortype messageIdGeneratorType = GraylogSinkOptions.DefaultMessageGeneratorType, int shortMessageMaxLength = GraylogSinkOptions.DefaultShortMessageMaxLength, int stackTraceDepth = GraylogSinkOptions.DefaultStackTraceDepth, string facility = GraylogSinkOptions.DefaultFacility ) { var options = new GraylogSinkOptions { HostnameOrAdress = hostnameOrAddress, Port = port, TransportType = transportType, MinimumLogEventLevel = minimumLogEventLevel, MessageGeneratorType = messageIdGeneratorType, ShortMessageMaxLength = shortMessageMaxLength, StackTraceDepth = stackTraceDepth, Facility = facility }; return loggerSinkConfiguration.Graylog(options); } } }
Optimize away empty string literals.
using Veil.Parser; namespace Veil.Compiler { internal partial class VeilTemplateCompiler<T> { private void EmitWriteLiteral(SyntaxTreeNode.WriteLiteralNode node) { LoadWriterToStack(); emitter.LoadConstant(node.LiteralContent); CallWriteFor(typeof(string)); } } }
using Veil.Parser; namespace Veil.Compiler { internal partial class VeilTemplateCompiler<T> { private void EmitWriteLiteral(SyntaxTreeNode.WriteLiteralNode node) { if (string.IsNullOrEmpty(node.LiteralContent)) return; LoadWriterToStack(); emitter.LoadConstant(node.LiteralContent); CallWriteFor(typeof(string)); } } }
Add ability to enter commands
using ArduinoWindowsRemoteControl.Helpers; using ArduinoWindowsRemoteControl.Interfaces; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ArduinoWindowsRemoteControl.UI { public partial class EditCommandForm : Form { private List<int> _pressedButtons = new List<int>(); public EditCommandForm() { InitializeComponent(); cbRemoteCommand.Items.AddRange(EnumHelpers.GetAvailableEnumValues<RemoteCommand>().ToArray()); } private void btCancel_Click(object sender, EventArgs e) { Close(); } private void tbCommand_KeyDown(object sender, KeyEventArgs e) { if (!_pressedButtons.Contains(e.KeyValue)) { tbCommand.Text += WinAPIHelpers.GetKeyStringForVirtualCode((byte)e.KeyValue); _pressedButtons.Add(e.KeyValue); } e.Handled = true; } private void tbCommand_KeyUp(object sender, KeyEventArgs e) { _pressedButtons.Remove(e.KeyValue); e.Handled = true; } private void tbCommand_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = true; } } }
using ArduinoWindowsRemoteControl.Helpers; using ArduinoWindowsRemoteControl.Interfaces; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ArduinoWindowsRemoteControl.UI { public partial class EditCommandForm : Form { private List<int> _pressedButtons = new List<int>(); private bool _isKeyStrokeEnabled = false; public EditCommandForm() { InitializeComponent(); cbRemoteCommand.Items.AddRange(EnumHelpers.GetAvailableEnumValues<RemoteCommand>().ToArray()); } private void btCancel_Click(object sender, EventArgs e) { Close(); } private void tbCommand_KeyDown(object sender, KeyEventArgs e) { if (!_pressedButtons.Contains(e.KeyValue)) { //key command ended, start new one if (_pressedButtons.Count == 0) { _isKeyStrokeEnabled = false; } if (_isKeyStrokeEnabled) { tbCommand.Text += "-"; } else { if (tbCommand.Text.Length > 0) tbCommand.Text += ","; } tbCommand.Text += WinAPIHelpers.GetKeyStringForVirtualCode((byte)e.KeyValue); tbCommand.SelectionStart = tbCommand.Text.Length; _pressedButtons.Add(e.KeyValue); } else { if (_pressedButtons.Last() == e.KeyValue) { _isKeyStrokeEnabled = true; } } e.Handled = true; } private void tbCommand_KeyUp(object sender, KeyEventArgs e) { _pressedButtons.Remove(e.KeyValue); e.Handled = true; } private void tbCommand_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = true; } } }
Make one of two red tests green by implementing basic support for the Values-method with Id-Property.
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Linq.Expressions; namespace ExRam.Gremlinq { public sealed class ValuesGremlinStep<TSource, TTarget> : NonTerminalGremlinStep { private readonly Expression<Func<TSource, TTarget>>[] _projections; public ValuesGremlinStep(Expression<Func<TSource, TTarget>>[] projections) { this._projections = projections; } public override IEnumerable<TerminalGremlinStep> Resolve(IGraphModel model) { yield return new TerminalGremlinStep( "values", this._projections .Select(projection => { if (projection.Body is MemberExpression memberExpression) return model.GetIdentifier(memberExpression.Member.Name); throw new NotSupportedException(); }) .ToImmutableList()); } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Linq.Expressions; namespace ExRam.Gremlinq { public sealed class ValuesGremlinStep<TSource, TTarget> : NonTerminalGremlinStep { private readonly Expression<Func<TSource, TTarget>>[] _projections; public ValuesGremlinStep(Expression<Func<TSource, TTarget>>[] projections) { this._projections = projections; } public override IEnumerable<TerminalGremlinStep> Resolve(IGraphModel model) { var keys = this._projections .Select(projection => { if (projection.Body is MemberExpression memberExpression) return model.GetIdentifier(memberExpression.Member.Name); throw new NotSupportedException(); }) .ToArray(); var numberOfIdSteps = keys .OfType<T>() .Count(x => x == T.Id); var propertyKeys = keys .OfType<string>() .Cast<object>() .ToArray(); if (numberOfIdSteps > 1 || (numberOfIdSteps > 0 && propertyKeys.Length > 0)) throw new NotSupportedException(); if (numberOfIdSteps > 0) yield return new TerminalGremlinStep("id"); else { yield return new TerminalGremlinStep( "values", propertyKeys .ToImmutableList()); } } } }
Make it configurable if high or low throws.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IPOCS_Programmer.ObjectTypes { public class PointsMotor_Pulse : PointsMotor { public override byte motorTypeId { get { return 1; } } public byte ThrowLeftOutput { get; set; } public byte ThrowRightOutput { get; set; } public byte positionPin { get; set; } public bool reverseStatus { get; set; } public override List<byte> Serialize() { var vector = new List<byte>(); vector.Add(motorTypeId); vector.Add(this.ThrowLeftOutput); vector.Add(this.ThrowRightOutput); vector.Add(positionPin); vector.Add((byte)(reverseStatus ? 1 : 0)); return vector; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IPOCS_Programmer.ObjectTypes { public class PointsMotor_Pulse : PointsMotor { public override byte motorTypeId { get { return 1; } } public byte ThrowLeftOutput { get; set; } public byte ThrowRightOutput { get; set; } public byte positionPin { get; set; } public bool reverseStatus { get; set; } public bool lowToThrow { get; set; } public override List<byte> Serialize() { var vector = new List<byte>(); vector.Add(motorTypeId); vector.Add(this.ThrowLeftOutput); vector.Add(this.ThrowRightOutput); vector.Add(positionPin); vector.Add((byte)(reverseStatus ? 1 : 0)); vector.Add((byte)(lowToThrow ? 1 : 0)); return vector; } } }
Fix status text not updating upon reset
using UnityEngine; using UnityEngine.UI; /// <summary> /// Attach this to the status text game object /// </summary> public class StatusText : MonoBehaviour { Text text; GlobalGame game; public GlobalGame Game { get { return game; } set { if (game != null) { game.WinnerChanged -= HandleGameStateChanged; game.TurnChanged -= HandleGameStateChanged; } game = value; game.WinnerChanged += HandleGameStateChanged; game.TurnChanged += HandleGameStateChanged; } } private void Start() { text = GetComponent<Text>(); if (game != null) { HandleGameStateChanged(null, null); } } public void HandleGameStateChanged(object o, GameEventArgs e) { if (game.GameOver()) { if (game.Winner != null) { text.text = game.Winner.Name + " wins!"; return; } text.text = "Tie game"; return; } text.text = game.ActivePlayer().Name + "'s turn"; } }
using UnityEngine; using UnityEngine.UI; /// <summary> /// Attach this to the status text game object /// </summary> public class StatusText : MonoBehaviour { Text text; GlobalGame game; public GlobalGame Game { get { return game; } set { if (game != null) { game.WinnerChanged -= HandleGameStateChanged; game.TurnChanged -= HandleGameStateChanged; } game = value; if (game != null) { game.WinnerChanged += HandleGameStateChanged; game.TurnChanged += HandleGameStateChanged; } UpdateState(); } } void UpdateState() { HandleGameStateChanged(game, null); } private void Start() { text = GetComponent<Text>(); UpdateState(); } public void HandleGameStateChanged(object o, GameEventArgs e) { if (game == null) { text.text = ""; return; } if (game.GameOver()) { if (game.Winner != null) { text.text = game.Winner.Name + " wins!"; return; } text.text = "Tie game"; return; } text.text = game.ActivePlayer().Name + "'s turn"; } }
Fix null error on status text initialization
using UnityEngine; using UnityEngine.UI; /// <summary> /// Attach this to the status text game object /// </summary> public class StatusText : MonoBehaviour { Text text; GlobalGame game; public GlobalGame Game { get { return game; } set { if (game != null) { game.WinnerChanged -= HandleGameStateChanged; game.TurnChanged -= HandleGameStateChanged; } game = value; if (game != null) { game.WinnerChanged += HandleGameStateChanged; game.TurnChanged += HandleGameStateChanged; } UpdateState(); } } void UpdateState() { HandleGameStateChanged(game, null); } private void Start() { text = GetComponent<Text>(); UpdateState(); } public void HandleGameStateChanged(object o, GameEventArgs e) { if (game == null) { text.text = ""; return; } if (game.GameOver()) { if (game.Winner != null) { text.text = game.Winner.Name + " wins!"; return; } text.text = "Tie game"; return; } text.text = game.ActivePlayer().Name + "'s turn"; } }
using UnityEngine; using UnityEngine.UI; /// <summary> /// Attach this to the status text game object /// </summary> public class StatusText : MonoBehaviour { GlobalGame game; public GlobalGame Game { get { return game; } set { if (game != null) { game.WinnerChanged -= HandleGameStateChanged; game.TurnChanged -= HandleGameStateChanged; } game = value; if (game != null) { game.WinnerChanged += HandleGameStateChanged; game.TurnChanged += HandleGameStateChanged; } UpdateState(); } } void UpdateState() { HandleGameStateChanged(game, null); } private void Awake() { UpdateState(); } public void HandleGameStateChanged(object o, GameEventArgs e) { Text text = GetComponent<Text>(); if (game == null) { text.text = ""; return; } if (game.GameOver()) { if (game.Winner != null) { text.text = game.Winner.Name + " wins!"; return; } text.text = "Tie game"; return; } text.text = game.ActivePlayer().Name + "'s turn"; } }
Add service alert for app update notice
using System; using System.Linq; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using CorvallisBus.Core.Models; using HtmlAgilityPack; namespace CorvallisBus.Core.WebClients { public static class ServiceAlertsClient { static readonly Uri FEED_URL = new Uri("https://www.corvallisoregon.gov/news?field_microsite_tid=581"); static readonly HttpClient httpClient = new HttpClient(); public static async Task<List<ServiceAlert>> GetServiceAlerts() { var responseStream = await httpClient.GetStreamAsync(FEED_URL); var htmlDocument = new HtmlDocument(); htmlDocument.Load(responseStream); var alerts = htmlDocument.DocumentNode.SelectNodes("//tbody/tr") .Select(row => ParseRow(row)) .ToList(); return alerts; } private static ServiceAlert ParseRow(HtmlNode row) { var anchor = row.Descendants("a").First(); var relativeLink = anchor.Attributes["href"].Value; var link = new Uri(FEED_URL, relativeLink).ToString(); var title = anchor.InnerText; var publishDate = row.Descendants("span") .First(node => node.HasClass("date-display-single")) .Attributes["content"] .Value; return new ServiceAlert(title, publishDate, link); } } }
using System; using System.Linq; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using CorvallisBus.Core.Models; using HtmlAgilityPack; namespace CorvallisBus.Core.WebClients { public static class ServiceAlertsClient { static readonly Uri FEED_URL = new Uri("https://www.corvallisoregon.gov/news?field_microsite_tid=581"); static readonly HttpClient httpClient = new HttpClient(); public static async Task<List<ServiceAlert>> GetServiceAlerts() { var responseStream = await httpClient.GetStreamAsync(FEED_URL); var htmlDocument = new HtmlDocument(); htmlDocument.Load(responseStream); var alerts = htmlDocument.DocumentNode.SelectNodes("//tbody/tr") .Select(row => ParseRow(row)) .ToList(); alerts.Insert(0, new ServiceAlert( title: "App Update for Upcoming CTS Schedule", publishDate: "2019-09-09T00:00:00-07:00", link: "https://rikkigibson.github.io/corvallisbus")); return alerts; } private static ServiceAlert ParseRow(HtmlNode row) { var anchor = row.Descendants("a").First(); var relativeLink = anchor.Attributes["href"].Value; var link = new Uri(FEED_URL, relativeLink).ToString(); var title = anchor.InnerText; var publishDate = row.Descendants("span") .First(node => node.HasClass("date-display-single")) .Attributes["content"] .Value; return new ServiceAlert(title, publishDate, link); } } }
Fix NaN floating point comparison
using System; using DesktopWidgets.Properties; namespace DesktopWidgets.Helpers { public static class DoubleHelper { public static bool IsEqual(this double val1, double val2) => double.IsNaN(val1) || double.IsNaN(val1) || (Math.Abs(val1 - val2) > Settings.Default.DoubleComparisonTolerance); } }
using System; using DesktopWidgets.Properties; namespace DesktopWidgets.Helpers { public static class DoubleHelper { public static bool IsEqual(this double val1, double val2) => double.IsNaN(val1) || double.IsNaN(val2) || (Math.Abs(val1 - val2) > Settings.Default.DoubleComparisonTolerance); } }
Tweak key format in analytics request
using System.Collections; using System.Collections.Specialized; using System.Text; namespace TweetDuck.Core.Other.Analytics{ sealed class AnalyticsReport : IEnumerable{ private OrderedDictionary data = new OrderedDictionary(32); private int separators; public void Add(int ignored){ // adding separators to pretty print data.Add((++separators).ToString(), null); } public void Add(string key, string value){ data.Add(key, value); } public AnalyticsReport FinalizeReport(){ if (!data.IsReadOnly){ data = data.AsReadOnly(); } return this; } public IEnumerator GetEnumerator(){ return data.GetEnumerator(); } public NameValueCollection ToNameValueCollection(){ NameValueCollection collection = new NameValueCollection(); foreach(DictionaryEntry entry in data){ if (entry.Value != null){ collection.Add((string)entry.Key, (string)entry.Value); } } return collection; } public override string ToString(){ StringBuilder build = new StringBuilder(); foreach(DictionaryEntry entry in data){ if (entry.Value == null){ build.AppendLine(); } else{ build.AppendLine(entry.Key+": "+entry.Value); } } return build.ToString(); } } }
using System.Collections; using System.Collections.Specialized; using System.Text; namespace TweetDuck.Core.Other.Analytics{ sealed class AnalyticsReport : IEnumerable{ private OrderedDictionary data = new OrderedDictionary(32); private int separators; public void Add(int ignored){ // adding separators to pretty print data.Add((++separators).ToString(), null); } public void Add(string key, string value){ data.Add(key, value); } public AnalyticsReport FinalizeReport(){ if (!data.IsReadOnly){ data = data.AsReadOnly(); } return this; } public IEnumerator GetEnumerator(){ return data.GetEnumerator(); } public NameValueCollection ToNameValueCollection(){ NameValueCollection collection = new NameValueCollection(); foreach(DictionaryEntry entry in data){ if (entry.Value != null){ collection.Add(((string)entry.Key).ToLower().Replace(' ', '_'), (string)entry.Value); } } return collection; } public override string ToString(){ StringBuilder build = new StringBuilder(); foreach(DictionaryEntry entry in data){ if (entry.Value == null){ build.AppendLine(); } else{ build.AppendLine(entry.Key+": "+entry.Value); } } return build.ToString(); } } }
Update spectator/multiplayer endpoint in line with new deployment
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Online { public class ProductionEndpointConfiguration : EndpointConfiguration { public ProductionEndpointConfiguration() { WebsiteRootUrl = APIEndpointUrl = @"https://osu.ppy.sh"; APIClientSecret = @"FGc9GAtyHzeQDshWP5Ah7dega8hJACAJpQtw6OXk"; APIClientID = "5"; SpectatorEndpointUrl = "https://spectator2.ppy.sh/spectator"; MultiplayerEndpointUrl = "https://spectator2.ppy.sh/multiplayer"; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Online { public class ProductionEndpointConfiguration : EndpointConfiguration { public ProductionEndpointConfiguration() { WebsiteRootUrl = APIEndpointUrl = @"https://osu.ppy.sh"; APIClientSecret = @"FGc9GAtyHzeQDshWP5Ah7dega8hJACAJpQtw6OXk"; APIClientID = "5"; SpectatorEndpointUrl = "https://spectator.ppy.sh/spectator"; MultiplayerEndpointUrl = "https://spectator.ppy.sh/multiplayer"; } } }
Hide character fields header if no fields
@using JoinRpg.Web.Models @model CharacterDetailsViewModel <div> @Html.Partial("CharacterNavigation", Model.Navigation) @* TODO: Жесточайше причесать эту страницу*@ <dl class="dl-horizontal"> <dt>Игрок</dt> <dd>@Html.DisplayFor(model => model, "IPlayerCharacter")</dd> <dt>@Html.DisplayNameFor(model => model.Description)</dt> <dd>@Html.DisplayFor(model => model.Description)</dd> <dt>@Html.DisplayNameFor(model => model.ParentGroups)</dt> <dd>@Html.DisplayFor(model => model.ParentGroups)</dd> </dl> <h4>Поля персонажа</h4> <div class="form-horizontal"> @Html.Partial("_EditFieldsPartial", Model.Fields) </div> @Html.Partial("_PlotForCharacterPartial", Model.Plot) </div>
@using JoinRpg.Web.Models @model CharacterDetailsViewModel <div> @Html.Partial("CharacterNavigation", Model.Navigation) @* TODO: Жесточайше причесать эту страницу*@ <dl class="dl-horizontal"> <dt>Игрок</dt> <dd>@Html.DisplayFor(model => model, "IPlayerCharacter")</dd> <dt>@Html.DisplayNameFor(model => model.Description)</dt> <dd>@Html.DisplayFor(model => model.Description)</dd> <dt>@Html.DisplayNameFor(model => model.ParentGroups)</dt> <dd>@Html.DisplayFor(model => model.ParentGroups)</dd> </dl> @if (Model.Fields.CharacterFields.Any()) { <h4>Поля персонажа</h4> <div class="form-horizontal"> @Html.Partial("_EditFieldsPartial", Model.Fields) </div> } @Html.Partial("_PlotForCharacterPartial", Model.Plot) </div>
Add CIV.Interfaces reference in Main
using static System.Console; using CIV.Ccs; namespace CIV { class Program { static void Main(string[] args) { var text = System.IO.File.ReadAllText(args[0]); var processes = CcsFacade.ParseAll(text); var trace = CcsFacade.RandomTrace(processes["Prison"], 450); foreach (var action in trace) { WriteLine(action); } } } }
using static System.Console; using CIV.Ccs; using CIV.Interfaces; namespace CIV { class Program { static void Main(string[] args) { var text = System.IO.File.ReadAllText(args[0]); var processes = CcsFacade.ParseAll(text); var trace = CcsFacade.RandomTrace(processes["Prison"], 450); foreach (var action in trace) { WriteLine(action); } } } }
Revert "Revert "registration of api controllers fixed""
using System.Web.Http; using Autofac; using Autofac.Integration.WebApi; namespace ReSharperTnT { public class Bootstrapper { static Bootstrapper() { Init(); } public static void Init() { var bootstrapper = new Bootstrapper(); var container = bootstrapper.CreateContainer(); var autofacWebApiDependencyResolver = new AutofacWebApiDependencyResolver(container); GlobalConfiguration.Configuration.DependencyResolver = autofacWebApiDependencyResolver; } private readonly IContainer _container; public Bootstrapper() { var builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(typeof (Bootstrapper).Assembly) .AsImplementedInterfaces(); builder.RegisterAssemblyTypes(typeof (Bootstrapper).Assembly) .Where(c=>c.Name.EndsWith("Controller")) .AsSelf(); _container = builder.Build(); } public IContainer CreateContainer() { return _container; } public T Get<T>() { return _container.Resolve<T>(); } } }
using System.Reflection; using System.Web.Http; using Autofac; using Autofac.Integration.WebApi; namespace ReSharperTnT { public class Bootstrapper { public static void Init() { var bootstrapper = new Bootstrapper(); var container = bootstrapper.CreateContainer(); var autofacWebApiDependencyResolver = new AutofacWebApiDependencyResolver(container); GlobalConfiguration.Configuration.DependencyResolver = autofacWebApiDependencyResolver; } private readonly IContainer _container; public Bootstrapper() { var builder = new ContainerBuilder(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterAssemblyTypes(typeof (Bootstrapper).Assembly) .AsImplementedInterfaces(); _container = builder.Build(); } public IContainer CreateContainer() { return _container; } public T Get<T>() { return _container.Resolve<T>(); } } }
Add new fluent syntax: DayOfWeek.Monday.EveryWeek()
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RecurringDates { public static class Extensions { public static SetUnionRule Or(this IRule first, params IRule[] otherRules) { return new SetUnionRule {Rules = new[] {first}.Concat(otherRules)}; } public static SetIntersectionRule And(this IRule first, params IRule[] otherRules) { return new SetIntersectionRule { Rules = new[] { first }.Concat(otherRules) }; } public static SetDifferenceRule Except(this IRule includeRule, IRule excludeRule) { return new SetDifferenceRule { IncludeRule = includeRule , ExcludeRule = excludeRule }; } public static NotRule Not(this IRule rule) { return new NotRule { ReferencedRule = rule }; } public static NthInMonthRule NthInMonth(this IRule rule, int nthOccurrence) { return new NthInMonthRule {Nth = nthOccurrence, ReferencedRule = rule}; } public static MonthsFilterRule InMonths(this IRule rule, params Month[] months) { return new MonthsFilterRule { Months = months, ReferencedRule = rule }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RecurringDates { public static class Extensions { public static SetUnionRule Or(this IRule first, params IRule[] otherRules) { return new SetUnionRule {Rules = new[] {first}.Concat(otherRules)}; } public static SetIntersectionRule And(this IRule first, params IRule[] otherRules) { return new SetIntersectionRule { Rules = new[] { first }.Concat(otherRules) }; } public static SetDifferenceRule Except(this IRule includeRule, IRule excludeRule) { return new SetDifferenceRule { IncludeRule = includeRule , ExcludeRule = excludeRule }; } public static NotRule Not(this IRule rule) { return new NotRule { ReferencedRule = rule }; } public static NthInMonthRule NthInMonth(this IRule rule, int nthOccurrence) { return new NthInMonthRule {Nth = nthOccurrence, ReferencedRule = rule}; } public static MonthsFilterRule InMonths(this IRule rule, params Month[] months) { return new MonthsFilterRule { Months = months, ReferencedRule = rule }; } public static DayOfWeekRule EveryWeek(this DayOfWeek dow) { return new DayOfWeekRule(dow); } } }
Add missing dependencies to autofac module
using Arkivverket.Arkade.Core; using Arkivverket.Arkade.Core.Noark5; using Arkivverket.Arkade.Identify; using Arkivverket.Arkade.Logging; using Arkivverket.Arkade.Tests; using Arkivverket.Arkade.Tests.Noark5; using Autofac; namespace Arkivverket.Arkade.Util { public class ArkadeAutofacModule : Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<TarCompressionUtility>().As<ICompressionUtility>(); builder.RegisterType<TestSessionFactory>().AsSelf(); builder.RegisterType<ArchiveIdentifier>().As<IArchiveIdentifier>(); builder.RegisterType<Noark5TestEngine>().AsSelf().SingleInstance(); builder.RegisterType<ArchiveContentReader>().As<IArchiveContentReader>(); builder.RegisterType<TestProvider>().As<ITestProvider>(); builder.RegisterType<StatusEventHandler>().As<IStatusEventHandler>().SingleInstance(); builder.RegisterType<Noark5TestProvider>().AsSelf(); } } }
using Arkivverket.Arkade.Core; using Arkivverket.Arkade.Core.Addml; using Arkivverket.Arkade.Core.Noark5; using Arkivverket.Arkade.Identify; using Arkivverket.Arkade.Logging; using Arkivverket.Arkade.Tests; using Arkivverket.Arkade.Tests.Noark5; using Autofac; namespace Arkivverket.Arkade.Util { public class ArkadeAutofacModule : Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<AddmlDatasetTestEngine>().AsSelf(); builder.RegisterType<AddmlProcessRunner>().AsSelf(); builder.RegisterType<ArchiveContentReader>().As<IArchiveContentReader>(); builder.RegisterType<ArchiveIdentifier>().As<IArchiveIdentifier>(); builder.RegisterType<FlatFileReaderFactory>().AsSelf(); builder.RegisterType<Noark5TestEngine>().AsSelf().SingleInstance(); builder.RegisterType<Noark5TestProvider>().AsSelf(); builder.RegisterType<StatusEventHandler>().As<IStatusEventHandler>().SingleInstance(); builder.RegisterType<TarCompressionUtility>().As<ICompressionUtility>(); builder.RegisterType<TestEngineFactory>().AsSelf(); builder.RegisterType<TestProvider>().As<ITestProvider>(); builder.RegisterType<TestSessionFactory>().AsSelf(); } } }
Enable tracing for IAP code
// // Copyright 2019 Google LLC // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // using NUnit.Framework; using System.Diagnostics; namespace Google.Solutions.IapDesktop.Application.Test { public abstract class FixtureBase { [SetUp] public void SetUpTracing() { TraceSources.IapDesktop.Listeners.Add(new ConsoleTraceListener()); TraceSources.IapDesktop.Switch.Level = SourceLevels.Verbose; } } }
// // Copyright 2019 Google LLC // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // using NUnit.Framework; using System.Diagnostics; namespace Google.Solutions.IapDesktop.Application.Test { public abstract class FixtureBase { private static TraceSource[] Traces = new[] { Google.Solutions.Compute.TraceSources.Compute, Google.Solutions.IapDesktop.Application.TraceSources.IapDesktop }; [SetUp] public void SetUpTracing() { var listener = new ConsoleTraceListener(); foreach (var trace in Traces) { trace.Listeners.Add(listener); trace.Switch.Level = System.Diagnostics.SourceLevels.Verbose; } } } }
Fix issues related to open dialogs when a player disconnects
// SampSharp // Copyright 2022 Tim Potze // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace SampSharp.Entities.SAMP; /// <summary>Represents a system for handling dialog functionality</summary> public class DialogSystem : ISystem { [Event] // ReSharper disable once UnusedMember.Local private void OnPlayerDisconnect(VisibleDialog player, DisconnectReason _) { player.Handler(new DialogResult(DialogResponse.Disconnected, 0, null)); } [Event] // ReSharper disable once UnusedMember.Local private void OnDialogResponse(VisibleDialog player, int dialogId, int response, int listItem, string inputText) { if (dialogId != DialogService.DialogId) return; // Prevent dialog hacks player.ResponseReceived = true; player.Handler(new DialogResult(response == 1 ? DialogResponse.LeftButton : DialogResponse.RightButtonOrCancel, listItem, inputText)); } }
// SampSharp // Copyright 2022 Tim Potze // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace SampSharp.Entities.SAMP; /// <summary>Represents a system for handling dialog functionality</summary> public class DialogSystem : ISystem { [Event] // ReSharper disable once UnusedMember.Local private void OnPlayerDisconnect(VisibleDialog player, DisconnectReason _) { player.ResponseReceived = true; player.Handler(new DialogResult(DialogResponse.Disconnected, 0, null)); } [Event] // ReSharper disable once UnusedMember.Local private void OnDialogResponse(VisibleDialog player, int dialogId, int response, int listItem, string inputText) { if (dialogId != DialogService.DialogId) return; // Prevent dialog hacks player.ResponseReceived = true; player.Handler(new DialogResult(response == 1 ? DialogResponse.LeftButton : DialogResponse.RightButtonOrCancel, listItem, inputText)); player.Destroy(); } }
Add missing ARC runtime linker flag
using System; using MonoTouch.ObjCRuntime; [assembly: LinkWith ("PSPDFKit.a", LinkTarget.ArmV7s | LinkTarget.ArmV7 | LinkTarget.Simulator, ForceLoad = true, IsCxx = true, Frameworks = "MediaPlayer CoreText QuartzCore MessageUI ImageIO CoreMedia CoreGraphics AVFoundation", LinkerFlags = "-lz -ObjC")]
using System; using MonoTouch.ObjCRuntime; [assembly: LinkWith ("PSPDFKit.a", LinkTarget.ArmV7s | LinkTarget.ArmV7 | LinkTarget.Simulator, ForceLoad = true, IsCxx = true, Frameworks = "MediaPlayer CoreText QuartzCore MessageUI ImageIO CoreMedia CoreGraphics AVFoundation", LinkerFlags = "-lz -ObjC -fobjc-arc")]
Debug mode only enabled for Debug Build configuration
using System.Reflection; using Funq; using ServiceStack.Common.Web; using ServiceStack.ServiceHost; using ServiceStack.Text; using ServiceStack.WebHost.Endpoints; using SimpleEventMonitor.Core; namespace SimpleEventMonitor.Web { public class AppHostSimpleEventMonitor : AppHostBase { public AppHostSimpleEventMonitor(IEventDataStore dataStore) : base("SimpleEventMonitorServices", Assembly.GetExecutingAssembly()) { Container.Register(dataStore); } public override void Configure(Container container) { JsConfig.IncludeNullValues = true; SetConfig( new EndpointHostConfig { DebugMode = true, DefaultContentType = ContentType.Json, EnableFeatures = Feature.All }); } } }
using System.Reflection; using Funq; using ServiceStack.Common.Web; using ServiceStack.ServiceHost; using ServiceStack.Text; using ServiceStack.WebHost.Endpoints; using SimpleEventMonitor.Core; namespace SimpleEventMonitor.Web { public class AppHostSimpleEventMonitor : AppHostBase { public AppHostSimpleEventMonitor(IEventDataStore dataStore) : base("SimpleEventMonitorServices", Assembly.GetExecutingAssembly()) { Container.Register(dataStore); } public override void Configure(Container container) { #if DEBUG bool debug = true; var enableFeatures = Feature.All; #else bool debug = false; var enableFeatures = Feature.All.Remove(Feature.Metadata); #endif JsConfig.IncludeNullValues = true; SetConfig( new EndpointHostConfig { DebugMode = debug, DefaultContentType = ContentType.Json, EnableFeatures = enableFeatures }); } } }
Fix screen capture durring test failure
using System; using System.Drawing.Imaging; using System.IO; using OpenQA.Selenium; namespace Selenium.WebDriver.Equip { public class TestCapture { private IWebDriver _browser = null; private string fileName; public TestCapture(IWebDriver iWebDriver, string type = "Failed") { fileName = string.Format(@"{0}\{1}.{2}", Directory.GetCurrentDirectory(), DateTime.Now.Ticks, type); _browser = iWebDriver; } public void CaptureWebPage() { WebDriverLogsLogs(); PageSource(); ScreenShot(); } public void PageSource() { string htmlFile = string.Format(@"{0}.html", fileName); using (var sw = new StreamWriter(htmlFile, false)) sw.Write(_browser.PageSource); } public void ScreenShot() { _browser.TakeScreenShot(fileName + ".jpeg", ScreenshotImageFormat.Jpeg); } public void WebDriverLogsLogs() { foreach (var log in _browser.Manage().Logs.AvailableLogTypes) using (var sw = new StreamWriter(string.Format(@"{0}.{1}.log", fileName, log), false)) foreach (var logentry in _browser.Manage().Logs.GetLog(log)) sw.WriteLine(logentry); } } }
using OpenQA.Selenium; using System; using System.IO; using System.Reflection; namespace Selenium.WebDriver.Equip { public class TestCapture { private IWebDriver _browser = null; private string fileName; public TestCapture(IWebDriver iWebDriver, string type = "Failed") { fileName = $@"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\{DateTime.Now.Ticks}.{type}"; _browser = iWebDriver; } public void CaptureWebPage() { WebDriverLogsLogs(); PageSource(); ScreenShot(); } public void PageSource() { string htmlFile = $"{fileName}.html"; using (var sw = new StreamWriter(htmlFile, false)) sw.Write(_browser.PageSource); } public void ScreenShot() { _browser.TakeScreenShot(fileName + ".jpeg", ScreenshotImageFormat.Jpeg); } public void WebDriverLogsLogs() { foreach (var log in _browser.Manage().Logs.AvailableLogTypes) using (var sw = new StreamWriter($"{fileName}.{log}.log", false)) foreach (var logentry in _browser.Manage().Logs.GetLog(log)) sw.WriteLine(logentry); } } }
Switch simple array diff to default until Efficient array diffing is implemented
namespace JsonDiffPatchDotNet { public sealed class Options { public Options() { ArrayDiff = ArrayDiffMode.Efficient; TextDiff = TextDiffMode.Efficient; MinEfficientTextDiffLength = 50; } public ArrayDiffMode ArrayDiff { get; set; } public TextDiffMode TextDiff { get; set; } public long MinEfficientTextDiffLength { get; set; } } }
namespace JsonDiffPatchDotNet { public sealed class Options { public Options() { ArrayDiff = ArrayDiffMode.Simple; TextDiff = TextDiffMode.Efficient; MinEfficientTextDiffLength = 50; } public ArrayDiffMode ArrayDiff { get; set; } public TextDiffMode TextDiff { get; set; } public long MinEfficientTextDiffLength { get; set; } } }
Add a hover effect to video player seek bar
using System.Drawing; using System.Windows.Forms; namespace TweetDuck.Video.Controls{ sealed class SeekBar : ProgressBar{ private readonly SolidBrush brush; public SeekBar(){ brush = new SolidBrush(Color.White); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); } protected override void OnPaint(PaintEventArgs e){ if (brush.Color != ForeColor){ brush.Color = ForeColor; } Rectangle rect = e.ClipRectangle; rect.Width = (int)(rect.Width*((double)Value/Maximum)); e.Graphics.FillRectangle(brush, rect); } protected override void Dispose(bool disposing){ base.Dispose(disposing); if (disposing){ brush.Dispose(); } } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace TweetDuck.Video.Controls{ sealed class SeekBar : ProgressBar{ private readonly SolidBrush brushFore; private readonly SolidBrush brushHover; private readonly SolidBrush brushOverlap; public SeekBar(){ brushFore = new SolidBrush(Color.White); brushHover = new SolidBrush(Color.White); brushOverlap = new SolidBrush(Color.White); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); } protected override void OnPaint(PaintEventArgs e){ if (brushFore.Color != ForeColor){ brushFore.Color = ForeColor; brushHover.Color = Color.FromArgb(128, ForeColor); brushOverlap.Color = Color.FromArgb(80+ForeColor.R*11/16, 80+ForeColor.G*11/16, 80+ForeColor.B*11/16); } Rectangle rect = e.ClipRectangle; Point cursor = PointToClient(Cursor.Position); int width = rect.Width; int progress = (int)(width*((double)Value/Maximum)); rect.Width = progress; e.Graphics.FillRectangle(brushFore, rect); if (cursor.X >= 0 && cursor.Y >= 0 && cursor.X <= width && cursor.Y <= rect.Height){ if (progress >= cursor.X){ rect.Width = cursor.X; e.Graphics.FillRectangle(brushOverlap, rect); } else{ rect.X = progress; rect.Width = cursor.X-rect.X; e.Graphics.FillRectangle(brushHover, rect); } } } protected override void Dispose(bool disposing){ base.Dispose(disposing); if (disposing){ brushFore.Dispose(); brushHover.Dispose(); brushOverlap.Dispose(); } } } }
Replace SQLite path for MBTiles files with full path, so that doesn't throw an exception on UWP
using System.IO; using BruTile.MbTiles; using Mapsui.Layers; using Mapsui.UI; using SQLite; namespace Mapsui.Samples.Common.Maps { public class MbTilesSample : ISample { // This is a hack used for iOS/Android deployment public static string MbTilesLocation { get; set; } = @"." + Path.DirectorySeparatorChar + "MbTiles"; public string Name => "1 MbTiles"; public string Category => "Data"; public void Setup(IMapControl mapControl) { mapControl.Map = CreateMap(); } public static Map CreateMap() { var map = new Map(); map.Layers.Add(CreateMbTilesLayer(Path.Combine(MbTilesLocation, "world.mbtiles"), "regular")); return map; } public static TileLayer CreateMbTilesLayer(string path, string name) { var mbTilesTileSource = new MbTilesTileSource(new SQLiteConnectionString(path, true)); var mbTilesLayer = new TileLayer(mbTilesTileSource) { Name = name}; return mbTilesLayer; } } }
using System.IO; using BruTile.MbTiles; using Mapsui.Layers; using Mapsui.UI; using SQLite; namespace Mapsui.Samples.Common.Maps { public class MbTilesSample : ISample { // This is a hack used for iOS/Android deployment public static string MbTilesLocation { get; set; } = @"." + Path.DirectorySeparatorChar + "MbTiles"; public string Name => "1 MbTiles"; public string Category => "Data"; public void Setup(IMapControl mapControl) { mapControl.Map = CreateMap(); } public static Map CreateMap() { var map = new Map(); map.Layers.Add(CreateMbTilesLayer(Path.GetFullPath(Path.Combine(MbTilesLocation, "world.mbtiles")), "regular")); return map; } public static TileLayer CreateMbTilesLayer(string path, string name) { var mbTilesTileSource = new MbTilesTileSource(new SQLiteConnectionString(path, true)); var mbTilesLayer = new TileLayer(mbTilesTileSource) { Name = name}; return mbTilesLayer; } } }
Fix smoke test to use common LocationName
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; namespace Google.Cloud.Redis.V1Beta1.SmokeTests { public class CloudRedisClientSmokeTest { public static int Main(string[] args) { var client = CloudRedisClient.Create(); var locationName = new LocationName(args[0], "-"); var instances = client.ListInstances(locationName); foreach (var instance in instances) { Console.WriteLine(instance.Name); } // Success Console.WriteLine("Smoke test passed OK"); return 0; } } }
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using Google.Api.Gax.ResourceNames; namespace Google.Cloud.Redis.V1Beta1.SmokeTests { public class CloudRedisClientSmokeTest { public static int Main(string[] args) { var client = CloudRedisClient.Create(); var locationName = new LocationName(args[0], "-"); var instances = client.ListInstances(locationName); foreach (var instance in instances) { Console.WriteLine(instance.Name); } // Success Console.WriteLine("Smoke test passed OK"); return 0; } } }
Enable auto-connection on pre-block bursting screen
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Common.Logging; using GladNet; namespace Booma.Proxy { [SceneTypeCreate(GameSceneType.ServerSelectionScreen)] [SceneTypeCreate(GameSceneType.PreShipSelectionScene)] [SceneTypeCreate(GameSceneType.CharacterSelectionScreen)] //probably more than just the character screen. public sealed class NetworkClientConnectionOnInitInitializable : IGameInitializable { private IConnectionService ConnectionService { get; } private IGameConnectionEndpointDetails ConnectionDetails { get; } private ILog Logger { get; } /// <inheritdoc /> public NetworkClientConnectionOnInitInitializable([NotNull] IConnectionService connectionService, [NotNull] IGameConnectionEndpointDetails connectionDetails, [NotNull] ILog logger) { ConnectionService = connectionService ?? throw new ArgumentNullException(nameof(connectionService)); ConnectionDetails = connectionDetails ?? throw new ArgumentNullException(nameof(connectionDetails)); Logger = logger ?? throw new ArgumentNullException(nameof(logger)); } /// <inheritdoc /> public Task OnGameInitialized() { if(Logger.IsInfoEnabled) Logger.Info($"Connectiong to: {ConnectionDetails.IpAddress}:{ConnectionDetails.Port}"); //This initializable actually just //connects a IConnectionService with the provided game details. return ConnectionService.ConnectAsync(ConnectionDetails.IpAddress, ConnectionDetails.Port); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Common.Logging; using GladNet; namespace Booma.Proxy { [SceneTypeCreate(GameSceneType.PreBlockBurstingScene)] [SceneTypeCreate(GameSceneType.ServerSelectionScreen)] [SceneTypeCreate(GameSceneType.PreShipSelectionScene)] [SceneTypeCreate(GameSceneType.CharacterSelectionScreen)] //probably more than just the character screen. public sealed class NetworkClientConnectionOnInitInitializable : IGameInitializable { private IConnectionService ConnectionService { get; } private IGameConnectionEndpointDetails ConnectionDetails { get; } private ILog Logger { get; } /// <inheritdoc /> public NetworkClientConnectionOnInitInitializable([NotNull] IConnectionService connectionService, [NotNull] IGameConnectionEndpointDetails connectionDetails, [NotNull] ILog logger) { ConnectionService = connectionService ?? throw new ArgumentNullException(nameof(connectionService)); ConnectionDetails = connectionDetails ?? throw new ArgumentNullException(nameof(connectionDetails)); Logger = logger ?? throw new ArgumentNullException(nameof(logger)); } /// <inheritdoc /> public Task OnGameInitialized() { if(Logger.IsInfoEnabled) Logger.Info($"Connectiong to: {ConnectionDetails.IpAddress}:{ConnectionDetails.Port}"); //This initializable actually just //connects a IConnectionService with the provided game details. return ConnectionService.ConnectAsync(ConnectionDetails.IpAddress, ConnectionDetails.Port); } } }
Set MicrogameCollection dirty in editor update
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; [CustomEditor(typeof(MicrogameCollection))] public class MicrogameCollectionEditor : Editor { public override void OnInspectorGUI() { MicrogameCollection collection = (MicrogameCollection)target; if (GUILayout.Button("Update Microgames")) { collection.updateMicrogames(); } DrawDefaultInspector(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; [CustomEditor(typeof(MicrogameCollection))] public class MicrogameCollectionEditor : Editor { public override void OnInspectorGUI() { MicrogameCollection collection = (MicrogameCollection)target; if (GUILayout.Button("Update Microgames")) { collection.updateMicrogames(); EditorUtility.SetDirty(collection); } DrawDefaultInspector(); } }
Add a link on Credit card registrations that have not paid
@using Microsoft.Web.Mvc @model CRP.Controllers.ViewModels.PaymentConfirmationViewModel @{ ViewBag.Title = "Confirmation"; } <div class="boundary"> <h2>Registration Confirmation</h2> <p>You have successfully registered for the following event:</p> <div> <label>Item: </label> @Model.Transaction.Item.Name </div> <div> <label>Amount: </label> @($"{Model.Transaction.Total:C}") </div> @if (Model.Transaction.Credit) { <div> <p>Payment is still due:</p> <form action="@Model.PostUrl" method="post" autocomplete="off" style="margin-right: 3px"> @foreach (var pair in Model.PaymentDictionary) { <input type="hidden" name="@pair.Key" value="@pair.Value"/> } <input type="hidden" name="signature" value="@Model.Signature"/> @Html.SubmitButton("Submit", "Click here to be taken to our payment site") </form> </div> } else if (Model.Transaction.Total > 0) { <div> @Html.Raw(Model.Transaction.Item.CheckPaymentInstructions) </div> } </div>
@using Microsoft.Web.Mvc @model CRP.Controllers.ViewModels.PaymentConfirmationViewModel @{ ViewBag.Title = "Confirmation"; } <div class="boundary"> <h2>Registration Confirmation</h2> <p>You have successfully registered for the following event:</p> <div> <label>Item: </label> @Model.Transaction.Item.Name </div> <div> <label>Amount: </label> @($"{Model.Transaction.Total:C}") </div> @if (Model.Transaction.Credit) { <div> <p>Payment is still due:</p> <form action="@Model.PostUrl" method="post" autocomplete="off" style="margin-right: 3px"> @foreach (var pair in Model.PaymentDictionary) { <input type="hidden" name="@pair.Key" value="@pair.Value"/> } <input type="hidden" name="signature" value="@Model.Signature"/> <input type="submit" class="btn btn-primary" value="Click here to be taken to our payment site"/> </form> </div> } else if (Model.Transaction.Total > 0) { <div> @Html.Raw(Model.Transaction.Item.CheckPaymentInstructions) </div> } </div>
Update D2RS to handle new networking infrastructure.
namespace Reaper.SharpBattleNet.Framework.DiabloIIRealmServer.Details { using System; using System.Linq; using System.Text; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Nini; using Nini.Config; using Nini.Ini; using Nini.Util; using NLog; using Reaper; using Reaper.SharpBattleNet; using Reaper.SharpBattleNet.Framework; using Reaper.SharpBattleNet.Framework.DiabloIIRealmServer; internal sealed class DiabloIIRealmServer : IDiabloIIRealmServer { private readonly IConfigSource _configuration = null; private readonly Logger _logger = LogManager.GetCurrentClassLogger(); public DiabloIIRealmServer(IConfigSource configuration) { _configuration = configuration; return; } public async Task Start(string[] commandArguments) { return; } public async Task Stop() { return; } } }
namespace Reaper.SharpBattleNet.Framework.DiabloIIRealmServer.Details { using System; using System.Linq; using System.Text; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Nini; using Nini.Config; using Nini.Ini; using Nini.Util; using NLog; using Reaper; using Reaper.SharpBattleNet; using Reaper.SharpBattleNet.Framework; using Reaper.SharpBattleNet.Framework.Networking; using Reaper.SharpBattleNet.Framework.DiabloIIRealmServer; internal sealed class DiabloIIRealmServer : IDiabloIIRealmServer { private readonly IConfigSource _configuration = null; private readonly INetworkManager _networkManager = null; private readonly Logger _logger = LogManager.GetCurrentClassLogger(); public DiabloIIRealmServer(IConfigSource configuration, INetworkManager networkManager) { _configuration = configuration; _networkManager = networkManager; return; } public async Task Start(string[] commandArguments) { await _networkManager.StartNetworking(); return; } public async Task Stop() { await _networkManager.StopNetworking(); return; } } }
Add edit links to noitces admin
@model LETS.ViewModels.MemberNoticesViewModel <h1>@string.Format("{0}'s {1}", @Model.Member.FirstLastName, T("notices"))</h1> @if (Model.Notices.Count().Equals(0)) { <p>@T("This member doesn't have any active notices")</p> } @foreach (var notice in Model.Notices) { @Display(notice) } @{ <div id="archivedNotices"> <h2>@T("Archived notices")</h2> <p><strong>@T("Expired notices will show up here until they are deleted or re-activated by publishing them.")</strong></p> <p>@T("Notices can also be archived if you don't want to delete them yet")</p> @if (Model.ArchivedNotices.Any()) { foreach (var archivedNotice in Model.ArchivedNotices) { @Display(archivedNotice) } } </div> }
@using LETS.Helpers; @model LETS.ViewModels.MemberNoticesViewModel <h1>@string.Format("{0}'s {1}", @Model.Member.FirstLastName, T("notices"))</h1> @if (Model.Notices.Count().Equals(0)) { <p>@T("This member doesn't have any active notices")</p> } @foreach (var notice in Model.Notices) { var id = notice.ContentItem.Id; @Display(notice) @Html.ActionLink(T("Edit").ToString(), "Edit", "Notice", new { area = "LETS", id = id }, new { @class = "edit" }) @:| @Html.ActionLink(T("Delete").ToString(), "Delete", "Notice", new { area = "LETS", id = id }, new { @class = "edit", itemprop = "UnsafeUrl RemoveUrl" }) @:| @*var published = Helpers.IsPublished(notice.ContentPart.Id); if (published) { @Html.Link(T("Archive").Text, Url.Action("Unpublish", "Notice", new { area = "LETS", id = notice.Id }), new { @class = "edit", itemprop = "UnsafeUrl ArchiveUrl" }) } else { @Html.ActionLink(T("Publish").ToString(), "Publish", "Notice", new { area = "LETS", id = notice.Id }, new { @class = "edit", itemprop = "UnsafeUrl" }) }*@ } @{ <div id="archivedNotices"> <h2>@T("Archived notices")</h2> <p><strong>@T("Expired notices will show up here until they are deleted or re-activated by publishing them.")</strong></p> <p>@T("Notices can also be archived if you don't want to delete them yet")</p> @if (Model.ArchivedNotices.Any()) { foreach (var archivedNotice in Model.ArchivedNotices) { @Display(archivedNotice) } } </div> } @Html.AntiForgeryTokenOrchard()
Fix IndexOutOfBounds exception on application closing
using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; namespace XmlParserWpf { public class FilesViewModel: ObservableCollection<FilesListItem> { public const int NoneSelection = -1; private int _selectedIndex = NoneSelection; public int SelectedIndex { get { return _selectedIndex; } set { if (_selectedIndex != value) { _selectedIndex = value; OnPropertyChanged(new PropertyChangedEventArgs("SelectedIndex")); OnPropertyChanged(new PropertyChangedEventArgs("SelectedFile")); } } } public FilesListItem SelectedFile => (SelectedIndex != NoneSelection ? this[SelectedIndex] : null); public void AddAndSelect(FilesListItem item) { Add(item); SelectedIndex = IndexOf(item); } public bool HasFile(string path) { return this.Any(x => x.Path.Equals(path)); } public void SelectIfExists(string path) { if (HasFile(path)) SelectedIndex = IndexOf(this.First(x => x.Path.Equals(path))); } public void RemoveSelected() { if (SelectedIndex < 0) return; RemoveAt(SelectedIndex); if (Count == 0) SelectedIndex = NoneSelection; } } }
using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; namespace XmlParserWpf { public class FilesViewModel: ObservableCollection<FilesListItem> { public const int NoneSelection = -1; private int _selectedIndex = NoneSelection; public int SelectedIndex { get { return _selectedIndex; } set { if (_selectedIndex != value) { _selectedIndex = value; OnPropertyChanged(new PropertyChangedEventArgs("SelectedIndex")); OnPropertyChanged(new PropertyChangedEventArgs("SelectedFile")); } } } public FilesListItem SelectedFile => ((Count > 0) && (SelectedIndex != NoneSelection)) ? this[SelectedIndex] : null; public void AddAndSelect(FilesListItem item) { Add(item); SelectedIndex = IndexOf(item); } public bool HasFile(string path) { return this.Any(x => x.Path.Equals(path)); } public void SelectIfExists(string path) { if (HasFile(path)) SelectedIndex = IndexOf(this.First(x => x.Path.Equals(path))); } public void RemoveSelected() { if (SelectedIndex < 0) return; RemoveAt(SelectedIndex); if (Count == 0) SelectedIndex = NoneSelection; } } }
Fix gestione codici chiamata in Trasferimento Chiamata
using MongoDB.Driver; using MongoDB.Driver.Linq; using Persistence.MongoDB; using SO115App.Models.Servizi.Infrastruttura.GestioneTrasferimentiChiamate.CodiciChiamate; using System.Collections.Generic; namespace SO115App.Persistence.MongoDB.GestioneTrasferimentiChiamate.CodiciChiamate { public class GetCodiciChiamate : IGetCodiciChiamate { private readonly DbContext _dbContext; public GetCodiciChiamate(DbContext dbContext) => _dbContext = dbContext; public List<string> Get(string CodSede) { return _dbContext.RichiestaAssistenzaCollection.AsQueryable() .Where(c => c.TestoStatoRichiesta == "C" && c.CodSOCompetente == CodSede) .Select(c => c.Codice) .ToList(); } } }
using MongoDB.Driver; using MongoDB.Driver.Linq; using Persistence.MongoDB; using SO115App.API.Models.Classi.Organigramma; using SO115App.API.Models.Classi.Soccorso; using SO115App.Models.Servizi.Infrastruttura.GestioneTrasferimentiChiamate.CodiciChiamate; using SO115App.Models.Servizi.Infrastruttura.SistemiEsterni.ServizioSede; using System.Collections.Generic; using System.Linq; namespace SO115App.Persistence.MongoDB.GestioneTrasferimentiChiamate.CodiciChiamate { public class GetCodiciChiamate : IGetCodiciChiamate { private readonly DbContext _dbContext; private readonly IGetAlberaturaUnitaOperative _getAlberaturaUnitaOperative; public GetCodiciChiamate(DbContext dbContext, IGetAlberaturaUnitaOperative getAlberaturaUnitaOperative) { _dbContext = dbContext; _getAlberaturaUnitaOperative = getAlberaturaUnitaOperative; } public List<string> Get(string CodSede) { var listaSediAlberate = _getAlberaturaUnitaOperative.ListaSediAlberata(); var pinNodi = new List<PinNodo>(); pinNodi.Add(new PinNodo(CodSede, true)); foreach (var figlio in listaSediAlberate.GetSottoAlbero(pinNodi)) { pinNodi.Add(new PinNodo(figlio.Codice, true)); } var filtroSediCompetenti = Builders<RichiestaAssistenza>.Filter .In(richiesta => richiesta.CodSOCompetente, pinNodi.Select(uo => uo.Codice)); var lista = _dbContext.RichiestaAssistenzaCollection.Find(filtroSediCompetenti).ToList(); return lista.Where(c => c.TestoStatoRichiesta == "C") .Select(c => c.Codice).ToList(); } } }
Add difficulty calculator beatmap decoder fallback
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Beatmaps.Formats { /// <summary> /// A <see cref="LegacyBeatmapDecoder"/> built for difficulty calculation of legacy <see cref="Beatmap"/>s /// <remarks> /// To use this, the decoder must be registered by the application through <see cref="LegacyDifficultyCalculatorBeatmapDecoder.Register"/>. /// Doing so will override any existing <see cref="Beatmap"/> decoders. /// </remarks> /// </summary> public class LegacyDifficultyCalculatorBeatmapDecoder : LegacyBeatmapDecoder { public LegacyDifficultyCalculatorBeatmapDecoder(int version = LATEST_VERSION) : base(version) { ApplyOffsets = false; } public new static void Register() { AddDecoder<Beatmap>(@"osu file format v", m => new LegacyDifficultyCalculatorBeatmapDecoder(int.Parse(m.Split('v').Last()))); } protected override TimingControlPoint CreateTimingControlPoint() => new LegacyDifficultyCalculatorControlPoint(); private class LegacyDifficultyCalculatorControlPoint : TimingControlPoint { public override double BeatLength { get; set; } = DEFAULT_BEAT_LENGTH; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Beatmaps.Formats { /// <summary> /// A <see cref="LegacyBeatmapDecoder"/> built for difficulty calculation of legacy <see cref="Beatmap"/>s /// <remarks> /// To use this, the decoder must be registered by the application through <see cref="LegacyDifficultyCalculatorBeatmapDecoder.Register"/>. /// Doing so will override any existing <see cref="Beatmap"/> decoders. /// </remarks> /// </summary> public class LegacyDifficultyCalculatorBeatmapDecoder : LegacyBeatmapDecoder { public LegacyDifficultyCalculatorBeatmapDecoder(int version = LATEST_VERSION) : base(version) { ApplyOffsets = false; } public new static void Register() { AddDecoder<Beatmap>(@"osu file format v", m => new LegacyDifficultyCalculatorBeatmapDecoder(int.Parse(m.Split('v').Last()))); SetFallbackDecoder<Beatmap>(() => new LegacyDifficultyCalculatorBeatmapDecoder()); } protected override TimingControlPoint CreateTimingControlPoint() => new LegacyDifficultyCalculatorControlPoint(); private class LegacyDifficultyCalculatorControlPoint : TimingControlPoint { public override double BeatLength { get; set; } = DEFAULT_BEAT_LENGTH; } } }
Test data for last 3 tile types.
using System; using HexWorld.Enums; namespace HexWorld { public class Tile { public TileTypes Type { get; set; } public bool IsWater { get; set; } public string Printable { get; set; } public Tile(TileTypes type) { ChangeTile(type); } public void ChangeTile(TileTypes type) { Type = type; switch (Type) { case TileTypes.Ocean: IsWater = true; // Printable = "▓▓▓"; Printable = " "; break; case TileTypes.Desert: IsWater = false; Printable = "░░░"; break; case TileTypes.Mountain: IsWater = false; Printable = "╔╬╗"; break; case TileTypes.Hill: IsWater = false; Printable = "▅▂▅"; break; case TileTypes.Grassland: IsWater = false; Printable = "▒▒▒"; break; case TileTypes.Steppe: IsWater = false; Printable = "░▒░"; break; case TileTypes.Tundra: IsWater = false; Printable = "***"; break; default: throw new ArgumentException("Unknown Tile Type"); } } public override string ToString() { return Printable; } } }
using System; using HexWorld.Enums; namespace HexWorld { public class Tile { public TileTypes Type { get; set; } public bool IsWater { get; set; } public string Printable { get; set; } public Tile(TileTypes type) { ChangeTile(type); } public void ChangeTile(TileTypes type) { Type = type; switch (Type) { case TileTypes.Ocean: IsWater = true; // Printable = "▓▓▓"; Printable = " "; break; case TileTypes.Desert: IsWater = false; Printable = "░░░"; break; case TileTypes.Mountain: IsWater = false; Printable = "╔╬╗"; break; case TileTypes.Hill: IsWater = false; Printable = "▅▂▅"; break; case TileTypes.Grassland: IsWater = false; Printable = "▒▒▒"; break; case TileTypes.Steppe: IsWater = false; Printable = "░▒░"; break; case TileTypes.Tundra: IsWater = false; Printable = "***"; break; case TileTypes.Jungle: IsWater = false; Printable = "╫╫╫"; break; case TileTypes.Forest: IsWater = false; Printable = "┼┼┼"; break; case TileTypes.Swamp: IsWater = false; Printable = "▚▞▜"; break; default: throw new ArgumentException("Unknown Tile Type"); } } public override string ToString() { return Printable; } } }
Add broken test to testproj
namespace testproj { using System; using JetBrains.dotMemoryUnit; using NUnit.Framework; [TestFixture] public class UnitTest1 { [Test] public void TestMethod1() { dotMemory.Check( memory => { var str1 = "1"; var str2 = "2"; var str3 = "3"; Assert.LessOrEqual(2, memory.ObjectsCount); Console.WriteLine(str1 + str2 + str3); }); } } }
namespace testproj { using System; using System.Collections.Generic; using JetBrains.dotMemoryUnit; using NUnit.Framework; [TestFixture] public class UnitTest1 { [Test] public void TestMethod1() { var strs = new List<string>(); var memoryCheckPoint = dotMemory.Check(); strs.Add(GenStr()); strs.Add(GenStr()); strs.Add(GenStr()); dotMemory.Check( memory => { var strCount = memory .GetDifference(memoryCheckPoint) .GetNewObjects() .GetObjects(i => i.Type == typeof(string)) .ObjectsCount; Assert.LessOrEqual(strCount, 2); }); strs.Clear(); } [Test] public void TestMethod2() { var strs = new List<string>(); var memoryCheckPoint = dotMemory.Check(); strs.Add(GenStr()); strs.Add(GenStr()); dotMemory.Check( memory => { var strCount = memory .GetDifference(memoryCheckPoint) .GetNewObjects() .GetObjects(i => i.Type == typeof(string)) .ObjectsCount; Assert.LessOrEqual(strCount, 2); }); strs.Clear(); } private static string GenStr() { return Guid.NewGuid().ToString(); } } }
Fix the player score counter (IsFaking always returned true)
using UnityEngine; using UnityEngine.Networking; public class PlayerState : NetworkBehaviour { [SyncVar] string fakingTheory; [SyncVar] int score; void Start() { fakingTheory = null; score = 0; } [Command] public void CmdSetFakingState(string newFakingTheory) { fakingTheory = newFakingTheory; } [Command] public void CmdAddScore(int value) { score += value; } public bool IsFaking() { return (fakingTheory != null); } void OnGUI() { if (!isLocalPlayer) { return; } GUI.BeginGroup(new Rect(Screen.width / 2 - 100, Screen.height - 100, 200, 200)); GUILayout.Label("Score: " + score); if (IsFaking()) { GUILayout.Label("Faking using " + fakingTheory); } GUI.EndGroup(); } }
using System; using UnityEngine; using UnityEngine.Networking; public class PlayerState : NetworkBehaviour { [SyncVar] string fakingTheory; [SyncVar] int score; void Start() { fakingTheory = null; score = 0; } [Command] public void CmdSetFakingState(string newFakingTheory) { fakingTheory = newFakingTheory; } [Command] public void CmdAddScore(int value) { score += value; } public bool IsFaking() { return !String.IsNullOrEmpty(fakingTheory); } void OnGUI() { if (!isLocalPlayer) { return; } GUI.BeginGroup(new Rect(Screen.width / 2 - 100, Screen.height - 100, 200, 200)); GUILayout.Label("Score: " + score); if (IsFaking()) { GUILayout.Label("Faking using " + fakingTheory); } GUI.EndGroup(); } }
Add conditions to background tasks
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Windows.ApplicationModel.Background; using Gitter.Services.Abstract; namespace Gitter.Services.Concrete { public class BackgroundTaskService : IBackgroundTaskService { public Dictionary<string, string> Tasks { get { return new Dictionary<string, string> { {"NotificationsBackgroundTask", "Gitter.Tasks"} }; } } public async Task RegisterTasksAsync() { foreach (var kvTask in Tasks) { if (BackgroundTaskRegistration.AllTasks.Any(task => task.Value.Name == kvTask.Key)) break; await RegisterTaskAsync(kvTask.Key, kvTask.Value); } } private async Task RegisterTaskAsync(string taskName, string taskNamespace) { var requestAccess = await BackgroundExecutionManager.RequestAccessAsync(); if (requestAccess == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity || requestAccess == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity) { var taskBuilder = new BackgroundTaskBuilder { Name = taskName, TaskEntryPoint = string.Format("{0}.{1}", taskNamespace, taskName) }; // Set the condition trigger that feels right for you taskBuilder.SetTrigger(new TimeTrigger(15, false)); taskBuilder.Register(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Windows.ApplicationModel.Background; using Gitter.Services.Abstract; namespace Gitter.Services.Concrete { public class BackgroundTaskService : IBackgroundTaskService { public Dictionary<string, string> Tasks { get { return new Dictionary<string, string> { {"NotificationsBackgroundTask", "Gitter.Tasks"} }; } } public async Task RegisterTasksAsync() { foreach (var kvTask in Tasks) { if (BackgroundTaskRegistration.AllTasks.Any(task => task.Value.Name == kvTask.Key)) break; await RegisterTaskAsync(kvTask.Key, kvTask.Value); } } private async Task RegisterTaskAsync(string taskName, string taskNamespace) { var requestAccess = await BackgroundExecutionManager.RequestAccessAsync(); if (requestAccess == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity || requestAccess == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity) { var taskBuilder = new BackgroundTaskBuilder { Name = taskName, TaskEntryPoint = string.Format("{0}.{1}", taskNamespace, taskName) }; // Set the condition trigger that feels right for you taskBuilder.SetTrigger(new TimeTrigger(15, false)); taskBuilder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable)); taskBuilder.AddCondition(new SystemCondition(SystemConditionType.UserNotPresent)); taskBuilder.Register(); } } } }
Add option to mark exceptions as observed
using System; namespace Mindscape.Raygun4Net { public class RaygunSettings { private static RaygunSettings settings; private const string DefaultApiEndPoint = "https://api.raygun.io/entries"; private const string DefaultPulseEndPoint = "https://api.raygun.io/events"; public static RaygunSettings Settings { get { return settings ?? (settings = new RaygunSettings { ApiEndpoint = new Uri(DefaultApiEndPoint), PulseEndpoint = new Uri(DefaultPulseEndPoint) }); } } public Uri ApiEndpoint { get; set; } public Uri PulseEndpoint{ get; set; } } }
using System; namespace Mindscape.Raygun4Net { public class RaygunSettings { private static RaygunSettings settings; private const string DefaultApiEndPoint = "https://api.raygun.io/entries"; private const string DefaultPulseEndPoint = "https://api.raygun.io/events"; public static RaygunSettings Settings { get { return settings ?? (settings = new RaygunSettings { ApiEndpoint = new Uri(DefaultApiEndPoint), PulseEndpoint = new Uri(DefaultPulseEndPoint) }); } } public Uri ApiEndpoint { get; set; } public Uri PulseEndpoint{ get; set; } public bool SetUnobservedTaskExceptionsAsObserved { get; set; } } }
Put in some debugging code for looking at what functions have been added to the rooted event handler.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MatterHackers.Agg.UI { public class RootedObjectEventHandler { EventHandler InternalEvent; public void RegisterEvent(EventHandler functionToCallOnEvent, ref EventHandler functionThatWillBeCalledToUnregisterEvent) { InternalEvent += functionToCallOnEvent; functionThatWillBeCalledToUnregisterEvent += (sender, e) => { InternalEvent -= functionToCallOnEvent; }; } public void UnregisterEvent(EventHandler functionToCallOnEvent, ref EventHandler functionThatWillBeCalledToUnregisterEvent) { InternalEvent -= functionToCallOnEvent; // After we remove it it will still be removed again in the functionThatWillBeCalledToUnregisterEvent // But it is valid to attempt remove more than once. } public void CallEvents(Object sender, EventArgs e) { if (InternalEvent != null) { InternalEvent(this, e); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MatterHackers.Agg.UI { public class RootedObjectEventHandler { #if DEBUG private event EventHandler InternalEventForDebug; private List<EventHandler> DebugEventDelegates = new List<EventHandler>(); private event EventHandler InternalEvent { //Wraps the PrivateClick event delegate so that we can track which events have been added and clear them if necessary add { InternalEventForDebug += value; DebugEventDelegates.Add(value); } remove { InternalEventForDebug -= value; DebugEventDelegates.Remove(value); } } #else EventHandler InternalEvent; #endif public void RegisterEvent(EventHandler functionToCallOnEvent, ref EventHandler functionThatWillBeCalledToUnregisterEvent) { InternalEvent += functionToCallOnEvent; functionThatWillBeCalledToUnregisterEvent += (sender, e) => { InternalEvent -= functionToCallOnEvent; }; } public void UnregisterEvent(EventHandler functionToCallOnEvent, ref EventHandler functionThatWillBeCalledToUnregisterEvent) { InternalEvent -= functionToCallOnEvent; // After we remove it it will still be removed again in the functionThatWillBeCalledToUnregisterEvent // But it is valid to attempt remove more than once. } public void CallEvents(Object sender, EventArgs e) { #if DEBUG if (InternalEventForDebug != null) { InternalEventForDebug(this, e); } #else if (InternalEvent != null) { InternalEvent(this, e); } #endif } } }
Add in check for null pointers.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GrienerTest { public partial class PolygonClip { #if false void insert(node *ins, node *first, node *last) { node *aux=first; while(aux != last && aux->alpha < ins->alpha) aux = aux->next; ins->next = aux; ins->prev = aux->prev; ins->prev->next = ins; ins->next->prev = ins; } #endif void insert(Node ins,Node first,Node last) { Node aux = first; while (aux != last && aux.alpha < ins.alpha) aux = aux.next; ins.next = aux; ins.prev = aux.prev; ins.prev.next = ins; ins.next.prev = ins; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GrienerTest { public partial class PolygonClip { #if false void insert(node *ins, node *first, node *last) { node *aux=first; while(aux != last && aux->alpha < ins->alpha) aux = aux->next; ins->next = aux; ins->prev = aux->prev; ins->prev->next = ins; ins->next->prev = ins; } #endif void insert(Node ins,Node first,Node last) { Node aux = first; while (aux != last && aux.alpha < ins.alpha) aux = aux.next; ins.next = aux; ins.prev = aux.prev; /* * Feb 2017. Check against null pointer */ if (ins.prev != null) { ins.prev.next = ins; } if (ins.next != null) { ins.next.prev = ins; } } } }
Add nick wolf contact info.
@{ ViewBag.Title = "Contact"; } <h2>@ViewBag.Title.</h2> <h3>@ViewBag.Message</h3> <address> One Microsoft Way<br /> Redmond, WA 98052-6399<br /> <abbr title="Phone">P:</abbr> 425.555.0100 </address> <address> <strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br /> <strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a> <strong>Pat:</strong> <a href="mailto:patrick.fulton@zirmed.com">patrick.fulton@zirmed.com</a> <strong>Dustin:</strong> <a href="mailto:dustin.crawford@zirmed.com">dustin.crawford@zirmed.com</a> </address>
@{ ViewBag.Title = "Contact"; } <h2>@ViewBag.Title.</h2> <h3>@ViewBag.Message</h3> <address> One Microsoft Way<br /> Redmond, WA 98052-6399<br /> <abbr title="Phone">P:</abbr> 425.555.0100 </address> <address> <strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br /> <strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a> <strong>Pat:</strong> <a href="mailto:patrick.fulton@zirmed.com">patrick.fulton@zirmed.com</a> <strong>Dustin:</strong> <a href="mailto:dustin.crawford@zirmed.com">dustin.crawford@zirmed.com</a> <strong>Nicolas:</strong> <a href="mailto:nick.wolf@zirmed.com">nick.wolf@zirmed.com</a> </address>
Fix indentation when changing inside multiline block
using System; using Mono.TextEditor; using ICSharpCode.NRefactory; namespace JustEnoughVi { public class ChangeInnerBlock : ChangeCommand { public ChangeInnerBlock(TextEditorData editor, char openingChar, char closingChar) : base(editor, TextObject.InnerBlock, openingChar, closingChar) { } protected override void Run() { CommandRange range = _selector(); ChangeRange(range); if (range != CommandRange.Empty) { // Move caret inside if it is on on opening character and block is empty if (range.Length == 0 && Editor.Caret.Offset < range.Start) Editor.Caret.Offset++; else { // if block still has two newlines inside, then drop inside block and indent int del1 = NewLine.GetDelimiterLength(Editor.Text[range.Start - 1], Editor.Text[range.Start]); if (del1 > 0) { int del2Start = range.Start - 1 + del1; int del2 = NewLine.GetDelimiterLength(Editor.Text[del2Start], Editor.Text[del2Start + 1]); if (del2 > 0) IndentInsideBlock(range.Start); } } } } private void IndentInsideBlock(int blockStart) { int end = blockStart; while (Char.IsWhiteSpace(Editor.Text[end])) end++; Editor.SetSelection(blockStart, end); Editor.DeleteSelectedText(); MiscActions.InsertNewLine(Editor); } } }
using System; using Mono.TextEditor; using ICSharpCode.NRefactory.Utils; using ICSharpCode.NRefactory; namespace JustEnoughVi { public class ChangeInnerBlock : ChangeCommand { public ChangeInnerBlock(TextEditorData editor, char openingChar, char closingChar) : base(editor, TextObject.InnerBlock, openingChar, closingChar) { } protected override void Run() { CommandRange range = _selector(); ChangeRange(range); if (range != CommandRange.Empty) { // Move caret inside if it is on on opening character and block is empty if (range.Length == 0 && Editor.Caret.Offset < range.Start) Editor.Caret.Offset++; else { // if block still has two newlines inside, then drop inside block and indent int del1 = NewLine.GetDelimiterLength(Editor.Text[range.Start - 1], Editor.Text[range.Start]); if (del1 > 0) { int del2Start = range.Start - 1 + del1; int del2 = NewLine.GetDelimiterLength(Editor.Text[del2Start], Editor.Text[del2Start + 1]); if (del2 > 0) IndentInsideBlock(range.Start - 2); } } } } private void IndentInsideBlock(int openingChar) { string indentation = Editor.GetLineIndent(Editor.OffsetToLineNumber(openingChar)); if (indentation != null && indentation.Length > 0) Editor.Insert(Editor.Caret.Offset, indentation); MiscActions.InsertTab(Editor); } } }
Use portable ToCharArray overload yielding equivalent result
using System; using System.IO; using System.Text; namespace EvilDICOM.Core.IO.Writing { public class DICOMBinaryWriter : IDisposable { private readonly BinaryWriter _writer; /// <summary> /// Constructs a new writer from a file path. /// </summary> /// <param name="filePath">path to the file to be written</param> public DICOMBinaryWriter(string filePath) { _writer = new BinaryWriter( File.Open(filePath, FileMode.Create), Encoding.UTF8); } public DICOMBinaryWriter(Stream stream) { _writer = new BinaryWriter(stream, Encoding.UTF8); } public void Dispose() { _writer.Dispose(); } public void Write(byte b) { _writer.Write(b); } public void Write(byte[] bytes) { _writer.Write(bytes); } public void Write(char[] chars) { _writer.Write(chars); } public void Write(string chars) { char[] asCharArray = chars.ToCharArray(0, chars.Length); Write(asCharArray); } public void WriteNullBytes(int numberToWrite) { for (int i = 0; i < numberToWrite; i++) { Write(0x00); } } } }
using System; using System.IO; using System.Text; namespace EvilDICOM.Core.IO.Writing { public class DICOMBinaryWriter : IDisposable { private readonly BinaryWriter _writer; /// <summary> /// Constructs a new writer from a file path. /// </summary> /// <param name="filePath">path to the file to be written</param> public DICOMBinaryWriter(string filePath) { _writer = new BinaryWriter( File.Open(filePath, FileMode.Create), Encoding.UTF8); } public DICOMBinaryWriter(Stream stream) { _writer = new BinaryWriter(stream, Encoding.UTF8); } public void Dispose() { _writer.Dispose(); } public void Write(byte b) { _writer.Write(b); } public void Write(byte[] bytes) { _writer.Write(bytes); } public void Write(char[] chars) { _writer.Write(chars); } public void Write(string chars) { char[] asCharArray = chars.ToCharArray(); Write(asCharArray); } public void WriteNullBytes(int numberToWrite) { for (int i = 0; i < numberToWrite; i++) { Write(0x00); } } } }
Allow to run build even if git repo informations are not available
#tool "nuget:?package=GitVersion.CommandLine" #addin "Cake.Yaml" public class ContextInfo { public string NugetVersion { get; set; } public string AssemblyVersion { get; set; } public GitVersion Git { get; set; } public string BuildVersion { get { return NugetVersion + "-" + Git.Sha; } } } ContextInfo _versionContext = null; public ContextInfo VersionContext { get { if(_versionContext == null) throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property."); return _versionContext; } } public ContextInfo ReadContext(FilePath filepath) { _versionContext = DeserializeYamlFromFile<ContextInfo>(filepath); _versionContext.Git = GitVersion(); return _versionContext; } public void UpdateAppVeyorBuildVersionNumber() { var increment = 0; while(increment < 10) { try { var version = VersionContext.BuildVersion; if(increment > 0) version += "-" + increment; AppVeyor.UpdateBuildVersion(version); break; } catch { increment++; } } }
#tool "nuget:?package=GitVersion.CommandLine" #addin "Cake.Yaml" public class ContextInfo { public string NugetVersion { get; set; } public string AssemblyVersion { get; set; } public GitVersion Git { get; set; } public string BuildVersion { get { return NugetVersion + "-" + Git.Sha; } } } ContextInfo _versionContext = null; public ContextInfo VersionContext { get { if(_versionContext == null) throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property."); return _versionContext; } } public ContextInfo ReadContext(FilePath filepath) { _versionContext = DeserializeYamlFromFile<ContextInfo>(filepath); try { _versionContext.Git = GitVersion(); } catch { _versionContext.Git = new Cake.Common.Tools.GitVersion.GitVersion(); } return _versionContext; } public void UpdateAppVeyorBuildVersionNumber() { var increment = 0; while(increment < 10) { try { var version = VersionContext.BuildVersion; if(increment > 0) version += "-" + increment; AppVeyor.UpdateBuildVersion(version); break; } catch { increment++; } } }
Add some code to dump known colors
using System; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; class Program { [STAThread] static void Main(string[] args) { var app = new Application(); var window = new Window(); window.WindowStartupLocation = WindowStartupLocation.CenterScreen; window.WindowState = WindowState.Maximized; window.Title = "SystemColors"; var content = new ListBox(); foreach (var prop in typeof(SystemColors).GetProperties().Where(p => p.PropertyType == typeof(SolidColorBrush))) { var brush = prop.GetValue(null) as SolidColorBrush; var rect = new Rectangle() { Width = 100, Height = 20, Fill = brush }; var panel = new StackPanel() { Orientation = Orientation.Horizontal }; panel.Children.Add(new TextBlock() { Text = prop.Name, Width = 200 }); panel.Children.Add(rect); panel.Children.Add(new TextBlock() { Text = brush.Color.ToString(), Margin = new Thickness(8, 0, 8, 0) }); content.Items.Add(panel); } window.Content = content; app.Run(window); } }
using System; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; class Program { [STAThread] static void Main(string[] args) { var app = new Application(); var window = new Window(); window.WindowStartupLocation = WindowStartupLocation.CenterScreen; window.WindowState = WindowState.Maximized; window.Title = "SystemColors"; var content = new ListBox(); var sb = new StringBuilder(); foreach (var prop in typeof(SystemColors).GetProperties().Where(p => p.PropertyType == typeof(SolidColorBrush))) { var brush = prop.GetValue(null) as SolidColorBrush; var rect = new Rectangle() { Width = 100, Height = 20, Fill = brush }; var panel = new StackPanel() { Orientation = Orientation.Horizontal }; panel.Children.Add(new TextBlock() { Text = prop.Name, Width = 200 }); panel.Children.Add(rect); panel.Children.Add(new TextBlock() { Text = brush.Color.ToString(), Margin = new Thickness(8, 0, 8, 0) }); content.Items.Add(panel); } foreach (var prop in typeof(Colors).GetProperties().Where(p => p.PropertyType == typeof(Color))) { var color = (Color)prop.GetValue(null); sb.AppendLine($"{color.R / 255.0}, {color.G / 255.0}, {color.B / 255.0},"); //sb.AppendLine($"{color.ScR}, {color.ScG}, {color.ScB},"); } // Clipboard.SetText(sb.ToString()); window.Content = content; app.Run(window); } }
Revert "Revert "auswertung von tags gebessert""
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using Antlr4.Runtime; using Antlr4.Runtime.Misc; using Antlr4.Runtime.Tree; namespace Twee2Z.Analyzer { public static class TweeAnalyzer { public static ObjectTree.Tree Parse(StreamReader input) { return Parse2(Lex(input)); } public static ObjectTree.Tree Parse2(CommonTokenStream input) { System.Console.WriteLine("Parse twee file ..."); Twee.StartContext startContext = new Twee(input).start(); TweeVisitor visit = new TweeVisitor(); visit.Visit(startContext); System.Console.WriteLine("Convert parse tree into object tree ..."); return visit.Tree; } public static CommonTokenStream Lex(StreamReader input) { System.Console.WriteLine("Lex twee file ..."); AntlrInputStream antlrStream = new AntlrInputStream(input.ReadToEnd()); return new CommonTokenStream(new LEX(antlrStream)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using Antlr4.Runtime; using Antlr4.Runtime.Misc; using Antlr4.Runtime.Tree; namespace Twee2Z.Analyzer { public static class TweeAnalyzer { public static ObjectTree.Tree Parse(StreamReader input) { return Parse2(Lex(input)); } public static ObjectTree.Tree Parse2(CommonTokenStream input) { System.Console.WriteLine("Parse twee file ..."); Twee.StartContext startContext = new Twee(input).start(); TweeVisitor visit = new TweeVisitor(); visit.Visit(startContext); System.Console.WriteLine("Convert parse tree into object tree ..."); return visit.Tree; } public static CommonTokenStream Lex(StreamReader input) { System.Console.WriteLine("Lex twee file ..."); AntlrInputStream antlrStream = new AntlrInputStream(input.ReadToEnd()); return new CommonTokenStream(new LEX(antlrStream)); } } }
Fix to ensure Delta start time is reset when storage is re-created
using System; using System.Threading.Tasks; using Eurofurence.App.Domain.Model.Abstractions; using Eurofurence.App.Domain.Model.Sync; using Eurofurence.App.Server.Services.Abstractions; namespace Eurofurence.App.Server.Services.Storage { public class StorageService<T> : IStorageService { private readonly IEntityStorageInfoRepository _entityStorageInfoRepository; private readonly string _entityType; public StorageService(IEntityStorageInfoRepository entityStorageInfoRepository, string entityType) { _entityStorageInfoRepository = entityStorageInfoRepository; _entityType = entityType; } public async Task TouchAsync() { var record = await GetEntityStorageRecordAsync(); record.LastChangeDateTimeUtc = DateTime.UtcNow; await _entityStorageInfoRepository.ReplaceOneAsync(record); } public async Task ResetDeltaStartAsync() { var record = await GetEntityStorageRecordAsync(); record.DeltaStartDateTimeUtc = DateTime.UtcNow; await _entityStorageInfoRepository.ReplaceOneAsync(record); } public Task<EntityStorageInfoRecord> GetStorageInfoAsync() { return GetEntityStorageRecordAsync(); } private async Task<EntityStorageInfoRecord> GetEntityStorageRecordAsync() { var record = await _entityStorageInfoRepository.FindOneAsync(_entityType); if (record == null) { record = new EntityStorageInfoRecord {EntityType = _entityType}; record.NewId(); record.Touch(); await _entityStorageInfoRepository.InsertOneAsync(record); } return record; } } }
using System; using System.Threading.Tasks; using Eurofurence.App.Domain.Model.Abstractions; using Eurofurence.App.Domain.Model.Sync; using Eurofurence.App.Server.Services.Abstractions; namespace Eurofurence.App.Server.Services.Storage { public class StorageService<T> : IStorageService { private readonly IEntityStorageInfoRepository _entityStorageInfoRepository; private readonly string _entityType; public StorageService(IEntityStorageInfoRepository entityStorageInfoRepository, string entityType) { _entityStorageInfoRepository = entityStorageInfoRepository; _entityType = entityType; } public async Task TouchAsync() { var record = await GetEntityStorageRecordAsync(); record.LastChangeDateTimeUtc = DateTime.UtcNow; await _entityStorageInfoRepository.ReplaceOneAsync(record); } public async Task ResetDeltaStartAsync() { var record = await GetEntityStorageRecordAsync(); record.DeltaStartDateTimeUtc = DateTime.UtcNow; await _entityStorageInfoRepository.ReplaceOneAsync(record); } public Task<EntityStorageInfoRecord> GetStorageInfoAsync() { return GetEntityStorageRecordAsync(); } private async Task<EntityStorageInfoRecord> GetEntityStorageRecordAsync() { var record = await _entityStorageInfoRepository.FindOneAsync(_entityType); if (record == null) { record = new EntityStorageInfoRecord { EntityType = _entityType, DeltaStartDateTimeUtc = DateTime.UtcNow }; record.NewId(); record.Touch(); await _entityStorageInfoRepository.InsertOneAsync(record); } return record; } } }
Revert "Added place to output products"
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Vending.Core { public class VendingMachine { private readonly List<Coin> _coins = new List<Coin>(); private readonly List<Coin> _returnTray = new List<Coin>(); private readonly List<string> _output = new List<string>(); public IEnumerable<Coin> ReturnTray => _returnTray; public IEnumerable<string> Output => _output; public void Dispense(string sku) { _output.Add(sku); } public void Accept(Coin coin) { if (coin.Value() == 0) { _returnTray.Add(coin); return; } _coins.Add(coin); } public string GetDisplayText() { if (!_coins.Any()) { return "INSERT COIN"; } return $"{CurrentTotal():C}"; } private decimal CurrentTotal() { var counts = new Dictionary<Coin, int>() { {Coin.Nickel, 0}, {Coin.Dime, 0}, {Coin.Quarter, 0} }; foreach (var coin in _coins) { counts[coin]++; } decimal total = 0; foreach (var coinCount in counts) { total += (coinCount.Value * coinCount.Key.Value()); } return ConvertCentsToDollars(total); } private static decimal ConvertCentsToDollars(decimal total) { return total / 100; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Vending.Core { public class VendingMachine { private readonly List<Coin> _coins = new List<Coin>(); private readonly List<Coin> _returnTray = new List<Coin>(); public IEnumerable<Coin> ReturnTray => _returnTray; public void Dispense(string soda) { } public void Accept(Coin coin) { if (coin.Value() == 0) { _returnTray.Add(coin); return; } _coins.Add(coin); } public string GetDisplayText() { if (!_coins.Any()) { return "INSERT COIN"; } return $"{CurrentTotal():C}"; } private decimal CurrentTotal() { var counts = new Dictionary<Coin, int>() { {Coin.Nickel, 0}, {Coin.Dime, 0}, {Coin.Quarter, 0} }; foreach (var coin in _coins) { counts[coin]++; } decimal total = 0; foreach (var coinCount in counts) { total += (coinCount.Value * coinCount.Key.Value()); } return ConvertCentsToDollars(total); } private static decimal ConvertCentsToDollars(decimal total) { return total / 100; } } }
Fix display of color code
using System; using System.Globalization; using System.Windows.Data; using System.Windows.Media; namespace MaterialDesignDemo.Converters { public class BrushToHexConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) return null; string lowerHexString(int i) => i.ToString("X").ToLower(); var brush = (SolidColorBrush)value; var hex = lowerHexString(brush.Color.R) + lowerHexString(brush.Color.G) + lowerHexString(brush.Color.B); return "#" + hex; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
using System; using System.Globalization; using System.Windows.Data; using System.Windows.Media; namespace MaterialDesignDemo.Converters { public class BrushToHexConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) return null; string lowerHexString(int i) => i.ToString("X2").ToLower(); var brush = (SolidColorBrush)value; var hex = lowerHexString(brush.Color.R) + lowerHexString(brush.Color.G) + lowerHexString(brush.Color.B); return "#" + hex; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
Add remark to doc comment
using System; namespace RockLib.Messaging { /// <summary> /// Defines an interface for receiving messages. To start receiving messages, /// set the value of the <see cref="MessageHandler"/> property. /// </summary> public interface IReceiver : IDisposable { /// <summary> /// Gets the name of this instance of <see cref="IReceiver"/>. /// </summary> string Name { get; } /// <summary> /// Gets or sets the message handler for this receiver. When set, the receiver is started /// and will invoke the value's <see cref="IMessageHandler.OnMessageReceived"/> method /// when messages are received. /// </summary> IMessageHandler MessageHandler { get; set; } /// <summary> /// Occurs when a connection is established. /// </summary> event EventHandler Connected; /// <summary> /// Occurs when a connection is lost. /// </summary> event EventHandler<DisconnectedEventArgs> Disconnected; } }
using System; namespace RockLib.Messaging { /// <summary> /// Defines an interface for receiving messages. To start receiving messages, /// set the value of the <see cref="MessageHandler"/> property. /// </summary> public interface IReceiver : IDisposable { /// <summary> /// Gets the name of this instance of <see cref="IReceiver"/>. /// </summary> string Name { get; } /// <summary> /// Gets or sets the message handler for this receiver. When set, the receiver is started /// and will invoke the value's <see cref="IMessageHandler.OnMessageReceived"/> method /// when messages are received. /// </summary> /// <remarks> /// Implementions of this interface should not allow this property to be set to null or /// to be set more than once. /// </remarks> IMessageHandler MessageHandler { get; set; } /// <summary> /// Occurs when a connection is established. /// </summary> event EventHandler Connected; /// <summary> /// Occurs when a connection is lost. /// </summary> event EventHandler<DisconnectedEventArgs> Disconnected; } }
Add city power and water variables.
using Citysim.Map; namespace Citysim { public class City { /// <summary> /// Amount of cash available. /// </summary> public int cash = 10000; // $10,000 starting cash /// <summary> /// The world. Needs generation. /// </summary> public World world = new World(); } }
using Citysim.Map; namespace Citysim { public class City { /// <summary> /// Amount of cash available. /// </summary> public int cash = 10000; // $10,000 starting cash /// <summary> /// MW (mega watts) of electricity available to the city. /// </summary> public int power = 0; /// <summary> /// ML (mega litres) of water available to the city. /// </summary> public int water = 0; /// <summary> /// The world. Needs generation. /// </summary> public World world = new World(); } }
Remove whitespace in informational text
// Copyright 2018 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using System.Reflection; namespace Nuke.Common.Utilities { public static class AssemblyExtensions { public static string GetInformationalText(this Assembly assembly) { return $"version {assembly.GetVersionText()} ({EnvironmentInfo.Platform}, {EnvironmentInfo.Framework})"; } public static string GetVersionText(this Assembly assembly) { var informationalVersion = assembly.GetAssemblyInformationalVersion(); var plusIndex = informationalVersion.IndexOf(value: '+'); return plusIndex == -1 ? "LOCAL" : informationalVersion.Substring(startIndex: 0, length: plusIndex); } private static string GetAssemblyInformationalVersion(this Assembly assembly) { return assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion; } } }
// Copyright 2018 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using System.Reflection; namespace Nuke.Common.Utilities { public static class AssemblyExtensions { public static string GetInformationalText(this Assembly assembly) { return $"version {assembly.GetVersionText()} ({EnvironmentInfo.Platform},{EnvironmentInfo.Framework})"; } public static string GetVersionText(this Assembly assembly) { var informationalVersion = assembly.GetAssemblyInformationalVersion(); var plusIndex = informationalVersion.IndexOf(value: '+'); return plusIndex == -1 ? "LOCAL" : informationalVersion.Substring(startIndex: 0, length: plusIndex); } private static string GetAssemblyInformationalVersion(this Assembly assembly) { return assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion; } } }
Rename Tenant to Domain in the web api template
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Company.WebApplication1 { public class AzureAdB2COptions { public string ClientId { get; set; } public string AzureAdB2CInstance { get; set; } public string Tenant { get; set; } public string SignUpSignInPolicyId { get; set; } public string DefaultPolicy => SignUpSignInPolicyId; public string Authority => $"{AzureAdB2CInstance}/{Tenant}/{DefaultPolicy}/v2.0"; public string Audience => ClientId; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Company.WebApplication1 { public class AzureAdB2COptions { public string ClientId { get; set; } public string AzureAdB2CInstance { get; set; } public string Domain { get; set; } public string SignUpSignInPolicyId { get; set; } public string DefaultPolicy => SignUpSignInPolicyId; public string Authority => $"{AzureAdB2CInstance}/{Domain}/{DefaultPolicy}/v2.0"; public string Audience => ClientId; } }
Fix classification test to use object type.
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.LiveShare.CustomProtocol; using Xunit; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests { public class ClassificationsHandlerTests : AbstractLiveShareRequestHandlerTests { [Fact] public async Task TestClassificationsAsync() { var markup = @"class A { void M() { {|classify:var|} i = 1; } }"; var (solution, ranges) = CreateTestSolution(markup); var classifyLocation = ranges["classify"].First(); var results = await TestHandleAsync<ClassificationParams, ClassificationSpan[]>(solution, CreateClassificationParams(classifyLocation)); AssertCollectionsEqual(new ClassificationSpan[] { CreateClassificationSpan("keyword", classifyLocation.Range) }, results, AssertClassificationsEqual); } private static void AssertClassificationsEqual(ClassificationSpan expected, ClassificationSpan actual) { Assert.Equal(expected.Classification, actual.Classification); Assert.Equal(expected.Range, actual.Range); } private static ClassificationSpan CreateClassificationSpan(string classification, Range range) => new ClassificationSpan() { Classification = classification, Range = range }; private static ClassificationParams CreateClassificationParams(Location location) => new ClassificationParams() { Range = location.Range, TextDocument = CreateTextDocumentIdentifier(location.Uri) }; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.LiveShare.CustomProtocol; using Xunit; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests { public class ClassificationsHandlerTests : AbstractLiveShareRequestHandlerTests { [Fact] public async Task TestClassificationsAsync() { var markup = @"class A { void M() { {|classify:var|} i = 1; } }"; var (solution, ranges) = CreateTestSolution(markup); var classifyLocation = ranges["classify"].First(); var results = await TestHandleAsync<ClassificationParams, object[]>(solution, CreateClassificationParams(classifyLocation)); AssertCollectionsEqual(new ClassificationSpan[] { CreateClassificationSpan("keyword", classifyLocation.Range) }, results, AssertClassificationsEqual); } private static void AssertClassificationsEqual(ClassificationSpan expected, ClassificationSpan actual) { Assert.Equal(expected.Classification, actual.Classification); Assert.Equal(expected.Range, actual.Range); } private static ClassificationSpan CreateClassificationSpan(string classification, Range range) => new ClassificationSpan() { Classification = classification, Range = range }; private static ClassificationParams CreateClassificationParams(Location location) => new ClassificationParams() { Range = location.Range, TextDocument = CreateTextDocumentIdentifier(location.Uri) }; } }
Add code to remove all old settings
namespace Mappy { using System; using System.Windows.Forms; using UI.Forms; public static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] public static void Main() { Application.ThreadException += Program.OnGuiUnhandedException; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } private static void HandleUnhandledException(object o) { Exception e = o as Exception; if (e != null) { throw e; } } private static void OnGuiUnhandedException(object sender, System.Threading.ThreadExceptionEventArgs e) { HandleUnhandledException(e.Exception); } } }
namespace Mappy { using System; using System.IO; using System.Windows.Forms; using UI.Forms; public static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] public static void Main() { RemoveOldVersionSettings(); Application.ThreadException += Program.OnGuiUnhandedException; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } private static void HandleUnhandledException(object o) { Exception e = o as Exception; if (e != null) { throw e; } } private static void OnGuiUnhandedException(object sender, System.Threading.ThreadExceptionEventArgs e) { HandleUnhandledException(e.Exception); } private static void RemoveOldVersionSettings() { string appDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); string oldDir = Path.Combine(appDir, @"Armoured_Fish"); try { if (Directory.Exists(oldDir)) { Directory.Delete(oldDir, true); } } catch (IOException) { // we don't care if this fails } } } }
Fix flush unclaer data bugs.
using System.Collections.Generic; using DotNetCore.CAP.Models; namespace DotNetCore.CAP { public abstract class CapTransactionBase : ICapTransaction { private readonly IDispatcher _dispatcher; private readonly IList<CapPublishedMessage> _bufferList; protected CapTransactionBase(IDispatcher dispatcher) { _dispatcher = dispatcher; _bufferList = new List<CapPublishedMessage>(1); } public bool AutoCommit { get; set; } public object DbTransaction { get; set; } protected internal virtual void AddToSent(CapPublishedMessage msg) { _bufferList.Add(msg); } protected void Flush() { foreach (var message in _bufferList) { _dispatcher.EnqueueToPublish(message); } } public abstract void Commit(); public abstract void Rollback(); public abstract void Dispose(); } }
using System.Collections.Generic; using DotNetCore.CAP.Models; namespace DotNetCore.CAP { public abstract class CapTransactionBase : ICapTransaction { private readonly IDispatcher _dispatcher; private readonly IList<CapPublishedMessage> _bufferList; protected CapTransactionBase(IDispatcher dispatcher) { _dispatcher = dispatcher; _bufferList = new List<CapPublishedMessage>(1); } public bool AutoCommit { get; set; } public object DbTransaction { get; set; } protected internal virtual void AddToSent(CapPublishedMessage msg) { _bufferList.Add(msg); } protected virtual void Flush() { foreach (var message in _bufferList) { _dispatcher.EnqueueToPublish(message); } _bufferList.Clear(); } public abstract void Commit(); public abstract void Rollback(); public abstract void Dispose(); } }
Fix one remaining case of incorrect audio testing
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; namespace osu.Framework.Tests.Audio { [TestFixture] public class DevicelessAudioTest : AudioThreadTest { public override void SetUp() { base.SetUp(); // lose all devices Manager.SimulateDeviceLoss(); } [Test] public void TestPlayTrackWithoutDevices() { var track = Manager.Tracks.Get("Tracks.sample-track.mp3"); // start track track.Restart(); Assert.IsTrue(track.IsRunning); CheckTrackIsProgressing(track); // stop track track.Stop(); WaitForOrAssert(() => !track.IsRunning, "Track did not stop", 1000); Assert.IsFalse(track.IsRunning); // seek track track.Seek(0); Assert.IsFalse(track.IsRunning); Assert.AreEqual(track.CurrentTime, 0); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; namespace osu.Framework.Tests.Audio { [TestFixture] public class DevicelessAudioTest : AudioThreadTest { public override void SetUp() { base.SetUp(); // lose all devices Manager.SimulateDeviceLoss(); } [Test] public void TestPlayTrackWithoutDevices() { var track = Manager.Tracks.Get("Tracks.sample-track.mp3"); // start track track.Restart(); Assert.IsTrue(track.IsRunning); CheckTrackIsProgressing(track); // stop track track.Stop(); WaitForOrAssert(() => !track.IsRunning, "Track did not stop", 1000); Assert.IsFalse(track.IsRunning); // seek track track.Seek(0); Assert.IsFalse(track.IsRunning); WaitForOrAssert(() => track.CurrentTime == 0, "Track did not seek correctly", 1000); } } }
Make the jumbotron inside a container.
 <div id="my-jumbotron" class="jumbotron"> <div class="container"> <h1>Welcome!</h1> <p>We are Sweet Water Revolver. This is our website. Please look around and check out our...</p> <p><a class="btn btn-primary btn-lg" role="button">... showtimes.</a></p> </div> </div>
<div class="container"> <div id="my-jumbotron" class="jumbotron"> <h1>Welcome!</h1> <p>We are Sweet Water Revolver. This is our website. Please look around and check out our...</p> <p><a class="btn btn-primary btn-lg" role="button">... showtimes.</a></p> </div> </div>
Fix Error With Skill Test
using UnityEngine; using System.Collections; public class test : Skill { private float duration = 10f; private float expiration; bool active; Player player; private int bonusStrength; protected override void Start() { base.Start(); base.SetBaseValues(15, 16000, 150, "Ignite", SkillLevel.Level1); player = GetComponent<Player>(); } protected override void Update() { base.Update(); if(active && Time.time >= expiration) { active = false; player.transform.GetChild(0).GetComponent<DealDamage>().isMagic = false; player.SetStrength(player.GetStrength() - bonusStrength); } } public override void UseSkill(GameObject caller, GameObject target = null, object optionalParameters = null) { base.UseSkill(gameObject); expiration = Time.time + duration; active = true; player.transform.GetChild(0).GetComponent<DealDamage>().isMagic = true; bonusStrength = player.GetIntelligence() / 2; player.SetStrength(player.GetStrength() + bonusStrength); } } public class skilltesting : MonoBehaviour { float castInterval; private Skill testSkill; // Use this for initialization void Start () { gameObject.AddComponent<Fireball>(); testSkill = GetComponent<Skill>(); } // Update is called once per frame void Update () { if(testSkill.GetCoolDownTimer() <= 0) { testSkill.UseSkill(gameObject); } } }
using UnityEngine; using System.Collections; public class test : Skill { private float duration = 10f; private float expiration; bool active; Player player; private int bonusStrength; protected override void Start() { base.Start(); base.SetBaseValues(15, 16000, 150, "Ignite", SkillLevel.Level1); player = GetComponent<Player>(); } protected override void Update() { base.Update(); if(active && Time.time >= expiration) { active = false; player.transform.GetChild(0).GetComponent<DealDamage>().isMagic = false; player.SetStrength(player.GetStrength() - bonusStrength); } } public override void UseSkill(GameObject caller, GameObject target = null, object optionalParameters = null) { base.UseSkill(gameObject); expiration = Time.time + duration; active = true; player.transform.GetChild(0).GetComponent<DealDamage>().isMagic = true; bonusStrength = player.GetIntelligence() / 2; player.SetStrength(player.GetStrength() + bonusStrength); } } public class skilltesting : MonoBehaviour { float castInterval; private Skill testSkill; // Use this for initialization void Start () { gameObject.AddComponent<FireballSkill>(); testSkill = GetComponent<Skill>(); } // Update is called once per frame void Update () { if(testSkill.GetCoolDownTimer() <= 0) { testSkill.UseSkill(gameObject); } } }
Add edge case unit tests
using Xunit; namespace Pioneer.Pagination.Tests { /// <summary> /// Clamp Tests /// </summary> public class ClampTests { private readonly PaginatedMetaService _sut = new PaginatedMetaService(); [Fact] public void LastPageDisplayed() { var result = _sut.GetMetaData(10, 11, 1); Assert.True(result.NextPage.PageNumber == 10, "Expected: Last Page "); } [Fact] public void FirstPageDisplayed() { var result = _sut.GetMetaData(10, 0, 1); Assert.True(result.NextPage.PageNumber == 1, "Expected: First Page "); } } }
using Xunit; namespace Pioneer.Pagination.Tests { /// <summary> /// Clamp Tests /// </summary> public class ClampTests { private readonly PaginatedMetaService _sut = new PaginatedMetaService(); [Fact] public void NextPageIsLastPageInCollectionWhenRequestedPageIsGreatedThenCollection() { var result = _sut.GetMetaData(10, 11, 1); Assert.True(result.NextPage.PageNumber == 10, "Expected: Last Page "); } [Fact] public void PreviousPageIsLastPageMinusOneInCollectionWhenRequestedPageIsGreatedThenCollection() { var result = _sut.GetMetaData(10, 11, 1); Assert.True(result.PreviousPage.PageNumber == 9, "Expected: Last Page "); } [Fact] public void PreviousPageIsFirstPageInCollectionWhenRequestedPageIsZero() { var result = _sut.GetMetaData(10, 0, 1); Assert.True(result.PreviousPage.PageNumber == 1, "Expected: First Page "); } [Fact] public void NextPageIsSecondPageInCollectionWhenRequestedPageIsZero() { var result = _sut.GetMetaData(10, 0, 1); Assert.True(result.NextPage.PageNumber == 2, "Expected: First Page "); } [Fact] public void PreviousPageIsFirstPageInCollectionWhenRequestedPageIsNegative() { var result = _sut.GetMetaData(10, -1, 1); Assert.True(result.PreviousPage.PageNumber == 1, "Expected: First Page "); } [Fact] public void NextPageIsSecondPageInCollectionWhenRequestedPageIsNegative() { var result = _sut.GetMetaData(10, -1, 1); Assert.True(result.NextPage.PageNumber == 2, "Expected: First Page "); } } }
Enable https redirection and authorization for non-dev envs only
using TruckRouter.Models; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddTransient<IMazeSolver, MazeSolverBFS>(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
using TruckRouter.Models; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddTransient<IMazeSolver, MazeSolverBFS>(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); app.UseDeveloperExceptionPage(); } else { app.UseHttpsRedirection(); app.UseAuthorization(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
Add test for authorization requirement in TraktUserCustomListUpdateRequest
namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth { using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using TraktApiSharp.Experimental.Requests.Base.Put; using TraktApiSharp.Experimental.Requests.Users.OAuth; using TraktApiSharp.Objects.Get.Users.Lists; using TraktApiSharp.Objects.Post.Users; [TestClass] public class TraktUserCustomListUpdateRequestTests { [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserCustomListUpdateRequestIsNotAbstract() { typeof(TraktUserCustomListUpdateRequest).IsAbstract.Should().BeFalse(); } [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserCustomListUpdateRequestIsSealed() { typeof(TraktUserCustomListUpdateRequest).IsSealed.Should().BeTrue(); } [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserCustomListUpdateRequestIsSubclassOfATraktSingleItemPutByIdRequest() { typeof(TraktUserCustomListUpdateRequest).IsSubclassOf(typeof(ATraktSingleItemPutByIdRequest<TraktList, TraktUserCustomListPost>)).Should().BeTrue(); } } }
namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth { using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using TraktApiSharp.Experimental.Requests.Base.Put; using TraktApiSharp.Experimental.Requests.Users.OAuth; using TraktApiSharp.Objects.Get.Users.Lists; using TraktApiSharp.Objects.Post.Users; using TraktApiSharp.Requests; [TestClass] public class TraktUserCustomListUpdateRequestTests { [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserCustomListUpdateRequestIsNotAbstract() { typeof(TraktUserCustomListUpdateRequest).IsAbstract.Should().BeFalse(); } [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserCustomListUpdateRequestIsSealed() { typeof(TraktUserCustomListUpdateRequest).IsSealed.Should().BeTrue(); } [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserCustomListUpdateRequestIsSubclassOfATraktSingleItemPutByIdRequest() { typeof(TraktUserCustomListUpdateRequest).IsSubclassOf(typeof(ATraktSingleItemPutByIdRequest<TraktList, TraktUserCustomListPost>)).Should().BeTrue(); } [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserCustomListUpdateRequestHasAuthorizationRequired() { var request = new TraktUserCustomListUpdateRequest(null); request.AuthorizationRequirement.Should().Be(TraktAuthorizationRequirement.Required); } } }
Add original constructor signature as there is Inception code which looks for it
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Umbraco.Inception.Attributes { [AttributeUsage(AttributeTargets.Property)] public class UmbracoTabAttribute : Attribute { public string Name { get; set; } public int SortOrder { get; set; } public UmbracoTabAttribute(string name, int sortOrder = 0) { Name = name; SortOrder = sortOrder; } } }
using System; namespace Umbraco.Inception.Attributes { [AttributeUsage(AttributeTargets.Property)] public class UmbracoTabAttribute : Attribute { public string Name { get; set; } public int SortOrder { get; set; } public UmbracoTabAttribute(string name) { Name = name; SortOrder = 0; } public UmbracoTabAttribute(string name, int sortOrder = 0) { Name = name; SortOrder = sortOrder; } } }
Revert "Revert "Added "final door count" comment at return value.""
using System.Linq; namespace HundredDoors { public static class HundredDoors { /// <summary> /// Solves the 100 Doors problem /// </summary> /// <returns>An array with 101 values, each representing a door (except 0). True = open</returns> public static bool[] Solve() { // Create our array with 101 values, all of them false. We'll only use 1~100 to simplify it bool[] doors = Enumerable.Repeat(false, 101).ToArray(); // We'll pass 100 times, each pass we'll start at door #pass and increment by pass, toggling the current door for (int pass = 1; pass <= 100; pass++) for (int i = pass; i < doors.Length; i += pass) doors[i] = !doors[i]; return doors; } } }
using System.Linq; namespace HundredDoors { public static class HundredDoors { /// <summary> /// Solves the 100 Doors problem /// </summary> /// <returns>An array with 101 values, each representing a door (except 0). True = open</returns> public static bool[] Solve() { // Create our array with 101 values, all of them false. We'll only use 1~100 to simplify it bool[] doors = Enumerable.Repeat(false, 101).ToArray(); // We'll pass 100 times, each pass we'll start at door #pass and increment by pass, toggling the current door for (int pass = 1; pass <= 100; pass++) for (int i = pass; i < doors.Length; i += pass) doors[i] = !doors[i]; return doors; //final door count } } }
Fix log command and return log lines
using Cake.Core; using Cake.Core.Annotations; using System; namespace Cake.Docker { partial class DockerAliases { /// <summary> /// Logs <paramref name="container"/> using default settings. /// </summary> /// <param name="context">The context.</param> /// <param name="container">The list of containers.</param> [CakeMethodAlias] public static void DockerLogs(this ICakeContext context, string container) { DockerLogs(context, new DockerContainerLogsSettings(), container); } /// <summary> /// Logs <paramref name="container"/> using the given <paramref name="settings"/>. /// </summary> /// <param name="context">The context.</param> /// <param name="container">The list of containers.</param> /// <param name="settings">The settings.</param> [CakeMethodAlias] public static void DockerLogs(this ICakeContext context, DockerContainerLogsSettings settings, string container) { if (context == null) { throw new ArgumentNullException("context"); } if (container == null) { throw new ArgumentNullException("container"); } var runner = new GenericDockerRunner<DockerContainerLogsSettings>(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); runner.Run("start", settings ?? new DockerContainerLogsSettings(), new string[] { container }); } } }
using Cake.Core; using Cake.Core.Annotations; using System; using System.Linq; using System.Collections.Generic; namespace Cake.Docker { partial class DockerAliases { /// <summary> /// Logs <paramref name="container"/> using default settings. /// </summary> /// <param name="context">The context.</param> /// <param name="container">The list of containers.</param> [CakeMethodAlias] public static IEnumerable<string> DockerLogs(this ICakeContext context, string container) { return DockerLogs(context, new DockerContainerLogsSettings(), container); } /// <summary> /// Logs <paramref name="container"/> using the given <paramref name="settings"/>. /// </summary> /// <param name="context">The context.</param> /// <param name="container">The list of containers.</param> /// <param name="settings">The settings.</param> [CakeMethodAlias] public static IEnumerable<string> DockerLogs(this ICakeContext context, DockerContainerLogsSettings settings, string container) { if (context == null) { throw new ArgumentNullException("context"); } if (container == null) { throw new ArgumentNullException("container"); } var runner = new GenericDockerRunner<DockerContainerLogsSettings>(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); return runner.RunWithResult("logs", settings ?? new DockerContainerLogsSettings(), r => r.ToArray(), new string[] { container }); } } }
Make DropdDownNavigationWorks more reliable and use new test methods.
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Bonobo.Git.Server.Controllers; using Bonobo.Git.Server.Test.Integration.Web; using Bonobo.Git.Server.Test.IntegrationTests.Helpers; using SpecsFor.Mvc; namespace Bonobo.Git.Server.Test.IntegrationTests { using OpenQA.Selenium.Support.UI; using OpenQA.Selenium; [TestClass] public class SharedLayoutTests : IntegrationTestBase { [TestMethod, TestCategory(TestCategories.WebIntegrationTest)] public void DropdownNavigationWorks() { var reponame = "A_Nice_Repo"; var id1 = ITH.CreateRepositoryOnWebInterface(reponame); var id2 = ITH.CreateRepositoryOnWebInterface("other_name"); app.NavigateTo<RepositoryController>(c => c.Detail(id2)); var element = app.Browser.FindElementByCssSelector("select#Repositories"); var dropdown = new SelectElement(element); dropdown.SelectByText(reponame); app.UrlMapsTo<RepositoryController>(c => c.Detail(id1)); app.WaitForElementToBeVisible(By.CssSelector("select#Repositories"), TimeSpan.FromSeconds(10)); dropdown = new SelectElement(app.Browser.FindElementByCssSelector("select#Repositories")); dropdown.SelectByText("other_name"); app.UrlMapsTo<RepositoryController>(c => c.Detail(id2)); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Bonobo.Git.Server.Controllers; using Bonobo.Git.Server.Test.Integration.Web; using Bonobo.Git.Server.Test.IntegrationTests.Helpers; using SpecsFor.Mvc; namespace Bonobo.Git.Server.Test.IntegrationTests { using OpenQA.Selenium.Support.UI; using OpenQA.Selenium; using System.Threading; [TestClass] public class SharedLayoutTests : IntegrationTestBase { [TestMethod, TestCategory(TestCategories.WebIntegrationTest)] public void DropdownNavigationWorks() { var reponame = ITH.MakeName(); var otherreponame = ITH.MakeName(reponame + "_other"); var repoId = ITH.CreateRepositoryOnWebInterface(reponame); var otherrepoId = ITH.CreateRepositoryOnWebInterface(otherreponame); app.NavigateTo<RepositoryController>(c => c.Detail(otherrepoId)); var element = app.Browser.FindElementByCssSelector("select#Repositories"); var dropdown = new SelectElement(element); dropdown.SelectByText(reponame); Thread.Sleep(2000); app.UrlMapsTo<RepositoryController>(c => c.Detail(repoId)); app.WaitForElementToBeVisible(By.CssSelector("select#Repositories"), TimeSpan.FromSeconds(10)); dropdown = new SelectElement(app.Browser.FindElementByCssSelector("select#Repositories")); dropdown.SelectByText(otherreponame); Thread.Sleep(2000); app.UrlMapsTo<RepositoryController>(c => c.Detail(otherrepoId)); } } }
Rework exception asserts to improve failure messages.
using System; using System.Linq; using System.Linq.Expressions; using FluentAssertions; namespace PSql.Tests { using static ScriptExecutor; internal static class StringExtensions { internal static void ShouldOutput( this string script, params object[] expected ) { if (script is null) throw new ArgumentNullException(nameof(script)); if (expected is null) throw new ArgumentNullException(nameof(expected)); var (objects, exception) = Execute(script); exception.Should().BeNull(); objects.Should().HaveCount(expected.Length); objects .Select(o => o?.BaseObject) .Should().BeEquivalentTo(expected, x => x.IgnoringCyclicReferences()); } internal static void ShouldThrow<T>( this string script, string messagePart ) where T : Exception { script.ShouldThrow<T>( e => e.Message.Contains(messagePart, StringComparison.OrdinalIgnoreCase) ); } internal static void ShouldThrow<T>( this string script, Expression<Func<T, bool>>? predicate = null ) where T : Exception { if (script is null) throw new ArgumentNullException(nameof(script)); var (_, exception) = Execute(script); exception.Should().NotBeNull().And.BeAssignableTo<T>(); if (predicate is not null) exception.Should().Match<T>(predicate); } } }
using System; using System.Linq; using System.Linq.Expressions; using FluentAssertions; namespace PSql.Tests { using static ScriptExecutor; internal static class StringExtensions { internal static void ShouldOutput( this string script, params object[] expected ) { if (script is null) throw new ArgumentNullException(nameof(script)); if (expected is null) throw new ArgumentNullException(nameof(expected)); var (objects, exception) = Execute(script); exception.Should().BeNull(); objects.Should().HaveCount(expected.Length); objects .Select(o => o?.BaseObject) .Should().BeEquivalentTo(expected, x => x.IgnoringCyclicReferences()); } internal static void ShouldThrow<T>(this string script, string messagePart) where T : Exception { var exception = script.ShouldThrow<T>(); exception.Message.Should().Contain(messagePart); } internal static T ShouldThrow<T>(this string script) where T : Exception { if (script is null) throw new ArgumentNullException(nameof(script)); var (_, exception) = Execute(script); return exception .Should().NotBeNull() .And .BeAssignableTo<T>() .Subject; } } }
Fix build when targeting .NET Framework 3.5 as Func only supports covariance on .NET Framework 4.0 and higher.
using Microsoft.VisualStudio.TestTools.UnitTesting; using Renci.SshNet.Security.Cryptography; using Renci.SshNet.Tests.Common; using System; namespace Renci.SshNet.Tests.Classes { /// <summary> /// Holds information about key size and cipher to use /// </summary> [TestClass] public class CipherInfoTest : TestBase { /// <summary> ///A test for CipherInfo Constructor ///</summary> [TestMethod()] public void CipherInfoConstructorTest() { int keySize = 0; // TODO: Initialize to an appropriate value Func<byte[], byte[], BlockCipher> cipher = null; // TODO: Initialize to an appropriate value CipherInfo target = new CipherInfo(keySize, cipher); Assert.Inconclusive("TODO: Implement code to verify target"); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Renci.SshNet.Security.Cryptography; using Renci.SshNet.Tests.Common; using System; namespace Renci.SshNet.Tests.Classes { /// <summary> /// Holds information about key size and cipher to use /// </summary> [TestClass] public class CipherInfoTest : TestBase { /// <summary> ///A test for CipherInfo Constructor ///</summary> [TestMethod()] public void CipherInfoConstructorTest() { int keySize = 0; // TODO: Initialize to an appropriate value Func<byte[], byte[], Cipher> cipher = null; // TODO: Initialize to an appropriate value CipherInfo target = new CipherInfo(keySize, cipher); Assert.Inconclusive("TODO: Implement code to verify target"); } } }
Fix a warning about a cref in an XML doc comment.
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.CodeAnalysis { /// <summary> /// Indicates that the implementing type can be serialized via <see cref="ToString"/> /// for diagnostic message purposes. /// </summary> /// <remarks> /// Not appropriate on types that require localization, since localization should /// happen after serialization. /// </remarks> internal interface IMessageSerializable { } }
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.CodeAnalysis { /// <summary> /// Indicates that the implementing type can be serialized via <see cref="object.ToString"/> /// for diagnostic message purposes. /// </summary> /// <remarks> /// Not appropriate on types that require localization, since localization should /// happen after serialization. /// </remarks> internal interface IMessageSerializable { } }
Change get method and add the new getter
using System.Collections.Generic; using System.Threading.Tasks; using Smooth.IoC.Dapper.Repository.UnitOfWork.Data; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo { public interface IRepository<TEntity, TPk> where TEntity : class, IEntity<TPk> { TEntity Get(TPk key, ISession session = null); Task<TEntity> GetAsync(TPk key, ISession session = null); IEnumerable<TEntity> GetAll(ISession session = null); Task<IEnumerable<TEntity>> GetAllAsync(ISession session = null); TPk SaveOrUpdate(TEntity entity, IUnitOfWork transaction); Task<TPk> SaveOrUpdateAsync(TEntity entity, IUnitOfWork transaction); } }
using System.Collections.Generic; using System.Threading.Tasks; using Smooth.IoC.Dapper.Repository.UnitOfWork.Data; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo { public interface IRepository<TEntity, TPk> where TEntity : class, IEntity<TPk> { TEntity GetKey(TPk key, ISession session = null); Task<TEntity> GetKeyAsync(TPk key, ISession session = null); TEntity Get(TEntity entity, ISession session = null); Task<TEntity> GetAsync(TEntity entity, ISession session = null) IEnumerable<TEntity> GetAll(ISession session = null); Task<IEnumerable<TEntity>> GetAllAsync(ISession session = null); TPk SaveOrUpdate(TEntity entity, IUnitOfWork transaction); Task<TPk> SaveOrUpdateAsync(TEntity entity, IUnitOfWork transaction); } }
Revert "Exclude the first word"
using System; using System.Diagnostics; using System.Linq; namespace mountain_thoughts { public class Program { public static void Main(string[] args) { Process mountainProcess = NativeMethods.GetMountainProcess(); if (mountainProcess == null) { Console.WriteLine("Could not get process. Is Mountain running?"); Console.ReadLine(); Environment.Exit(1); } IntPtr handle = mountainProcess.Handle; IntPtr address = NativeMethods.GetStringAddress(mountainProcess); Twitter.Authenticate(); NativeMethods.StartReadingString(handle, address, Callback); Console.ReadLine(); NativeMethods.StopReadingString(); } private static void Callback(string thought) { string properThought = string.Empty; foreach (string word in thought.Split(' ').Skip(1)) { string lowerWord = word; if (word != "I") lowerWord = word.ToLowerInvariant(); properThought += lowerWord + " "; } properThought = properThought.Trim(); Console.WriteLine(properThought); Twitter.Tweet(string.Format("\"{0}\"", properThought)); } } }
using System; using System.Diagnostics; namespace mountain_thoughts { public class Program { public static void Main(string[] args) { Process mountainProcess = NativeMethods.GetMountainProcess(); if (mountainProcess == null) { Console.WriteLine("Could not get process. Is Mountain running?"); Console.ReadLine(); Environment.Exit(1); } IntPtr handle = mountainProcess.Handle; IntPtr address = NativeMethods.GetStringAddress(mountainProcess); Twitter.Authenticate(); NativeMethods.StartReadingString(handle, address, Callback); Console.ReadLine(); NativeMethods.StopReadingString(); } private static void Callback(string thought) { string properThought = string.Empty; foreach (string word in thought.Split(' ')) { string lowerWord = word; if (word != "I") lowerWord = word.ToLowerInvariant(); properThought += lowerWord + " "; } properThought = properThought.Trim(); Console.WriteLine(properThought); Twitter.Tweet(string.Format("\"{0}\"", properThought)); } } }
Fix not to use expression-bodied constructors (cont.)
//----------------------------------------------------------------------- // <copyright file="AllScoreData.cs" company="None"> // Copyright (c) IIHOSHI Yoshinori. // Licensed under the BSD-2-Clause license. See LICENSE.txt file in the project root for full license information. // </copyright> //----------------------------------------------------------------------- #pragma warning disable SA1600 // Elements should be documented using System.Collections.Generic; namespace ThScoreFileConverter.Models.Th165 { internal class AllScoreData { private readonly List<IScore> scores; public AllScoreData() => this.scores = new List<IScore>(Definitions.SpellCards.Count); public Th095.HeaderBase Header { get; private set; } public IReadOnlyList<IScore> Scores => this.scores; public IStatus Status { get; private set; } public void Set(Th095.HeaderBase header) => this.Header = header; public void Set(IScore score) => this.scores.Add(score); public void Set(IStatus status) => this.Status = status; } }
//----------------------------------------------------------------------- // <copyright file="AllScoreData.cs" company="None"> // Copyright (c) IIHOSHI Yoshinori. // Licensed under the BSD-2-Clause license. See LICENSE.txt file in the project root for full license information. // </copyright> //----------------------------------------------------------------------- #pragma warning disable SA1600 // Elements should be documented using System.Collections.Generic; namespace ThScoreFileConverter.Models.Th165 { internal class AllScoreData { private readonly List<IScore> scores; public AllScoreData() { this.scores = new List<IScore>(Definitions.SpellCards.Count); } public Th095.HeaderBase Header { get; private set; } public IReadOnlyList<IScore> Scores => this.scores; public IStatus Status { get; private set; } public void Set(Th095.HeaderBase header) => this.Header = header; public void Set(IScore score) => this.scores.Add(score); public void Set(IStatus status) => this.Status = status; } }
Handle the TwoHour time interval for strategies - was defaulting to 15
namespace MultiMiner.Win.Extensions { static class TimeIntervalExtensions { public static int ToMinutes(this MultiMiner.Win.ApplicationConfiguration.TimerInterval timerInterval) { int coinStatsMinutes; switch (timerInterval) { case ApplicationConfiguration.TimerInterval.FiveMinutes: coinStatsMinutes = 5; break; case ApplicationConfiguration.TimerInterval.ThirtyMinutes: coinStatsMinutes = 30; break; case ApplicationConfiguration.TimerInterval.OneHour: coinStatsMinutes = 1 * 60; break; case ApplicationConfiguration.TimerInterval.ThreeHours: coinStatsMinutes = 3 * 60; break; case ApplicationConfiguration.TimerInterval.SixHours: coinStatsMinutes = 6 * 60; break; case ApplicationConfiguration.TimerInterval.TwelveHours: coinStatsMinutes = 12 * 60; break; default: coinStatsMinutes = 15; break; } return coinStatsMinutes; } } }
namespace MultiMiner.Win.Extensions { static class TimeIntervalExtensions { public static int ToMinutes(this MultiMiner.Win.ApplicationConfiguration.TimerInterval timerInterval) { int coinStatsMinutes; switch (timerInterval) { case ApplicationConfiguration.TimerInterval.FiveMinutes: coinStatsMinutes = 5; break; case ApplicationConfiguration.TimerInterval.ThirtyMinutes: coinStatsMinutes = 30; break; case ApplicationConfiguration.TimerInterval.OneHour: coinStatsMinutes = 1 * 60; break; case ApplicationConfiguration.TimerInterval.TwoHours: coinStatsMinutes = 2 * 60; break; case ApplicationConfiguration.TimerInterval.ThreeHours: coinStatsMinutes = 3 * 60; break; case ApplicationConfiguration.TimerInterval.SixHours: coinStatsMinutes = 6 * 60; break; case ApplicationConfiguration.TimerInterval.TwelveHours: coinStatsMinutes = 12 * 60; break; default: coinStatsMinutes = 15; break; } return coinStatsMinutes; } } }
Add missing XML docs to code. bugid: 272
using System; namespace Csla.Serialization.Mobile { /// <summary> /// Placeholder for null child objects. /// </summary> [Serializable()] public sealed class NullPlaceholder : IMobileObject { #region Constructors public NullPlaceholder() { // Nothing } #endregion #region IMobileObject Members public void GetState(SerializationInfo info) { // Nothing } public void GetChildren(SerializationInfo info, MobileFormatter formatter) { // Nothing } public void SetState(SerializationInfo info) { // Nothing } public void SetChildren(SerializationInfo info, MobileFormatter formatter) { // Nothing } #endregion } }
using System; namespace Csla.Serialization.Mobile { /// <summary> /// Placeholder for null child objects. /// </summary> [Serializable()] public sealed class NullPlaceholder : IMobileObject { #region Constructors /// <summary> /// Creates an instance of the type. /// </summary> public NullPlaceholder() { // Nothing } #endregion #region IMobileObject Members /// <summary> /// Method called by MobileFormatter when an object /// should serialize its data. The data should be /// serialized into the SerializationInfo parameter. /// </summary> /// <param name="info"> /// Object to contain the serialized data. /// </param> public void GetState(SerializationInfo info) { // Nothing } /// <summary> /// Method called by MobileFormatter when an object /// should serialize its child references. The data should be /// serialized into the SerializationInfo parameter. /// </summary> /// <param name="info"> /// Object to contain the serialized data. /// </param> /// <param name="formatter"> /// Reference to the formatter performing the serialization. /// </param> public void GetChildren(SerializationInfo info, MobileFormatter formatter) { // Nothing } /// <summary> /// Method called by MobileFormatter when an object /// should be deserialized. The data should be /// deserialized from the SerializationInfo parameter. /// </summary> /// <param name="info"> /// Object containing the serialized data. /// </param> public void SetState(SerializationInfo info) { // Nothing } /// <summary> /// Method called by MobileFormatter when an object /// should deserialize its child references. The data should be /// deserialized from the SerializationInfo parameter. /// </summary> /// <param name="info"> /// Object containing the serialized data. /// </param> /// <param name="formatter"> /// Reference to the formatter performing the deserialization. /// </param> public void SetChildren(SerializationInfo info, MobileFormatter formatter) { // Nothing } #endregion } }
Change user picture field to PictureUrl
// Copyright (c) ComUnity 2015 // Hans Malherbe <hansm@comunity.co.za> using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace CEP { public class UserProfile { [Key, Required, StringLength(10, MinimumLength = 10, ErrorMessage = "Mobile number must be exactly 10 digits")] public string Cell { get; set; } [StringLength(50)] public string Name { get; set; } [StringLength(50)] public string Surname { get; set; } [StringLength(100)] public string HouseNumberAndStreetName { get; set; } [StringLength(10)] public string PostalCode { get; set; } [StringLength(50)] public string Province { get; set; } [StringLength(100)] public string Picture { get; set; } [StringLength(10)] public string HomePhone { get; set; } [StringLength(10)] public string WorkPhone { get; set; } [StringLength(350)] public string Email { get; set; } [StringLength(13)] public string IdNumber { get; set; } [StringLength(100)] public string CrmContactId { get; set; } public virtual ICollection<Feedback> Feedbacks { get; set; } public virtual ICollection<FaultLog> Faults { get; set; } } }
// Copyright (c) ComUnity 2015 // Hans Malherbe <hansm@comunity.co.za> using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace CEP { public class UserProfile { [Key, Required, StringLength(10, MinimumLength = 10, ErrorMessage = "Mobile number must be exactly 10 digits")] public string Cell { get; set; } [StringLength(50)] public string Name { get; set; } [StringLength(50)] public string Surname { get; set; } [StringLength(100)] public string HouseNumberAndStreetName { get; set; } [StringLength(10)] public string PostalCode { get; set; } [StringLength(50)] public string Province { get; set; } [StringLength(2000)] public string PictureUrl { get; set; } [StringLength(10)] public string HomePhone { get; set; } [StringLength(10)] public string WorkPhone { get; set; } [StringLength(350)] public string Email { get; set; } [StringLength(13)] public string IdNumber { get; set; } [StringLength(100)] public string CrmContactId { get; set; } public virtual ICollection<Feedback> Feedbacks { get; set; } public virtual ICollection<FaultLog> Faults { get; set; } } }
Change the way we match args to property tokens to more closely match Serilog when you pass in too few or too many arguments
using System; using System.Collections.Generic; using System.Linq; using Akka.Event; using Serilog.Events; using Serilog.Parsing; namespace Akka.Serilog.Event.Serilog { public class SerilogLogMessageFormatter : ILogMessageFormatter { private readonly MessageTemplateCache _templateCache; public SerilogLogMessageFormatter() { _templateCache = new MessageTemplateCache(new MessageTemplateParser()); } public string Format(string format, params object[] args) { var template = _templateCache.Parse(format); var propertyTokens = template.Tokens.OfType<PropertyToken>().ToArray(); var properties = new Dictionary<string, LogEventPropertyValue>(); if (propertyTokens.Length != args.Length) throw new FormatException("Invalid number or arguments provided."); for (var i = 0; i < propertyTokens.Length; i++) { var arg = args[i]; properties.Add(propertyTokens[i].PropertyName, new ScalarValue(arg)); } return template.Render(properties); } } }
using System; using System.Collections.Generic; using System.Linq; using Akka.Event; using Serilog.Events; using Serilog.Parsing; namespace Akka.Serilog.Event.Serilog { public class SerilogLogMessageFormatter : ILogMessageFormatter { private readonly MessageTemplateCache _templateCache; public SerilogLogMessageFormatter() { _templateCache = new MessageTemplateCache(new MessageTemplateParser()); } public string Format(string format, params object[] args) { var template = _templateCache.Parse(format); var propertyTokens = template.Tokens.OfType<PropertyToken>().ToArray(); var properties = new Dictionary<string, LogEventPropertyValue>(); for (var i = 0; i < args.Length; i++) { var propertyToken = propertyTokens.ElementAtOrDefault(i); if (propertyToken == null) break; properties.Add(propertyToken.PropertyName, new ScalarValue(args[i])); } return template.Render(properties); } } }
Call 'update' with Delta time
using System; using System.Collections.Generic; using System.Linq; using Duality; using RockyTV.Duality.Plugins.IronPython.Resources; using IronPython.Hosting; using IronPython.Runtime; using IronPython.Compiler; using Microsoft.Scripting; using Microsoft.Scripting.Hosting; namespace RockyTV.Duality.Plugins.IronPython { public class ScriptExecutor : Component, ICmpInitializable, ICmpUpdatable { public ContentRef<PythonScript> Script { get; set; } [DontSerialize] private PythonExecutionEngine _engine; protected PythonExecutionEngine Engine { get { return _engine; } } public void OnInit(InitContext context) { if (!Script.IsAvailable) return; _engine = new PythonExecutionEngine(Script.Res.Content); _engine.SetVariable("gameObject", GameObj); if (_engine.HasMethod("start")) _engine.CallMethod("start"); } public void OnUpdate() { if (_engine.HasMethod("update")) _engine.CallMethod("update"); } public void OnShutdown(ShutdownContext context) { if (context == ShutdownContext.Deactivate) { GameObj.DisposeLater(); } } } }
using System; using System.Collections.Generic; using System.Linq; using Duality; using RockyTV.Duality.Plugins.IronPython.Resources; using IronPython.Hosting; using IronPython.Runtime; using IronPython.Compiler; using Microsoft.Scripting; using Microsoft.Scripting.Hosting; namespace RockyTV.Duality.Plugins.IronPython { public class ScriptExecutor : Component, ICmpInitializable, ICmpUpdatable { public ContentRef<PythonScript> Script { get; set; } [DontSerialize] private PythonExecutionEngine _engine; protected PythonExecutionEngine Engine { get { return _engine; } } protected virtual float Delta { get { return Time.MsPFMult * Time.TimeMult; } } public void OnInit(InitContext context) { if (!Script.IsAvailable) return; _engine = new PythonExecutionEngine(Script.Res.Content); _engine.SetVariable("gameObject", GameObj); if (_engine.HasMethod("start")) _engine.CallMethod("start"); } public void OnUpdate() { if (_engine.HasMethod("update")) _engine.CallMethod("update", Delta); } public void OnShutdown(ShutdownContext context) { if (context == ShutdownContext.Deactivate) { GameObj.DisposeLater(); } } } }
Change version up to 1.1.0
using UnityEngine; using System.Reflection; [assembly: AssemblyVersion("1.0.0.*")] public class Loader : MonoBehaviour { /// <summary> /// DebugUI prefab to instantiate. /// </summary> [SerializeField] private GameObject _debugUI; /// <summary> /// ModalDialog prefab to instantiate. /// </summary> [SerializeField] private GameObject _modalDialog; /// <summary> /// MainMenu prefab to instantiate. /// </summary> [SerializeField] private GameObject _mainMenu; /// <summary> /// InGameUI prefab to instantiate. /// </summary> [SerializeField] private GameObject _inGameUI; /// <summary> /// SoundManager prefab to instantiate. /// </summary> [SerializeField] private GameObject _soundManager; /// <summary> /// GameManager prefab to instantiate. /// </summary> [SerializeField] private GameObject _gameManager; protected void Awake() { // Check if the instances have already been assigned to static variables or they are still null. if (DebugUI.Instance == null) { Instantiate(_debugUI); } if (ModalDialog.Instance == null) { Instantiate(_modalDialog); } if (MainMenu.Instance == null) { Instantiate(_mainMenu); } if (InGameUI.Instance == null) { Instantiate(_inGameUI); } if (SoundManager.Instance == null) { Instantiate(_soundManager); } if (GameManager.Instance == null) { Instantiate(_gameManager); } } }
using UnityEngine; using System.Reflection; [assembly: AssemblyVersion("1.1.0.*")] public class Loader : MonoBehaviour { /// <summary> /// DebugUI prefab to instantiate. /// </summary> [SerializeField] private GameObject _debugUI; /// <summary> /// ModalDialog prefab to instantiate. /// </summary> [SerializeField] private GameObject _modalDialog; /// <summary> /// MainMenu prefab to instantiate. /// </summary> [SerializeField] private GameObject _mainMenu; /// <summary> /// InGameUI prefab to instantiate. /// </summary> [SerializeField] private GameObject _inGameUI; /// <summary> /// SoundManager prefab to instantiate. /// </summary> [SerializeField] private GameObject _soundManager; /// <summary> /// GameManager prefab to instantiate. /// </summary> [SerializeField] private GameObject _gameManager; protected void Awake() { // Check if the instances have already been assigned to static variables or they are still null. if (DebugUI.Instance == null) { Instantiate(_debugUI); } if (ModalDialog.Instance == null) { Instantiate(_modalDialog); } if (MainMenu.Instance == null) { Instantiate(_mainMenu); } if (InGameUI.Instance == null) { Instantiate(_inGameUI); } if (SoundManager.Instance == null) { Instantiate(_soundManager); } if (GameManager.Instance == null) { Instantiate(_gameManager); } } }
Put variables in Main first
using System; using System.Collections.Generic; using System.IO; using System.Linq; using static System.Console; namespace ConsoleApp { public class Table { private readonly string tableName; private readonly IEnumerable<Column> columns; public Table(string tableName, IEnumerable<Column> columns) { this.tableName = tableName; this.columns = columns; } public void OutputMigrationCode(TextWriter writer) { writer.Write(@"namespace Cucu { [Migration("); writer.Write(DateTime.Now.ToString("yyyyMMddHHmmss")); writer.Write(@")] public class Vaca : Migration { public override void Up() { Create.Table("""); writer.Write(tableName); writer.Write(@""")"); columns.ToList().ForEach(c => { writer.WriteLine(); writer.Write(c.FluentMigratorCode()); }); writer.WriteLine(@"; } public override void Down() { // nothing here yet } } }"); } } class Program { private static void Main() { var columnsProvider = new ColumnsProvider(@"Server=.\SQLEXPRESS;Database=LearnORM;Trusted_Connection=True;"); var tableName = "Book"; var columns = columnsProvider.GetColumnsAsync("dbo", tableName).GetAwaiter().GetResult(); new Table(tableName, columns).OutputMigrationCode(Out); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using static System.Console; namespace ConsoleApp { public class Table { private readonly string tableName; private readonly IEnumerable<Column> columns; public Table(string tableName, IEnumerable<Column> columns) { this.tableName = tableName; this.columns = columns; } public void OutputMigrationCode(TextWriter writer) { writer.Write(@"namespace Cucu { [Migration("); writer.Write(DateTime.Now.ToString("yyyyMMddHHmmss")); writer.Write(@")] public class Vaca : Migration { public override void Up() { Create.Table("""); writer.Write(tableName); writer.Write(@""")"); columns.ToList().ForEach(c => { writer.WriteLine(); writer.Write(c.FluentMigratorCode()); }); writer.WriteLine(@"; } public override void Down() { // nothing here yet } } }"); } } class Program { private static void Main() { var connectionString = @"Server=.\SQLEXPRESS;Database=LearnORM;Trusted_Connection=True;"; var schemaName = "dbo"; var tableName = "Book"; var columnsProvider = new ColumnsProvider(connectionString); var columns = columnsProvider.GetColumnsAsync(schemaName, tableName).GetAwaiter().GetResult(); new Table(tableName, columns).OutputMigrationCode(Out); } } }