// ----------------------------------------------------
// THIS WHOLE File CAN GO AWAY WHEN WE TARGET 4.5 ONLY
// ----------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;

namespace Octokit
{
    [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
    [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
    public interface IReadOnlyDictionary<TKey, TValue> : IReadOnlyCollection<KeyValuePair<TKey, TValue>>
    {
        bool ContainsKey(TKey key);
        bool TryGetValue(TKey key, out TValue value);

        TValue this[TKey key] { get; }
        IEnumerable<TKey> Keys { get; }
        IEnumerable<TValue> Values { get; }
    }

    public interface IReadOnlyCollection<out T> : IEnumerable<T>
    {
        int Count { get; }
    }

    public class ReadOnlyCollection<TItem> : IReadOnlyCollection<TItem>
    {
        readonly List<TItem> _source;

        public ReadOnlyCollection(IEnumerable<TItem> source)
        {
            _source = new List<TItem>(source);
        }

        public IEnumerator<TItem> GetEnumerator()
        {
            return _source.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public int Count
        {
            get { return _source.Count; }
        }
    }

    [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
    [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
    public class ReadOnlyDictionary<TKey, TValue> : IReadOnlyDictionary<TKey, TValue>
    {
        readonly IDictionary<TKey, TValue> _source;

        public ReadOnlyDictionary(IDictionary<TKey, TValue> source)
        {
            _source = new Dictionary<TKey, TValue>(source);
        }

        public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
        {
            return _source.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public int Count
        {
            get { return _source.Count; }
        }

        public bool ContainsKey(TKey key)
        {
            return _source.ContainsKey(key);
        }

        public bool TryGetValue(TKey key, out TValue value)
        {
            return _source.TryGetValue(key, out value);
        }

        public TValue this[TKey key]
        {
            get { return _source[key]; }
        }

        public IEnumerable<TKey> Keys
        {
            get { return _source.Keys; }
        }

        public IEnumerable<TValue> Values
        {
            get { return _source.Values; }
        }
    }
}

Add .net 4.5 compatibility shim classes

Add .net 4.5 compatibility shim classes

Implemented some of the interfaces and classes we use in our .NET 4.5
version.


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

namespace PhotoLife.Factories
{
    interface IViewModelFactory
    {
    }
}

Add view model factory interface

Add view model factory interface


using System;
using System.Linq.Expressions;
using Xunit;

namespace ExpressionToCodeTest
{
    public class ExpressionInterpretationBug
    {
        struct AStruct
        {
            public int AValue;
        }

        class SomethingMutable
        {
            public AStruct AStructField;
        }

        static Expression<Func<T>> Expr<T>(Expression<Func<T>> e)
            => e;

        [Fact]
        public void DotNetCoreIsNotBuggy()
        {
            var expr_compiled = Expr(() => new SomethingMutable { AStructField = { AValue = 2 } }).Compile(false)();
            Assert.Equal(2, expr_compiled.AStructField.AValue);

            var expr_interpreted = Expr(() => new SomethingMutable { AStructField = { AValue = 2 } }).Compile(true)();
            Assert.Equal(2, expr_interpreted.AStructField.AValue);
        }
    }
}

Add an expression interpretation bug test


// 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 BenchmarkDotNet.Attributes;
using osu.Framework.Bindables;

namespace osu.Framework.Benchmarks
{
    public class BenchmarkBindableInstantiation
    {
        private Bindable<int> bindable;

        [GlobalSetup]
        public void GlobalSetup() => bindable = new Bindable<int>();

        /// <summary>
        /// Creates an instance of the bindable directly by construction.
        /// </summary>
        [Benchmark(Baseline = true)]
        public Bindable<int> CreateInstanceViaConstruction() => new Bindable<int>();

        /// <summary>
        /// Creates an instance of the bindable via <see cref="Activator.CreateInstance(Type, object[])"/>.
        /// This used to be how <see cref="Bindable{T}.GetBoundCopy"/> creates an instance before binding, which has turned out to be inefficient in performance.
        /// </summary>
        [Benchmark]
        public Bindable<int> CreateInstanceViaActivatorWithParams() => (Bindable<int>)Activator.CreateInstance(typeof(Bindable<int>), 0);

        /// <summary>
        /// Creates an instance of the bindable via <see cref="Activator.CreateInstance(Type)"/>.
        /// More performant than <see cref="CreateInstanceViaActivatorWithParams"/>, due to not passing parameters to <see cref="Activator"/> during instance creation.
        /// </summary>
        [Benchmark]
        public Bindable<int> CreateInstanceViaActivatorWithoutParams() => (Bindable<int>)Activator.CreateInstance(typeof(Bindable<int>), true);
    }
}

Add benchmarks for bindable binding

Add benchmarks for bindable binding


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Orchard.Alias.Implementation.Holder;
using Orchard.Alias.Implementation.Storage;

namespace Orchard.Alias.Implementation.Updater {
    public interface IAliasHolderUpdater : IDependency {
        void Refresh();
    }

    public class AliasHolderUpdater : IAliasHolderUpdater {
        private readonly IAliasHolder _aliasHolder;
        private readonly IAliasStorage _storage;
        private readonly IAliasUpdateCursor _cursor;

        public AliasHolderUpdater(IAliasHolder aliasHolder, IAliasStorage storage, IAliasUpdateCursor cursor) {
            _aliasHolder = aliasHolder;
            _storage = storage;
            _cursor = cursor;
        }

        public void Refresh() {
            // only retreive aliases which have not been processed yet
            var aliases = _storage.List(x => x.Id > _cursor.Cursor).ToArray();

            // update the last processed id
            if (aliases.Any()) {
                _cursor.Cursor = aliases.Last().Item5;
                _aliasHolder.SetAliases(aliases.Select(alias => new AliasInfo { Path = alias.Item1, Area = alias.Item2, RouteValues = alias.Item3 }));
            }
        }
    }
}

Replace missing file lost during merge

Replace missing file lost during merge


// Resources.cs
// <copyright file="Resources.cs"> This code is protected under the MIT License. </copyright>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EnigmaUtilities
{
    /// <summary>
    /// A static class with commonly used functions throughout multiple classes.
    /// </summary>
    public static class Resources
    {
        /// <summary>
        /// Gets the alphabet as a string.
        /// </summary>
        public static string Alphabet
        {
            get
            {
                return "abcdefghijkmnopqrstuvwxyz";
            }
        }

        /// <summary>
        /// Performs modulus operations on an integer.
        /// </summary>
        /// <param name="i"> The integer to modulus. </param>
        /// <param name="j"> The integer to modulus by. </param>
        /// <returns> The integer after modulus operations. </returns>
        /// <remarks> Performs negative modulus python style. </remarks>
        public static int Mod(int i, int j)
        {
            return ((i % j) + j) % j;
        }

        /// <summary>
        /// Gets the character value of an integer.
        /// </summary>
        /// <param name="i"> The integer to convert to a character. </param>
        /// <returns> The character value of the integer. </returns>
        public static char ToChar(this int i)
        {
            return Alphabet[Mod(i, 26)];
        }

        /// <summary>
        /// Gets the index in the alphabet of a character.
        /// </summary>
        /// <param name="c"> The character to convert to an integer. </param>
        /// <returns> The integer value of the character. </returns>
        /// <remarks> Will return -1 if not in the alphabet. </remarks>
        public static int ToInt(this char c)
        {
            return Alphabet.Contains(c) ? Alphabet.IndexOf(c) : -1;
        }
    }
}

Add a static resources library

Add a static resources library


#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2018 Atif Aziz. 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.
#endregion

namespace MoreLinq.Experimental
{
    using System.Collections.Generic;

    /// <summary>
    /// Provides a set of static methods for querying objects that
    /// implement <see cref="IEnumerable{T}" />. THE METHODS ARE EXPERIMENTAL.
    /// THEY MAY BE UNSTABLE AND UNTESTED. THEY MAY BE REMOVED FROM A FUTURE
    /// MAJOR OR MINOR RELEASE AND POSSIBLY WITHOUT NOTICE. USE THEM AT YOUR
    /// OWN RISK. THE METHODS ARE PUBLISHED FOR FIELD EXPERIMENTATION TO
    /// SOLICIT FEEDBACK ON THEIR UTILITY AND DESIGN/IMPLEMENTATION DEFECTS.
    /// </summary>

    public static partial class ExperimentalEnumerable
    {
    }
}

Add namespace & type for experimental work

Closes #209


using Marten.Linq;
using Marten.Services;
using Marten.Services.Includes;
using Marten.Testing.Documents;
using Shouldly;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Xunit;

namespace Marten.Testing.Bugs
{
    public class compiled_query_problem_with_includes_and_ICompiledQuery_reuse : DocumentSessionFixture<IdentityMap>
    {
        public class IssueWithUsers : ICompiledListQuery<Issue>
        {
            public List<User> Users { get; set; }
            // Can also work like that:
            //public List<User> Users => new List<User>();

            public Expression<Func<IQueryable<Issue>, IEnumerable<Issue>>> QueryIs()
            {
                return query => query.Include<Issue, IssueWithUsers>(x => x.AssigneeId, x => x.Users, JoinType.Inner);
            }
        }

        [Fact]
        public void can_get_includes_with_compiled_queries()
        {
            var user1 = new User();
            var user2 = new User();

            var issue1 = new Issue { AssigneeId = user1.Id, Title = "Garage Door is busted" };
            var issue2 = new Issue { AssigneeId = user2.Id, Title = "Garage Door is busted" };
            var issue3 = new Issue { AssigneeId = user2.Id, Title = "Garage Door is busted" };

            theSession.Store(user1, user2);
            theSession.Store(issue1, issue2, issue3);
            theSession.SaveChanges();

            // Issue first query
            using (var session = theStore.QuerySession())
            {
                var query = new IssueWithUsers();
                var issues = session.Query(query).ToArray();

                query.Users.Count.ShouldBe(2);
                issues.Count().ShouldBe(3);

                query.Users.Any(x => x.Id == user1.Id);
                query.Users.Any(x => x.Id == user2.Id);
            }

            // Issue second query
            using (var session = theStore.QuerySession())
            {
                var query = new IssueWithUsers();
                var issues = session.Query(query).ToArray();

                // Should populate this instance of IssueWithUsers
                query.Users.ShouldNotBeNull();
                // Should not re-use a previous instance of IssueWithUsers, which would make the count 4
                query.Users.Count.ShouldBe(2);
                issues.Count().ShouldBe(3);

                query.Users.Any(x => x.Id == user1.Id);
                query.Users.Any(x => x.Id == user2.Id);
            }
        }
    }
}

Add failing test for compiled queries with Includes


using System;

namespace ZocMonLib.Service.Reduce
{
    public class ReduceServiceRunner
    {
        private readonly ISystemLogger _logger;
        private System.Timers.Timer _timer;
        private readonly ISettings _settings;

        public ReduceServiceRunner(ISettings settings)
        {
            _logger = settings.LoggerProvider.CreateLogger(typeof(ReduceServiceRunner));
            _settings = settings;
        }

        public void Start()
        {
            Log("ReduceServiceRunner - Starting");

            if (_settings.Enabled)
            {
                Log("ReduceServiceRunner - Timing setup");

                _timer = new System.Timers.Timer(_settings.AutoReduceInterval) { AutoReset = true };
                _timer.Elapsed += (sender, eventArgs) =>
                {
                    Log(String.Format(" - Executing Reduce Start: {0:yyyy/MM/dd_HH:mm:ss-fff}", DateTime.Now));
                    _settings.RecordReduce.ReduceAll(false);
                    Log(String.Format(" - Executing Reduce Finish: {0:yyyy/MM/dd_HH:mm:ss-fff}", DateTime.Now));
                };

                _timer.Start();
            }
        }

        public void Stop()
        {
            Log("ReduceServiceRunner - Finished");

            if (_timer != null)
                _timer.Stop();
        }

        private void Log(string info)
        {
            _logger.Info(info);
            Console.WriteLine(info);
        }
    }
}

using System;

namespace ZocMonLib.Service.Reduce
{
    public class ReduceServiceRunner
    {
        private readonly ISystemLogger _logger;
        private System.Timers.Timer _timer;
        private readonly ISettings _settings;

        public ReduceServiceRunner(ISettings settings)
        {
            _logger = settings.LoggerProvider.CreateLogger(typeof(ReduceServiceRunner));
            _settings = settings;
        }

        public void Start()
        {
            Log("ReduceServiceRunner - Starting");

            if (_settings.Enabled)
            {
                Log("ReduceServiceRunner - Timing setup");

                _timer = new System.Timers.Timer(_settings.AutoReduceInterval) { AutoReset = false };
                _timer.Elapsed += (sender, eventArgs) =>
                {
                    Log(String.Format(" - Executing Reduce Start: {0:yyyy/MM/dd_HH:mm:ss-fff}", DateTime.Now));
                    _settings.RecordReduce.ReduceAll(false);
                    Log(String.Format(" - Executing Reduce Finish: {0:yyyy/MM/dd_HH:mm:ss-fff}", DateTime.Now));
                    _timer.Start();
                };

                _timer.Start();
            }
        }

        public void Stop()
        {
            Log("ReduceServiceRunner - Finished");

            if (_timer != null)
                _timer.Stop();
        }

        private void Log(string info)
        {
            _logger.Info(info);
            Console.WriteLine(info);
        }
    }
}

Set up timer so that it can't start reducing while previous reduction is still in progress.


using System.Collections.Generic;
using Xunit;

namespace HandlebarsDotNet.Test
{
    public class ReadmeTests
    {
        [Fact]
        public void RegisterBlockHelper()
        {
            var handlebars = Handlebars.Create();
            handlebars.RegisterHelper("StringEqualityBlockHelper", (output, options, context, arguments) =>
            {
                if (arguments.Length != 2)
                {
                    throw new HandlebarsException("{{#StringEqualityBlockHelper}} helper must have exactly two arguments");
                }

                var left = arguments.At<string>(0);
                var right = arguments[1] as string;
                if (left == right) options.Template(output, context);
                else options.Inverse(output, context);
            });

            var animals = new Dictionary<string, string>
            {
                {"Fluffy", "cat" },
                {"Fido", "dog" },
                {"Chewy", "hamster" }
            };

            var template = "{{#each this}}The animal, {{@key}}, {{#StringEqualityBlockHelper @value 'dog'}}is a dog{{else}}is not a dog{{/StringEqualityBlockHelper}}.\r\n{{/each}}";
            var compiledTemplate = handlebars.Compile(template);
            string templateOutput = compiledTemplate(animals);

            Assert.Equal(
                "The animal, Fluffy, is not a dog.\r\n" +
                         "The animal, Fido, is a dog.\r\n" +
                         "The animal, Chewy, is not a dog.\r\n",
                templateOutput
            );
        }
    }
}

Add test to cover `RegisterBlockHelper` readme example


using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
using static Nito.ConnectedProperties.ConnectedProperty;

namespace UnitTests
{
    class UsageExamples
    {
        [Fact]
        public void SimpleUsage()
        {
            var obj = new object();

            var nameProperty = GetConnectedProperty(obj, "Name");
            nameProperty.Set("Bob");

            Assert.Equal("Bob", ReadName(obj));
        }

        private static string ReadName(object obj)
        {
            var nameProperty = GetConnectedProperty(obj, "Name");
            return nameProperty.Get();
        }
    }
}

Add usage examples for double-checking doc examples.


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

namespace Chutes.Optimization.Entities
{
    public class Path
    {
        LinkedList<Gamespace> _path = new LinkedList<Gamespace>();

        public Path()
        {
            _path.Clear();
        }

        public Gamespace Add(Gamespace space)
        {
            if (_path.Any())
                _path.AddAfter(_path.Last, space);
            else
                _path.AddFirst(space);
            return space;
        }

        public int Length
        {
            get { return _path.Count; }
        }

        public int RollCount
        {
            get { return _path.Where(s => !s.PathTo.HasValue).Count(); }
        }

        public override string ToString()
        {
            var sb = new StringBuilder();
            foreach (var item in _path)
                sb.Append(item.Index.ToString("00") + " ");
            return sb.ToString();
        }

        public IEnumerable<Gamespace> Reverse()
        {
            throw new NotImplementedException();
        }

    }
}

Add path.cs to source control

Add path.cs to source control


using System;
using System.Collections.Generic;
using System.IO;
using TwitchLib;
using TwitchLib.TwitchClientClasses;
using System.Net;

namespace JefBot.Commands
{
    internal class CoinPluginCommand : IPluginCommand
    {
        public string PluginName => "Coin";
        public string Command => "coin";
        public IEnumerable<string> Aliases => new[] { "c", "flip" };
        public bool Loaded { get; set; } = true;

        Random rng = new Random();

        public void Execute(ChatCommand command, TwitchClient client)
        {
            if (rng.Next(1000) > 1)
            {
                var result = rng.Next(0, 1) == 1 ? "heads" : "tails";

                client.SendMessage(command.ChatMessage.Channel,
                    $"{command.ChatMessage.Username} flipped a coin, it was {result}");
            }
            else
            {
                client.SendMessage(command.ChatMessage.Channel,
                    $"{command.ChatMessage.Username} flipped a coin, it landed on it's side...");
            }

        }
    }
}

Add coin flipping command. Sometimes lands on it's side. No idea why!


#if !NETSTANDARD2_1
namespace System.Diagnostics.CodeAnalysis
{
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
    sealed class AllowNullAttribute : Attribute
    {
    }
    [AttributeUsage(AttributeTargets.Method, Inherited = false)]
    sealed class DoesNotReturnAttribute : Attribute
    {
    }
    [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
    sealed class DoesNotReturnIfAttribute : Attribute
    {
        public bool ParameterValue { get; }

        public DoesNotReturnIfAttribute(bool parameterValue)
        {
            ParameterValue = parameterValue;
        }
    }
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
    sealed class DisallowNullAttribute : Attribute
    {
    }
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
    sealed class MaybeNullAttribute : Attribute
    {
    }
    [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
    sealed class MaybeNullWhenAttribute : Attribute
    {
        public bool ReturnValue { get; }

        public MaybeNullWhenAttribute(bool returnValue)
        {
            ReturnValue = returnValue;
        }
    }
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
    sealed class NotNullAttribute : Attribute
    {
    }
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
    sealed class NotNullIfNotNullAttribute : Attribute
    {
        public string ParameterName { get; }

        public NotNullIfNotNullAttribute(string parameterName)
        {
            ParameterName = parameterName;
        }
    }
    [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
    sealed class NotNullWhenAttribute : Attribute
    {
        public bool ReturnValue { get; }

        public NotNullWhenAttribute(bool returnValue)
        {
            ReturnValue = returnValue;
        }
    }
}
#endif

Add suport of nullable reference type attributes for lower TFM


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

namespace NBi.Core.Members.Ranges
{
    internal class DateRangeBuilder : BaseBuilder
    {
        protected new DateRange Range
        {
            get
            {
                return (DateRange)base.Range;
            }
        }

        protected override void InternalBuild()
        {
            if (string.IsNullOrEmpty(Range.Format))
                Result = Build(Range.Start, Range.End, Range.Culture, ToShortDatePattern);
            else
                Result = Build(Range.Start, Range.End, Range.Culture, Range.Format);
        }

        public IEnumerable<string> Build(DateTime start, DateTime end, CultureInfo culture, Func<CultureInfo, DateTime,  string> dateFormatter)
        {
            var list = new List<string>();

            var date= start;

            while (date <= end)
            {
                var dateString = dateFormatter(culture, date);
                list.Add(dateString);
                date = date.AddDays(1);
            }

            return list;
        }

        public IEnumerable<string> Build(DateTime start, DateTime end, CultureInfo culture, string format)
        {
            var list = new List<string>();

            var date = start;

            while (date <= end)
            {
                var dateString = date.ToString(format, culture.DateTimeFormat);
                list.Add(dateString);
                date = date.AddDays(1);
            }

            return list;
        }

        protected string ToLongDatePattern(CultureInfo culture, DateTime value)
        {
            return value.ToString(culture.DateTimeFormat.LongDatePattern);
        }

        protected string ToShortDatePattern(CultureInfo culture, DateTime value)
        {
            return value.ToString(culture.DateTimeFormat.ShortDatePattern);
        }
    }
}

Add the builder of DateRange

Add the builder of DateRange


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

using OpenTK.Graphics.ES30;

namespace osu.Framework.Graphics
{
    public struct BlendingInfo
    {
        public BlendingFactorSrc Source;
        public BlendingFactorDest Destination;
        public BlendingFactorSrc SourceAlpha;
        public BlendingFactorDest DestinationAlpha;

        public BlendingInfo(bool additive)
        {
            Source = BlendingFactorSrc.SrcAlpha;
            Destination = BlendingFactorDest.OneMinusSrcAlpha;
            SourceAlpha = BlendingFactorSrc.One;
            DestinationAlpha = BlendingFactorDest.One;

            Additive = additive;
        }

        public bool Additive
        {
            set { Destination = value ? BlendingFactorDest.One : BlendingFactorDest.OneMinusSrcAlpha; }
        }

        /// <summary>
        /// Copies the current BlendingInfo into target.
        /// </summary>
        /// <param name="target">The BlendingInfo to be filled with the copy.</param>
        public void Copy(ref BlendingInfo target)
        {
            target.Source = Source;
            target.Destination = Destination;
            target.SourceAlpha = Source;
            target.DestinationAlpha = Destination;
        }

        public bool Equals(BlendingInfo other)
        {
            return other.Source == Source && other.Destination == Destination && other.SourceAlpha == SourceAlpha && other.DestinationAlpha == DestinationAlpha;
        }
    }
}

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

using OpenTK.Graphics.ES30;

namespace osu.Framework.Graphics
{
    public struct BlendingInfo
    {
        public BlendingFactorSrc Source;
        public BlendingFactorDest Destination;
        public BlendingFactorSrc SourceAlpha;
        public BlendingFactorDest DestinationAlpha;

        public BlendingInfo(bool additive)
        {
            Source = BlendingFactorSrc.SrcAlpha;
            Destination = BlendingFactorDest.OneMinusSrcAlpha;
            SourceAlpha = BlendingFactorSrc.One;
            DestinationAlpha = BlendingFactorDest.One;

            Additive = additive;
        }

        public bool Additive
        {
            set { Destination = value ? BlendingFactorDest.One : BlendingFactorDest.OneMinusSrcAlpha; }
        }

        /// <summary>
        /// Copies the current BlendingInfo into target.
        /// </summary>
        /// <param name="target">The BlendingInfo to be filled with the copy.</param>
        public void Copy(ref BlendingInfo target)
        {
            target.Source = Source;
            target.Destination = Destination;
            target.SourceAlpha = SourceAlpha;
            target.DestinationAlpha = DestinationAlpha;
        }

        public bool Equals(BlendingInfo other)
        {
            return other.Source == Source && other.Destination == Destination && other.SourceAlpha == SourceAlpha && other.DestinationAlpha == DestinationAlpha;
        }
    }
}

Fix incorrect copying of blending values.


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

using System.Linq;
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Beatmaps.Timing;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Taiko.Objects;
using osu.Game.Tests.Visual;

namespace osu.Game.Rulesets.Taiko.Tests
{
    public class TestSceneBarLineGeneration : OsuTestScene
    {
        [Test]
        public void TestCloseBarLineGeneration()
        {
            const double start_time = 1000;

            var beatmap = new Beatmap<TaikoHitObject>
            {
                HitObjects =
                {
                    new Hit
                    {
                        Type = HitType.Centre,
                        StartTime = start_time
                    }
                },
                BeatmapInfo =
                {
                    Difficulty = new BeatmapDifficulty { SliderTickRate = 4 },
                    Ruleset = new TaikoRuleset().RulesetInfo
                },
            };

            beatmap.ControlPointInfo.Add(start_time, new TimingControlPoint());
            beatmap.ControlPointInfo.Add(start_time + 1, new TimingControlPoint());

            var barlines = new BarLineGenerator<BarLine>(beatmap).BarLines;

            AddAssert("first barline generated", () => barlines.Any(b => b.StartTime == start_time));
            AddAssert("second barline generated", () => barlines.Any(b => b.StartTime == start_time + 1));
        }

        [Test]
        public void TestOmitBarLineEffectPoint()
        {
            const double start_time = 1000;
            const double beat_length = 500;

            const int time_signature_numerator = 4;

            var beatmap = new Beatmap<TaikoHitObject>
            {
                HitObjects =
                {
                    new Hit
                    {
                        Type = HitType.Centre,
                        StartTime = start_time
                    }
                },
                BeatmapInfo =
                {
                    Difficulty = new BeatmapDifficulty { SliderTickRate = 4 },
                    Ruleset = new TaikoRuleset().RulesetInfo
                },
            };

            beatmap.ControlPointInfo.Add(start_time, new TimingControlPoint
            {
                BeatLength = beat_length,
                TimeSignature = new TimeSignature(time_signature_numerator)
            });

            beatmap.ControlPointInfo.Add(start_time, new EffectControlPoint { OmitFirstBarLine = true });

            var barlines = new BarLineGenerator<BarLine>(beatmap).BarLines;

            AddAssert("first barline ommited", () => !barlines.Any(b => b.StartTime == start_time));
            AddAssert("second barline generated", () => barlines.Any(b => b.StartTime == start_time + (beat_length * time_signature_numerator)));
        }
    }
}

Add tests for the BarLineGenerator

Add tests for the BarLineGenerator


using System;

namespace Nohros
{
  /// <summary>
  /// A implementation of the <see cref="ISupplier{T}"/> class that supply
  /// elements of type <typeparamref name="T"/> in a sequence.
  /// </summary>
  /// <typeparam name="T">
  /// The type of objects supplied.
  /// </typeparam>
  public interface ISupplierStream<T> : ISupplier<T>
  {
    /// <summary>
    /// Gets a value indicating if an item available is available from the
    /// supplier.
    /// </summary>
    /// <value>
    /// <c>true</c> if an item is available from the supplier(that is, if
    /// <see cref="ISupplier{T}.Supply"/> method wolud return a value);
    /// otherwise <c>false</c>.
    /// </value>
    bool Available { get; }
  }
}

Create a supplier that supply elements continually(Stream).


// 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.IO;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Platform;
using osu.Game.Graphics.Cursor;
using osu.Game.Tournament.Screens.Drawings;

namespace osu.Game.Tournament.Tests.Screens
{
    public class TestSceneDrawingsScreen : TournamentTestScene
    {
        [BackgroundDependencyLoader]
        private void load(Storage storage)
        {
            using (var stream = storage.GetStream("drawings.txt", FileAccess.Write))
            using (var writer = new StreamWriter(stream))
            {
                writer.WriteLine("KR : South Korea : KOR");
                writer.WriteLine("US : United States : USA");
                writer.WriteLine("PH : Philippines : PHL");
                writer.WriteLine("BR : Brazil : BRA");
                writer.WriteLine("JP : Japan : JPN");
            }

            Add(new OsuContextMenuContainer
            {
                RelativeSizeAxes = Axes.Both,
                Child = new DrawingsScreen()
            });
        }
    }
}

Add test scene for drawings screen

Add test scene for drawings screen


using System;
using System.Collections.Generic;
using System.Linq;
using Nito.Comparers;
using Nito.Comparers.Util;
using Xunit;

namespace UnitTests
{
    public class ComparableBase_Struct_DefaultComparerUnitTests
    {
        private struct Person : IComparable<Person>, IEquatable<Person>, IComparable
        {
            public static readonly IFullComparer<Person> DefaultComparer = ComparerBuilder.For<Person>().OrderBy(p => p.LastName).ThenBy(p => p.FirstName);

            public string FirstName { get; set; }
            public string LastName { get; set; }

            public override bool Equals(object obj) => ComparableImplementations.ImplementEquals(DefaultComparer, this, obj);

            public override int GetHashCode() => ComparableImplementations.ImplementGetHashCode(DefaultComparer, this);

            public int CompareTo(Person other) => ComparableImplementations.ImplementCompareTo(DefaultComparer, this, other);

            public bool Equals(Person other) => ComparableImplementations.ImplementEquals(DefaultComparer, this, other);

            public int CompareTo(object obj) => ComparableImplementations.ImplementCompareTo(DefaultComparer, this, obj);
        }

        private static readonly Person AbeAbrams = new Person { FirstName = "Abe", LastName = "Abrams" };
        private static readonly Person JackAbrams = new Person { FirstName = "Jack", LastName = "Abrams" };
        private static readonly Person WilliamAbrams = new Person { FirstName = "William", LastName = "Abrams" };
        private static readonly Person CaseyJohnson = new Person { FirstName = "Casey", LastName = "Johnson" };

        [Fact]
        public void ImplementsComparerDefault()
        {
            var list = new List<Person> { JackAbrams, CaseyJohnson, AbeAbrams, WilliamAbrams };
            list.Sort();
            Assert.Equal(new[] { AbeAbrams, JackAbrams, WilliamAbrams, CaseyJohnson }, list);
        }

        [Fact]
        public void ImplementsComparerDefault_Hash()
        {
            var set = new HashSet<Person> { JackAbrams, CaseyJohnson, AbeAbrams };
            Assert.True(set.Contains(new Person { FirstName = AbeAbrams.FirstName, LastName = AbeAbrams.LastName }));
            Assert.False(set.Contains(WilliamAbrams));
        }

        [Fact]
        public void ImplementsComparerDefault_NonGeneric()
        {
            var set = new System.Collections.ArrayList() { JackAbrams, CaseyJohnson, AbeAbrams };
            Assert.True(set.Contains(new Person { FirstName = AbeAbrams.FirstName, LastName = AbeAbrams.LastName }));
            Assert.False(set.Contains(WilliamAbrams));
        }
    }
}

Add examples and unit tests for comparing structs.


//  https://leetcode.com/problems/reorder-list/
//
//   Given a singly linked list L: L0→L1→…→Ln-1→Ln,
//   reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
//
//   You must do this in-place without altering the nodes' values.
//
//   For example,
//   Given {1,2,3,4}, reorder it to {1,4,2,3}.

using System;

public class ListNode {
    public int val;
    public ListNode next;
    public ListNode(int x) { val = x; }

    public override String ToString()
    {
        return String.Format("{0} {1}", val, next == null ? String.Empty : next.ToString());
    }
}

public class Solution {
    public void ReorderList(ListNode head) {
        if (head == null)
        {
            return;
        }

        var slow = head;
        var mid = new ListNode(0);
        mid.next = slow;
        var fast = head;
        while (fast != null && fast.next != null)
        {
            mid.next = slow;
            slow = slow.next;
            fast = fast.next.next;
        }

        mid.next.next = null;
        mid = slow;
        ListNode prev = null;
        while (slow != null)
        {
            var next = slow.next;
            slow.next = prev;
            prev = slow;
            slow = next;
        }

        mid = prev;
        while (mid != null)
        {
            var firstNext = head.next;
            var secondNext = mid.next;
            head.next = mid;
            mid.next = firstNext;
            head = firstNext;
            mid = secondNext;
        }
    }

    static void Main()
    {
        ListNode root = null;
        for (var i = 4; i >= 1; i--)
        {
            root = new ListNode(i) { next = root };
        }

        Console.WriteLine(root);
        new Solution().ReorderList(root);
        Console.WriteLine(root);

        root = null;
        for (var i = 3; i >= 1; i--)
        {
            root = new ListNode(i) { next = root };
        }

        Console.WriteLine(root);
        new Solution().ReorderList(root);
        Console.WriteLine(root);
    }
}

Reorder list - off by one

Reorder list - off by one


using AsmResolver.DotNet.Builder;
using AsmResolver.DotNet.Code.Cil;
using AsmResolver.DotNet.Signatures;
using AsmResolver.PE.DotNet.Cil;
using AsmResolver.PE.DotNet.Metadata.Tables.Rows;
using Xunit;

namespace AsmResolver.DotNet.Tests.Builder
{
    public class CilMethodBodySerializerTest
    {
        [Theory]
        [InlineData(false, true, 0)]
        [InlineData(false, false, 100)]
        [InlineData(false, null, 100)]
        [InlineData(true, true, 0)]
        [InlineData(true, false, 100)]
        [InlineData(true, null, 0)]
        public void ComputeMaxStackOnBuildOverride(bool computeMaxStack, bool? computeMaxStackOverride, int expectedMaxStack)
        {
            const int maxStack = 100;

            var module = new ModuleDefinition("SomeModule", KnownCorLibs.SystemPrivateCoreLib_v4_0_0_0);
            var main = new MethodDefinition(
                "Main",
                MethodAttributes.Public | MethodAttributes.Static,
                MethodSignature.CreateStatic(module.CorLibTypeFactory.Void));

            main.CilMethodBody = new CilMethodBody(main)
            {
                ComputeMaxStackOnBuild = computeMaxStack,
                MaxStack = maxStack,
                Instructions = {new CilInstruction(CilOpCodes.Ret)},
                LocalVariables = {new CilLocalVariable(module.CorLibTypeFactory.Int32)} // Force fat method body.
            };

            module.GetOrCreateModuleType().Methods.Add(main);
            module.ManagedEntrypoint = main;

            var builder = new ManagedPEImageBuilder(new DotNetDirectoryFactory
            {
                MethodBodySerializer = new CilMethodBodySerializer
                {
                    ComputeMaxStackOnBuildOverride = computeMaxStackOverride
                }
            });

            var newImage = builder.CreateImage(module);
            var newModule = ModuleDefinition.FromImage(newImage);

            Assert.Equal(expectedMaxStack, newModule.ManagedEntrypointMethod.CilMethodBody.MaxStack);
        }
    }
}

Add unit test for compute max stack override.


// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.AspNetCore.Components.RenderTree;

namespace Microsoft.AspNetCore.Components.Web
{
    /// <summary>
    /// Provides methods for building a collection of <see cref="RenderTreeFrame"/> entries.
    /// </summary>
    public static class RenderTreeBuilderExtensions
    {
        // The "prevent default" and "stop bubbling" flags behave like attributes, in that:
        // - you can have multiple of them on a given element (for separate events)
        // - you can add and remove them dynamically
        // - they are independent of other attributes (e.g., you can "stop bubbling" of a given
        //   event type on an element that doesn't itself have a handler for that event)
        // As such, they are represented as attributes to give the right diffing behavior.
        //
        // As a private implementation detail, their internal representation is magic-named
        // attributes. This may change in the future. If we add support for multiple-same
        // -named-attributes-per-element (#14365), then we will probably also declare a new
        // AttributeType concept, and have specific attribute types for these flags, and
        // the "name" can simply be the name of the event being modified.

        /// <summary>
        /// Appends a frame representing an instruction to prevent the default action
        /// for a specified event.
        /// </summary>
        /// <param name="builder">The <see cref="RenderTreeBuilder"/>.</param>
        /// <param name="sequence">An integer that represents the position of the instruction in the source code.</param>
        /// <param name="eventName">The name of the event to be affected.</param>
        /// <param name="value">True if the default action is to be prevented, otherwise false.</param>
        public static void AddEventPreventDefaultAttribute(this RenderTreeBuilder builder, int sequence, string eventName, bool value)
        {
            builder.AddAttribute(sequence, $"__internal_preventDefault_{eventName}", value);
        }

        /// <summary>
        /// Appends a frame representing an instruction to stop the specified event from
        /// bubbling up beyond the current element.
        /// </summary>
        /// <param name="builder">The <see cref="RenderTreeBuilder"/>.</param>
        /// <param name="sequence">An integer that represents the position of the instruction in the source code.</param>
        /// <param name="eventName">The name of the event to be affected.</param>
        /// <param name="value">True if bubbling should stop bubbling here, otherwise false.</param>
        public static void AddEventStopBubblingAttribute(this RenderTreeBuilder builder, int sequence, string eventName, bool value)
        {
            builder.AddAttribute(sequence, $"__internal_stopBubbling_{eventName}", value);
        }
    }
}

Add RenderTreeBuilder extension methods for "prevent default" and "stop bubbling"


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

using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Osu.Objects;
using osuTK;

namespace osu.Game.Rulesets.Osu.Tests
{
    [TestFixture]
    public class TestCaseHitCircleLongCombo : Game.Tests.Visual.TestCasePlayer
    {
        public TestCaseHitCircleLongCombo()
            : base(new OsuRuleset())
        {
        }

        protected override IBeatmap CreateBeatmap(Ruleset ruleset)
        {
            var beatmap = new Beatmap
            {
                BeatmapInfo = new BeatmapInfo
                {
                    BaseDifficulty = new BeatmapDifficulty { CircleSize = 6 },
                    Ruleset = ruleset.RulesetInfo
                }
            };

            for (int i = 0; i < 512; i++)
                beatmap.HitObjects.Add(new HitCircle { Position = new Vector2(256, 192), StartTime = i * 100 });

            return beatmap;
        }
    }
}

Add a TestCase for looong combos

Add a TestCase for looong combos


using System;

namespace System.ComponentModel.DataAnnotations
{
  /// <summary>
  /// Specifies that a data field value must
  /// fall within the specified range.
  /// </summary>
  [AttributeUsage(AttributeTargets.Property)]
  public class StringLengthAttribute : ValidationAttribute
  {
    private int _max;

    public StringLengthAttribute(int stringMaxLength)
    {
      _max = stringMaxLength;
      ErrorMessage = "Field length must not exceed maximum length.";
    }

      /// <summary>
    /// Validates the specified value with respect to
    /// the current validation attribute.
    /// </summary>
    /// <param name="value">Value of the object to validate.</param>
    /// <param name="validationContext">The context information about the validation operation.</param>
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
      if (value != null && value.ToString().Length > _max)
        return new ValidationResult(this.ErrorMessage);
      else
        return null;
    }
  }
}

using System;

namespace System.ComponentModel.DataAnnotations
{
  /// <summary>
  /// Specifies that a data field value must
  /// fall within the specified range.
  /// </summary>
  [AttributeUsage(AttributeTargets.Property)]
  public class StringLengthAttribute : ValidationAttribute
  {
    private int _max;

    /// <summary>
    /// Creates an instance of the attribute.
    /// </summary>
    /// <param name="stringMaxLength">Maximum string length allowed.</param>
    public StringLengthAttribute(int stringMaxLength)
    {
      _max = stringMaxLength;
      ErrorMessage = "Field length must not exceed maximum length.";
    }

      /// <summary>
    /// Validates the specified value with respect to
    /// the current validation attribute.
    /// </summary>
    /// <param name="value">Value of the object to validate.</param>
    /// <param name="validationContext">The context information about the validation operation.</param>
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
      if (value != null && value.ToString().Length > _max)
        return new ValidationResult(this.ErrorMessage);
      else
        return null;
    }
  }
}

Fix comment on attribute ctor. bugid: 862


//Synchronous template
//-----------------------------------------------------------------------------------
// PCB-Investigator Automation Script
// Created on 14.10.2015
// Autor Fabio Gruber
//
// Select all elements outside the board contour, e.g. to delete them.
//-----------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Text;
using PCBI.Plugin;
using PCBI.Plugin.Interfaces;
using System.Windows.Forms;
using System.Drawing;
using PCBI.Automation;
using System.IO;
using System.Drawing.Drawing2D;
using PCBI.MathUtils;

namespace PCBIScript
{
   public class PScript : IPCBIScript
	{
		public PScript()
		{
		}

 		public void Execute(IPCBIWindow Parent)
        {
            IStep step = Parent.GetCurrentStep();
            IMatrix matrix = Parent.GetMatrix();
            if (step == null) return;
            IODBObject profile = step.GetPCBOutlineAsODBObject();

            foreach (string layerName in step.GetAllLayerNames())
            {
                if (matrix.GetMatrixLayerType(layerName) == MatrixLayerType.Component)
                    continue; //no component layer

                ILayer Layer = step.GetLayer(layerName);
                if (Layer is IODBLayer)
                {
                    bool foundOne = false;
                    IODBLayer layer = (IODBLayer)Layer;
                    foreach (IODBObject obj in layer.GetAllLayerObjects())
                    {
                        if (profile.IsPointOfSecondObjectIncluded(obj))
                        {
                            //inside not relevant
                        }
                        else
                        {
                            obj.Select(true);
                            foundOne = true;
                        }
                    }
                    if (foundOne) Layer.EnableLayer(true);
                }
            }
            Parent.UpdateSelection();
            Parent.UpdateView();
        }
    }
}

Select everything outside of pcb profile


using System.Linq;
using slang.Lexing.Rules.Core;
using slang.Lexing.Trees.Nodes;

namespace slang.Lexing.Trees.Transformers
{
    public static class RepeatRuleExtensions
    {
        public static Tree Transform (this Repeat rule)
        {
            var tree = rule.Value.Transform ();
            var transitions = tree.Root.Transitions;

            tree.Leaves
                .ToList ()
                .ForEach (leaf => {
                    transitions.ToList ().ForEach (transition => leaf.Transitions.Add (transition.Key, transition.Value));
                    leaf.Transitions [Character.Any] = new Transition (null, rule.TokenCreator);
                });

            return tree;
        }
    }
}

Transform repeat rules into a tree

Transform repeat rules into a tree


//  https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
//   Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
//
//   For example,
//   Given 1->2->3->3->4->4->5, return 1->2->5.
//   Given 1->1->1->2->3, return 2->3.
//
//   https://leetcode.com/submissions/detail/67082686/
//
//   Submission Details
//   166 / 166 test cases passed.
//      Status: Accepted
//      Runtime: 171 ms
//
//          Submitted: 9 hours, 19 minutes ago
public class Solution {
    public ListNode DeleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        if (head.val == head.next.val) {
            while (head.next != null && head.val == head.next.val) {
                head = head.next;
            }

            return DeleteDuplicates(head.next);
        }

        head.next = DeleteDuplicates(head.next);
        return head;
    }
}

Remove duplicates from sorted list II

Remove duplicates from sorted list II


using System.Collections.Generic;
using System.Linq;
using PathFinder.Cars.DAL.Model;
using PathFinder.Cars.WebApi.Queries;

namespace CarsControllersTests
{
    public class CarContextQueryMockBuilder
    {
        private readonly CarContextMock _fakeQuery;

        public CarContextQueryMockBuilder()
        {
            _fakeQuery = new CarContextMock();
        }

        public ICarsContextQuery CarsContextQuery
        {
            get { return _fakeQuery; }
        }

        public CarContextQueryMockBuilder SetCars(IEnumerable<Car> cars)
        {
            _fakeQuery.Cars = new EnumerableQuery<Car>(cars);
            return this;
        }

        public CarContextQueryMockBuilder SetUsers(IEnumerable<User> users)
        {
            _fakeQuery.Users = new EnumerableQuery<User>(users);
            return this;
        }

        public CarContextQueryMockBuilder SetCarBrands(IEnumerable<CarBrand> carBrands)
        {
            _fakeQuery.CarBrands = new EnumerableQuery<CarBrand>(carBrands);
            return this;
        }

        public CarContextQueryMockBuilder SetCarColors(IEnumerable<CarColor> carColors)
        {
            _fakeQuery.CarColors = new EnumerableQuery<CarColor>(carColors);
            return this;
        }

        public CarContextQueryMockBuilder SetCarModels(IEnumerable<CarModel> carModels)
        {
            _fakeQuery.CarModels = new EnumerableQuery<CarModel>(carModels);
            return this;
        }
    }

    public class CarContextMock : ICarsContextQuery
    {
        public CarContextMock()
        {
            Users = new EnumerableQuery<User>(Enumerable.Empty<User>());
            CarColors = new EnumerableQuery<CarColor>(Enumerable.Empty<CarColor>());
            CarBrands = new EnumerableQuery<CarBrand>(Enumerable.Empty<CarBrand>());
            CarModels = new EnumerableQuery<CarModel>(Enumerable.Empty<CarModel>());
            Cars = new EnumerableQuery<Car>(Enumerable.Empty<Car>());
        }

        public IOrderedQueryable<User> Users { get; set; }

        public IOrderedQueryable<CarBrand> CarBrands { get; set;  }

        public IOrderedQueryable<CarColor> CarColors { get; set; }

        public IOrderedQueryable<CarModel> CarModels { get; set; }

        public IOrderedQueryable<Car> Cars { get; set; }
    }
}

Add mock builder for CarsContextQuery

Add mock builder for CarsContextQuery


#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion

namespace log4net {

    ///
    /// Provides information about the environment the assembly has
    /// been built for.
    ///
    public sealed class AssemblyInfo {
        /// Version of the assembly
        public const string Version = "1.2.11";

        /// Version of the framework targeted
#if NET_1_1
        public const decimal TargetFrameworkVersion = 1.1M;
#elif NET_4_0
        public const decimal TargetFrameworkVersion = 4.0M;
#elif NET_2_0 || NETCF_2_0 || MONO_2_0
#if !CLIENT_PROFILE
        public const decimal TargetFrameworkVersion = 2.0M;
#else
        public const decimal TargetFrameworkVersion = 3.5M;
#endif  // Client Profile
#else
        public const decimal TargetFrameworkVersion = 1.0M;
#endif

        /// Type of framework targeted
#if CLI
        public const string TargetFramework = "CLI Compatible Frameworks";
#elif NET
        public const string TargetFramework = ".NET Framework";
#elif NETCF
        public const string TargetFramework = ".NET Compact Framework";
#elif MONO
        public const string TargetFramework = "Mono";
#elif SSCLI
        public const string TargetFramework = "Shared Source CLI";
#else
        public const string TargetFramework = "Unknown";
#endif

        /// Does it target a client profile?
#if !CLIENT_PROFILE
        public const bool ClientProfile = false;
#else
        public const bool ClientProfile = true;
#endif

        ///
        /// Identifies the version and target for this assembly.
        ///
        public static string Info {
            get {
                return string.Format("Apache log4net version {0} compiled for {1}{2} {3}",
                                     Version, TargetFramework,
                                     /* Can't use
                                     ClientProfile && true ? " Client Profile" :
                                        or the compiler whines about unreachable expressions
                                     */
#if !CLIENT_PROFILE
                                     string.Empty,
#else
                                     " Client Profile",
#endif
                                     TargetFrameworkVersion);
            }
        }
    }

}

Make metadata accessible without reflection

git-svn-id: 7230453ef4d2e9c957b80d4737114f575fc9f7f8@1159843 13f79535-47bb-0310-9956-ffa450edef68


//-----------------------------------------------------------------------------------
// PCB-Investigator Automation Script
// Created on 2014-04-24
// Autor support@easylogix.de
// www.pcb-investigator.com
// SDK online reference http://www.pcb-investigator.com/sites/default/files/documents/InterfaceDocumentation/Index.html
// SDK http://www.pcb-investigator.com/en/sdk-participate
//
// Set Profil to fix Rectangle.
// The example rectangle is fixed size with 15 Inch x 10 Inch, just change the newBounds rectangle to get the size your company needs.
//-----------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Text;
using PCBI.Plugin;
using PCBI.Plugin.Interfaces;
using System.Windows.Forms;
using System.Drawing;
using PCBI.Automation;
using System.IO;
using System.Drawing.Drawing2D;
using PCBI.MathUtils;

namespace PCBIScript
{
	public class PScript : IPCBIScript
	{
		public PScript()
		{
		}

		public void Execute(IPCBIWindow parent)
		{
			  IFilter filter = new IFilter(parent);
            IODBObject outlinePolygon = filter.CreateOutlinePolygon();
            IStep parentStep = parent.GetCurrentStep();
            ISurfaceSpecifics spec = (ISurfaceSpecifics)outlinePolygon.GetSpecifics();

            spec.StartPolygon(false, new PointF());
            RectangleF newBounds = new RectangleF(0, 0, 15000, 10000);

            //create 4 lines and add them to an contour polygon
            PointF leftUp = new PointF(newBounds.Left, newBounds.Top);
            PointF leftDown = new PointF(newBounds.Left, newBounds.Bottom);
            PointF rightUp = new PointF(newBounds.Right, newBounds.Top);
            PointF rightDown = new PointF(newBounds.Right, newBounds.Bottom);
            spec.AddLine(leftUp, rightUp);
            spec.AddLine(rightUp, rightDown);
            spec.AddLine(rightDown, leftDown);
            spec.AddLine(leftDown, leftUp);

            spec.EndPolygon(); //close the new contour

            parentStep.SetPCBOutline(spec);
            parent.UpdateView();
		}

		public  StartMethode GetStartMethode()
		{
			return StartMethode.Synchronous;
		}
    }
}

Set Profil to fix Rectangle

Set Profil to fix Rectangle

Set Profil to fix Rectangle.
The example rectangle is fixed size with 15 Inch x 10 Inch, just change the newBounds rectangle to get the size your company needs.


using System;
using NUnit.Framework;

namespace InfiniMap.Test
{
    [TestFixture]
    public class MapTests
    {
        private Map createMap(int chunkSize, int chunksToFill)
        {
            var map = new Map(chunkSize, chunkSize);

            for (int x = 0; x <= (chunksToFill * chunkSize-1); x++)
            {
                for (int y = 0; y <= (chunksToFill * chunkSize-1); y++)
                {
                    map[x, y].BlockId = (ushort) x;
                    map[x, y].BlockMeta = (ushort) y;
                }
            }

            return map;
        }

        [Test]
        public void FreesChunksProperly()
        {
            var map = createMap(16, 1);

            var dictionaryCount = map.Chunks.Count;

            map.UnloadArea(0, 0, 1);

            Assert.That(dictionaryCount > map.Chunks.Count);
        }
    }
}

Add missing file for Map tests

Add missing file for Map tests


using System.Collections.Generic;
using Glimpse.AspNet.Extensions;
using Glimpse.AspNet.Model;
using Glimpse.Core.Extensibility;

namespace Glimpse.AspNet.SerializationConverter
{
    public class SessionModelConverter : SerializationConverter<List<SessionModel>>
    {
        public override object Convert(List<SessionModel> obj)
        {
            var result = new List<object[]> { new[] { "Key", "Value", "Type" } };
            foreach (var item in obj)
            {
                result.Add(new[] { item.Key, item.Value, item.Type });
            }

            return result;
        }
    }
}

using System.Collections.Generic;
using Glimpse.AspNet.Extensions;
using Glimpse.AspNet.Model;
using Glimpse.Core.Extensibility;
using Glimpse.Core.Plugin.Assist;

namespace Glimpse.AspNet.SerializationConverter
{
    public class SessionModelConverter : SerializationConverter<List<SessionModel>>
    {
        public override object Convert(List<SessionModel> obj)
        {
            var root = new TabSection("Key", "Value", "Type");
            foreach (var item in obj)
            {
                root.AddRow().Column(item.Key).Column(item.Value).Column(item.Type);
            }

            return root.Build();
        }
    }
}

Refactor var in Session to be consistent with rest of the plugins


using System;
using System.Threading.Tasks;
using Nito.AsyncEx;
using System.Linq;
using System.Threading;
using System.Diagnostics.CodeAnalysis;
using Xunit;

namespace UnitTests
{
    public class SingleDisposableUnitTests
    {
        [Fact]
        public void ConstructedWithNullContext_DisposeIsANoop()
        {
            var disposable = new DelegateSingleDisposable<object>(null, _ => { Assert.False(true, "Callback invoked"); });
            disposable.Dispose();
        }

        [Fact]
        public void ConstructedWithContext_DisposeReceivesThatContext()
        {
            var providedContext = new object();
            object seenContext = null;
            var disposable = new DelegateSingleDisposable<object>(providedContext, context => { seenContext = context; });
            disposable.Dispose();
            Assert.Same(providedContext, seenContext);
        }

        [Fact]
        public void DisposeOnlyCalledOnce()
        {
            var counter = 0;
            var disposable = new DelegateSingleDisposable<object>(new object(), _ => { ++counter; });
            disposable.Dispose();
            disposable.Dispose();
            Assert.Equal(1, counter);
        }

        private sealed class DelegateSingleDisposable<T>: SingleDisposable<T>
            where T : class
        {
            private readonly Action<T> _callback;

            public DelegateSingleDisposable(T context, Action<T> callback)
                : base(context)
            {
                _callback = callback;
            }

            protected override void Dispose(T context)
            {
                _callback(context);
            }
        }
    }
}

Add unit tests for SingleDisposable.

Add unit tests for SingleDisposable.


using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

[assembly: AssemblyProduct("Harbour.RedisSessionStateStore")]

[assembly: AssemblyCompany("http://www.adrianphinney.com")]
[assembly: AssemblyCopyright("Copyright © Harbour Inc. 2012")]
[assembly: AssemblyDescription("An ASP.NET Redis SessionStateStoreProvider.")]

[assembly: ComVisible(false)]

using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

[assembly: AssemblyProduct("Harbour.RedisSessionStateStore")]

[assembly: AssemblyCompany("http://github.com/TheCloudlessSky/Harbour.RedisSessionStateStore")]
[assembly: AssemblyCopyright("Copyright © Harbour Inc. 2014")]
[assembly: AssemblyDescription("An ASP.NET Redis SessionStateStoreProvider.")]

[assembly: ComVisible(false)]

Update website and copyright year.

Update website and copyright year.


using System;
using N2.Web.UI.WebControls;

namespace N2.Edit
{
	[ToolbarPlugin("", "tpPreview", "{url}", ToolbarArea.Preview, Targets.Preview, "~/Edit/Img/Ico/Png/eye.png", 0, ToolTip = "edit", GlobalResourceClassName = "Toolbar")]
	[ControlPanelLink("cpAdminister", "~/edit/img/ico/png/application_side_tree.png", "~/edit/?selected={Selected.Path}", "Administer site", -50, ControlPanelState.Visible, Target = Targets.Top)]
	[ControlPanelSeparator(0, ControlPanelState.Visible)]
	public partial class Default : Web.EditPage
	{
		protected string SelectedPath = "/";
		protected string SelectedUrl = "~/";

		protected override void OnInit(EventArgs e)
		{
			try
			{
				SelectedPath = SelectedItem.Path;
				SelectedPath = Engine.EditManager.GetPreviewUrl(SelectedItem);
			}
			catch(Exception ex)
			{
				Trace.Write(ex.ToString());
				Response.Redirect("install/begin/default.aspx");
			}

			base.OnInit(e);
		}
	}
}

using System;
using N2.Web.UI.WebControls;

namespace N2.Edit
{
	[ToolbarPlugin("", "tpPreview", "{url}", ToolbarArea.Preview, Targets.Preview, "~/Edit/Img/Ico/Png/eye.png", 0, ToolTip = "edit", GlobalResourceClassName = "Toolbar")]
	[ControlPanelLink("cpAdminister", "~/edit/img/ico/png/application_side_tree.png", "~/edit/?selected={Selected.Path}", "Administer site", -50, ControlPanelState.Visible, Target = Targets.Top)]
	[ControlPanelSeparator(0, ControlPanelState.Visible)]
	public partial class Default : Web.EditPage
	{
		string selectedPath;
		string selectedUrl;

		public string SelectedPath
		{
			get { return selectedPath ?? "/"; }
		}
		public string SelectedUrl
		{
			get { return selectedUrl ?? "~/"; }
		}

		protected override void OnInit(EventArgs e)
		{
			try
			{
				selectedPath = SelectedItem.Path;
				selectedUrl = Engine.EditManager.GetPreviewUrl(SelectedItem);
			}
			catch(Exception ex)
			{
				Trace.Write(ex.ToString());
				Response.Redirect("install/begin/default.aspx");
			}

			base.OnInit(e);
		}
	}
}

Select start page by default instead of root


//
// Copyright (c) Microsoft and contributors.  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.
//

// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.

using System;
using System.Linq;

namespace Microsoft.Azure.Management.DataFactories.Models
{
    /// <summary>
    /// Data center location of the data factory.
    /// </summary>
    public static partial class Location
    {
        /// <summary>
        /// West US
        /// </summary>
        public const string WestUS = "westus";
    }
}

//
// Copyright (c) Microsoft and contributors.  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.
//

// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.

using System;
using System.Linq;

namespace Microsoft.Azure.Management.DataFactories.Models
{
    /// <summary>
    /// Data center location of the data factory.
    /// </summary>
    public static partial class Location
    {
        /// <summary>
        /// West US
        /// </summary>
        public const string WestUS = "westus";

        /// <summary>
        /// North Europe
        /// </summary>
        public const string NorthEurope = "northeurope";
    }
}

Add NorthEurope to location enum for Data Factories


using System.Threading.Tasks;
using NUnit.Framework;
using Robust.Client.Console;
using Robust.Shared.Interfaces.Network;
using Robust.Shared.IoC;

namespace Content.IntegrationTests.Tests
{
    [TestFixture]
    public class ReconnectTest : ContentIntegrationTest
    {
        [Test]
        public async Task Test()
        {
            var client = StartClient();
            var server = StartServer();

            await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync());

            // Connect.

            client.SetConnectTarget(server);

            client.Post(() => IoCManager.Resolve<IClientNetManager>().ClientConnect(null, 0, null));

            // Run some ticks for the handshake to complete and such.

            for (var i = 0; i < 10; i++)
            {
                server.RunTicks(1);
                await server.WaitIdleAsync();
                client.RunTicks(1);
                await client.WaitIdleAsync();
            }

            await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync());

            client.Post(() => IoCManager.Resolve<IClientConsole>().ProcessCommand("disconnect"));

            // Run some ticks for the disconnect to complete and such.
            for (var i = 0; i < 5; i++)
            {
                server.RunTicks(1);
                await server.WaitIdleAsync();
                client.RunTicks(1);
                await client.WaitIdleAsync();
            }

            await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync());

            // Reconnect.

            client.SetConnectTarget(server);

            client.Post(() => IoCManager.Resolve<IClientNetManager>().ClientConnect(null, 0, null));

            // Run some ticks for the handshake to complete and such.

            for (var i = 0; i < 10; i++)
            {
                server.RunTicks(1);
                await server.WaitIdleAsync();
                client.RunTicks(1);
                await client.WaitIdleAsync();
            }

            await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync());
        }
    }
}

Add test asserting reconnect works.

Add test asserting reconnect works.


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

namespace Postolego.Converters {
    public class TextDependentOnSelectedIndexConverter : IValueConverter {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            var invalue = (int)value;
            string text = "";
            if(invalue < 1) {
                text = "UNREAD";
            } else if(invalue == 1) {
                text = "ARCHIVE";
            } else {
                text = "FAVORITES";
            }
            return text;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            return null;
        }
    }
}

Add 'tabs' and header with converter on main page


using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text;

namespace NSync.Core
{
    public static class Http
    {
        /// <summary>
        /// Download data from an HTTP URL and insert the result into the
        /// cache. If the data is already in the cache, this returns
        /// a cached value. The URL itself is used as the key.
        /// </summary>
        /// <param name="url">The URL to download.</param>
        /// <param name="headers">An optional Dictionary containing the HTTP
        /// request headers.</param>
        /// <returns>The data downloaded from the URL.</returns>
        public static IObservable<byte[]> DownloadUrl(string url, Dictionary<string, string> headers = null)
        {
            var ret = makeWebRequest(new Uri(url), headers)
                .SelectMany(processAndCacheWebResponse)
                .Multicast(new AsyncSubject<byte[]>());

            ret.Connect();
            return ret;
        }

