using dnlib.DotNet;

namespace Confuser.Core.Project.Patterns {
	/// <summary>
	///     A function that compare the namespace of definition.
	/// </summary>
	public class NamespaceFunction : PatternFunction {
		internal const string FnName = "namespace";

		/// <inheritdoc />
		public override string Name {
			get { return FnName; }
		}

		/// <inheritdoc />
		public override int ArgumentCount {
			get { return 1; }
		}

		/// <inheritdoc />
		public override object Evaluate(IDnlibDef definition) {
			if (!(definition is TypeDef) && !(definition is IMemberDef))
				return false;
			object ns = Arguments[0].Evaluate(definition);
			var type = definition as TypeDef;
			if (type == null)
				type = ((IMemberDef)definition).DeclaringType;
			return type != null && type.Namespace == ns.ToString();
		}
	}
}

using dnlib.DotNet;

namespace Confuser.Core.Project.Patterns {
	/// <summary>
	///     A function that compare the namespace of definition.
	/// </summary>
	public class NamespaceFunction : PatternFunction {
		internal const string FnName = "namespace";

		/// <inheritdoc />
		public override string Name {
			get { return FnName; }
		}

		/// <inheritdoc />
		public override int ArgumentCount {
			get { return 1; }
		}

		/// <inheritdoc />
		public override object Evaluate(IDnlibDef definition) {
			if (!(definition is TypeDef) && !(definition is IMemberDef))
				return false;
			object ns = Arguments[0].Evaluate(definition);

			var type = definition as TypeDef;
			if (type == null)
				type = ((IMemberDef)definition).DeclaringType;

			while (type.IsNested)
				type = type.DeclaringType;

			return type != null && type.Namespace == ns.ToString();
		}
	}
}

Fix namespace function not using top level types


using System.Collections.Generic;
using System.Text.RegularExpressions;
using Rant.Stringes;
using Rant.Stringes.Tokens;

namespace Rant.Vocabulary
{
    internal static class Dic2Lexer
    {
        private const RegexOptions DicRegexOptions = RegexOptions.Compiled;

        private static readonly LexerRules<DicTokenType> Rules;