        static IObservable<byte[]> processAndCacheWebResponse(WebResponse wr)
        {
            var hwr = (HttpWebResponse)wr;
            if ((int)hwr.StatusCode >= 400) {
                return Observable.Throw<byte[]>(new WebException(hwr.StatusDescription));
            }

            var ms = new MemoryStream();
            hwr.GetResponseStream().CopyTo(ms);

            var ret = ms.ToArray();
            return Observable.Return(ret);
        }

        static IObservable<WebResponse> makeWebRequest(
            Uri uri,
            Dictionary<string, string> headers = null,
            string content = null,
            int retries = 3,
            TimeSpan? timeout = null)
        {
            var request = Observable.Defer(() => {
                var hwr = WebRequest.Create(uri);
                if (headers != null) {
                    foreach (var x in headers) {
                        hwr.Headers[x.Key] = x.Value;
                    }
                }

                if (content == null) {
                    return Observable.FromAsyncPattern<WebResponse>(hwr.BeginGetResponse, hwr.EndGetResponse)();
                }

                var buf = Encoding.UTF8.GetBytes(content);
                return Observable.FromAsyncPattern<Stream>(hwr.BeginGetRequestStream, hwr.EndGetRequestStream)()
                    .SelectMany(x => Observable.FromAsyncPattern<byte[], int, int>(x.BeginWrite, x.EndWrite)(buf, 0, buf.Length))
                    .SelectMany(_ => Observable.FromAsyncPattern<WebResponse>(hwr.BeginGetResponse, hwr.EndGetResponse)());
            });

            return request.Timeout(timeout ?? TimeSpan.FromSeconds(15)).Retry(retries);
        }
    }
}

Add an Rx-friendly HTTP downloader

Add an Rx-friendly HTTP downloader


@using System.Configuration;
@{
    ViewBag.Title = "Login";
}

<div id="root" style="width: 280px; margin: 40px auto;">
</div>
@Html.AntiForgeryToken()
<script src="https://cdn.auth0.com/js/lock-7.9.min.js"></script>
<script>
    if (!window.location.origin) {
        window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
    }

    var lock = new Auth0Lock('@ConfigurationManager.AppSettings["auth0:ClientId"]', '@ConfigurationManager.AppSettings["auth0:Domain"]');

    var xsrf = document.getElementsByName("__RequestVerificationToken")[0].value;

    lock.show({
        container: 'root'
      , callbackURL: window.location.origin + '/signin-auth0'
      , responseType: 'code'
      , authParams: {
          scope: 'openid name email',
          state: 'xsrf=' + xsrf + '&ru=' + '@ViewBag.ReturnUrl'
      }
    });
</script>

@using System.Configuration;
@{
    ViewBag.Title = "Login";
}

<div id="root" style="width: 280px; margin: 40px auto;">
</div>
@Html.AntiForgeryToken()
<script src="https://cdn.auth0.com/js/lock-7.11.min.js"></script>
<script>
    if (!window.location.origin) {
        window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
    }

    var lock = new Auth0Lock('@ConfigurationManager.AppSettings["auth0:ClientId"]', '@ConfigurationManager.AppSettings["auth0:Domain"]');

    var xsrf = document.getElementsByName("__RequestVerificationToken")[0].value;

    lock.show({
        container: 'root'
      , callbackURL: window.location.origin + '/signin-auth0'
      , responseType: 'code'
      , authParams: {
          scope: 'openid name email',
          state: 'xsrf=' + xsrf + '&ru=' + '@ViewBag.ReturnUrl'
      }
    });
</script>

Update lock to version 7.11

Update lock to version 7.11


// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

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

namespace HoloToolkit.Unity
{
    public class RaycastResultComparer : IComparer<RaycastResult>
    {
        public int Compare(RaycastResult left, RaycastResult right)
        {
            var result = CompareRaycastsByCanvasDepth(left, right);
            if (result != 0) { return result; }
            return CompareRaycastsByDistance(left, right);
        }