        static Dic2Lexer()
        {
            Rules = new LexerRules<DicTokenType>
            {
                {new Regex(@"\#\s*(?<value>[^\r]*)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Directive, 2},
                {new Regex(@"\|\s*(?<value>[^\r]*)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Property, 2},
                {new Regex(@"\>\s*(?<value>[^\r]*)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Entry, 2},
                {new Regex(@"\s+"), DicTokenType.Ignore}
            };
            Rules.AddEndToken(DicTokenType.EOF);
            Rules.IgnoreRules.Add(DicTokenType.Ignore);
        }

        public static IEnumerable<Token<DicTokenType>> Tokenize(string data)
        {
            Token<DicTokenType> token;
            var reader = new StringeReader(data);
            while ((token = reader.ReadToken(Rules)).Identifier != DicTokenType.EOF)
            {
                yield return token;
            }
        }
    }

    internal enum DicTokenType
    {
        Directive,
        Entry,
        Property,
        Ignore,
        EOF
    }
}

using System.Collections.Generic;
using System.Text.RegularExpressions;
using Rant.Stringes;
using Rant.Stringes.Tokens;

namespace Rant.Vocabulary
{
    internal static class Dic2Lexer
    {
        private const RegexOptions DicRegexOptions = RegexOptions.Compiled;

        private static readonly LexerRules<DicTokenType> Rules;

        static Dic2Lexer()
        {
            Rules = new LexerRules<DicTokenType>
            {
                {new Regex(@"\#\s*(?<value>.*?)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Directive, 2},
                {new Regex(@"\|\s*(?<value>.*?)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Property, 2},
                {new Regex(@"\>\s*(?<value>.*?)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Entry, 2},
                {new Regex(@"\s+"), DicTokenType.Ignore}
            };
            Rules.AddEndToken(DicTokenType.EOF);
            Rules.IgnoreRules.Add(DicTokenType.Ignore);
        }

        public static IEnumerable<Token<DicTokenType>> Tokenize(string data)
        {
            Token<DicTokenType> token;
            var reader = new StringeReader(data);
            while ((token = reader.ReadToken(Rules)).Identifier != DicTokenType.EOF)
            {
                yield return token;
            }
        }
    }

    internal enum DicTokenType
    {
        Directive,
        Entry,
        Property,
        Ignore,
        EOF
    }
}

Fix Dic2 lexer regexes to work properly on Linux


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Testing;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.Play.HUD;

namespace osu.Game.Tests.Visual.Gameplay
{
    public class TestSceneSkinnableScoreCounter : SkinnableTestScene
    {
        private IEnumerable<SkinnableScoreCounter> scoreCounters => CreatedDrawables.OfType<SkinnableScoreCounter>();

        protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset();

        [SetUpSteps]
        public void SetUpSteps()
        {
            AddStep("Create combo counters", () => SetContents(() =>
            {
                var comboCounter = new SkinnableScoreCounter();
                comboCounter.Current.Value = 1;
                return comboCounter;
            }));
        }

        [Test]
        public void TestScoreCounterIncrementing()
        {
            AddStep(@"Reset all", delegate
            {
                foreach (var s in scoreCounters)
                    s.Current.Value = 0;
            });

            AddStep(@"Hit! :D", delegate
            {
                foreach (var s in scoreCounters)
                    s.Current.Value += 300;
            });
        }
    }
}

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Testing;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.Play.HUD;

namespace osu.Game.Tests.Visual.Gameplay
{
    public class TestSceneSkinnableScoreCounter : SkinnableTestScene
    {
        private IEnumerable<SkinnableScoreCounter> scoreCounters => CreatedDrawables.OfType<SkinnableScoreCounter>();

        protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset();

        [SetUpSteps]
        public void SetUpSteps()
        {
            AddStep("Create combo counters", () => SetContents(() =>
            {
                var comboCounter = new SkinnableScoreCounter();
                comboCounter.Current.Value = 1;
                return comboCounter;
            }));
        }

        [Test]
        public void TestScoreCounterIncrementing()
        {
            AddStep(@"Reset all", delegate
            {
                foreach (var s in scoreCounters)
                    s.Current.Value = 0;
            });

            AddStep(@"Hit! :D", delegate
            {
                foreach (var s in scoreCounters)
                    s.Current.Value += 300;
            });
        }

        [Test]
        public void TestVeryLargeScore()
        {
            AddStep("set large score", () => scoreCounters.ForEach(counter => counter.Current.Value = 1_00_000_000));
        }
    }
}

Add test coverage for score counter alignment


// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

namespace MartinCostello.AdventOfCode.Puzzles.Y2016
{
    using Xunit;

    /// <summary>
    /// A class containing tests for the <see cref="Day18"/> class. This class cannot be inherited.
    /// </summary>
    public static class Day18Tests
    {
        [Theory]
        [InlineData("..^^.", 3, 6)]
        [InlineData(".^^.^.^^^^", 10, 38)]
        public static void Y2016_Day18_FindSafeTileCount_Returns_Correct_Solution(string firstRowTiles, int rows, int expected)
        {
            // Act
            int actual = Day18.FindSafeTileCount(firstRowTiles, rows);

            // Assert
            Assert.Equal(expected, actual);
        }

        [Theory]
        [InlineData("40", 1987)]
        public static void Y2016_Day18_Solve_Returns_Correct_Solution(string rows, int expected)
        {
            // Arrange
            string[] args = new[] { rows };

            // Act
            var puzzle = PuzzleTestHelpers.SolvePuzzle<Day18>(args);

            // Assert
            Assert.Equal(expected, puzzle.SafeTileCount);
        }
    }
}

// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

namespace MartinCostello.AdventOfCode.Puzzles.Y2016
{
    using Xunit;

    /// <summary>
    /// A class containing tests for the <see cref="Day18"/> class. This class cannot be inherited.
    /// </summary>
    public static class Day18Tests
    {
        [Theory]
        [InlineData("..^^.", 3, 6)]
        [InlineData(".^^.^.^^^^", 10, 38)]
        public static void Y2016_Day18_FindSafeTileCount_Returns_Correct_Solution(string firstRowTiles, int rows, int expected)
        {
            // Act
            int actual = Day18.FindSafeTileCount(firstRowTiles, rows);

            // Assert
            Assert.Equal(expected, actual);
        }

        [Theory]
        [InlineData("40", 1987)]
        [InlineData("400000", 19984714)]
        public static void Y2016_Day18_Solve_Returns_Correct_Solution(string rows, int expected)
        {
            // Arrange
            string[] args = new[] { rows };

            // Act
            var puzzle = PuzzleTestHelpers.SolvePuzzle<Day18>(args);

            // Assert
            Assert.Equal(expected, puzzle.SafeTileCount);
        }
    }
}

Add test for day 18 part 2

Add test for day 18 part 2

Add a test for part 2 of the puzzle for day 18.


using System;
using System.Linq;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Diploms.Core;
using System.Collections.Generic;

namespace Diploms.DataLayer
{
    public static class DiplomContentSystemExtensions
    {
        public static void EnsureSeedData(this DiplomContext context)
        {
            if (context.AllMigrationsApplied())
            {
                if (!context.Roles.Any())
                {
                    context.Roles.AddRange(Role.Admin, Role.Owner, Role.Student, Role.Teacher);
                    context.SaveChanges();
                }
                if(!context.Users.Any())
                {
                    context.Users.Add(new User{
                        Id = 1,
                        Login = "admin",
                        PasswordHash = @"WgHWgYQpzkpETS0VemCGE15u2LNPjTbtocMdxtqLll8=",
                        Roles = new List<UserRole>
                        {
                            new UserRole
                            {
                                UserId = 1,
                                RoleId = 1
                            }
                        }
                    });
                }
            }
        }
        private static bool AllMigrationsApplied(this DiplomContext context)
        {
            var applied = context.GetService<IHistoryRepository>()
                .GetAppliedMigrations()
                .Select(m => m.MigrationId);

            var total = context.GetService<IMigrationsAssembly>()
                .Migrations
                .Select(m => m.Key);

            return !total.Except(applied).Any();
        }
    }
}

using System;
using System.Linq;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Diploms.Core;
using System.Collections.Generic;

namespace Diploms.DataLayer
{
    public static class DiplomContentSystemExtensions
    {
        public static void EnsureSeedData(this DiplomContext context)
        {
            if (context.AllMigrationsApplied())
            {
                if (!context.Roles.Any())
                {
                    context.Roles.AddRange(Role.Admin, Role.Owner, Role.Student, Role.Teacher);
                    context.SaveChanges();
                }
                if(!context.Users.Any())
                {
                    context.Users.Add(new User{
                        Id = 1,
                        Login = "admin",
                        PasswordHash = @"WgHWgYQpzkpETS0VemCGE15u2LNPjTbtocMdxtqLll8=",
                        Roles = new List<UserRole>
                        {
                            new UserRole
                            {
                                UserId = 1,
                                RoleId = 1
                            }
                        }
                    });
                }

                context.SaveChanges();
            }
        }
        private static bool AllMigrationsApplied(this DiplomContext context)
        {
            var applied = context.GetService<IHistoryRepository>()
                .GetAppliedMigrations()
                .Select(m => m.MigrationId);

            var total = context.GetService<IMigrationsAssembly>()
                .Migrations
                .Select(m => m.Key);

            return !total.Except(applied).Any();
        }
    }
}

Fix saving changes when seeding data

Fix saving changes when seeding data


#region

using System.Linq;
using System.Management;
using UlteriusServer.TaskServer.Api.Models;
using UlteriusServer.TaskServer.Api.Serialization;
using vtortola.WebSockets;

#endregion

namespace UlteriusServer.TaskServer.Api.Controllers.Impl
{
    internal class GpuController : ApiController
    {
        private readonly WebSocket client;
        private readonly Packets packet;
        private readonly ApiSerializator serializator = new ApiSerializator();

        public GpuController(WebSocket client, Packets packet)
        {
            this.client = client;
            this.packet = packet;
        }

        public void GetGpuInformation()
        {
            var searcher =
                new ManagementObjectSearcher("SELECT * FROM Win32_VideoController");

            var gpus = (from ManagementBaseObject mo in searcher.Get()
                select new GpuInformation
                {
                    Name = mo["Name"]?.ToString(),
                    ScreenInfo = mo["VideoModeDescription"]?.ToString(),
                    DriverVersion = mo["DriverVersion"]?.ToString(),
                    RefreshRate = int.Parse(mo["CurrentRefreshRate"]?.ToString()),
                    AdapterRam = mo["AdapterRAM"]?.ToString(),
                    VideoArchitecture = int.Parse(mo["VideoArchitecture"]?.ToString()),
                    VideoMemoryType = int.Parse(mo["VideoMemoryType"]?.ToString()),
                    InstalledDisplayDrivers = mo["InstalledDisplayDrivers"]?.ToString()?.Split(','),
                    AdapterCompatibility = mo["AdapterCompatibility"]?.ToString()
                }).ToList();
            var data = new
            {
                gpus
            };
            serializator.Serialize(client, packet.endpoint, packet.syncKey, data);
        }
    }
}

#region

using System.Linq;
using System.Management;
using UlteriusServer.TaskServer.Api.Models;
using UlteriusServer.TaskServer.Api.Serialization;
using vtortola.WebSockets;

#endregion

namespace UlteriusServer.TaskServer.Api.Controllers.Impl
{
    internal class GpuController : ApiController
    {
        private readonly WebSocket client;
        private readonly Packets packet;
        private readonly ApiSerializator serializator = new ApiSerializator();

        public GpuController(WebSocket client, Packets packet)
        {
            this.client = client;
            this.packet = packet;
        }

        public void GetGpuInformation()
        {
            var searcher =
                new ManagementObjectSearcher("SELECT * FROM Win32_VideoController");

            var gpus = (from ManagementBaseObject mo in searcher.Get()
                select new GpuInformation
                {
                    Name = mo["Name"]?.ToString(),
                    ScreenInfo = mo["VideoModeDescription"]?.ToString(),
                    DriverVersion = mo["DriverVersion"]?.ToString(),
                    RefreshRate = int.Parse(mo["CurrentRefreshRate"]?.ToString() ?? "0"),
                    AdapterRam = mo["AdapterRAM"]?.ToString(),
                    VideoArchitecture = int.Parse(mo["VideoArchitecture"]?.ToString() ?? "0"),
                    VideoMemoryType = int.Parse(mo["VideoMemoryType"]?.ToString() ?? "0"),
                    InstalledDisplayDrivers = mo["InstalledDisplayDrivers"]?.ToString()?.Split(','),
                    AdapterCompatibility = mo["AdapterCompatibility"]?.ToString()
                }).ToList();
            var data = new
            {
                gpus
            };
            serializator.Serialize(client, packet.endpoint, packet.syncKey, data);
        }
    }
}

Set to 0 if null

Set to 0 if null


using UnityEngine;
using System.Collections;

public class PlateformerManager : MonoBehaviour {

	public float MoveSpeed;
	public float JumpForce;
	public float Gravity;
	public float TimerForDifficulty;
	float timeUntilEndGame;

	public static PlateformerManager Instance;

	void Awake ()
	{
		PlateformerManager.Instance = this;
	}

	// Use this for initialization
	void Start ()
	{
		this.timeUntilEndGame = Time.time + TimerForDifficulty;
		Physics2D.gravity = new Vector2(0f, this.Gravity);
	}

	// Update is called once per frame
	void Update ()
	{
		if(Time.time > this.timeUntilEndGame)
		{
			if(GameObject.FindGameObjectWithTag("Player").GetComponent<PlateformerCharacter>().LockMove)
			{
				GameManager.Instance.LevelEnd(true);
			}
			else
			{
				GameManager.Instance.LevelEnd(false);
			}
		}
	}

	public float GetJumpForce ()
	{
		return this.JumpForce;
	}

	public float GetMoveSpeed ()
	{
		return this.MoveSpeed;
	}

	public float GetGravity ()
	{
		return this.Gravity;
	}
}

using UnityEngine;
using System.Collections;

public class PlateformerManager : MonoBehaviour {

	public float MoveSpeed;
	public float JumpForce;
	public float Gravity;
	public float TimerForDifficulty;
	float timeUntilEndGame;

	public static PlateformerManager Instance;

	void Awake ()
	{
		PlateformerManager.Instance = this;
	}

	// Use this for initialization
	void Start ()
	{
		this.timeUntilEndGame = Time.time + TimerForDifficulty;
	}

	// Update is called once per frame
	void Update ()
	{
		if(Time.time > this.timeUntilEndGame)
		{
			if(GameObject.FindGameObjectWithTag("Player").GetComponent<PlateformerCharacter>().LockMove)
			{
				GameManager.Instance.LevelEnd(true);
			}
			else
			{
				GameManager.Instance.LevelEnd(false);
			}
		}
	}

	void FixedUpdate ()
	{
		Physics2D.gravity = new Vector2(0f, this.Gravity);
	}

	public float GetJumpForce ()
	{
		return this.JumpForce;
	}

	public float GetMoveSpeed ()
	{
		return this.MoveSpeed;
	}

	public float GetGravity ()
	{
		return this.Gravity;
	}
}

Update plateformer gravity at fixed update


// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details

using System.Reflection;
using System.Runtime.CompilerServices;

//[assembly: AssemblyVersion("0.0.0.*")]
[assembly: AssemblyTitle ("NDesk.DBus")]
[assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")]
[assembly: AssemblyCopyright ("Copyright (C) Alp Toker")]
[assembly: AssemblyCompany ("NDesk")]

[assembly: InternalsVisibleTo ("dbus-sharp-glib")]
[assembly: InternalsVisibleTo ("dbus-monitor")]
[assembly: InternalsVisibleTo ("dbus-daemon")]

// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details

using System.Reflection;
using System.Runtime.CompilerServices;

//[assembly: AssemblyVersion("0.0.0.*")]
[assembly: AssemblyTitle ("NDesk.DBus")]
[assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")]
[assembly: AssemblyCopyright ("Copyright (C) Alp Toker")]
[assembly: AssemblyCompany ("NDesk")]

[assembly: InternalsVisibleTo ("NDesk.DBus.GLib")]
[assembly: InternalsVisibleTo ("dbus-monitor")]
[assembly: InternalsVisibleTo ("dbus-daemon")]

Use the correct strong name for dbus-sharp-glib friend assembly


using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using Jose;

namespace Nexmo.Api
{
    internal class Jwt
    {
        internal static string CreateToken(string appId, string privateKeyFile)
        {
            var tokenData = new byte[64];
            var rng = RandomNumberGenerator.Create();
            rng.GetBytes(tokenData);
            var jwtTokenId = Convert.ToBase64String(tokenData);

            var payload = new Dictionary<string, object>
            {
                { "iat", (long) (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds },
                { "application_id", appId },
                { "jti", jwtTokenId }
            };

            var pemContents = File.ReadAllText(privateKeyFile);
            var rsa = PemParse.DecodePEMKey(pemContents);

            return JWT.Encode(payload, rsa, JwsAlgorithm.RS256);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using Jose;

namespace Nexmo.Api
{
    internal class Jwt
    {
        internal static string CreateToken(string appId, string privateKey)
        {
            var tokenData = new byte[64];
            var rng = RandomNumberGenerator.Create();
            rng.GetBytes(tokenData);
            var jwtTokenId = Convert.ToBase64String(tokenData);

            var payload = new Dictionary<string, object>
            {
                { "iat", (long) (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds },
                { "application_id", appId },
                { "jti", jwtTokenId }
            };

            var rsa = PemParse.DecodePEMKey(privateKey);

            return JWT.Encode(payload, rsa, JwsAlgorithm.RS256);
        }
    }
}

Remove IO dependency; expect contents of private key and not path to key


using System;
using System.Xml.Linq;

namespace Buildalyzer.Construction
{
    public class PackageReference : IPackageReference
    {
        public string Name { get; }
        public string Version { get; }

        internal PackageReference(XElement packageReferenceElement)
        {
            this.Name = packageReferenceElement.GetAttributeValue("Include");
            this.Version = packageReferenceElement.GetAttributeValue("Version");
        }
    }
}

using System;
using System.Xml.Linq;

namespace Buildalyzer.Construction
{
    public class PackageReference : IPackageReference
    {
        public string Name { get; }
        public string Version { get; }

        internal PackageReference(XElement packageReferenceElement)
        {
            this.Name = packageReferenceElement.GetAttributeValue("Include") ?? packageReferenceElement.GetAttributeValue("Update");
            this.Version = packageReferenceElement.GetAttributeValue("Version");
        }
    }
}

Add support for update property

Add support for update property


using System;

namespace GUtils.IO
{
    public static class FileSizes
    {
        public const UInt64 B = 1024;
        public const UInt64 KiB = 1024 * B;
        public const UInt64 MiB = 1024 * KiB;
        public const UInt64 GiB = 1024 * MiB;
        public const UInt64 TiB = 1024 * GiB;
        public const UInt64 PiB = 1024 * TiB;

        private static readonly String[] _suffixes = new[] { "B", "KiB", "MiB", "GiB", "TiB", "PiB" };

        public static String Format ( UInt64 Size )
        {
            var i = ( Int32 ) Math.Round ( Math.Log ( Size, 1024 ) );
            return $"{Size / ( Math.Pow ( B, i ) )} {_suffixes[i]}";
        }
    }
}

using System;

namespace GUtils.IO
{
    public static class FileSizes
    {
        public const UInt64 B = 1024;
        public const UInt64 KiB = 1024 * B;
        public const UInt64 MiB = 1024 * KiB;
        public const UInt64 GiB = 1024 * MiB;
        public const UInt64 TiB = 1024 * GiB;
        public const UInt64 PiB = 1024 * TiB;

        private static readonly String[] _suffixes = new[] { "B", "KiB", "MiB", "GiB", "TiB", "PiB" };

        public static String Format ( UInt64 Size )
        {
            var i = ( Int32 ) Math.Floor ( Math.Log ( Size, 1024 ) );
            return $"{Size / ( Math.Pow ( B, i ) )} {_suffixes[i]}";
        }
    }
}

Use floor for better file sizes

Use floor for better file sizes

Outputs (64 KiB instead of 0.06 MiB)


namespace Mapsui;

public class MRect2
{
    public MPoint Max { get; }
    public MPoint Min { get; }

    public double MaxX => Max.X;
    public double MaxY => Max.Y;
    public double MinX => Min.X;
    public double MinY => Min.Y;

    public MPoint Centroid => new MPoint(Max.X - Min.X, Max.Y - Min.Y);

    public double Width => Max.X - MinX;
    public double Height => Max.Y - MinY;

    public double Bottom => Min.Y;
    public double Left => Min.X;
    public double Top => Max.Y;
    public double Right => Max.X;

    public MPoint TopLeft => new MPoint(Left, Top);
    public MPoint TopRight => new MPoint(Right, Top);
    public MPoint BottomLeft => new MPoint(Left, Bottom);
    public MPoint BottomRight => new MPoint(Right, Bottom);

    //IEnumerable<MPoint> Vertices { get; }

    //MRect Clone();
    //bool Contains(MPoint? p);
    //bool Contains(MRect r);
    //bool Equals(MRect? other);
    //double GetArea();
    //MRect Grow(double amount);
    //MRect Grow(double amountInX, double amountInY);
    //bool Intersects(MRect? box);
    //MRect Join(MRect? box);
    //MRect Multiply(double factor);
    //MQuad Rotate(double degrees);
}

using System.Collections.Generic;

namespace Mapsui;

public class MRect2
{
    public MPoint Max { get; }
    public MPoint Min { get; }

    public double MaxX => Max.X;
    public double MaxY => Max.Y;
    public double MinX => Min.X;
    public double MinY => Min.Y;

    public MPoint Centroid => new MPoint(Max.X - Min.X, Max.Y - Min.Y);

    public double Width => Max.X - MinX;
    public double Height => Max.Y - MinY;

    public double Bottom => Min.Y;
    public double Left => Min.X;
    public double Top => Max.Y;
    public double Right => Max.X;

    public MPoint TopLeft => new MPoint(Left, Top);
    public MPoint TopRight => new MPoint(Right, Top);
    public MPoint BottomLeft => new MPoint(Left, Bottom);
    public MPoint BottomRight => new MPoint(Right, Bottom);

    /// <summary>
    ///     Returns the vertices in clockwise order from bottom left around to bottom right
    /// </summary>
    public IEnumerable<MPoint> Vertices
    {
        get
        {
            yield return BottomLeft;
            yield return TopLeft;
            yield return TopRight;
            yield return BottomRight;
        }
    }
    //MRect Clone();
    //bool Contains(MPoint? p);
    //bool Contains(MRect r);
    //bool Equals(MRect? other);
    //double GetArea();
    //MRect Grow(double amount);
    //MRect Grow(double amountInX, double amountInY);
    //bool Intersects(MRect? box);
    //MRect Join(MRect? box);
    //MRect Multiply(double factor);
    //MQuad Rotate(double degrees);
}

Add our own Vertices method

Add our own Vertices method


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using twitch_tv_viewer.Models;

namespace twitch_tv_viewer.Services
{
    public class TwitchChannelService : ITwitchChannelService
    {
        public async Task<string> PlayVideo(TwitchChannel channel, string quality)
        {
            var startInfo = new ProcessStartInfo
            {
                FileName = "livestreamer",
                Arguments = $"--http-query-param client_id=spyiu9jqdnfjtwv6l1xjk5zgt8qb91l twitch.tv/{channel.Name} {quality}",
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            };

            var process = new Process
            {
                StartInfo = startInfo
            };

            process.Start();

            return await process.StandardOutput.ReadToEndAsync();
        }

        public async Task<string> PlayVideo(TwitchChannel twitchChannel) => await PlayVideo(twitchChannel, "source");

        public void OpenChat(TwitchChannel channel)
        {
            Process.Start($"http://twitch.tv/{channel.Name}/chat?popout=");
        }
    }
}

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using twitch_tv_viewer.Models;
using twitch_tv_viewer.Repositories;

namespace twitch_tv_viewer.Services
{
    public class TwitchChannelService : ITwitchChannelService
    {
        public TwitchChannelService()
        {
            Settings = new SettingsRepository();
        }

        public ISettingsRepository Settings { get; set; }

        public async Task<string> PlayVideo(TwitchChannel channel, string quality)
        {
            var startInfo = new ProcessStartInfo
            {
                FileName = "livestreamer",
                Arguments = $"--http-query-param client_id=spyiu9jqdnfjtwv6l1xjk5zgt8qb91l twitch.tv/{channel.Name} {quality}",
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            };

            var process = new Process
            {
                StartInfo = startInfo
            };

            process.Start();

            return await process.StandardOutput.ReadToEndAsync();
        }

        public async Task<string> PlayVideo(TwitchChannel twitchChannel) => await PlayVideo(twitchChannel, Settings.Quality);

        public void OpenChat(TwitchChannel channel)
        {
            Process.Start($"http://twitch.tv/{channel.Name}/chat?popout=");
        }
    }
}

Use settings repository in twitch channel service


using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BatteryCommander.Web.Models;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace BatteryCommander.Web.Queries
{
    public class GetSUTARequests : IRequest<IEnumerable<SUTA>>
    {
        [FromRoute]
        public int Unit { get; set; }

        // Search by Soldier, Status, Dates

        private class Handler : IRequestHandler<GetSUTARequests, IEnumerable<SUTA>>
        {
            private readonly Database db;

            public Handler(Database db)
            {
                this.db = db;
            }

            public async Task<IEnumerable<SUTA>> Handle(GetSUTARequests request, CancellationToken cancellationToken)
            {
                return
                    await AsQueryable(db)
                    .Where(suta => suta.Soldier.UnitId == request.Unit)
                    .ToListAsync(cancellationToken);
            }
        }

        public static IQueryable<SUTA> AsQueryable(Database db)
        {
            return
                 db
                 .SUTAs
                 .Include(suta => suta.Soldier)
                 .ThenInclude(soldier => soldier.Unit)
                 .Include(suta => suta.Supervisor)
                 .Include(suta => suta.Events);
        }
    }
}

using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BatteryCommander.Web.Models;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace BatteryCommander.Web.Queries
{
    public class GetSUTARequests : IRequest<IEnumerable<SUTA>>
    {
        [FromRoute]
        public int Unit { get; set; }

        // Search by Soldier, Status, Dates

        private class Handler : IRequestHandler<GetSUTARequests, IEnumerable<SUTA>>
        {
            private readonly Database db;

            public Handler(Database db)
            {
                this.db = db;
            }

            public async Task<IEnumerable<SUTA>> Handle(GetSUTARequests request, CancellationToken cancellationToken)
            {
                return
                    await AsQueryable(db)
                    .Where(suta => suta.Soldier.UnitId == request.Unit)
                    .OrderBy(suta => suta.StartDate)
                    .ToListAsync(cancellationToken);
            }
        }

        public static IQueryable<SUTA> AsQueryable(Database db)
        {
            return
                 db
                 .SUTAs
                 .Include(suta => suta.Soldier)
                 .ThenInclude(soldier => soldier.Unit)
                 .Include(suta => suta.Supervisor)
                 .Include(suta => suta.Events);
        }
    }
}

Order by start date by default

Order by start date by default

#501


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FizzBuzz.ConsoleApp;
using TechTalk.SpecFlow;

namespace FizzBuzz.Specification.AutomationLayer
{
  [Binding]
  public class StepDefinitions
  {
    private int currentNumber;
    private string currentResult;

    [Given(@"the current number is '(.*)'")]
    public void GivenTheCurrentNumberIs(int currentNumber)
    {
      this.currentNumber = currentNumber;
    }

    [When(@"I print the number")]
    public void WhenIPrintTheNumber()
    {
      this.currentResult = new FizzBuzzer().Print(this.currentNumber);
    }

    [Then(@"the result is '(.*)'")]
    public void ThenTheResultIs(int p0)
    {
      ScenarioContext.Current.Pending();
    }
  }
}

using System;
using FizzBuzz.ConsoleApp;
using NFluent;
using TechTalk.SpecFlow;

namespace FizzBuzz.Specification.AutomationLayer
{
  [Binding]
  public class StepDefinitions
  {
    private int currentNumber;
    private string currentResult;

    [Given(@"the current number is '(.*)'")]
    public void GivenTheCurrentNumberIs(int currentNumber)
    {
      this.currentNumber = currentNumber;
    }

    [When(@"I print the number")]
    public void WhenIPrintTheNumber()
    {
      this.currentResult = new FizzBuzzer().Print(this.currentNumber);
    }

    [Then(@"the result is '(.*)'")]
    public void ThenTheResultIs(string expectedResult)
    {
      Check.That(this.currentResult).IsEqualTo(expectedResult);
    }
  }
}

Implement third step of automation layer


using UnityEngine;
using System.Collections;

[SelectionBase]
[DisallowMultipleComponent]
public class Unit : MonoBehaviour {

    [SerializeField]
    string faction;
    [SerializeField]
    int maxHeath = 100;
    [SerializeField]
    int health;

    // This function is called on Component Placement/Replacement
    void Reset()
    {

    }

	// Use this for initialization
	void Start ()
    {

	}

	// Update is called once per frame
	void Update ()
    {

	}
}

using UnityEngine;
using System.Collections;

[SelectionBase]
[DisallowMultipleComponent]
public class Unit : MonoBehaviour {

    [SerializeField]
    string faction;
    [SerializeField]
    int maxHeath = 100;
    [SerializeField]
    int health;

    // This function is called on Component Placement/Replacement
    void Reset()
    {

    }

	// Use this for initialization
	void Start ()
    {

	}

	// Update is called once per frame
	void Update ()
    {

	}

    //Called every frame in editor
    void OnDrawGizmos()
    {

    }
}

Test for CRLF line ending bug

Test for CRLF line ending bug

edit: working


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Serilog;

namespace Commencement.Jobs.Common.Logging
{
    public static class LogHelper
    {
        private static bool _loggingSetup = false;

        public static void ConfigureLogging()
        {
            if (_loggingSetup) return; //only setup logging once

            Log.Logger = new LoggerConfiguration()
                .WriteTo.Stackify()
                .WriteTo.Console()
                .CreateLogger();

            AppDomain.CurrentDomain.UnhandledException +=
                (sender, eventArgs) =>
                    Log.Fatal(eventArgs.ExceptionObject as Exception, eventArgs.ExceptionObject.ToString());

            _loggingSetup = true;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Serilog;
using Serilog.Exceptions.Destructurers;

namespace Commencement.Jobs.Common.Logging
{
    public static class LogHelper
    {
        private static bool _loggingSetup = false;

        public static void ConfigureLogging()
        {
            if (_loggingSetup) return; //only setup logging once

            Log.Logger = new LoggerConfiguration()
                .WriteTo.Stackify()
                .WriteTo.Console()
                .Enrich.With<ExceptionEnricher>()
                .CreateLogger();

            AppDomain.CurrentDomain.UnhandledException +=
                (sender, eventArgs) =>
                    Log.Fatal(eventArgs.ExceptionObject as Exception, eventArgs.ExceptionObject.ToString());

            _loggingSetup = true;
        }
    }
}

Add it to the job log too.

Add it to the job log too.


using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;

namespace Tgstation.Server.Host.IO
{
	/// <summary>
	/// <see cref="ISymlinkFactory"/> for windows systems
	/// </summary>
	sealed class WindowsSymlinkFactory : ISymlinkFactory
	{
		/// <inheritdoc />
		public Task CreateSymbolicLink(string targetPath, string linkPath, CancellationToken cancellationToken) => Task.Factory.StartNew(() =>
		{
			if (targetPath == null)
				throw new ArgumentNullException(nameof(targetPath));
			if (linkPath == null)
				throw new ArgumentNullException(nameof(linkPath));

			//check if its not a file
			var flags = File.Exists(targetPath) ? 0 : 3; //SYMBOLIC_LINK_FLAG_DIRECTORY | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE on win10 1607+ developer mode

			cancellationToken.ThrowIfCancellationRequested();
			if (!NativeMethods.CreateSymbolicLink(linkPath, targetPath, flags))
				throw new Win32Exception(Marshal.GetLastWin32Error());
		}, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current);
	}
}

using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;

namespace Tgstation.Server.Host.IO
{
	/// <summary>
	/// <see cref="ISymlinkFactory"/> for windows systems
	/// </summary>
	sealed class WindowsSymlinkFactory : ISymlinkFactory
	{
		/// <inheritdoc />
		public Task CreateSymbolicLink(string targetPath, string linkPath, CancellationToken cancellationToken) => Task.Factory.StartNew(() =>
		{
			if (targetPath == null)
				throw new ArgumentNullException(nameof(targetPath));
			if (linkPath == null)
				throw new ArgumentNullException(nameof(linkPath));

			//check if its not a file
			var flags = File.Exists(targetPath) ? 2 : 3; //SYMBOLIC_LINK_FLAG_DIRECTORY and SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE on win10 1607+ developer mode

			cancellationToken.ThrowIfCancellationRequested();
			if (!NativeMethods.CreateSymbolicLink(linkPath, targetPath, flags))
				throw new Win32Exception(Marshal.GetLastWin32Error());
		}, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current);
	}
}

Fix unprivileged file symlink creation

Fix unprivileged file symlink creation


using System;
using System.Collections.Generic;

namespace FisherYates
{
    public static class FisherYates
    {
        /*
        ** http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
        */

        static readonly Random Rand = new Random();

	public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> list)
	{
		var rand = Rand;
		var enumerable = list as T[] ?? list.ToArray();
		for (var i = enumerable.Length; i > 1; i--)
		{
			// First step : Pick random element to swap.
			var j = rand.Next(i);

			// Second step : Swap.
			var tmp = enumerable[j];
			enumerable[j] = enumerable[i - 1];
			enumerable[i - 1] = tmp;
		}
		return enumerable;
	}
    }
}

using System;
using System.Collections.Generic;
using System.Linq;

namespace FisherYates
{
    public static class FisherYates
    {
        /*
        ** http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
        */

        static readonly Random Rand = new Random();

	public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> list)
	{
		var rand = Rand;
		var enumerable = list as T[] ?? list.ToArray();
		for (var i = enumerable.Length; i > 1; i--)
		{
			// First step : Pick random element to swap.
			var j = rand.Next(i);

			// Second step : Swap.
			var tmp = enumerable[j];
			enumerable[j] = enumerable[i - 1];
			enumerable[i - 1] = tmp;
		}
		return enumerable;
	}
    }
}

Remove whitespace and add using

Remove whitespace and add using


using NUnit.Framework;
using System;
using Microsoft.Boogie;
using Microsoft.Basetypes;
using System.IO;
using symbooglix;

namespace SymbooglixLibTests
{
    [TestFixture()]
    public class Literal
    {
        public Literal()
        {
            SymbooglixTest.setupDebug();
        }

        [Test()]
        public void bitvector()
        {
            var literal = new LiteralExpr(Token.NoToken, BigNum.FromInt(19), 32); // 19bv32
            checkLiteral(literal, "(_ bv19 32)");
        }

        [Test()]
        public void Bools()
        {
            checkLiteral(Expr.True, "true");
            checkLiteral(Expr.False, "false");
        }

        private void checkLiteral(LiteralExpr e, string expected)
        {
            using (var writer = new StringWriter())
            {
                var printer = new SMTLIBQueryPrinter(writer);
                printer.Traverse(e);
                Assert.IsTrue(writer.ToString() == expected);
            }
        }
    }
}

using NUnit.Framework;
using System;
using Microsoft.Boogie;
using Microsoft.Basetypes;
using System.IO;
using symbooglix;

namespace ExprSMTLIBTest
{
    [TestFixture()]
    public class Literal
    {
        public Literal()
        {
            SymbooglixLibTests.SymbooglixTest.setupDebug();
        }

        [Test()]
        public void bitvector()
        {
            var literal = new LiteralExpr(Token.NoToken, BigNum.FromInt(19), 32); // 19bv32
            checkLiteral(literal, "(_ bv19 32)");
        }

        [Test()]
        public void Bools()
        {
            checkLiteral(Expr.True, "true");
            checkLiteral(Expr.False, "false");
        }

        private void checkLiteral(LiteralExpr e, string expected)
        {
            using (var writer = new StringWriter())
            {
                var printer = new SMTLIBQueryPrinter(writer);
                printer.Traverse(e);
                Assert.IsTrue(writer.ToString() == expected);
            }
        }
    }
}

Move the ExprSMTLIB test cases (there's only one right now) into their own namespace.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.Practices.Unity;
using UI.AddComponent;

namespace UI
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            this.MainWindow = new MainWindow();
            var compManager = new MEF_CompositionManager();
            compManager.ComposeParts();
            var container = new UnityContainer();
            foreach (var component in compManager.ImportedComponents)
            {
                container.RegisterType(component.Provider.Key, component.Provider.Value);
                container.RegisterType(typeof(WorkspaceViewModel), component.Workspace, component.Workspace.Name);
            }

            container.RegisterType<IWorkspaceService, WorkspaceService>();

            this.MainWindow.DataContext = container.Resolve<CalculatorViewModel>();

            this.MainWindow.Show();
        }
    }

    public interface IWorkspaceService
    {
        IEnumerable<WorkspaceViewModel> GetWorkspaces();
    }

    public class WorkspaceService : IWorkspaceService
    {
        private readonly IUnityContainer container;

        public WorkspaceService(IUnityContainer container)
        {
            this.container = container;
        }

        public IEnumerable<WorkspaceViewModel> GetWorkspaces()
        {
            return container.ResolveAll<WorkspaceViewModel>().ToArray();;
        }
    }

}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.Practices.Unity;
using UI.AddComponent;

namespace UI
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            this.MainWindow = new MainWindow();
            var compManager = new MEF_CompositionManager();
            compManager.ComposeParts();
            var container = new UnityContainer();
            foreach (var component in compManager.ImportedComponents)
            {
                container.RegisterType(component.Provider.Key, component.Provider.Value);
                container.RegisterType(typeof(WorkspaceViewModel), component.Workspace, Guid.NewGuid().ToString());
            }

            container.RegisterType<IWorkspaceService, WorkspaceService>();

            this.MainWindow.DataContext = container.Resolve<CalculatorViewModel>();

            this.MainWindow.Show();
        }
    }

    public interface IWorkspaceService
    {
        IEnumerable<WorkspaceViewModel> GetWorkspaces();
    }

    public class WorkspaceService : IWorkspaceService
    {
        private readonly IUnityContainer container;

        public WorkspaceService(IUnityContainer container)
        {
            this.container = container;
        }

        public IEnumerable<WorkspaceViewModel> GetWorkspaces()
        {
            return container.ResolveAll<WorkspaceViewModel>().ToArray();
        }
    }

}

Add Guid as name for workspace registration


using EvoSim;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace EvoCommand {
    class Program {
        static void Main(string[] args) {
            Simulation sim = new Simulation();

            sim.Initialize(sim);

            DateTime startTime = DateTime.UtcNow;
            DateTime lastUpdate;
            DateTime lastSerializationTime = DateTime.UtcNow;
            long i = 0;
            while (true) {
                lastUpdate = DateTime.UtcNow;
                update(new GameTime(DateTime.UtcNow - startTime, lastUpdate - lastUpdate));

                i++;

                if (i % 1000000 == 1)
                    Console.WriteLine("Programm still active - " + DateTime.Now.ToString());

                // Save progress every minute
                if ((DateTime.UtcNow - lastSerializationTime).TotalSeconds > 10) {
                    lastSerializationTime = DateTime.UtcNow;
                    sim.TileMap.SerializeToFile("tilemap.dat");
                    sim.CreatureManager.Serialize("creatures.dat", "graveyard/graveyard");
                    Console.WriteLine("Save everything.");
                }

            }
        }

        public static void update(GameTime gametime) {

        }
    }
}

using EvoSim;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace EvoCommand {
    class Program {
        static void Main(string[] args) {
            Simulation sim = new Simulation();

            sim.Initialize(sim);

            DateTime startTime = DateTime.UtcNow;
            DateTime lastUpdate;
            DateTime lastSerializationTime = DateTime.UtcNow;
            long i = 0;
            while (true) {
                lastUpdate = DateTime.UtcNow;
                sim.NotifyTick(new GameTime(DateTime.UtcNow - startTime, lastUpdate - lastUpdate));

                i++;

                if (i % 1000000 == 1)
                    Console.WriteLine("Programm still active - " + DateTime.Now.ToString());

                // Save progress every minute
                if ((DateTime.UtcNow - lastSerializationTime).TotalSeconds > 10) {
                    lastSerializationTime = DateTime.UtcNow;
                    sim.TileMap.SerializeToFile("tilemap.dat");
                    sim.CreatureManager.Serialize("creatures.dat", "graveyard/graveyard");
                    Console.WriteLine("Save everything.");
                }

            }
        }
    }
}

Update now actually does things in EvoCommand


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace netcore.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        // GET api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace netcore.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        // GET api/values
        [HttpGet]
        public IEnumerable<Value> Get()
        {
            return new Value[] {
              new Value { Id = 1, Text = "value1"},
              new Value { Id = 2, Text = "value2"}
            };
        }

        // GET api/values/5
        [HttpGet("{id:int}")]
        public Value Get(int id)
        {
            return new Value { Id = id, Text = "value" };
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
    public class Value {
      public int Id { get; set; }
      public string Text { get; set; }
    }
}

Add Value object with Id and Text

Add Value object with Id and Text


using System;
using System.Threading.Tasks;
using SoraBot.Data.Repositories.Interfaces;
using SoraBot.Services.Cache;

namespace SoraBot.Services.Guilds
{
    public class PrefixService : IPrefixService
    {
        public const string CACHE_PREFIX = "prfx:";
        public const short CACHE_TTL_MINS = 60;

        private readonly ICacheService _cacheService;
        private readonly IGuildRepository _guildRepo;

        public PrefixService(ICacheService cacheService, IGuildRepository guildRepo)
        {
            _cacheService = cacheService;
            _guildRepo = guildRepo;
        }

        public async Task<string> GetPrefix(ulong id)
        {
            string idStr = CACHE_PREFIX + id.ToString();
            return await _cacheService.GetOrSetAndGetAsync(idStr,
                async () => await _guildRepo.GetGuildPrefix(id).ConfigureAwait(false) ?? "$",
                TimeSpan.FromMinutes(CACHE_TTL_MINS)).ConfigureAwait(false);
        }

        public async Task<bool> SetPrefix(ulong id, string prefix)
        {
            // Let's set it in the DB. And if it succeeds we'll also add it to our cache
            if (!await _guildRepo.SetGuildPrefix(id, prefix).ConfigureAwait(false))
                return false;
            // Update the Cache
            string idStr = CACHE_PREFIX + id.ToString();
            _cacheService.Set(idStr, prefix, TimeSpan.FromMinutes(CACHE_TTL_MINS));
            return true;
        }
    }
}

using System;
using System.Threading.Tasks;
using SoraBot.Data.Repositories.Interfaces;
using SoraBot.Services.Cache;

namespace SoraBot.Services.Guilds
{
    public class PrefixService : IPrefixService
    {
        public const string CACHE_PREFIX = "prfx:";
        // public const short CACHE_TTL_MINS = 60;

        private readonly ICacheService _cacheService;
        private readonly IGuildRepository _guildRepo;

        public PrefixService(ICacheService cacheService, IGuildRepository guildRepo)
        {
            _cacheService = cacheService;
            _guildRepo = guildRepo;
        }

        public async Task<string> GetPrefix(ulong id)
        {
            string idStr = CACHE_PREFIX + id.ToString();
            return await _cacheService.GetOrSetAndGetAsync(idStr,
                async () => await _guildRepo.GetGuildPrefix(id).ConfigureAwait(false) ?? "$"
            ).ConfigureAwait(false);
        }

        public async Task<bool> SetPrefix(ulong id, string prefix)
        {
            // Let's set it in the DB. And if it succeeds we'll also add it to our cache
            if (!await _guildRepo.SetGuildPrefix(id, prefix).ConfigureAwait(false))
                return false;
            // Update the Cache
            string idStr = CACHE_PREFIX + id.ToString();
            _cacheService.Set(idStr, prefix);
            return true;
        }
    }
}

Set TTL for prefix to infinity rn

Set TTL for prefix to infinity rn


using System;
using System.Diagnostics;
using HandlebarsDotNet.Collections;
using HandlebarsDotNet.EqualityComparers;
using HandlebarsDotNet.Runtime;

namespace HandlebarsDotNet
{
	[DebuggerDisplay("undefined")]
	public class UndefinedBindingResult : IEquatable<UndefinedBindingResult>
    {
	    private static readonly LookupSlim<string, GcDeferredValue<string, UndefinedBindingResult>, StringEqualityComparer> Cache
		    = new LookupSlim<string, GcDeferredValue<string, UndefinedBindingResult>, StringEqualityComparer>(new StringEqualityComparer(StringComparison.OrdinalIgnoreCase));

	    public static UndefinedBindingResult Create(string value) => Cache.GetOrAdd(value, ValueFactory).Value;

	    private static readonly Func<string, GcDeferredValue<string, UndefinedBindingResult>> ValueFactory = s =>
	    {
		    return new GcDeferredValue<string, UndefinedBindingResult>(s, v => new UndefinedBindingResult(v));
	    };

	    public readonly string Value;

	    private UndefinedBindingResult(string value) => Value = value;

	    public override string ToString() => Value;

	    public bool Equals(UndefinedBindingResult other) => Value == other?.Value;

	    public override bool Equals(object obj) => obj is UndefinedBindingResult other && Equals(other);

	    public override int GetHashCode() => Value != null ? Value.GetHashCode() : 0;
    }
}

using System;
using System.Diagnostics;
using HandlebarsDotNet.Collections;
using HandlebarsDotNet.EqualityComparers;
using HandlebarsDotNet.Runtime;

namespace HandlebarsDotNet
{
	[DebuggerDisplay("undefined")]
	public class UndefinedBindingResult : IEquatable<UndefinedBindingResult>
    {
	    private static readonly LookupSlim<string, GcDeferredValue<string, UndefinedBindingResult>, StringEqualityComparer> Cache
		    = new LookupSlim<string, GcDeferredValue<string, UndefinedBindingResult>, StringEqualityComparer>(new StringEqualityComparer(StringComparison.Ordinal));

	    public static UndefinedBindingResult Create(string value) => Cache.GetOrAdd(value, ValueFactory).Value;

	    private static readonly Func<string, GcDeferredValue<string, UndefinedBindingResult>> ValueFactory = s =>
	    {
		    return new GcDeferredValue<string, UndefinedBindingResult>(s, v => new UndefinedBindingResult(v));
	    };

	    public readonly string Value;

	    private UndefinedBindingResult(string value) => Value = value;

	    public override string ToString() => Value;

	    public bool Equals(UndefinedBindingResult other) => Value == other?.Value;

	    public override bool Equals(object obj) => obj is UndefinedBindingResult other && Equals(other);

	    public override int GetHashCode() => Value != null ? Value.GetHashCode() : 0;
    }
}

Use case sensitive cache for Undefined result


using System.Threading.Tasks;
using Basic.Models;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using MR.AspNetCore.Jobs;

namespace Basic
{
	public class Program
	{
		public static async Task Main(string[] args)
		{
			var host = CreateWebHostBuilder(args).Build();

			await host.StartJobsAsync();
			using (var scope = host.Services.CreateScope())
			{
				var context = scope.ServiceProvider.GetService<AppDbContext>();
				await context.Database.MigrateAsync();
			}

			host.Run();
		}

		public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
			WebHost.CreateDefaultBuilder(args)
				.UseStartup<Startup>();
	}
}

using System.Threading.Tasks;
using Basic.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MR.AspNetCore.Jobs;

namespace Basic
{
	public class Program
	{
		public static async Task Main(string[] args)
		{
			var host = CreateHostBuilder(args).Build();

			await host.StartJobsAsync();
			using (var scope = host.Services.CreateScope())
			{
				var context = scope.ServiceProvider.GetService<AppDbContext>();
				await context.Database.MigrateAsync();
			}

			host.Run();
		}

		public static IHostBuilder CreateHostBuilder(string[] args) =>
			Host.CreateDefaultBuilder(args)
				.ConfigureWebHostDefaults(webBuilder =>
				{
					webBuilder.UseStartup<Startup>();
				});
	}
}

Use generic host in sample

Use generic host in sample


using System;
using System.Web;
using System.Web.Hosting;
using System.Configuration;

namespace NuGet.Server.Infrastructure
{
    public class PackageUtility
    {

        internal static string PackagePhysicalPath;
        private static string DefaultPackagePhysicalPath = HostingEnvironment.MapPath("~/Packages");

        static PackageUtility()
        {
            string packagePath = ConfigurationManager.AppSettings["NuGetPackagePath"];
            if (string.IsNullOrEmpty(packagePath))
            {
                PackagePhysicalPath = DefaultPackagePhysicalPath;
            }
            else
            {
                PackagePhysicalPath = packagePath;
            }
        }

        public static Uri GetPackageUrl(string path, Uri baseUri)
        {
            return new Uri(baseUri, GetPackageDownloadUrl(path));
        }

        private static string GetPackageDownloadUrl(string path)
        {
            return VirtualPathUtility.ToAbsolute("~/Packages/" + path);
        }
    }
}

using System;
using System.Web;
using System.Web.Hosting;
using System.Configuration;
using System.IO;

namespace NuGet.Server.Infrastructure
{
    public class PackageUtility
    {

        internal static string PackagePhysicalPath;
        private static string DefaultPackagePhysicalPath = HostingEnvironment.MapPath("~/Packages");

        static PackageUtility()
        {
            string packagePath = ConfigurationManager.AppSettings["NuGetPackagePath"];
            if (string.IsNullOrEmpty(packagePath))
            {
                PackagePhysicalPath = DefaultPackagePhysicalPath;
            }
            else
            {
                if (Path.IsPathRooted(packagePath))
                {
                    PackagePhysicalPath = packagePath;
                }
                else
                {
                    PackagePhysicalPath = HostingEnvironment.MapPath(packagePath);
                }
            }
        }

        public static Uri GetPackageUrl(string path, Uri baseUri)
        {
            return new Uri(baseUri, GetPackageDownloadUrl(path));
        }

        private static string GetPackageDownloadUrl(string path)
        {
            return VirtualPathUtility.ToAbsolute("~/Packages/" + path);
        }
    }
}

Check if the specified path is a physical or a virtual path


namespace NTwitch
{
    public interface IEntity
    {
        ITwitchClient Client { get; }
        uint Id { get; }
    }
}

namespace NTwitch
{
    public interface IEntity
    {
        ITwitchClient Client { get; }
        ulong Id { get; }
    }
}

Change id type from uint to ulong

Change id type from uint to ulong


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Booma.Proxy
{
	/// <summary>
	/// The collection of network players that are known about.
	/// </summary>
	public interface INetworkPlayerCollection : IEnumerable<INetworkPlayer>
	{
		/// <summary>
		/// The local player.
		/// </summary>
		INetworkPlayer Local { get; }

		/// <summary>
		/// The networked players.
		/// </summary>
		IEnumerable<INetworkPlayer> Players { get; }

		/// <summary>
		/// The networked player's excluding the <see cref="Local"/> player.
		/// </summary>
		IEnumerable<INetworkPlayer> ExcludingLocal { get; }

		/// <summary>
		/// Returns the <see cref="INetworkPlayer"/> with the id.
		/// Or null if the player doesn't exist.
		/// </summary>
		/// <param name="id">The id to check for.</param>
		/// <returns>The <see cref="INetworkPlayer"/> with the id or null.</returns>
		INetworkPlayer this[int id] { get; }

		/// <summary>
		/// Indicates if it contains the <see cref="id"/> key value.
		/// </summary>
		/// <param name="id">The id to check for.</param>
		/// <returns>True if the collection contains the ID.</returns>
		bool ContainsId(int id);
	}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Booma.Proxy
{
	/// <summary>
	/// The collection of network players that are known about.
	/// </summary>
	public interface INetworkPlayerCollection : IEnumerable<INetworkPlayer>
	{
		/// <summary>
		/// The networked players.
		/// </summary>
		IEnumerable<INetworkPlayer> Players { get; }

		/// <summary>
		/// Returns the <see cref="INetworkPlayer"/> with the id.
		/// Or null if the player doesn't exist.
		/// </summary>
		/// <param name="id">The id to check for.</param>
		/// <returns>The <see cref="INetworkPlayer"/> with the id or null.</returns>
		INetworkPlayer this[int id] { get; }

		/// <summary>
		/// Indicates if it contains the <see cref="id"/> key value.
		/// </summary>
		/// <param name="id">The id to check for.</param>
		/// <returns>True if the collection contains the ID.</returns>
		bool ContainsId(int id);
	}
}

Remove uneeded player collection methods


// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// 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 Google.Api.Gax;
using System;
using System.Linq;
using Xunit;

namespace Google.Monitoring.V3
{
    [Collection(nameof(MonitoringFixture))]
    public class GroupServiceClientSnippets
    {
        private readonly MonitoringFixture _fixture;

        public GroupServiceClientSnippets(MonitoringFixture fixture)
        {
            _fixture = fixture;
        }

        [Fact]
        public void ListGroups()
        {
            string projectId = _fixture.ProjectId;

            // Snippet: ListGroups
            GroupServiceClient client = GroupServiceClient.Create();
            string projectName = MetricServiceClient.FormatProjectName(projectId);
            IPagedEnumerable<ListGroupsResponse, Group> groups = client.ListGroups(projectName, "", "", "");
            foreach (Group group in groups.Take(10))
            {
                Console.WriteLine($"{group.Name}: {group.DisplayName}");
            }
            // End snippet
        }
    }
}

// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// 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 Google.Api.Gax;
using System;
using System.Linq;
using Xunit;

namespace Google.Monitoring.V3
{
    [Collection(nameof(MonitoringFixture))]
    public class GroupServiceClientSnippets
    {
        private readonly MonitoringFixture _fixture;

        public GroupServiceClientSnippets(MonitoringFixture fixture)
        {
            _fixture = fixture;
        }

        /* TODO: Reinstate when ListGroups is present again.
        [Fact]
        public void ListGroups()
        {
            string projectId = _fixture.ProjectId;

            // Snippet: ListGroups
            GroupServiceClient client = GroupServiceClient.Create();
            string projectName = MetricServiceClient.FormatProjectName(projectId);
            IPagedEnumerable<ListGroupsResponse, Group> groups = client.ListGroups(projectName, "", "", "");
            foreach (Group group in groups.Take(10))
            {
                Console.WriteLine($"{group.Name}: {group.DisplayName}");
            }
            // End snippet
        }
        */
    }
}

Comment out non-compiling test while we don't flatten ListGroups


// 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.Rulesets.Osu.Skinning
{
    public enum OsuSkinConfiguration
    {
        HitCirclePrefix,
        HitCircleOverlap,
        SliderBorderSize,
        SliderPathRadius,
        AllowSliderBallTint,
        CursorExpand,
        CursorRotate,
        HitCircleOverlayAboveNumber,
        HitCircleOverlayAboveNumer, // Some old skins will have this typo
		SpinnerFrequencyModulate
    }
}

Replace accidental tab with spaces

Replace accidental tab with spaces


//
//  Query.cs
//
//  Author:
//       Roman M. Yagodin <roman.yagodin@gmail.com>
//
//  Copyright (c) 2016 Roman M. Yagodin
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Linq;
using R7.University.Models;

namespace R7.University.Queries
{
    public class Query<TEntity> where TEntity: class
    {
        private readonly IModelContext modelContext;

        public Query (IModelContext modelContext)
        {
            this.modelContext = modelContext;
        }

        public IEnumerable<TEntity> Execute ()
        {
            return modelContext.Query<TEntity> ().ToList ();
        }
    }
}

//
//  Query.cs
//
//  Author:
//       Roman M. Yagodin <roman.yagodin@gmail.com>
//
//  Copyright (c) 2016 Roman M. Yagodin
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Linq;
using R7.University.Models;

namespace R7.University.Queries
{
    public class Query<TEntity> where TEntity: class
    {
        private readonly IModelContext modelContext;

        public Query (IModelContext modelContext)
        {
            this.modelContext = modelContext;
        }

        public IList<TEntity> Execute ()
        {
            return modelContext.Query<TEntity> ().ToList ();
        }

        public IList<TEntity> Execute<TKey> (Func<TEntity,TKey> keySelector)
        {
            return modelContext.Query<TEntity> ().OrderBy (keySelector).ToList ();
        }
    }
}

Add execute method overload with ordering


// 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;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics;
using osu.Game.Online.Multiplayer;
using osuTK;

namespace osu.Game.Screens.Multi.Match.Components
{
    public class Footer : CompositeDrawable
    {
        public const float HEIGHT = 100;

        public Action OnStart;
        public readonly Bindable<PlaylistItem> SelectedItem = new Bindable<PlaylistItem>();

        private readonly Drawable background;

        public Footer()
        {
            RelativeSizeAxes = Axes.X;
            Height = HEIGHT;

            InternalChildren = new[]
            {
                background = new Box { RelativeSizeAxes = Axes.Both },
                new ReadyButton
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    Size = new Vector2(600, 50),
                    SelectedItem = { BindTarget = SelectedItem },
                    Action = () => OnStart?.Invoke()
                }
            };
        }

        [BackgroundDependencyLoader]
        private void load(OsuColour colours)
        {
            background.Colour = Color4Extensions.FromHex(@"28242d");
        }
    }
}

// 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;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics;
using osu.Game.Online.Multiplayer;
using osuTK;

namespace osu.Game.Screens.Multi.Match.Components
{
    public class Footer : CompositeDrawable
    {
        public const float HEIGHT = 50;

        public Action OnStart;
        public readonly Bindable<PlaylistItem> SelectedItem = new Bindable<PlaylistItem>();

        private readonly Drawable background;

        public Footer()
        {
            RelativeSizeAxes = Axes.X;
            Height = HEIGHT;

            InternalChildren = new[]
            {
                background = new Box { RelativeSizeAxes = Axes.Both },
                new ReadyButton
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    Size = new Vector2(600, 50),
                    SelectedItem = { BindTarget = SelectedItem },
                    Action = () => OnStart?.Invoke()
                }
            };
        }

        [BackgroundDependencyLoader]
        private void load(OsuColour colours)
        {
            background.Colour = Color4Extensions.FromHex(@"28242d");
        }
    }
}

Reduce footer height to match back button


using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace Tiesmaster.Dcc
{
    public class Startup
    {
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            if(env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello from DCC ;)");
            });
        }
    }
}

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;

namespace Tiesmaster.Dcc
{
    public class Startup
    {
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            if(env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.RunProxy(new ProxyOptions { Host = "jsonplaceholder.typicode.com" });
        }
    }
}

Change hello world implementation to using the

proxy.


namespace BmpListener.Bgp
{
    internal class PathAttributeMultiExitDisc : PathAttribute
    {
        public int? Metric { get; private set; }

        public override void Decode(byte[] data, int offset)
        {
            //Array.Reverse(data, offset, 0);
            //Metric = BitConverter.ToInt32(data, 0);
        }
    }
}

using BmpListener.Utilities;

namespace BmpListener.Bgp
{
    internal class PathAttributeMultiExitDisc : PathAttribute
    {
        public uint Metric { get; private set; }

        public override void Decode(byte[] data, int offset)
        {
            Metric = EndianBitConverter.Big.ToUInt32(data, offset);
        }
    }
}

Add multi-exit discriminator (MED) support


using System;
using System.Data;

namespace Gigobyte.Daterpillar.Data
{
    public class MySQLSchemaAggregator : SchemaAggregatorBase
    {
        public MySQLSchemaAggregator(IDbConnection connection) : base(connection)
        {
        }

        protected override string GetColumnInfoQuery(string tableName)
        {
            throw new NotImplementedException();
        }

        protected override string GetForeignKeyInfoQuery(string tableName)
        {
            throw new NotImplementedException();
        }

        protected override string GetIndexColumnsQuery(string indexIdentifier)
        {
            throw new NotImplementedException();
        }

        protected override string GetIndexInfoQuery(string tableName)
        {
            throw new NotImplementedException();
        }

        protected override string GetTableInfoQuery()
        {
            throw new NotImplementedException();
        }
    }
}

using System;
using System.Data;

namespace Gigobyte.Daterpillar.Data
{
    public class MySQLSchemaAggregator : SchemaAggregatorBase
    {
        public MySQLSchemaAggregator(IDbConnection connection) : base(connection)
        {
        }

        protected override string GetColumnInfoQuery(string tableName)
        {
            return $"SELECT c.`COLUMN_NAME` AS `Name`, c.DATA_TYPE AS `Type`, if(c.CHARACTER_MAXIMUM_LENGTH IS NULL, if(c.NUMERIC_PRECISION IS NULL, 0, c.NUMERIC_PRECISION), c.CHARACTER_MAXIMUM_LENGTH) AS `Scale`, if(c.NUMERIC_SCALE IS NULL, 0, c.NUMERIC_SCALE) AS `Precision`, c.IS_NULLABLE AS `Nullable`, c.COLUMN_DEFAULT AS `Default`, if(c.EXTRA = 'auto_increment', 1, 0) AS `Auto`, c.COLUMN_COMMENT AS `Comment` FROM information_schema.`COLUMNS` c WHERE c.TABLE_SCHEMA = '{Schema.Name}' AND c.`TABLE_NAME` = '{tableName}';";
        }

        protected override string GetForeignKeyInfoQuery(string tableName)
        {
            return $"SELECT rc.`CONSTRAINT_NAME` AS `Name`, fc.FOR_COL_NAME AS `Column`, rc.REFERENCED_TABLE_NAME AS `Referecne_Table`, fc.REF_COL_NAME AS `Reference_Column`, rc.UPDATE_RULE AS `On_Update`, rc.DELETE_RULE AS `On_Delete`, rc.MATCH_OPTION AS `On_Match` FROM information_schema.REFERENTIAL_CONSTRAINTS rc JOIN information_schema.INNODB_SYS_FOREIGN_COLS fc ON fc.ID = concat(rc.`CONSTRAINT_SCHEMA`, '/', rc.`CONSTRAINT_NAME`) WHERE rc.`CONSTRAINT_SCHEMA` = '{Schema.Name}' AND rc.`TABLE_NAME` = '{tableName}';";
        }

        protected override string GetIndexColumnsQuery(string indexIdentifier)
        {
            throw new NotImplementedException();
        }

        protected override string GetIndexInfoQuery(string tableName)
        {
            throw new NotImplementedException();
        }

        protected override string GetTableInfoQuery()
        {
            return $"SELECT t.TABLE_NAME AS `Name`, t.TABLE_COMMENT AS `Comment` FROM information_schema.TABLES t WHERE t.TABLE_SCHEMA = '{Schema.Name}';";
        }
    }
}

Add implementation details to MySQLScheamAggregator.cs


using System;
using System.Collections.Generic;
using System.Xml.Serialization;

namespace SevenDigital.Api.Schema.Playlists.Response
{
	[Serializable]
	public class PlaylistLocation : UserBasedUpdatableItem
	{
		[XmlAttribute("id")]
		public string Id { get; set; }

		[XmlElement("name")]
		public string Name { get; set; }

		[XmlArray("links")]
		[XmlArrayItem("link")]
		public List<Link> Links { get; set; }

		[XmlElement("trackCount")]
		public int TrackCount { get; set; }

		[XmlElement("visibility")]
		public PlaylistVisibilityType Visibility { get; set; }

		[XmlElement("status")]
		public PlaylistStatusType Status { get; set; }

		[XmlArray("tags")]
		[XmlArrayItem("tag")]
		public List<Tag> Tags { get; set; }

		public override string ToString()
		{
			return string.Format("{0}: {1}", Id, Name);
		}
	}
}

using System;
using System.Collections.Generic;
using System.Xml.Serialization;

namespace SevenDigital.Api.Schema.Playlists.Response
{
	[Serializable]
	public class PlaylistLocation : UserBasedUpdatableItem
	{
		[XmlAttribute("id")]
		public string Id { get; set; }

		[XmlElement("name")]
		public string Name { get; set; }

		[XmlArray("links")]
		[XmlArrayItem("link")]
		public List<Link> Links { get; set; }

		[XmlElement("trackCount")]
		public int TrackCount { get; set; }

		[XmlElement("visibility")]
		public PlaylistVisibilityType Visibility { get; set; }

		[XmlElement("description")]
		public string Description { get; set; }

		[XmlElement("image")]
		public string Image { get; set; }

		[XmlElement("status")]
		public PlaylistStatusType Status { get; set; }

		[XmlArray("tags")]
		[XmlArrayItem("tag")]
		public List<Tag> Tags { get; set; }

		public override string ToString()
		{
			return string.Format("{0}: {1}", Id, Name);
		}
	}
}

Add image and description to playlist location


using AvalonStudio.MainMenu;
using AvalonStudio.Menus;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Text;

namespace WalletWasabi.Gui.Shell.MainMenu
{
	internal class ToolsMainMenuItems
	{
		private IMenuItemFactory _menuItemFactory;

		[ImportingConstructor]
		public ToolsMainMenuItems(IMenuItemFactory menuItemFactory)
		{
			_menuItemFactory = menuItemFactory;
		}

		#region MainMenu

		[ExportMainMenuItem("Tools")]
		[DefaultOrder(1)]
		public IMenuItem Tools => _menuItemFactory.CreateHeaderMenuItem("Tools", null);

		#endregion MainMenu

		#region Group

		[ExportMainMenuDefaultGroup("Tools", "Wallet")]
		[DefaultOrder(0)]
		public object WalletGroup => null;

		[ExportMainMenuDefaultGroup("Tools", "Settings")]
		[DefaultOrder(1)]
		public object SettingsGroup => null;

		#endregion Group

		#region MenuItem

		[ExportMainMenuItem("Tools", "Wallet")]
		[DefaultOrder(0)]
		[DefaultGroup("Wallet")]
		public IMenuItem GenerateWallet => _menuItemFactory.CreateCommandMenuItem("Tools.WalletManager");

		[ExportMainMenuItem("Tools", "Settings")]
		[DefaultOrder(1)]
		[DefaultGroup("Settings")]
		public IMenuItem Settings => _menuItemFactory.CreateCommandMenuItem("Tools.Settings");

		#endregion MenuItem
	}
}

using AvalonStudio.MainMenu;
using AvalonStudio.Menus;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Text;

namespace WalletWasabi.Gui.Shell.MainMenu
{
	internal class ToolsMainMenuItems
	{
		private IMenuItemFactory _menuItemFactory;

		[ImportingConstructor]
		public ToolsMainMenuItems(IMenuItemFactory menuItemFactory)
		{
			_menuItemFactory = menuItemFactory;
		}

		#region MainMenu

		[ExportMainMenuItem("Tools")]
		[DefaultOrder(1)]
		public IMenuItem Tools => _menuItemFactory.CreateHeaderMenuItem("Tools", null);

		#endregion MainMenu

		#region Group

		[ExportMainMenuDefaultGroup("Tools", "Managers")]
		[DefaultOrder(0)]
		public object ManagersGroup => null;

		[ExportMainMenuDefaultGroup("Tools", "Settings")]
		[DefaultOrder(1)]
		public object SettingsGroup => null;

		#endregion Group

		#region MenuItem

		[ExportMainMenuItem("Tools", "Wallet Manager")]
		[DefaultOrder(0)]
		[DefaultGroup("Managers")]
		public IMenuItem GenerateWallet => _menuItemFactory.CreateCommandMenuItem("Tools.WalletManager");

		[ExportMainMenuItem("Tools", "Settings")]
		[DefaultOrder(1)]
		[DefaultGroup("Settings")]
		public IMenuItem Settings => _menuItemFactory.CreateCommandMenuItem("Tools.Settings");

		#endregion MenuItem
	}
}

Rename Wallets group to Managers group

Rename Wallets group to Managers group


// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE

using Android.App;
using Android.OS;
using Android.Content.PM;
using Android.Views;

namespace SampleGame.Android
{
    [Activity(Label = "SampleGame", ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, MainLauncher = true, Theme = "@android:style/Theme.NoTitleBar")]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            Window.AddFlags(WindowManagerFlags.Fullscreen);
            Window.AddFlags(WindowManagerFlags.KeepScreenOn);

            SetContentView(new SampleGameView(this));
        }
    }
}

// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE

using Android.App;
using Android.OS;
using Android.Content.PM;
using Android.Views;

namespace SampleGame.Android
{
    [Activity(ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, MainLauncher = true, Theme = "@android:style/Theme.NoTitleBar")]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            Window.AddFlags(WindowManagerFlags.Fullscreen);
            Window.AddFlags(WindowManagerFlags.KeepScreenOn);

            SetContentView(new SampleGameView(this));
        }
    }
}

Remove the label as you can not see it when running the app


#if !DEBUG
using System;
using System.IO;
#endif
using System.Threading;
using YGOSharp.OCGWrapper;

namespace YGOSharp
{
    public class Program
    {
        public static uint ClientVersion = 0x133D;

        public static void Main(string[] args)
        {
#if !DEBUG
            try
            {
#endif
                Config.Load(args);

                BanlistManager.Init(Config.GetString("BanlistFile", "lflist.conf"));
                Api.Init(Config.GetString("RootPath", "."), Config.GetString("ScriptDirectory", "script"), Config.GetString("DatabaseFile", "cards.cdb"));

                ClientVersion = Config.GetUInt("ClientVersion", ClientVersion);

                CoreServer server = new CoreServer();
                server.Start();
                while (server.IsRunning)
                {
                    server.Tick();
                    Thread.Sleep(1);
                }
#if !DEBUG
            }
            catch (Exception ex)
            {
                File.WriteAllText("crash_" + DateTime.UtcNow.ToString("yyyy-MM-dd_HH-mm-ss") + ".txt", ex.ToString());
            }
#endif
        }
    }
}

#if !DEBUG
using System;
using System.IO;
#endif
using System.Threading;
using YGOSharp.OCGWrapper;

namespace YGOSharp
{
    public class Program
    {
        public static uint ClientVersion = 0x1343;

        public static void Main(string[] args)
        {
#if !DEBUG
            try
            {
#endif
                Config.Load(args);

                BanlistManager.Init(Config.GetString("BanlistFile", "lflist.conf"));
                Api.Init(Config.GetString("RootPath", "."), Config.GetString("ScriptDirectory", "script"), Config.GetString("DatabaseFile", "cards.cdb"));

                ClientVersion = Config.GetUInt("ClientVersion", ClientVersion);

                CoreServer server = new CoreServer();
                server.Start();
                while (server.IsRunning)
                {
                    server.Tick();
                    Thread.Sleep(1);
                }
#if !DEBUG
            }
            catch (Exception ex)
            {
                File.WriteAllText("crash_" + DateTime.UtcNow.ToString("yyyy-MM-dd_HH-mm-ss") + ".txt", ex.ToString());
            }
#endif
        }
    }
}

Bump the protocol version to 0x1343

Bump the protocol version to 0x1343


using System;
using NUnit.Framework;
using RethinkDb;
using System.Net;
using System.Linq;
using System.Threading.Tasks;
using RethinkDb.Configuration;

namespace RethinkDb.Test
{
    public class TestBase
    {
        protected IConnection connection;

        [TestFixtureSetUp]
        public virtual void TestFixtureSetUp()
        {
            try
            {
                DoTestFixtureSetUp().Wait();
            }
            catch (Exception e)
            {
                Console.WriteLine("TestFixtureSetUp failed: {0}", e);
                throw;
            }
        }

        private async Task DoTestFixtureSetUp()
        {
            connection = ConfigConnectionFactory.Instance.Get("testCluster");
            connection.Logger = new DefaultLogger(LoggingCategory.Debug, Console.Out);

            await connection.ConnectAsync();

            try
            {
                var dbList = await connection.RunAsync(Query.DbList());
                if (dbList.Contains("test"))
                    await connection.RunAsync(Query.DbDrop("test"));
            }
            catch (Exception)
            {
            }
        }
    }
}

using System;
using NUnit.Framework;
using RethinkDb;
using System.Net;
using System.Linq;
using System.Threading.Tasks;
using RethinkDb.Configuration;

namespace RethinkDb.Test
{
    public class TestBase
    {
        protected IConnection connection;

        [TestFixtureSetUp]
        public virtual void TestFixtureSetUp()
        {
            try
            {
                DoTestFixtureSetUp().Wait();
            }
            catch (Exception e)
            {
                Console.WriteLine("TestFixtureSetUp failed: {0}", e);
                throw;
            }
        }

        private async Task DoTestFixtureSetUp()
        {
            connection = ConfigConnectionFactory.Instance.Get("testCluster");
            connection.Logger = new DefaultLogger(LoggingCategory.Warning, Console.Out);

            await connection.ConnectAsync();

            try
            {
                var dbList = await connection.RunAsync(Query.DbList());
                if (dbList.Contains("test"))
                    await connection.RunAsync(Query.DbDrop("test"));
            }
            catch (Exception)
            {
            }
        }
    }
}

Reduce unit test logger verbosity

Reduce unit test logger verbosity


using Livet;

namespace Anne.Foundation.Mvvm
{
    public class ViewModelBase : ViewModel
    {
        public ViewModelBase()
        {
            DisposableChecker.Add(this);
        }

        protected override void Dispose(bool disposing)
        {
            DisposableChecker.Remove(this);

            base.Dispose(disposing);
        }
    }
}

using Livet;

namespace Anne.Foundation.Mvvm
{
    public class ViewModelBase : ViewModel
    {
        public ViewModelBase()
        {
            DisposableChecker.Add(this);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
                DisposableChecker.Remove(this);

            base.Dispose(disposing);
        }
    }
}

Fix multiple dispose check problem

Fix multiple dispose check problem


using System.Linq;
using UniRx;
using UniRx.Triggers;
using UnityEngine;

public class WaveformRenderer : MonoBehaviour
{
    [SerializeField]
    Color color;

    void Awake()
    {
        var model = NotesEditorModel.Instance;
        var waveData = new float[500000];
        var skipSamples = 50;
        var lines = Enumerable.Range(0, waveData.Length / skipSamples)
            .Select(_ => new Line(Vector3.zero, Vector3.zero, color))
            .ToArray();

        this.LateUpdateAsObservable()
            .Where(_ => model.WaveformDisplayEnabled.Value)
            .SkipWhile(_ => model.Audio.clip == null)
            .Subscribe(_ =>
            {
                model.Audio.clip.GetData(waveData, model.Audio.timeSamples);
                var x = (model.CanvasWidth.Value / model.Audio.clip.samples) / 2f;
                var offsetX = model.CanvasOffsetX.Value;
                var offsetY = 200;

                for (int li = 0, wi = skipSamples / 2, l = waveData.Length; wi < l; li++, wi += skipSamples)
                {
                    lines[li].start.x = lines[li].end.x = wi * x + offsetX;
                    lines[li].end.y =  waveData[wi] * 45 - offsetY;
                    lines[li].start.y = waveData[wi - skipSamples / 2] * 45 - offsetY;
                }

                GLLineRenderer.RenderLines("waveform", lines);
            });
    }
}

using System.Linq;
using UniRx;
using UniRx.Triggers;
using UnityEngine;

public class WaveformRenderer : MonoBehaviour
{
    [SerializeField]
    Color color;

    void Awake()
    {
        var model = NotesEditorModel.Instance;
        var waveData = new float[500000];
        var skipSamples = 50;
        var lines = Enumerable.Range(0, waveData.Length / skipSamples)
            .Select(_ => new Line(Vector3.zero, Vector3.zero, color))
            .ToArray();

        this.LateUpdateAsObservable()
            .Where(_ => model.WaveformDisplayEnabled.Value)
            .SkipWhile(_ => model.Audio.clip == null)
            .Subscribe(_ =>
            {
                var timeSamples = Mathf.Min(model.Audio.timeSamples, model.Audio.clip.samples - 1);
                model.Audio.clip.GetData(waveData, timeSamples);

                var x = (model.CanvasWidth.Value / model.Audio.clip.samples) / 2f;
                var offsetX = model.CanvasOffsetX.Value;
                var offsetY = 200;

                for (int li = 0, wi = skipSamples / 2, l = waveData.Length; wi < l; li++, wi += skipSamples)
                {
                    lines[li].start.x = lines[li].end.x = wi * x + offsetX;
                    lines[li].end.y = waveData[wi] * 45 - offsetY;
                    lines[li].start.y = waveData[wi - skipSamples / 2] * 45 - offsetY;
                }

                GLLineRenderer.RenderLines("waveform", lines);
            });
    }
}

Fix offset samples for GetData

Fix offset samples for GetData


using System;
using System.Collections.Generic;
using ContractsWindow.Unity.Unity;
using UnityEngine;
using UnityEngine.UI;

namespace ContractsWindow.Unity.Interfaces
{
	public interface ICW_Window
	{
		bool HideTooltips { get; set; }

		bool BlizzyAvailable { get; }

		bool StockToolbar { get; set; }

		bool ReplaceToolbar { get; set; }

		bool LargeFont { get; set; }

		bool IgnoreScale { get; set; }

		float Scale { get; set; }

		float MasterScale { get; set; }

		string Version { get; }

		IList<IMissionSection> GetMissions { get; }

		IMissionSection GetCurrentMission { get; }

		void Rebuild();

		void NewMission(string title, Guid id);

		void SetWindowPosition(Rect r);
	}
}

using System;
using System.Collections.Generic;
using ContractsWindow.Unity.Unity;
using UnityEngine;
using UnityEngine.UI;

namespace ContractsWindow.Unity.Interfaces
{
	public interface ICW_Window
	{
		bool HideTooltips { get; set; }

		bool BlizzyAvailable { get; }

		bool StockToolbar { get; set; }

		bool ReplaceToolbar { get; set; }

		bool LargeFont { get; set; }

		bool IgnoreScale { get; set; }

		float Scale { get; set; }

		float MasterScale { get; }

		string Version { get; }

		Canvas MainCanvas { get; }

		IList<IMissionSection> GetMissions { get; }

		IMissionSection GetCurrentMission { get; }

		void Rebuild();

		void NewMission(string title, Guid id);

		void SetWindowPosition(Rect r);
	}
}

Fix UI scale; add Canvas property

Fix UI scale; add Canvas property


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(GridPositionComponent))]
[RequireComponent(typeof(ResourceSink))]
public class GridOutput : MonoBehaviour {
    private ResourceStorage ItemDestination;
    private ResourceSink ItemSource;

	// Use this for initialization
	void Start () {
        ItemDestination = GetComponentInParent<ResourceStorage>();
        ItemSource = GetComponent<ResourceSink>();

        ItemSource.DeliverItem = (item) =>
        {
            Debug.Log(new System.Diagnostics.StackTrace());
            Debug.Log(ItemDestination);
            Debug.Log(item);
            ItemDestination.AddResource(item.ResourceType, 1);
            // TODO destroy the in-game item
            return true;
        };
	}

	// Update is called once per frame
	void Update () {

	}
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(GridPositionComponent))]
[RequireComponent(typeof(ResourceSink))]
public class GridOutput : MonoBehaviour {
    private ResourceStorage ItemDestination;
    private ResourceSink ItemSource;

	// Use this for initialization
	void Start () {
        ItemDestination = GetComponentInParent<ResourceStorage>();
        ItemSource = GetComponent<ResourceSink>();

        ItemSource.DeliverItem = (item) =>
        {
            Debug.Log(new System.Diagnostics.StackTrace());
            Debug.Log(ItemDestination);
            Debug.Log(item);
            ItemDestination.AddResource(item.ResourceType, 1);
            Destroy(item.gameObject);
            return true;
        };
	}

	// Update is called once per frame
	void Update () {

	}
}

Destroy factory items when moving them to stockpile