        private static int CompareRaycastsByCanvasDepth(RaycastResult left, RaycastResult right)
        {
            //Module is the graphic raycaster on the canvases.
            if (left.module.transform.IsParentOrChildOf(right.module.transform))
            {
                return right.depth.CompareTo(left.depth);
            }
            return 0;
        }

        private static int CompareRaycastsByDistance(RaycastResult left, RaycastResult right)
        {
            return left.distance.CompareTo(right.distance);
        }
    }
}

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

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

namespace HoloToolkit.Unity
{
    public class RaycastResultComparer : IComparer<RaycastResult>
    {
        private static readonly List<Func<RaycastResult, RaycastResult, int>> Comparers = new List<Func<RaycastResult, RaycastResult, int>>
        {
            CompareRaycastsBySortingLayer,
            CompareRaycastsBySortingOrder,
            CompareRaycastsByCanvasDepth,
            CompareRaycastsByDistance,
        };

        public int Compare(RaycastResult left, RaycastResult right)
        {
            for (var i = 0; i < Comparers.Count; i++)
            {
                var result = Comparers[i](left, right);
                if (result != 0)
                {
                    return result;
                }
            }
            return 0;
        }

        private static int CompareRaycastsBySortingOrder(RaycastResult left, RaycastResult right)
        {
            //Higher is better
            return right.sortingOrder.CompareTo(left.sortingOrder);
        }

        private static int CompareRaycastsBySortingLayer(RaycastResult left, RaycastResult right)
        {
            //Higher is better
            return right.sortingLayer.CompareTo(left.sortingLayer);
        }

        private static int CompareRaycastsByCanvasDepth(RaycastResult left, RaycastResult right)
        {
            //Module is the graphic raycaster on the canvases.
            if (left.module.transform.IsParentOrChildOf(right.module.transform))
            {
                //Higher is better
                return right.depth.CompareTo(left.depth);
            }
            return 0;
        }

        private static int CompareRaycastsByDistance(RaycastResult left, RaycastResult right)
        {
            //Lower is better
            return left.distance.CompareTo(right.distance);
        }
    }
}

Add sorting order/layer comparison Also move comparer methods into a list


// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Shell;

namespace Microsoft.VisualStudio.LanguageServices.Razor
{
    [Export(typeof(ForegroundDispatcher))]
    internal class VisualStudioForegroundDispatcher : ForegroundDispatcher
    {
        public override bool IsForegroundThread => ThreadHelper.CheckAccess();
    }
}

Add a default VS foregrounddispatcher

Add a default VS foregrounddispatcher


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

namespace ElectronicCash.Tests
{
    [TestFixture]
    class CustomerDataTests
    {
        //private static DateTime _dateTime = new DateTime();
        private static readonly Name CustomerName = new Name("Elmer", "T.", "Fudd", "Mr.");
        private static readonly StreetAddress CustomerAddress = new StreetAddress("20 Bunny Rd.", "Rabbits, Rabbitville", "12345");
        private readonly CustomerData _customerData = new CustomerData(CustomerName, "fudd@bunny.xyz",
            CustomerAddress, DateTime.UtcNow, new Guid());

        [Test]
        public void OnConstruction_NameShouldNotBeNull()
        {
            Assert.IsNotNull(CustomerName);
        }

        [Test]
        public void OnConstruction_NamePropertiesShouldNotBeNull()
        {
            Assert.IsNotNull(CustomerName.FirstName);
            Assert.IsNotNull(CustomerName.MiddleName);
            Assert.IsNotNull(CustomerName.LastName);
            Assert.IsNotNull(CustomerName.Title);
        }

        [Test]
        public void OnConstruction_CustomerAddressShouldNotBeNull()
        {
            Assert.IsNotNull(CustomerAddress);
        }

        [Test]
        public void OnConstruction_CustomerAddressWithoutAptPropertiesShouldNotBeNull()
        {
            Assert.IsNotNull(CustomerAddress.CityState);
            Assert.IsNotNull(CustomerAddress.Road);
            Assert.IsNotNull(CustomerAddress.ZipCode);
        }

        [Test]
        public void OnConstruction_CustomerDataObjectShouldNotBeNull()
        {
            Assert.IsNotNull(_customerData);
        }

        [Test]
        public void OnConstruction_CustomerDataPropertiesShouldNotBeNull()
        {
            Assert.IsNotNull(_customerData.CreatedDateTime);
            Assert.IsNotNull(_customerData.CustomerGuid);
            Assert.IsNotNull(_customerData.CustomerName);
            Assert.IsNotNull(_customerData.CustomerStreetAddress);
            Assert.IsNotNull(_customerData.Email);
            Assert.IsNotNull(_customerData.CreatedDateTime);
        }

        [Test]
        public void OnSerialization_OutputShouldBeValidJson()
        {
            var serialized = _customerData.GetCustomerDataJson(_customerData);

            var testRead =
        }
    }
}

Write various unit tests for CustomerData, Name, and StreetAddress


using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;

namespace Promact.Trappist.Core.Controllers
{
    [Route("api/question")]
    public class QuestionsController : Controller
    {
        private readonly IQuestionRepository _questionsRepository;
        public QuestionsController(IQuestionRepository questionsRepository)
        {
            _questionsRepository = questionsRepository;
        }

        [HttpGet]
        /// <summary>
        /// Gets all questions
        /// </summary>
        /// <returns>Questions list</returns>
        public IActionResult GetQuestions()
        {
            var questions = _questionsRepository.GetAllQuestions();
            return Json(questions);
        }
        [HttpPost]
        /// <summary>
        ///
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        /// <returns></returns>
        public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
        {
            _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion);
            return Ok();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        /// <returns></returns>
        public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
        {
            _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption);
            return Ok();
        }
    }
}

Create server side API for single multiple answer question


using System.IO;
using log4net.ObjectRenderer;
using log4net.Util.Serializer;

namespace Newtonsoft.Json.Serialization
{
    public class RendererMapJsonTextWriter : JsonTextWriter
    {
        private readonly RendererMap rendererMap;

        private readonly TextWriter textWriter;

        public RendererMapJsonTextWriter(RendererMap rendererMap, TextWriter textWriter) :
            base(textWriter)
        {
            this.textWriter = textWriter;

            this.rendererMap = rendererMap;
        }

        public override void WriteValue(object value)
        {
            if (value == null)
            {
                base.WriteValue(value);
            }
            else
            {
                var renderer = this.rendererMap.Get(value);

                if (renderer == null)
                {
                    base.WriteValue(value);
                }
                else
                {
                    Render(value, renderer);
                }
            }
        }

        private void Render(object value, IObjectRenderer renderer)
        {
            var serializer = renderer as ISerializer;

            if (serializer == null)
            {
                renderer.RenderObject(this.rendererMap, value, this.textWriter);
            }
            else
            {
                Serialize(value, serializer);
            }
        }

        private void Serialize(object value, ISerializer serializer)
        {
            this.textWriter.Write(serializer.Serialize(value));
        }
    }
}

Add JsonWriter impl. that defaults to using a RendererMap


namespace dotless.Core
{
    using System.Web;
    using System.Web.SessionState;

    public class LessCssWithSessionHttpHandler : LessCssHttpHandler, IRequiresSessionState
    {
    }

    public class LessCssHttpHandler : LessCssHttpHandlerBase, IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                var handler = Container.GetInstance<HandlerImpl>();

                handler.Execute();
            }
            catch (System.IO.FileNotFoundException ex)
            {
                context.Response.StatusCode = 404;
                context.Response.Write("/* File Not Found while parsing: " + ex.Message + " */");
                context.Response.End();
            }
            catch (System.IO.IOException ex)
            {
                context.Response.StatusCode = 500;
                context.Response.Write("/* Error in less parsing: " + ex.Message + " */");
                context.Response.End();
            }
        }

        public bool IsReusable
        {
            get { return true; }
        }
    }
}

namespace dotless.Core
{
    using System.Web;
    using System.Web.SessionState;

    public class LessCssWithSessionHttpHandler : LessCssHttpHandler, IRequiresSessionState
    {
    }

    public class LessCssHttpHandler : LessCssHttpHandlerBase, IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                var handler = Container.GetInstance<HandlerImpl>();

                handler.Execute();
            }
            catch (System.IO.FileNotFoundException ex)
            {
                context.Response.StatusCode = 404;
                if (context.Request.IsLocal)
                {
                    context.Response.Write("/* File Not Found while parsing: " + ex.Message + " */");
                }
                else
                {
                    context.Response.Write("/* Error Occurred. Consult log or view on local machine. */");
                }
                context.Response.End();
            }
            catch (System.IO.IOException ex)
            {
                context.Response.StatusCode = 500;
                if (context.Request.IsLocal)
                {
                    context.Response.Write("/* Error in less parsing: " + ex.Message + " */");
                }
                else
                {
                    context.Response.Write("/* Error Occurred. Consult log or view on local machine. */");
                }
                context.Response.End();
            }
        }

        public bool IsReusable
        {
            get { return true; }
        }
    }
}

Remove error message giving away path location if not accessing from the local machine


using System.Linq;
using NUnit.Framework;
using ZeroLog.Tests.Support;

namespace ZeroLog.Tests;

[TestFixture]
public class SanityChecks
{
    [Test]
    public void should_export_expected_types()
    {
        // This test prevents mistakenly adding public types in the future.

        var publicTypes = new[]
        {
            "ZeroLog.Appenders.Appender",
            "ZeroLog.Appenders.ConsoleAppender",
            "ZeroLog.Appenders.DateAndSizeRollingFileAppender",
            "ZeroLog.Appenders.NoopAppender",
            "ZeroLog.Appenders.StreamAppender",
            "ZeroLog.Configuration.AppenderConfiguration",
            "ZeroLog.Configuration.LoggerConfiguration",
            "ZeroLog.Configuration.LogMessagePoolExhaustionStrategy",
            "ZeroLog.Configuration.RootLoggerConfiguration",
            "ZeroLog.Configuration.ZeroLogConfiguration",
            "ZeroLog.Formatting.FormattedLogMessage",
            "ZeroLog.Log",
            "ZeroLog.Log+DebugInterpolatedStringHandler",
            "ZeroLog.Log+ErrorInterpolatedStringHandler",
            "ZeroLog.Log+FatalInterpolatedStringHandler",
            "ZeroLog.Log+InfoInterpolatedStringHandler",
            "ZeroLog.Log+TraceInterpolatedStringHandler",
            "ZeroLog.Log+WarnInterpolatedStringHandler",
            "ZeroLog.LogLevel",
            "ZeroLog.LogManager",
            "ZeroLog.LogMessage",
            "ZeroLog.LogMessage+AppendInterpolatedStringHandler",
            "ZeroLog.UnmanagedFormatterDelegate`1",
        };

        typeof(LogManager).Assembly
                          .ExportedTypes
                          .Select(i => i.FullName)
                          .ShouldBeEquivalentTo(publicTypes);
    }
}

Add a sanity check for exported types

Add a sanity check for exported types


using System;
using System.Collections.Generic;
using System.Text;

namespace Spring.Objects.Factory.Parsing
{
    public interface IProblemReporter
    {
        void Fatal(Problem problem);
        void Warning(Problem problem);
        void Error(Problem problem);
    }
}

Add missing file from code config branch


public static string GetProductVersion()
{
  var attribute = (AssemblyVersionAttribute)Assembly
    .GetExecutingAssembly()
    .GetCustomAttributes( typeof(AssemblyVersionAttribute), true )
    .Single();
   return attribute.InformationalVersion;
}

Add simple snippet to get InformationalVersion


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

using Xunit;

using Http2;

namespace Http2Tests
{
    public class ConnectionUnknownFrameTests
    {
        [Theory]
        [InlineData(true, 0)]
        [InlineData(true, 512)]
        [InlineData(false, 0)]
        [InlineData(false, 512)]
        public async Task ConnectionShouldIgnoreUnknownFramesWithPong(
            bool isServer, int payloadLength)
        {
            var inPipe = new BufferedPipe(1024);
            var outPipe = new BufferedPipe(1024);
            var http2Con = await ConnectionUtils.BuildEstablishedConnection(
                isServer, inPipe, outPipe);

            // send an undefined frame type
            var fh = new FrameHeader
            {
                Type = (FrameType)100,
                Flags = 33,
                Length = payloadLength,
                StreamId = 0,
            };
            await inPipe.WriteFrameHeader(fh);
            if (payloadLength != 0)
            {
                var payload = new byte[payloadLength];
                await inPipe.WriteAsync(new ArraySegment<byte>(payload));
            }

            // Send a ping afterwards
            // If we get a response the unknown frame in between was ignored
            var pingData = new byte[8];
            for (var i = 0; i < 8; i++) pingData[i] = (byte)i;
            await inPipe.WritePing(pingData, false);
            var res = await outPipe.ReadFrameHeaderWithTimeout();
            Assert.Equal(FrameType.Ping, res.Type);
            Assert.Equal(0u, res.StreamId);
            Assert.Equal(8, res.Length);
            Assert.Equal((byte)PingFrameFlags.Ack, res.Flags);
            var pongData = new byte[8];
            await outPipe.ReadAllWithTimeout(new ArraySegment<byte>(pongData));
        }
    }
}

Add a testcase for unknown frame types

Add a testcase for unknown frame types


#region License
/**
 * Copyright (c) 2013-2014 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file).
 * Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE
 */
#endregion

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

using NUnit.Framework;

using SharpNav;
using SharpNav.Geometry;

#if MONOGAME || XNA
using Microsoft.Xna.Framework;
#elif OPENTK
using OpenTK;
#elif SHARPDX
using SharpDX;
#elif UNITY3D
using UnityEngine;
#endif

namespace SharpNavTests
{
	[TestFixture]
	public class JSONTests
	{
		[Test]
		public void WriteJSONTest()
        {
            TiledNavMesh mesh = new TiledNavMesh(null);
            mesh.SaveJson("mesh.json");
		}

        [Test]
        public void ReadJSONTest()
        {
            TiledNavMesh mesh = TiledNavMesh.LoadJson("mesh.json");
        }
	}
}

#region License
/**
 * Copyright (c) 2013-2014 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file).
 * Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE
 */
#endregion

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

using NUnit.Framework;

using SharpNav;
using SharpNav.Geometry;

#if MONOGAME || XNA
using Microsoft.Xna.Framework;
#elif OPENTK
using OpenTK;
#elif SHARPDX
using SharpDX;
#elif UNITY3D
using UnityEngine;
#endif

namespace SharpNavTests
{
	[TestFixture]
	public class JSONTests
	{
		[Test]
		public void WriteJSONTest()
        {
			NavMeshGenerationSettings settings = NavMeshGenerationSettings.Default;
			CompactHeightfield heightField = new CompactHeightfield(new Heightfield(
                new BBox3(1, 1, 1, 5, 5, 5), settings), settings);
            PolyMesh polyMesh = new PolyMesh(new ContourSet(heightField, settings), 8);
            PolyMeshDetail polyMeshDetail = new PolyMeshDetail(polyMesh, heightField, settings);

            NavMeshBuilder buildData = new NavMeshBuilder(polyMesh, polyMeshDetail, new SharpNav.Pathfinding.OffMeshConnection[0], settings);
            TiledNavMesh mesh = new TiledNavMesh(buildData);
            mesh.SaveJson("mesh.json");
		}

        [Test]
        public void ReadJSONTest()
        {
            TiledNavMesh mesh = TiledNavMesh.LoadJson("mesh.json");
        }
	}
}

Update WriteJSONTest to initialize TiledNavMesh with non-null parameter


// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Xunit;

namespace System.Globalization.Tests
{
    public class KoreanCalendarTwoDigitYearMax
    {
        [Fact]
        public void TwoDigitYearMax()
        {
            Assert.Equal(4362, new KoreanCalendar().TwoDigitYearMax);
        }
    }
}

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Xunit;

namespace System.Globalization.Tests
{
    public class KoreanCalendarTwoDigitYearMax
    {
        [Fact]
        public void TwoDigitYearMax_Get()
        {
            Assert.Equal(4362, new KoreanCalendar().TwoDigitYearMax);
        }

        [Theory]
        [InlineData(99)]
        [InlineData(2016)]
        public void TwoDigitYearMax_Set(int newTwoDigitYearMax)
        {
            Calendar calendar = new KoreanCalendar();
            calendar.TwoDigitYearMax = newTwoDigitYearMax;
            Assert.Equal(newTwoDigitYearMax, calendar.TwoDigitYearMax);
        }
    }
}

Add a test for TwoDigitYearMax to KoreanCalendar


// This set of methods extends the most excellent Rotorz api. I built this set because,
// while I love Rotorz, I find its method paramaters frustrating to use. Specifically,
// I tend to send x coordinates first in my params, followed by y coordinates; while
// Rotorz transposes this. It has lead to many crazy-making bugs in my code.
//
// These extensions also act as an interface to guarantee against future api changes, etc.

using Rotorz.Tile;
using System;
using UnityEngine;

namespace Matcha.Unity
{
	public static class TileExtensions
	{
		public static void BulkEditBegin(this TileSystem map)
		{
			map.BeginBulkEdit();
		}

		public static void BulkEditEnd(this TileSystem map)
		{
			map.EndBulkEdit();
		}

		public static bool ClearTile(this TileSystem map, int x, int y)
		{
			return map.EraseTile(y, x);
		}

		public static TileData GetTileInfo(this TileSystem map, int x, int y)
		{
			return map.GetTile(y, x);
		}

		public static void RefreshNearbyTiles(this TileSystem map, int x, int y)
		{
			map.RefreshSurroundingTiles(y, x);
		}

		public static void RefreshTiles(this TileSystem map)
		{
			map.RefreshAllTiles();
		}

		public static TileData PaintTile(this Brush brush, TileSystem map, int x, int y)
		{
			return brush.Paint(map, y, x);
		}

		// transform extensions for checking nearby tile data
		public static GameObject GetTileInfo(this Transform transform, TileSystem tileSystem, int xDirection, int yDirection)
		{
			// grabs tile info at a given transform:
			// x = 0, y = 0 will get you the tile the transform occupies
			// plus or minus x or y will get you tiles backwards, forwards, up or down

			var convertedX = (int)Math.Floor(transform.position.x);
			var convertedY = (int)Math.Ceiling(Math.Abs(transform.position.y));

			TileData tile = tileSystem.GetTile(convertedY + yDirection, convertedX + xDirection);

			if (tile != null)
			{
				return tile.gameObject;
			}

			return null;
		}

		public static GameObject GetTileBelow(this Transform transform, TileSystem tileSystem, int direction)
		{
			var convertedX = (int)Math.Floor(transform.position.x);
			var convertedY = (int)Math.Floor(Math.Abs(transform.position.y));

			TileData tile = tileSystem.GetTile(convertedY, convertedX + direction);

			if (tile != null)
			{
				return tile.gameObject;
			}

			return null;
		}
	}
}

Extend the Rotorz Tile System api

Extend the Rotorz Tile System api

I built this set of extensions because, while I love Rotorz, I find its
method paramaters frustrating to use. Specifically, I tend to send x
coordinates first in my params, followed by y coordinates; while Rotorz
transposes these. It has lead to many crazy-making bugs in my code.

These extensions also act as an interface to guarantee against future
api changes, or migration to a new tile system.