using System;
using System.Collections.Generic;

namespace Cxxi
{
    /// <summary>
    /// Represents a C++ property.
    /// </summary>
    public class Property
    {
        public Property(string name, Declaration type)
        {
            Name = name;
            Type = type;
        }

        public string Name
        {
            get;
            set;
        }

        public Declaration Type
        {
            get;
            set;
        }

        public Method GetMethod
        {
            get;
            set;
        }

        public Method SetMethod
        {
            get;
            set;
        }
    }
}

using System;
using System.Collections.Generic;

namespace Cxxi
{
    /// <summary>
    /// Represents a C++ property.
    /// </summary>
    public class Property : Declaration
    {
        public Property(string name, Declaration type)
        {
            Name = name;
            Type = type;
        }

        public Declaration Type
        {
            get;
            set;
        }

        public Method GetMethod
        {
            get;
            set;
        }

        public Method SetMethod
        {
            get;
            set;
        }

        public override T Visit<T>(IDeclVisitor<T> visitor)
        {
            throw new NotImplementedException();
        }
    }
}

Change properties to inherit from declarations.


namespace ContractsWindow
{
	public enum contractSortClass
	{
		Difficulty = 1,
		Expiration = 2,
		Acceptance = 3,
		Reward = 4,
		Type = 5,
		Planet = 6,
	}
}

Move sort class to new file

Move sort class to new file


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

using System.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Testing;
using osu.Framework.Timing;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.UI;
using osu.Game.Tests.Visual;

namespace osu.Game.Tests.Gameplay
{
    [HeadlessTest]
    public class TestSceneProxyContainer : OsuTestScene
    {
        private HitObjectContainer hitObjectContainer;
        private ProxyContainer proxyContainer;
        private readonly ManualClock clock = new ManualClock();

        [SetUp]
        public void SetUp() => Schedule(() =>
        {
            Child = new Container
            {
                Children = new Drawable[]
                {
                    hitObjectContainer = new HitObjectContainer(),
                    proxyContainer = new ProxyContainer()
                },
                Clock = new FramedClock(clock)
            };
            clock.CurrentTime = 0;
        });

        [Test]
        public void TestProxyLifetimeManagement()
        {
            AddStep("Add proxy drawables", () =>
            {
                addProxy(new TestDrawableHitObject(1000));
                addProxy(new TestDrawableHitObject(3000));
                addProxy(new TestDrawableHitObject(5000));
            });

            AddStep($"time = 1000", () => clock.CurrentTime = 1000);
            AddAssert("One proxy is alive", () => proxyContainer.AliveChildren.Count == 1);
            AddStep($"time = 5000", () => clock.CurrentTime = 5000);
            AddAssert("One proxy is alive", () => proxyContainer.AliveChildren.Count == 1);
            AddStep($"time = 6000", () => clock.CurrentTime = 6000);
            AddAssert("No proxy is alive", () => proxyContainer.AliveChildren.Count == 0);
        }

        private void addProxy(DrawableHitObject drawableHitObject)
        {
            hitObjectContainer.Add(drawableHitObject);
            proxyContainer.AddProxy(drawableHitObject);
        }

        private class ProxyContainer : LifetimeManagementContainer
        {
            public IReadOnlyList<Drawable> AliveChildren => AliveInternalChildren;

            public void AddProxy(Drawable d) => AddInternal(d.CreateProxy());
        }

        private class TestDrawableHitObject : DrawableHitObject
        {
            protected override double InitialLifetimeOffset => 100;

            public TestDrawableHitObject(double startTime)
                : base(new HitObject { StartTime = startTime })
            {
            }

            protected override void UpdateInitialTransforms()
            {
                LifetimeEnd = LifetimeStart + 500;
            }
        }
    }
}

Add regression test for the pattern of using DHO proxy in `LifetimeManagementContainer`


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

using System;
using System.Runtime.InteropServices;

// TODO: This implementation is temporary until Environment.OSVersion is officially exposed,
//       at which point that should be used instead.

internal static partial class Interop
{
    internal enum OperatingSystem
    {
        Windows,
        Linux,
        OSX
    }

    internal static class PlatformDetection
    {
        internal static OperatingSystem OperatingSystem { get { return s_os.Value; } }

        private static readonly Lazy<OperatingSystem> s_os = new Lazy<OperatingSystem>(() =>
        {
            if (Environment.NewLine != "\r\n")
            {
                unsafe
                {
                    byte* buffer = stackalloc byte[8192]; // the size use with uname is platform specific; this should be large enough for any OS
                    if (uname(buffer) == 0)
                    {
                        return Marshal.PtrToStringAnsi((IntPtr)buffer) == "Darwin" ?
                            OperatingSystem.OSX :
                            OperatingSystem.Linux;
                    }
                }
            }
            return OperatingSystem.Windows;
        });

        // not in src\Interop\Unix to avoiding pulling platform-dependent files into all projects
        [DllImport("libc")]
        private static extern unsafe uint uname(byte* buf);
    }
}

Add a platform detection mechanism to use in tests

This should eventually be replaced with (or reimplemented based on) Environment.OSVersion, once it's available.


using Serilog;

namespace GitHub.Logging
{
    public static class ILoggerExtensions
    {
        public static void Assert(this ILogger logger, bool condition, string messageTemplate)
        {
            if (!condition)
            {
                messageTemplate = "Assertion Failed: " + messageTemplate;
#pragma warning disable Serilog004 // propertyValues might not be strings
                logger.Warning(messageTemplate);
#pragma warning restore Serilog004
            }
        }

        public static void Assert(this ILogger logger, bool condition, string messageTemplate, params object[] propertyValues)
        {
            if (!condition)
            {
                messageTemplate = "Assertion Failed: " + messageTemplate;
#pragma warning disable Serilog004 // propertyValues might not be strings
                logger.Warning(messageTemplate, propertyValues);
#pragma warning restore Serilog004
            }
        }
    }
}

using System;
using System.Globalization;
using System.Threading.Tasks;
using Serilog;

namespace GitHub.Logging
{
    public static class ILoggerExtensions
    {
        public static void Assert(this ILogger logger, bool condition, string messageTemplate)
        {
            if (!condition)
            {
                messageTemplate = "Assertion Failed: " + messageTemplate;
#pragma warning disable Serilog004 // propertyValues might not be strings
                logger.Warning(messageTemplate);
#pragma warning restore Serilog004
            }
        }

        public static void Assert(this ILogger logger, bool condition, string messageTemplate, params object[] propertyValues)
        {
            if (!condition)
            {
                messageTemplate = "Assertion Failed: " + messageTemplate;
#pragma warning disable Serilog004 // propertyValues might not be strings
                logger.Warning(messageTemplate, propertyValues);
#pragma warning restore Serilog004
            }
        }

        public static void Time(this ILogger logger, string name, Action method)
        {
            var startTime = DateTime.Now;
            method();
            logger.Information("{Name} took {Seconds} seconds", name, FormatSeconds(DateTime.Now - startTime));
        }

        public static T Time<T>(this ILogger logger, string name, Func<T> method)
        {
            var startTime = DateTime.Now;
            var value = method();
            logger.Information("{Name} took {Seconds} seconds", name, FormatSeconds(DateTime.Now - startTime));
            return value;
        }

        public static async Task TimeAsync(this ILogger logger, string name, Func<Task> methodAsync)
        {
            var startTime = DateTime.Now;
            await methodAsync().ConfigureAwait(false);
            logger.Information("{Name} took {Seconds} seconds", name, FormatSeconds(DateTime.Now - startTime));
        }

        public static async Task<T> TimeAsync<T>(this ILogger logger, string name, Func<Task<T>> methodAsync)
        {
            var startTime = DateTime.Now;
            var value = await methodAsync().ConfigureAwait(false);
            logger.Information("{Name} took {Seconds} seconds", name, FormatSeconds(DateTime.Now - startTime));
            return value;
        }

        static string FormatSeconds(TimeSpan timeSpan) => timeSpan.TotalSeconds.ToString("0.##", CultureInfo.InvariantCulture);
    }
}

Add extension methods for logging timings


using System;
using System.Threading;
using System.Threading.Tasks;

namespace CircuitBreaker.Net
{
    // The following code is taken from "Crafting a Task.TimeoutAfter Method" post by Joe Hoag
    // http://blogs.msdn.com/b/pfxteam/archive/2011/11/10/10235834.aspx
    public static class TaskExtensions
    {
        public static Task TimeoutAfter(this Task task, int millisecondsTimeout)
        {
            // Short-circuit #1: infinite timeout or task already completed
            if (task.IsCompleted || (millisecondsTimeout == Timeout.Infinite))
            {
                // Either the task has already completed or timeout will never occur.
                // No proxy necessary.
                return task;
            }

            // tcs.Task will be returned as a proxy to the caller
            TaskCompletionSource<VoidTypeStruct> tcs =
                new TaskCompletionSource<VoidTypeStruct>();

            // Short-circuit #2: zero timeout
            if (millisecondsTimeout == 0)
            {
                // We've already timed out.
                tcs.SetException(new TimeoutException());
                return tcs.Task;
            }

            // Set up a timer to complete after the specified timeout period
            Timer timer = new Timer(
                state =>
                    {
                        // Recover your state information
                        var myTcs = (TaskCompletionSource<VoidTypeStruct>)state;

                        // Fault our proxy with a TimeoutException
                        myTcs.TrySetException(new TimeoutException());
                    },
                tcs,
                millisecondsTimeout,
                Timeout.Infinite);

            // Wire up the logic for what happens when source task completes
            task.ContinueWith(
                (antecedent, state) =>
                    {
                        // Recover our state data
                        var tuple =
                            (Tuple<Timer, TaskCompletionSource<VoidTypeStruct>>)state;

                        // Cancel the Timer
                        tuple.Item1.Dispose();

                        // Marshal results to proxy
                        MarshalTaskResults(antecedent, tuple.Item2);
                    },
                Tuple.Create(timer, tcs),
                CancellationToken.None,
                TaskContinuationOptions.ExecuteSynchronously,
                TaskScheduler.Default);

            return tcs.Task;
        }

        internal struct VoidTypeStruct
        {
        }

        internal static void MarshalTaskResults<TResult>(
            Task source,
            TaskCompletionSource<TResult> proxy)
        {
            switch (source.Status)
            {
                case TaskStatus.Faulted:
                    proxy.TrySetException(source.Exception);
                    break;
                case TaskStatus.Canceled:
                    proxy.TrySetCanceled();
                    break;
                case TaskStatus.RanToCompletion:
                    Task<TResult> castedSource = source as Task<TResult>;
                    proxy.TrySetResult(
                        castedSource == null
                            ? default(TResult)
                            : // source is a Task
                            castedSource.Result); // source is a Task<TResult>
                    break;
            }
        }
    }
}

Add a Task extension to handle timeouts

Add a Task extension to handle timeouts


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

namespace Recipe.ClassAndGeneric
{
    /// <summary>
    /// Simple class that implements IComparable<>
    /// </summary>
    public class Square : IComparable<Square>
    {
        public Square()
        {
        }

        public Square(int height, int width)
        {
            this.Height = height;
            this.Width = width;
        }

        public int Height { get; set; }
        public int Width { get; set; }

        public int CompareTo(object obj)
        {
            Square square = obj as Square;
            if (square != null)
            {
                return CompareTo(square);
            }
            throw
                new ArgumentException("Both objects being compared must be of type Square");
        }

        public override string ToString() => ($"Height:{this.Height}  Width:{this.Width}");

        public override bool Equals(object obj)
        {
            if (obj == null)
            {
                return false;
            }
            Square square = obj as Square;
            if (square != null)
            {
                return this.Height == square.Height;
            }
            return false;
        }

        public override int GetHashCode()
        {
            return this.Height.GetHashCode() | this.Width.GetHashCode();
        }

        public static bool operator ==(Square x, Square y) => x.Equals(y);
        public static bool operator !=(Square x, Square y) => !(x == y);
        public static bool operator >(Square x, Square y) => (x.CompareTo(y) < 0);
        public static bool operator <(Square x, Square y) => (x.CompareTo(y) > 0);

        public int CompareTo(Square other)
        {
            long area1 = this.Height * this.Width;
            long area2 = other.Height * other.Width;

            if (area1 == area2)
            {
                return 0;
            }
            else if (area1 > area2)
            {
                return 1;
            }
            else if (area2 > area1)
            {
                return -1;
            }
            else
            {
                return -1;
            }
        }
    }
}

Add sample class with implementation of IComparable<>


using UnityEngine;
using UnityEngine.Assertions;

[ExecuteInEditMode]
public class AutoEnableTouchControls : BaseBehaviour
{
	private GameObject canvasGo;
	private GameObject eventSystem;

	void Start()
	{
		canvasGo = gameObject.transform.Find("Canvas").gameObject;
		Assert.IsNotNull(canvasGo);

		eventSystem = gameObject.transform.Find("EventSystem").gameObject;
		Assert.IsNotNull(eventSystem);

		#if UNITY_STANDALONE
			canvasGo.SetActive(false);
			eventSystem.SetActive(false);
		#endif

		#if UNITY_IOS
			canvasGo.SetActive(true);
			eventSystem.SetActive(true);
		#endif
	}
}

Add class to auto-activate touch controls.


using OfficeOpenXml;
public static class WorksheetExtensions
{
    public static string[,] ToStringArray(this ExcelWorksheet sheet)
    {
        string[,] answer = new string[sheet.Dimension.Rows, sheet.Dimension.Columns];
        for (var rowNumber = 1; rowNumber <= sheet.Dimension.Rows; rowNumber++)
        {
            for (var columnNumber = 1; columnNumber <= sheet.Dimension.Columns; columnNumber++)
            {
                var cell = sheet.Cells[rowNumber, columnNumber].Value;
                if (cell == null)
                {
                    answer[rowNumber -1, columnNumber -1] = "";
                }
                else
                {
                    answer[rowNumber - 1, columnNumber - 1] = cell.ToString();
                }
            }

        }
        return answer;
    }
}

Add an extension method to the worksheet


using Internal.ReadLine.Abstractions;

using System;

namespace ReadLine.Tests.Abstractions
{
    internal class Console2 : IConsole
    {
        public int CursorLeft => _cursorLeft;

        public int CursorTop => _cursorTop;

        public int BufferWidth => _bufferWidth;

        public int BufferHeight => _bufferHeight;

        private int _cursorLeft;
        private int _cursorTop;
        private int _bufferWidth;
        private int _bufferHeight;

        public Console2()
        {
            _cursorLeft = 0;
            _cursorTop = 0;
            _bufferWidth = 100;
            _bufferHeight = 100;
        }

        public void SetBufferSize(int width, int height)
        {
            _bufferWidth = width;
            _bufferHeight = height;
        }

        public void SetCursorPosition(int left, int top)
        {
            _cursorLeft = left;
            _cursorTop = top;
        }

        public void Write(string value)
        {
            _cursorLeft += value.Length;
        }

        public void WriteLine(string value)
        {
            _cursorLeft += value.Length;
        }
    }
}

Add Console abstraction for test suites

Add Console abstraction for test suites


using ClosedXML.Excel;
using NUnit.Framework;
using System;

namespace ClosedXML_Tests.Excel.Cells
{
    [TestFixture]
    public class DataTypeTests
    {
        [Test]
        public void ConvertNonNumericTextToNumberThrowsException()
        {
            using (var wb = new XLWorkbook())
            {
                var ws = wb.Worksheets.Add("Sheet1");
                var c = ws.Cell("A1");
                c.Value = "ABC123";
                Assert.Throws<ArgumentException>(() => c.DataType = XLDataType.Number);
            }
        }
    }
}

Add test for changing data type (Thanks @prankaty )


using Avalonia.Controls;
using Avalonia.Styling;
using BenchmarkDotNet.Attributes;

namespace Avalonia.Benchmarks.Styling
{
    [MemoryDiagnoser]
    public class SelectorBenchmark
    {
        private readonly Control _notMatchingControl;
        private readonly Calendar _matchingControl;
        private readonly Selector _isCalendarSelector;
        private readonly Selector _classSelector;

        public SelectorBenchmark()
        {
            _notMatchingControl = new Control();
            _matchingControl = new Calendar();

            const string className = "selector-class";

            _matchingControl.Classes.Add(className);

            _isCalendarSelector = Selectors.Is<Calendar>(null);
            _classSelector = Selectors.Class(null, className);
        }

        [Benchmark]
        public SelectorMatch IsSelector_NoMatch()
        {
            return _isCalendarSelector.Match(_notMatchingControl);
        }

        [Benchmark]
        public SelectorMatch IsSelector_Match()
        {
            return _isCalendarSelector.Match(_matchingControl);
        }

        [Benchmark]
        public SelectorMatch ClassSelector_NoMatch()
        {
            return _classSelector.Match(_notMatchingControl);
        }

        [Benchmark]
        public SelectorMatch ClassSelector_Match()
        {
            return _classSelector.Match(_matchingControl);
        }
    }
}

Add basic benchmarks for Is and Class selectors.


using System;

namespace Microsoft.Windows.PowerShell.ScriptAnalyzer
{
    public class Range
    {
        public Position Start { get; }
        public Position End { get; }
        public Range(Position start, Position end)
        {
            if (start > end)
            {
                throw new ArgumentException("start position cannot be before end position.");
            }

            Start = new Position(start);
            End = new Position(end);
        }

        public Range(int startLineNumber, int startColumnNumber, int endLineNumber, int endColumnNumber)
            : this(
                new Position(startLineNumber, startColumnNumber),
                new Position(endLineNumber, endColumnNumber))
        {

        }

        public Range(Range range)
        {
            if (range == null)
            {
                throw new ArgumentNullException(nameof(range));
            }

            Start = new Position(range.Start);
            End = new Position(range.End);
        }

        public Range Shift(int lineDelta, int columnDelta)
        {
            var newStart = Start.Shift(lineDelta, columnDelta);
            var newEnd = End.Shift(lineDelta, Start.Line == End.Line ? columnDelta : 0);
            return new Range(newStart, newEnd);
        }

        public static Range Normalize(Range refRange, Range range)
        {
            if (refRange == null)
            {
                throw new ArgumentNullException(nameof(refRange));
            }

            if (range == null)
            {
                throw new ArgumentNullException(nameof(range));
            }

            if (refRange.Start > range.Start)
            {
                throw new ArgumentException("reference range should start before range");
            }

            return range.Shift(
                1 - refRange.Start.Line,
                range.Start.Line == refRange.Start.Line ? 1 - refRange.Start.Column : 0);
        }
    }
}

Add type to represent range in a text file


using UnityEngine;
using System.Collections;

namespace ATP.AnimationPathTools.AudioSourceControllerComponent {

    public class AudioSourceController : MonoBehaviour {

        private void Start() {

        }

        private void Update() {

        }

    }

}

Create audio source controller component


// 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 System.Collections.Generic;
using System.Linq;
using osu.Framework.Extensions.ObjectExtensions;
using osu.Framework.Platform;

#nullable enable

namespace osu.Game.Rulesets
{
    public class AssemblyRulesetStore : RulesetStore
    {
        public override IEnumerable<RulesetInfo> AvailableRulesets => availableRulesets;

        private readonly List<RulesetInfo> availableRulesets = new List<RulesetInfo>();

        public AssemblyRulesetStore(Storage? storage = null)
            : base(storage)

        {
            List<Ruleset> instances = LoadedAssemblies.Values
                                                      .Select(r => Activator.CreateInstance(r) as Ruleset)
                                                      .Where(r => r != null)
                                                      .Select(r => r.AsNonNull())
                                                      .ToList();

            // add all legacy rulesets first to ensure they have exclusive choice of primary key.
            foreach (var r in instances.Where(r => r is ILegacyRuleset))
                availableRulesets.Add(new RulesetInfo(r.RulesetInfo.ShortName, r.RulesetInfo.Name, r.RulesetInfo.InstantiationInfo, r.RulesetInfo.OnlineID));
        }
    }
}

Add `RulesetStore` for use where realm is not present (ie. other projects)


using System;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Reflection;

namespace Simple.Data.Mysql
{
    public static class MysqlConnectorHelper
    {
        private static DbProviderFactory _dbFactory;

        private static DbProviderFactory DbFactory
        {
            get
            {
                if (_dbFactory == null)
                    _dbFactory = GetDbFactory();
                return _dbFactory;
            }
        }

        public static IDbConnection CreateConnection(string connectionString)
        {
            var connection = DbFactory.CreateConnection();
            connection.ConnectionString = connectionString;
            return connection;
        }

        public static DbDataAdapter CreateDataAdapter(string sqlCommand, IDbConnection connection)
        {
            var adapter = DbFactory.CreateDataAdapter();
            var command = (DbCommand)connection.CreateCommand();
            command.CommandText = sqlCommand;
            adapter.SelectCommand = command;
            return adapter;
        }

        private static DbProviderFactory GetDbFactory()
        {
            var mysqlAssembly =
                Assembly.LoadFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase.Substring(8)), "MySql.Data.dll"));
            var mysqlDbFactoryType = mysqlAssembly.GetType("MySql.Data.MySqlClient.MySqlClientFactory");
            return (DbProviderFactory) Activator.CreateInstance(mysqlDbFactoryType);
        }
    }
}

using System;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Reflection;

namespace Simple.Data.Mysql
{
    public static class MysqlConnectorHelper
    {
        private static DbProviderFactory _dbFactory;

        private static DbProviderFactory DbFactory
        {
            get
            {
                if (_dbFactory == null)
                    _dbFactory = GetDbFactory();
                return _dbFactory;
            }
        }

        public static IDbConnection CreateConnection(string connectionString)
        {
            var connection = DbFactory.CreateConnection();
            connection.ConnectionString = connectionString;
            return connection;
        }

        public static DbDataAdapter CreateDataAdapter(string sqlCommand, IDbConnection connection)
        {
            var adapter = DbFactory.CreateDataAdapter();
            var command = (DbCommand)connection.CreateCommand();
            command.CommandText = sqlCommand;
            adapter.SelectCommand = command;
            return adapter;
        }

        private static DbProviderFactory GetDbFactory()
        {
            var thisAssembly = typeof(MysqlSchemaProvider).Assembly;

            var path = thisAssembly.CodeBase.Replace("file:///", "").Replace("file://", "//");
            path = Path.GetDirectoryName(path);
            if (path == null) throw new ArgumentException("Unrecognised assemblyFile.");

            var mysqlAssembly = Assembly.LoadFrom(Path.Combine(path, "MySql.Data.dll"));

            var mysqlDbFactoryType = mysqlAssembly.GetType("MySql.Data.MySqlClient.MySqlClientFactory");
            return (DbProviderFactory)Activator.CreateInstance(mysqlDbFactoryType);
        }

    }
}

Fix for partial trust environments Assembly.GetExecutingAssembly() cannot be used in Partial trust environments Also linux type paths report file:// and not file:/// so substring(8) should not be used


using System;
using umbraco.DataLayer;

namespace umbraco.editorControls
{
	/// <summary>
	/// Summary description for cms.businesslogic.datatype.DefaultDataKeyValue.
	/// </summary>
    public class DefaultDataKeyValue : cms.businesslogic.datatype.DefaultData
	{
		public DefaultDataKeyValue(cms.businesslogic.datatype.BaseDataType DataType)  : base(DataType)
		{}
		/// <summary>
		/// Ov
		/// </summary>
		/// <param name="d"></param>
		/// <returns></returns>

		public override System.Xml.XmlNode ToXMl(System.Xml.XmlDocument d)
		{
			// Get the value from
			string v = "";
			try
			{
                IRecordsReader dr = SqlHelper.ExecuteReader("Select [value] from cmsDataTypeprevalues where id in (" + SqlHelper.EscapeString(Value.ToString()) + ")");

				while (dr.Read()) {
					if (v.Length == 0)
						v += dr.GetString("value");
					else
						v += "," + dr.GetString("value");
				}
				dr.Close();
			}
			catch {}
			return d.CreateCDataSection(v);
		}
	}
}

using System;
using umbraco.DataLayer;

namespace umbraco.editorControls
{
	/// <summary>
	/// Summary description for cms.businesslogic.datatype.DefaultDataKeyValue.
	/// </summary>
    public class DefaultDataKeyValue : cms.businesslogic.datatype.DefaultData
	{
		public DefaultDataKeyValue(cms.businesslogic.datatype.BaseDataType DataType)  : base(DataType)
		{}
		/// <summary>
		/// Ov
		/// </summary>
		/// <param name="d"></param>
		/// <returns></returns>

		public override System.Xml.XmlNode ToXMl(System.Xml.XmlDocument d)
		{
			// Get the value from
			string v = "";
			try
			{
                // Don't query if there's nothing to query for..
                if (string.IsNullOrWhiteSpace(Value.ToString()) == false)
                {
                    IRecordsReader dr = SqlHelper.ExecuteReader("Select [value] from cmsDataTypeprevalues where id in (@id)", SqlHelper.CreateParameter("id", Value.ToString()));

                    while (dr.Read())
                    {
                        if (v.Length == 0)
                            v += dr.GetString("value");
                        else
                            v += "," + dr.GetString("value");
                    }
                    dr.Close();
                }
			}
			catch {}
			return d.CreateCDataSection(v);
		}
	}
}

Fix errors in log caused by no prevalues beind selected.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;

using SlimDX;
using SlimDX.Direct3D11;

using VVVV.PluginInterfaces.V2;
using VVVV.PluginInterfaces.V1;

using FeralTic.DX11;
using FeralTic.DX11.Resources;

namespace VVVV.DX11.Nodes
{
    [PluginInfo(Name = "IndexOnlyDrawer", Category = "DX11.Drawer", Version = "", Author = "vux")]
    public class DX11IndexOnlyDrawerNode : IPluginEvaluate, IDX11ResourceProvider
    {
        [Input("Geometry In", CheckIfChanged = true)]
        protected Pin<DX11Resource<DX11IndexedGeometry>> FInGeom;

        [Input("Enabled",DefaultValue=1)]
        protected IDiffSpread<bool> FInEnabled;

        [Output("Geometry Out")]
        protected ISpread<DX11Resource<DX11IndexedGeometry>> FOutGeom;

        bool invalidate = false;

        public void Evaluate(int SpreadMax)
        {
            invalidate = false;

            if (this.FInGeom.PluginIO.IsConnected)
            {
                this.FOutGeom.SliceCount = SpreadMax;

                for (int i = 0; i < SpreadMax; i++) { if (this.FOutGeom[i] == null) { this.FOutGeom[i] = new DX11Resource<DX11IndexedGeometry>(); } }

                invalidate = this.FInGeom.IsChanged || this.FInEnabled.IsChanged;

                if (invalidate) { this.FOutGeom.Stream.IsChanged = true; }
            }
            else
            {
                this.FOutGeom.SliceCount = 0;
            }
        }

        public void Update(IPluginIO pin, DX11RenderContext context)
        {
            Device device = context.Device;

            for (int i = 0; i < this.FOutGeom.SliceCount; i++)
            {
                if (this.FInEnabled[i] && this.FInGeom[i].Contains(context))
                {
                    DX11IndexedGeometry v = (DX11IndexedGeometry)this.FInGeom[i][context].ShallowCopy();

                    DX11PerVertexIndexedDrawer drawer = new DX11PerVertexIndexedDrawer();
                    v.AssignDrawer(drawer);

                    this.FOutGeom[i][context] = v;

                }
                else
                {
                    this.FOutGeom[i][context] = this.FInGeom[i][context];
                }

            }
        }

        public void Destroy(IPluginIO pin, DX11RenderContext context, bool force)
        {
            //Not ownding resource eg: do nothing
        }
    }
}

Add index only drawer node

Add index only drawer node


using Newtonsoft.Json;

namespace TMDbLib.Objects.General
{
    public class SingleResultContainer<T>
    {
        [JsonProperty("id")]
        public int Id { get; set; }

        [JsonProperty("results")]
        public T Results { get; set; }
    }
}

Add container for non-array results

Add container for non-array results


using System;

using Xunit;

using Pingu.Filters;

namespace Pingu.Tests
{
    public class FilterTests
    {
        [Fact]
        public void Get_filter_throws_for_invalid_filter_type()
        {
            var arex = Assert.Throws<ArgumentOutOfRangeException>(() => DefaultFilters.GetFilterForType((FilterType)11));
            Assert.Equal("filter", arex.ParamName);
        }
    }
}

Test invalid filter type handling.

Tests: Test invalid filter type handling.


using FluentAssertions;
using Xunit;

namespace Okanshi.Test
{
    public class TagTest
    {
        [Fact]
        public void Creating_a_new_tag_sets_the_correct_key()
        {
            var expectedKey = "key";

            var tag = new Tag(expectedKey, "anything");

            tag.Key.Should().Be(expectedKey);
        }

        [Fact]
        public void Creating_a_new_tag_sets_the_correct_value()
        {
            var expectedValue = "value";

            var tag = new Tag("anything", expectedValue);

            tag.Value.Should().Be(expectedValue);
        }

        [Fact]
        public void Two_tags_with_the_same_key_and_value_should_be_equal()
        {
            var tag1 = new Tag("key", "value");
            var tag2 = new Tag("key", "value");

            tag1.Should().Be(tag2);
        }

        [Fact]
        public void Two_tags_with_the_same_key_and_value_should_have_same_hash()
        {
            var tag1Hash = new Tag("key", "value").GetHashCode();
            var tag2Hash = new Tag("key", "value").GetHashCode();

            tag1Hash.Should().Be(tag2Hash);
        }
    }
}

Add some basic tests for tags

Add some basic tests for tags


//-----------------------------------------------------------------------------------
// PCB-Investigator Automation Script
// Created on 16.06.2016
// Autor Fabio.Gruber
//
// Mark all components in max height regions of drc_comp layer.
// This checks each cmp over the surfaces on relevant layer with drc_max_height attribute.
//-----------------------------------------------------------------------------------
// GUID markHeightRegionTransgression_635963030633639805

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();
            if (step == null) return;

            string layernameTopHeightRestrictions = "drc_comp";
            ICMPLayer topCMPLayer = step.GetCMPLayer(true); //for bottom change here to false
            ILayer HeightRestirctionLayer = step.GetLayer(layernameTopHeightRestrictions);
            // check each cmp for height restrictions
            foreach (ICMPObject cmp in topCMPLayer.GetAllLayerObjects())
            {
                foreach (IODBObject surface in HeightRestirctionLayer.GetAllObjectInRectangle(cmp.Bounds))
                {
                    if (surface.IsPointOfSecondObjectIncluded(cmp, false)) //intersecting is ok?
                    {
                        //check height of cmp
                        IAttributeElement attributeMaxHeight = null;
                        foreach (IAttributeElement attribute in IAttribute.GetAllAttributes(surface))
                        {
                            if (attribute.AttributeEnum == PCBI.FeatureAttributeEnum.drc_max_height)
                            {
                                attributeMaxHeight = attribute;
                                break;
                            }
                        }
                        if (attributeMaxHeight == null) continue;

                        if (cmp.CompHEIGHT > (double)attributeMaxHeight.Value) //we know this attribute has double values
                        {
                            cmp.ObjectColorTemporary(Color.LightCoral); //change color to highlight cmps
                            //surface.ObjectColorTemporary(Color.Wheat);
                            surface.FreeText = "Check Height of " + cmp.Ref;
                            break;
                        }
                    }
                }
            }
            topCMPLayer.EnableLayer(true);
            HeightRestirctionLayer.EnableLayer(true);
            parent.UpdateView();
		}

    }
}

Mark Height Components with region transgression

Mark all components in max height regions of "drc_comp" layer.
This checks each cmp over the surfaces on relevant layer with "drc_max_height" attribute.


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

using System;
using System.Runtime.InteropServices;

namespace osu.Framework.Allocation
{
    /// <summary>
    /// Wrapper on <see cref="GCHandle" /> that supports the <see cref="IDisposable" /> pattern.
    /// </summary>
    public class ObjectHandle<T> : IDisposable
    {
        /// <summary>
        /// The object being referenced.
        /// </summary>
        public T Target { get; private set; }

        /// <summary>
        /// The pointer from the <see cref="GCHandle" />, if it is allocated.  Otherwise <see cref="IntPtr.Zero" />.
        /// </summary>
        public IntPtr Handle => handle.IsAllocated ? GCHandle.ToIntPtr(handle) : IntPtr.Zero;

        private GCHandle handle;

        /// <summary>
        /// Wraps the provided object with a <see cref="GCHandle" />, using the given <see cref="GCHandleType" />.
        /// </summary>
        /// <param name="target">The target object to wrap.</param>
        /// <param name="handleType">The handle type to use.</param>
        public ObjectHandle(T target, GCHandleType handleType)
        {
            Target = target;
            handle = GCHandle.Alloc(target, handleType);
        }

        /// <summary>
        /// Wrapper on <see cref="GCHandle.FromIntPtr" /> that returns the associated object.
        /// </summary>
        /// <returns>The associated object.</returns>
        /// <param name="handle">The pointer to the associated object.</param>
        public static T FromPointer(IntPtr handle) => (T)GCHandle.FromIntPtr(handle).Target;

        #region IDisposable Support

        private bool disposedValue;

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                    Target = default;

                if (handle.IsAllocated)
                    handle.Free();

                disposedValue = true;
            }
        }

        ~ObjectHandle()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion
    }
}

Add IDisposable wrapper on GCHandle

Add IDisposable wrapper on GCHandle


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NBitcoin;
using WalletWasabi.Helpers;
using WalletWasabi.Models;

namespace WalletWasabi.Gui.Models
{
	public class CoinsView : IEnumerable<SmartCoin>
	{
		private IEnumerable<SmartCoin> _coins;

		public CoinsView(IEnumerable<SmartCoin> coins)
		{
			_coins = Guard.NotNull(nameof(coins), coins);
		}

		public CoinsView UnSpent()
		{
			return new CoinsView(_coins.Where(x=>x.Unspent && !x.SpentAccordingToBackend));
		}

		public CoinsView Available()
		{
			return new CoinsView(_coins.Where(x=>!x.Unavailable));
		}

		public CoinsView CoinJoinInProcess()
		{
			return new CoinsView(_coins.Where(x=>x.CoinJoinInProgress));
		}

		public CoinsView Confirmed()
		{
			return new CoinsView(_coins.Where(x=>x.Confirmed));
		}

		public CoinsView Unconfirmed()
		{
			return new CoinsView(_coins.Where(x=>!x.Confirmed));
		}

		public CoinsView AtBlockHeight(Height height)
		{
			return new CoinsView(_coins.Where(x=>x.Height == height));
		}

		public CoinsView SpentBy(uint256 txid)
		{
			return new CoinsView(_coins.Where(x => x.SpenderTransactionId == txid));
		}

		public CoinsView ChildrenOf(SmartCoin coin)
		{
			return new CoinsView(_coins.Where(x => x.TransactionId == coin.SpenderTransactionId));
		}

		public CoinsView DescendatOf(SmartCoin coin)
		{
			IEnumerable<SmartCoin> Generator(SmartCoin coin)
			{
				foreach(var child in ChildrenOf(coin))
				{
					foreach(var childDescendat in ChildrenOf(child))
					{
						yield return childDescendat;
					}

					yield return child;
				}
			}

			return new CoinsView(Generator(coin));
		}

		public CoinsView FilterBy(Func<SmartCoin, bool> expression)
		{
			return new CoinsView(_coins.Where(expression));
		}

		public CoinsView OutPoints(IEnumerable<TxoRef> outPoints)
		{
			return new CoinsView(_coins.Where(x=> outPoints.Any( y=> y == x.GetOutPoint())));
		}

		public Money TotalAmount()
		{
			return _coins.Sum(x=>x.Amount);
		}

		public SmartCoin[] ToArray()
		{
			return _coins.ToArray();
		}

		public IEnumerator<SmartCoin> GetEnumerator()
		{
			return _coins.GetEnumerator();
		}

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

Add new CoinView class for query coins

Add new CoinView class for query coins


// Copyright 2015 Coinprism, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using OpenChain.Ledger.Validation;
using Xunit;

namespace OpenChain.Ledger.Tests
{
    public class StringPatternTests
    {
        [Fact]
        public void IsMatch_Success()
        {
            Assert.True(new StringPattern("name", PatternMatchingStrategy.Exact).IsMatch("name"));
            Assert.False(new StringPattern("name", PatternMatchingStrategy.Exact).IsMatch("name_suffix"));
            Assert.False(new StringPattern("name", PatternMatchingStrategy.Exact).IsMatch("nam"));
            Assert.False(new StringPattern("name", PatternMatchingStrategy.Exact).IsMatch("nams"));

            Assert.True(new StringPattern("name", PatternMatchingStrategy.Prefix).IsMatch("name"));
            Assert.True(new StringPattern("name", PatternMatchingStrategy.Prefix).IsMatch("name_suffix"));
            Assert.False(new StringPattern("name", PatternMatchingStrategy.Prefix).IsMatch("nam"));
            Assert.False(new StringPattern("name", PatternMatchingStrategy.Prefix).IsMatch("nams"));
        }
    }
}

Implement unit tests for the StringPattern class


// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.

[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0063:Use simple 'using' statement", Justification = "<Pending>", Scope = "member", Target = "~M:SimControl.TestUtils.Tests.DisposableTestAdapterTests.DisposableTestAdapter__CreateAndDispose__succeeds")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0063:Use simple 'using' statement", Justification = "<Pending>", Scope = "member", Target = "~M:SimControl.TestUtils.Tests.TempFilesTestAdapterTests.Create_temp_file__create_TempFilesTestAdapter__temp_file_is_deleted")]

Convert to new Visual Studio project types


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace MatterHackers.MatterControl.Testing
{
    public class TestingDispatch
    {
        string errorLogFileName = null;
        public TestingDispatch()
        {
            errorLogFileName = "ErrorLog.txt";
            string firstLine = string.Format("MatterControl Errors: {0:yyyy-MM-dd hh:mm:ss tt}", DateTime.Now);
            using (StreamWriter file = new StreamWriter(errorLogFileName))
            {
                file.WriteLine(errorLogFileName, firstLine);
            }
        }

        public void RunTests(string[] testCommands)
        {
            try { ReleaseTests.AssertDebugNotDefined(); }
            catch (Exception e) { DumpException(e); }

            try { MatterHackers.GCodeVisualizer.GCodeFile.AssertDebugNotDefined(); }
            catch (Exception e) { DumpException(e); }
        }

        void DumpException(Exception e)
        {
            using (StreamWriter w = File.AppendText(errorLogFileName))
            {
                w.WriteLine(e.Message);
                w.Write(e.StackTrace);
                w.WriteLine();
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace MatterHackers.MatterControl.Testing
{
    public class TestingDispatch
    {
        string errorLogFileName = null;
        public TestingDispatch()
        {
            string exePath = Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location );
            errorLogFileName = Path.Combine(exePath, "ErrorLog.txt");
            string firstLine = string.Format("MatterControl Errors: {0:yyyy-MM-dd hh:mm:ss tt}", DateTime.Now);
            using (StreamWriter file = new StreamWriter(errorLogFileName))
            {
                file.WriteLine(firstLine);
            }
        }

        public void RunTests(string[] testCommands)
        {
            try { ReleaseTests.AssertDebugNotDefined(); }
            catch (Exception e) { DumpException(e); }

            try { MatterHackers.GCodeVisualizer.GCodeFile.AssertDebugNotDefined(); }
            catch (Exception e) { DumpException(e); }
        }

        void DumpException(Exception e)
        {
            using (StreamWriter w = File.AppendText(errorLogFileName))
            {
                w.WriteLine(e.Message);
                w.Write(e.StackTrace);
                w.WriteLine();
            }
        }
    }
}

Write the ErrorLog into the exe's directory.


/*
 * Copyright (c) 2018 Google Inc.
 *
 * 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.
 */

// [START quickstart]

using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using System;
// Imports the Google Cloud Job Discovery client library
using Google.Apis.JobService.v2;
using Google.Apis.JobService.v2.Data;
using System.Linq;

namespace GoogleCloudSamples
{
    public class QuickStart
    {
        public static void Main(string[] args)
        {
            // Authorize the client using Application Default Credentials.
            // See: https://developers.google.com/identity/protocols/application-default-credentials
            GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result;
            // Specify the Service scope.
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[]
                {
                    Google.Apis.JobService.v2.JobServiceService.Scope.Jobs
                });
            }
            // Instantiate the Cloud Key Management Service API.
            JobServiceService jobServiceClient = new JobServiceService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                GZipEnabled = false
            });

            // List companies.
            ListCompaniesResponse result = jobServiceClient.Companies.List().Execute();
            Console.WriteLine("Request Id: " + result.Metadata.RequestId);
            if (result.Companies != null)
            {
                Console.WriteLine("Companies: ");
                result.Companies.ToList().ForEach(company => Console.WriteLine(company.Name));
            }
            else { Console.WriteLine("No companies found."); }
        }
    }
}
// [END quickstart]

Revert the Quickstart file which is deleted by mistake


#if NET45 || NET451
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;

namespace StackifyLib.Utils
{
    public class AsyncTracer
    {
        private static bool _AsyncTracerEnabled = false;
        private static DateTime _LastEnabledTest = DateTime.MinValue;

        public static bool EnsureAsyncTracer()
        {
            if (_AsyncTracerEnabled)
                return _AsyncTracerEnabled;

            if (_LastEnabledTest > DateTime.UtcNow.AddMinutes(-5))
            {
                return _AsyncTracerEnabled;
            }

            try
            {
                var t = Type.GetType("System.Threading.Tasks.AsyncCausalityTracer");
                if (t != null)
                {
                    var field = t.GetField("f_LoggingOn", BindingFlags.NonPublic | BindingFlags.Static);

                    if (field == null)
                    {
                        StackifyLib.Utils.StackifyAPILogger.Log("Unable to enable the AsyncCausalityTracer, f_LoggingOn field not found");
                        return _AsyncTracerEnabled;
                    }

                    if (field.FieldType.Name == "Boolean")
                    {
                        bool current = (bool)field.GetValue(null);

                        if (!current)
                        {
                            field.SetValue(null, true);
                        }
                    }
                    else
                    {
                        field.SetValue(null, (byte)4);
                    }

                    _AsyncTracerEnabled = true;

                }
                else
                {
                    _AsyncTracerEnabled = true; //never going to work.
                    StackifyLib.Utils.StackifyAPILogger.Log("Unable to enable the AsyncCausalityTracer, class not found");
                }
            }
            catch (Exception ex)
            {
                StackifyLib.Utils.StackifyAPILogger.Log("EnsureAsyncTracer Exception: " + ex.ToString());
                Debug.WriteLine(ex);
            }
            _LastEnabledTest = DateTime.UtcNow;

            return _AsyncTracerEnabled;
        }
    }
}
#endif

Add code to allow azure functions to force async on


@inherits UmbracoViewPage<BlockListModel>
@using Umbraco.Core.Models.Blocks
@{
    if (Model?.Layout == null || !Model.Layout.Any()) { return; }
}
<div class="umb-block-list">
    @foreach (var layout in Model.Layout)
    {
        if (layout?.Udi == null) { continue; }
        var data = layout.Data;
        @Html.Partial("BlockList/Components/" + data.ContentType.Alias, layout)
    }
</div>

@inherits UmbracoViewPage<BlockListModel>
@using Umbraco.Core.Models.Blocks
@{
    if (Model?.Layout == null || !Model.Layout.Any()) { return; }
}
<div class="umb-block-list">
    @foreach (var layout in Model.Layout)
    {
        if (layout?.Udi == null) { continue; }
        var data = layout.Data;
        try
        {
            @Html.Partial("BlockList/Components/" + data.ContentType.Alias, (data, layout.Settings))
        }
        catch (Exception ex)
        {
            global::Umbraco.Core.Composing.Current.Logger.Error(typeof(BlockListModel), ex, "Could not display block list component for content type {0}", data?.ContentType?.Alias);
        }
    }
</div>

Add error handling to default template

Add error handling to default template


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

namespace DotvvmAcademy.CourseFormat
{
    public class MarkdownStepInfo
    {
        public string Path { get; }

        public string Moniker { get; }

        public string Name { get; }

        public string CodeTaskPath { get; }
    }
}

Set the course directory as Content (for MSBuild)


// ***********************************************************************
// Copyright (c) 2009 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************

// ****************************************************************
//              Generated by the NUnit Syntax Generator
//
// Command Line: __COMMANDLINE__
//
//                  DO NOT MODIFY THIS FILE DIRECTLY
// ****************************************************************

using System;
using System.Collections;
using NUnit.Framework.Constraints;

namespace NUnit.Framework
{
    /// <summary>
    /// Helper class with properties and methods that supply
    /// a number of constraints used in Asserts.
    /// </summary>
    public class Contains
    {
        // $$GENERATE$$ $$STATIC$$
    }
}

Add file missed in bug fix 440109

Add file missed in bug fix 440109

--HG--
branch : bug-fix-440109
extra : convert_revision : charlie%40nunit.com-20091011205012-8qlpq4dtg1kdfyv9


namespace Snow
{
    using System;
    using System.Collections.Generic;
    using Nancy.Conventions;
    using Nancy.ViewEngines;

    public class SnowViewLocationConventions : IConvention
    {
        public static SnowSettings Settings { get; set; }

        public void Initialise(NancyConventions conventions)
        {
            ConfigureViewLocationConventions(conventions);
        }

        public Tuple<bool, string> Validate(NancyConventions conventions)
        {
            return Tuple.Create(true, string.Empty);
        }

        private static void ConfigureViewLocationConventions(NancyConventions conventions)
        {
            conventions.ViewLocationConventions = new List<Func<string, object, ViewLocationContext, string>>
            {
                (viewName, model, viewLocationContext) => Settings.PostsRaw.TrimEnd('/') + "/" + viewName,
                (viewName, model, viewLocationContext) => Settings.ThemesDir + Settings.Theme + "/" + Settings.LayoutsRaw.TrimEnd('/') + "/" + viewName,
                (viewName, model, viewLocationContext) => viewName
            };
        }
    }
}

namespace Snow
{
    using System;
    using System.Collections.Generic;
    using Nancy.Conventions;
    using Nancy.ViewEngines;

    public class SnowViewLocationConventions : IConvention
    {
        public static SnowSettings Settings { get; set; }

        public void Initialise(NancyConventions conventions)
        {
            ConfigureViewLocationConventions(conventions);
        }

        public Tuple<bool, string> Validate(NancyConventions conventions)
        {
            return Tuple.Create(true, string.Empty);
        }

        private static void ConfigureViewLocationConventions(NancyConventions conventions)
        {
            conventions.ViewLocationConventions = new List<Func<string, object, ViewLocationContext, string>>
            {
                (viewName, model, viewLocationContext) => Settings.PostsRaw.TrimEnd('/') + "/" + viewName,
                (viewName, model, viewLocationContext) => Settings.ThemesDir + Settings.Theme + "/" + Settings.LayoutsRaw.TrimEnd('/') + "/" + viewName,
                (viewName, model, viewLocationContext) => Settings.ThemesDir + Settings.Theme + "/" + viewName,
                (viewName, model, viewLocationContext) => viewName,
            };
        }
    }
}

Allow overriding default static files in theme


using System;
using System.Runtime.InteropServices;

namespace RocketMQ.Interop
{
    public static class PushConsumerWrap
    {
        [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr CreatePushConsumer(string groupId);

        [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern int DestroyPushConsumer(IntPtr consumer);

        [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern int StartPushConsumer(IntPtr consumer);

        [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern int ShutdownPushConsumer(IntPtr consumer);

        [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern int SetPushConsumerGroupID(IntPtr consumer, string groupId);

        [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern int SetPushConsumerNameServerAddress(IntPtr consumer, string namesrv);

        [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern int SetPushConsumerSessionCredentials(IntPtr consumer, string accessKey, string secretKey, string channel);

        [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern int Subscribe(IntPtr consumer, string topic, string expression);

        [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "GetPushConsumerGroupID")]
        internal static extern IntPtr GetPushConsumerGroupIDInternal(IntPtr consumer);

        public static string GetPushConsumerGroupID(IntPtr consumer)
        {
            var ptr = GetPushConsumerGroupIDInternal(consumer);
            if (ptr == IntPtr.Zero) return string.Empty;
            return Marshal.PtrToStringAnsi(ptr);
        }

        [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern int RegisterMessageCallback(
            IntPtr consumer,
            [MarshalAs(UnmanagedType.FunctionPtr)]
            MessageCallBack pCallback
        );

        public delegate int MessageCallBack(IntPtr consumer, IntPtr messageIntPtr);

        [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern int SetPushConsumerLogLevel(IntPtr consumer, CLogLevel level);
    }
}

Add pushconsumer wrap to donet

Add pushconsumer wrap  to donet


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

using System.Linq;
using NUnit.Framework;
using osu.Framework.Graphics.Containers;
using osu.Framework.Testing;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Screens.Play;

namespace osu.Game.Tests.Visual.Mods
{
    public class TestSceneModFailCondition : ModTestScene
    {
        private bool restartRequested;

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

        protected override TestPlayer CreateModPlayer(Ruleset ruleset)
        {
            var player = base.CreateModPlayer(ruleset);
            player.RestartRequested = () => restartRequested = true;
            return player;
        }

        protected override bool AllowFail => true;

        [SetUpSteps]
        public void SetUp()
        {
            AddStep("reset flag", () => restartRequested = false);
        }

        [Test]
        public void TestRestartOnFailDisabled() => CreateModTest(new ModTestData
        {
            Autoplay = false,
            Mod = new OsuModSuddenDeath(),
            PassCondition = () => !restartRequested && Player.ChildrenOfType<FailOverlay>().Single().State.Value == Visibility.Visible
        });

        [Test]
        public void TestRestartOnFailEnabled() => CreateModTest(new ModTestData
        {
            Autoplay = false,
            Mod = new OsuModSuddenDeath
            {
                Restart = { Value = true }
            },
            PassCondition = () => restartRequested && Player.ChildrenOfType<FailOverlay>().Single().State.Value == Visibility.Hidden
        });
    }
}

Add testing for auto-restart behaviour

Add testing for auto-restart behaviour


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

using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Configuration;
using osu.Framework.Platform;

namespace osu.Framework.Tests.Visual.Platform
{
    [Ignore("This test does not cover correct GL context acquire/release when ran headless.")]
    public class TestSceneExecutionModes : FrameworkTestScene
    {
        private Bindable<ExecutionMode> executionMode;

        [BackgroundDependencyLoader]
        private void load(FrameworkConfigManager configManager)
        {
            executionMode = configManager.GetBindable<ExecutionMode>(FrameworkSetting.ExecutionMode);
        }

        [Test]
        public void ToggleModeSmokeTest()
        {
            AddRepeatStep("toggle execution mode", () => executionMode.Value = executionMode.Value == ExecutionMode.MultiThreaded
                ? ExecutionMode.SingleThread
                : ExecutionMode.MultiThreaded, 2);
        }
    }
}

Add visual-only execution mode toggle test scene


using Aspose.Diagram;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharp.ProgrammersGuide.Load_Save_Convert
{
    public class CreateNewVisio
    {
        public static void Run()
        {
            //ExStart:CreateNewVisio

            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_LoadSaveConvert();

            // initialize a Diagram class
            Diagram diagram = new Diagram();

            // save diagram in the VSDX format
            diagram.Save(dataDir + "MyDiagram.vsdx", SaveFileFormat.VSDX);
            //ExEnd:CreateNewVisio
        }
    }
}

Create a new diagram example

Create a new diagram example


using System.ComponentModel;
using System.Threading.Tasks;

using Refit;

interface IFooWithOtherAttribute
{
    [Get("/")]
    Task GetRoot();

    [DisplayName("/")]
    Task PostRoot();
}

Add test class with other attribute on method


// 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.Data.SqlClient.Tests
{
    public class SqlConnectionBasicTests
    {

        [Fact]
        public void ConnectionTest()
        {
            Exception e = null;

            using (TestTdsServer server = TestTdsServer.StartTestServer())
            {
                try
                {
                    SqlConnection connection = new SqlConnection(server.ConnectionString);
                    connection.Open();
                }
                catch (Exception ce)
                {
                    e = ce;
                }
            }
            Assert.Null(e);
        }

    }

}

// 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.Data.SqlClient.Tests
{
    public class SqlConnectionBasicTests
    {

        [Fact]
        [ActiveIssue(14017)]
        public void ConnectionTest()
        {
            Exception e = null;

            using (TestTdsServer server = TestTdsServer.StartTestServer())
            {
                try
                {
                    SqlConnection connection = new SqlConnection(server.ConnectionString);
                    connection.Open();
                }
                catch (Exception ce)
                {
                    e = ce;
                }
            }
            Assert.Null(e);
        }

    }

}

Annotate the test with ActiveIssue

Annotate the test with ActiveIssue


/*
    Copyright 2020 Jeffrey Sharp

    Permission to use, copy, modify, and distribute this software for any
    purpose with or without fee is hereby granted, provided that the above
    copyright notice and this permission notice appear in all copies.

    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
    MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/

using System;
using System.Reflection;
using System.Runtime.Loader;
using Path = System.IO.Path;

#nullable enable

namespace PSql
{
    internal static class PSqlClient
    {
        private const string
            AssemblyPath = "PSql.Client.dll";

        private static string              LoadPath    { get; }
        private static AssemblyLoadContext LoadContext { get; }
        private static Assembly            Assembly    { get; }

        static PSqlClient()
        {
            LoadPath
                =  Path.GetDirectoryName(typeof(PSqlClient).Assembly.Location)
                ?? Environment.CurrentDirectory;

            LoadContext = new AssemblyLoadContext(nameof(PSqlClient));
            LoadContext.Resolving += OnResolving;

            Assembly = LoadAssembly(AssemblyPath);
        }

        internal static dynamic CreateObject(string typeName, params object?[]? arguments)
        {
            // NULLS: CreateInstance returns null only for valueless instances
            // of Nullable<T>, which cannot happen here.
            return Activator.CreateInstance(GetType(typeName), arguments)!;
        }

        internal static Type GetType(string name)
        {
            // NULLS: Does not return null when trowOnError is true.
            return Assembly.GetType(nameof(PSql) + "." + name, throwOnError: true)!;
        }

        private static Assembly? OnResolving(AssemblyLoadContext context, AssemblyName name)
        {
            var path = name.Name;
            if (string.IsNullOrEmpty(path))
                return null;

            if (!HasAssemblyExtension(path))
                path += ".dll";

            return LoadAssembly(context, path);
        }

        private static Assembly LoadAssembly(string path)
        {
            return LoadAssembly(LoadContext, path);
        }

        private static Assembly LoadAssembly(AssemblyLoadContext context, string path)
        {
            path = Path.Combine(LoadPath, path);

            return context.LoadFromAssemblyPath(path);
        }

        private static bool HasAssemblyExtension(string path)
        {
            return path.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)
                || path.EndsWith(".exe", StringComparison.OrdinalIgnoreCase);
        }
    }
}

Add class to load client in private load context.


//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.239
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Reflection;

[assembly: AssemblyVersion("0.0.0.0")]
[assembly: AssemblyFileVersion("0.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2012-03-05 11:24")]

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.239
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Reflection;

[assembly: AssemblyVersion("0.0.0.0")]
[assembly: AssemblyFileVersion("0.0.0.0")]
[assembly: AssemblyConfiguration("Debug built on 2012-01-01 00:00")]

Set AssemblyConfiguration attribute to a simple/default value.


using System.IO;
using System.Text;
using log4net.ObjectRenderer;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace log4net.Util.Serializer
{
    public class JsonDotNetSerializer : ISerializer
    {
        public RendererMap Map { get; set; }

        public object Serialize(object obj)
        {
            object result;

            if (obj != null)
            {
                using (var writer = new StringWriter(new StringBuilder()))
                using (var jsonWriter = new RendererMapJsonTextWriter(Map, writer) { CloseOutput = false })
                {
                    jsonWriter.WriteValue(obj);

                    result = writer.GetStringBuilder().ToString();
                }
            }
            else
            {
                result = JsonConvert.SerializeObject(obj);
            }

            return result;
        }
    }
}

Add ISerializer impl. that uses JSON.NET

…instead of the default JSON serializer implementation in
log4net.Ext.Json


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

namespace PetAdoptionCRM.Models
{
    public class EmployeeRole : IdentityRole
    {
    }
}

Add employee and manager as user roles

Add employee and manager as user roles


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

using System.IdentityModel.Tokens;
using System.Security.Cryptography;
using Infrastructure.Common;
using Xunit;

public static class SymmetricSecurityKeyTest
{
    [WcfFact]
    public static void method_GetSymmetricKey()
    {
        byte[] gsk = new byte[] { 0x02, 0x01, 0x04, 0x03 };
        MockGetSymmetricAlgorithm mgsakey = new MockGetSymmetricAlgorithm();
        Assert.NotNull(mgsakey.GetSymmetricKey());
        Assert.Equal(gsk, mgsakey.GetSymmetricKey());
    }

    [WcfFact]
    public static void method_GetSymmetricAlgorithm()
    {
        string algorit = "DES";
        MockGetSymmetricAlgorithm mgsaalg = new MockGetSymmetricAlgorithm();
        Assert.NotNull(mgsaalg.GetSymmetricAlgorithm(algorit));
        Assert.IsType<DESCryptoServiceProvider>(mgsaalg.GetSymmetricAlgorithm(algorit));
    }
}

public class MockGetSymmetricAlgorithm : SymmetricSecurityKey
{
    public override int KeySize => throw new System.NotImplementedException();

    public override byte[] DecryptKey(string algorithm, byte[] keyData)
    {
        throw new System.NotImplementedException();
    }

    public override byte[] EncryptKey(string algorithm, byte[] keyData)
    {
        throw new System.NotImplementedException();
    }

    public override byte[] GenerateDerivedKey(string algorithm, byte[] label, byte[] nonce, int derivedKeyLength, int offset)
    {
        throw new System.NotImplementedException();
    }

    public override ICryptoTransform GetDecryptionTransform(string algorithm, byte[] iv)
    {
        throw new System.NotImplementedException();
    }

    public override ICryptoTransform GetEncryptionTransform(string algorithm, byte[] iv)
    {
        throw new System.NotImplementedException();
    }

    public override int GetIVSize(string algorithm)
    {
        throw new System.NotImplementedException();
    }

    public override KeyedHashAlgorithm GetKeyedHashAlgorithm(string algorithm)
    {
        throw new System.NotImplementedException();
    }

    public override SymmetricAlgorithm GetSymmetricAlgorithm(string algorithm)
    {
        return new DESCryptoServiceProvider();
    }

    public override byte[] GetSymmetricKey()
    {
        byte[] gsk = new byte[] { 0x02, 0x01, 0x04, 0x03 };
        return gsk;
    }

    public override bool IsAsymmetricAlgorithm(string algorithm)
    {
        throw new System.NotImplementedException();
    }

    public override bool IsSupportedAlgorithm(string algorithm)
    {
        throw new System.NotImplementedException();
    }

    public override bool IsSymmetricAlgorithm(string algorithm)
    {
        throw new System.NotImplementedException();
    }
}

Add unit test for GetSymmetricAlgorithm.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace SCPI
{
    public class Commands
    {
        private Dictionary<string, ICommand> commands = new Dictionary<string, ICommand>();

        /// <summary>
        /// Creates a list of supported commands in the SCPI assembly
        /// </summary>
        /// <returns>The names of the supported commands</returns>
        public ICollection<string> Names()
        {
            return SupportedCommands().Select(t => t.Name).ToList();
        }

        /// <summary>
        /// Creates an instance of the requested command (if it does not exist)
        /// and returns it to the caller.
        /// </summary>
        /// <param name="command">Command name</param>
        /// <returns>Instance of the requested command</returns>
        public ICommand Get(string command)
        {
            ICommand cmd = null;

            if (!commands.TryGetValue(command, out cmd))
            {
                // Lazy initialization of the command
                var typeInfo = SupportedCommands().Where(ti => ti.Name.Equals(command)).Single();

                cmd = (ICommand)Activator.CreateInstance(typeInfo.AsType());

                commands.Add(command, cmd);
            }

            return cmd;
        }

        private static IEnumerable<TypeInfo> SupportedCommands()
        {
            var assembly = typeof(ICommand).GetTypeInfo().Assembly;

            // Supported commands are the ones that implement ICommand interface
            var commands = assembly.DefinedTypes.Where(ti => ti.ImplementedInterfaces.Contains(typeof(ICommand)));

            return commands;
        }
    }
}

Implement a class to query supported commands and get their instances.


// http://www.geeksforgeeks.org/print-a-pattern-without-using-any-loop/
//
//
// Print a pattern without using any loop
//
// Given a number n, print following pattern without using any loop.
//
// Input: n = 16
// Output: 16, 11, 6, 1, -4, 1, 6, 11, 16
//
// Input: n = 10
// Output: 10, 5, 0, 5, 10
//
using System;

class Program {
    static void Print(int i, int m, bool flag) {
        Console.Write("{0} ", i);
        if (i == m && !flag) {
            Console.WriteLine();
            return;
        }

        if (flag) {
            Print(i - 5, m, i - 5 > 0);
        } else {
            Print(i + 5, m, false);
        }
    }

    static void Main() {
        Print(16, 16, true);
        Print(10, 10, true);
    }
}

Print pattern without a loop

Print pattern without a loop


// 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.IO;
using System.Threading.Tasks;
using Xunit;

namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
{
    public class RazorCompileIntegrationTest : MSBuildIntegrationTestBase
    {
        [Fact]
        [InitializeTestProject("SimpleMvc")]
        public async Task RazorCompile_Success_CompilesAssembly()
        {
            var result = await DotnetMSBuild("RazorCompile");

            Assert.BuildPassed(result);

            // RazorGenerate should compile the assembly and pdb.
            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.dll");
            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.pdb");
            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.PrecompiledViews.dll");
            Assert.FileExists(result, IntermediateOutputPath, "SimpleMvc.PrecompiledViews.pdb");
        }

        [Fact]
        [InitializeTestProject("SimpleMvc")]
        public async Task RazorCompile_NoopsWithNoFiles()
        {
            Directory.Delete(Path.Combine(Project.DirectoryPath, "Views"), recursive: true);

            var result = await DotnetMSBuild("RazorCompile");

            Assert.BuildPassed(result);

            // Everything we do should noop - including building the app.
            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.dll");
            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.pdb");
            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.PrecompiledViews.dll");
            Assert.FileDoesNotExist(result, IntermediateOutputPath, "SimpleMvc.PrecompiledViews.pdb");
        }
    }
}

Add tests for RazorCompile target

Add tests for RazorCompile target

This target should be callable on its own without using Build so it
deserves a few tests.


using Xunit;
using Squirrel;
using Squirrel.Nodes;

namespace Tests
{
    public class EnvironmentTests
    {
        private static readonly string TestVariableName = "x";
        private static readonly INode TestVariableValue = new IntegerNode(1);

        [Fact]
        public void TestGetValueFromCurrentEnvironment() {
            var environment = new Environment();
            environment.Put(TestVariableName, TestVariableValue);
            Assert.Equal(TestVariableValue, environment.Get(TestVariableName));
        }

        [Fact]
        public void TestGetValueFromParentEnvironment() {
            var parentEnvironment = new Environment();
            var childEnvironment = new Environment(parentEnvironment);
            parentEnvironment.Put(TestVariableName, TestVariableValue);
            Assert.Equal(TestVariableValue, childEnvironment.Get(TestVariableName));
        }

        [Fact]
        public void TestGetValueFromGrandparentEnvironment() {
            var grandparentEnvironment = new Environment();
            var parentEnvironment = new Environment(grandparentEnvironment);
            var childEnvironment = new Environment(parentEnvironment);
            grandparentEnvironment.Put(TestVariableName, TestVariableValue);
            Assert.Equal(TestVariableValue, childEnvironment.Get(TestVariableName));
        }
    }
}

Create positive tests for getting values from nested environments


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

namespace DotSpatial.Tools
{
    class ImportWhiteboxRaster
    {
    }
}

Create a tool for importing Whitebox *.dep files


using System;
using NSec.Cryptography;
using Xunit;

namespace NSec.Tests.Algorithms
{
    public static class Sha512Tests
    {
        public static readonly string HashOfEmpty = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e";

        [Fact]
        public static void HashEmpty()
        {
            var a = new Sha512();

            var expected = HashOfEmpty.DecodeHex();
            var actual = a.Hash(ReadOnlySpan<byte>.Empty);

            Assert.Equal(a.DefaultHashSize, actual.Length);
            Assert.Equal(expected, actual);
        }

        [Theory]
        [InlineData(32)]
        [InlineData(41)]
        [InlineData(53)]
        [InlineData(61)]
        [InlineData(64)]
        public static void HashEmptyWithSize(int hashSize)
        {
            var a = new Sha512();

            var expected = HashOfEmpty.DecodeHex().Slice(0, hashSize);
            var actual = a.Hash(ReadOnlySpan<byte>.Empty, hashSize);

            Assert.Equal(hashSize, actual.Length);
            Assert.Equal(expected, actual);
        }

        [Theory]
        [InlineData(32)]
        [InlineData(41)]
        [InlineData(53)]
        [InlineData(61)]
        [InlineData(64)]
        public static void HashEmptyWithSpan(int hashSize)
        {
            var a = new Sha512();

            var expected = HashOfEmpty.DecodeHex().Slice(0, hashSize);
            var actual = new byte[hashSize];

            a.Hash(ReadOnlySpan<byte>.Empty, actual);
            Assert.Equal(expected, actual);
        }
    }
}

Add tests for Sha512 class

Add tests for Sha512 class


namespace EOpt.Math.Tests
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using EOpt.Math;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    [TestClass()]
    public class PointNDTests
    {

        [TestMethod()]
        public void PointNDConstrTest4()
        {
            PointND point = new PointND(12, 5);

            bool error = false;

            foreach (double item in point.Coordinates)
            {
                if (item != 12)
                    error = true;
            }

            Assert.IsTrue(!error && point.Dimension == 5);
        }

        [TestMethod()]
        public void PointNDConstrTest5()
        {
            double[] x = new double[4] { 45, 56, 8, 10 };

            PointND point = new PointND(x);

            Assert.IsTrue(point.Coordinates.SequenceEqual(x) && point.Dimension == 4);
        }

        [TestMethod()]
        public void EqualsTest()
        {
            PointND a = new PointND(2, 3);

            PointND b = new PointND(21, 4);

            PointND c = a.Clone();

            Assert.IsTrue(a.Equals(c) && !a.Equals(b));
        }

        [TestMethod()]
        public void CloneTest()
        {
            PointND p1, p2;

            p1 = new PointND(1, 2);

            p2 = p1.Clone();

            Assert.IsTrue(p1.Equals(p2));
        }

        [TestMethod()]
        public void ToStringTest()
        {
            PointND p1 = new PointND(90, 2);

            Assert.IsNotNull(p1.ToString());
        }
    }
}

Add unit tests for PointND.

Add unit tests for PointND.


// Copyright Matthias Koch 2017.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE

using System;
using System.IO;
using System.Linq;
using FluentAssertions;
using Nuke.Common.Tools.MSBuild;
using Nuke.Common.Tools.OpenCover;
using Nuke.Common.Tools.Xunit2;
using Nuke.Core.IO;
using Nuke.Core.Tooling;
using Xunit;

namespace Nuke.Common.Tests
{
    public class SettingsTest
    {
        private static PathConstruction.AbsolutePath RootDirectory
            => (PathConstruction.AbsolutePath) Directory.GetCurrentDirectory() / ".." / ".." / ".." / ".." / "..";

        private static void Assert<T> (Configure<T> configurator, string arguments)
            where T : ToolSettings, new()
        {
            configurator.Invoke(new T()).GetArguments().RenderForOutput().Should().Be(arguments);
        }

        [Fact]
        public void TestMSBuild ()
        {
            var projectFile = RootDirectory / "source" / "Nuke.Common" / "Nuke.Common.csproj";
            var solutionFile = RootDirectory / "Nuke.sln";

            Assert<MSBuildSettings>(x => x
                        .SetProjectFile(projectFile)
                        .SetTargetPlatform(MSBuildTargetPlatform.MSIL)
                        .SetConfiguration("Release")
                        .EnableNoLogo(),
                $"{projectFile} /nologo /property:Platform=AnyCPU /property:Configuration=Release");

            Assert<MSBuildSettings>(x => x
                        .SetProjectFile(solutionFile)
                        .SetTargetPlatform(MSBuildTargetPlatform.MSIL)
                        .ToggleRunCodeAnalysis(),
                $"{solutionFile} /property:Platform=\"Any CPU\" /property:RunCodeAnalysis=True");
        }

        [Fact]
        public void TestXunit2 ()
        {
            Assert<Xunit2Settings>(x => x
                        .AddTargetAssemblies("A.csproj")
                        .AddTargetAssemblyWithConfigs("B.csproj", "D.config", "new folder\\E.config"),
                "A.csproj  B.csproj D.config B.csproj \"new folder\\E.config\"");

            Assert<Xunit2Settings>(x => x
                        .SetResultPath("new folder\\data.xml"),
                "-Xml \"new folder\\data.xml\"");

            Assert<Xunit2Settings>(x => x
                        .SetResultPath("new folder\\data.xml", ResultFormat.HTML)
                        .EnableDiagnostics(),
                "-diagnostics -HTML \"new folder\\data.xml\"");
        }

        [Fact]
        public void TestOpenCover ()
        {
            var projectFile = RootDirectory / "source" / "Nuke.Common" / "Nuke.Common.csproj";

            Assert<OpenCoverSettings>(x => x
                        .SetTargetPath(projectFile)
                        .AddFilters("+[*]*", "-[xunit.*]*", "-[NUnit.*]*")
                        .SetTargetArguments("-diagnostics -HTML \"new folder\\data.xml\""),
                $"-target:{projectFile} -targetargs:\"-diagnostics -HTML \\\"new folder\\data.xml\\\"\" -filter:\"+[*]* -[xunit.*]* -[NUnit.*]*\"");
        }
    }
}

Add smoke tests for settings.

Add smoke tests for settings.


using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ZocMonLib;

namespace ZocMonLib
{
    public class StorageCommandsSetupSqlServer : IStorageCommandsSetup
    {
        public virtual IEnumerable<ReduceLevel> SelectAllReduceLevels(IDbConnection conn)
        {
            return DatabaseSqlHelper.CreateListWithConnection<ReduceLevel>(conn, StorageCommandsSqlServerQuery.ReduceLevelSql);
        }

        public virtual IEnumerable<MonitorConfig> SelectAllMonitorConfigs(IDbConnection conn)
        {
            return DatabaseSqlHelper.CreateListWithConnection<MonitorConfig>(conn, StorageCommandsSqlServerQuery.MonitorConfigSql);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ZocMonLib;

namespace ZocMonLib
{
    public class StorageCommandsSetupSqlServer : IStorageCommandsSetup
    {
        public virtual IEnumerable<ReduceLevel> SelectAllReduceLevels(IDbConnection conn)
        {
            const string sql = @"SELECT * FROM ReduceLevel";

            return DatabaseSqlHelper.Query<ReduceLevel>(conn, sql);
        }

        public virtual IEnumerable<MonitorConfig> SelectAllMonitorConfigs(IDbConnection conn)
        {
            const string sql = @"SELECT * FROM MonitorConfig";

            return DatabaseSqlHelper.Query<MonitorConfig>(conn, sql);
        }
    }
}

Switch over setup commands from using query class


using DiabloSpeech.Business.Twitch;
using DiabloSpeech.Business.Twitch.Processors;
using NUnit.Framework;
using tests.Twitch.Mocks;

namespace tests.Twitch
{
    public class PingCommandProcessorTest
    {
        PingCommandProcessor processor;
        TwitchConnectionMock connection;

        TwitchMessageData MessageData =>
            new TwitchMessageData();

        [SetUp]
        public void InitializeTest()
        {
            processor = new PingCommandProcessor();
            connection = new TwitchConnectionMock("test", "#test");
        }

        [Test]
        public void PingCommandThrowsWithoutConnection()
        {
            Assert.That(() => processor.Process(null, MessageData), Throws.ArgumentNullException);
        }

        [Test]
        public void PingCommandSendPongAndFlushes()
        {
            processor.Process(connection, MessageData);
            Assert.That(connection.FiredCommands.Count, Is.EqualTo(2));
            Assert.That(connection.FiredCommands[0], Is.EqualTo("PONG"));
            Assert.That(connection.FiredCommands[1], Is.EqualTo("__FLUSH"));
        }
    }
}

Add missing file for ping command test.

Add missing file for ping command 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.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.Threading;

namespace osu.Framework.Tests.Threading
{
    [TestFixture]
    public class ThreadedTaskSchedulerTest
    {
        /// <summary>
        /// On disposal, <see cref="ThreadedTaskScheduler"/> does a blocking shutdown sequence.
        /// This asserts all outstanding tasks are run before the shutdown completes.
        /// </summary>
        [Test]
        public void EnsureThreadedTaskSchedulerProcessesBeforeDispose()
        {
            int runCount = 0;

            const int target_count = 128;

            using (var taskScheduler = new ThreadedTaskScheduler(4, "test"))
            {
                for (int i = 0; i < target_count; i++)
                {
                    Task.Factory.StartNew(() =>
                    {
                        Interlocked.Increment(ref runCount);
                        Thread.Sleep(100);
                    }, default, TaskCreationOptions.HideScheduler, taskScheduler);
                }
            }

            Assert.AreEqual(target_count, runCount);
        }
    }
}

Add test covering ThreadedTaskScheduler shutdown


using System.Diagnostics;
using System.Threading;

static class DebugUtilities {
	public static void Burn(long ms) {
		Stopwatch stopwatch = Stopwatch.StartNew();
		while (stopwatch.ElapsedMilliseconds < ms) {
		}
	}

	public static void Sleep(long ms) {
		Stopwatch stopwatch = Stopwatch.StartNew();
		while (stopwatch.ElapsedMilliseconds < ms) {
			Thread.Yield();
		}
	}
}

Add debug utilities to sleep-wait and busy-wait for a given duration


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

using Microsoft.WindowsAzure.Storage.Blob;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Microsoft.Azure.WebJobs.Host.Blobs.Listeners
{
    internal class BlobTriggerMessage
    {
        public string FunctionId { get; set; }

        [JsonConverter(typeof(StringEnumConverter))]
        public BlobType BlobType { get; set; }

        public string ContainerName { get; set; }

        public string BlobName { get; set; }

        public string ETag { get; set; }
    }
}

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

using Microsoft.WindowsAzure.Storage.Blob;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Microsoft.Azure.WebJobs.Host.Blobs.Listeners
{
    internal class BlobTriggerMessage
    {
        public string Type { get { return "BlobTrigger"; } }

        public string FunctionId { get; set; }

        [JsonConverter(typeof(StringEnumConverter))]
        public BlobType BlobType { get; set; }

        public string ContainerName { get; set; }

        public string BlobName { get; set; }

        public string ETag { get; set; }
    }
}

Add message type to blob trigger.

Add message type to blob trigger.


using System;
using System.Collections.Generic;
using NUnit.Framework;
using System.Collections.ObjectModel;
using OpenQA.Selenium.Environment;

namespace OpenQA.Selenium
{
    [TestFixture]
    public class ElementPropertyTest : DriverTestFixture
    {
        [Test]
        [IgnoreBrowser(Browser.Edge)]
        [IgnoreBrowser(Browser.Chrome, "Chrome does not support get element property command")]
        [IgnoreBrowser(Browser.Opera)]
        [IgnoreBrowser(Browser.Remote)]
        [IgnoreBrowser(Browser.Safari)]
        public void ShouldReturnNullWhenGettingTheValueOfAPropertyThatIsNotListed()
        {
            driver.Url = simpleTestPage;
            IWebElement head = driver.FindElement(By.XPath("/html"));
            string attribute = head.GetProperty("cheese");
            Assert.IsNull(attribute);
        }

        [Test]
        [IgnoreBrowser(Browser.Edge)]
        [IgnoreBrowser(Browser.Chrome, "Chrome does not support get element property command")]
        [IgnoreBrowser(Browser.Opera)]
        [IgnoreBrowser(Browser.Remote)]
        [IgnoreBrowser(Browser.Safari)]
        public void CanRetrieveTheCurrentValueOfAProperty()
        {
            driver.Url = formsPage;
            IWebElement element = driver.FindElement(By.Id("working"));
            Assert.AreEqual(string.Empty, element.GetProperty("value"));
            element.SendKeys("hello world");
            Assert.AreEqual("hello world", element.GetProperty("value"));
        }
    }
}

using System;
using System.Collections.Generic;
using NUnit.Framework;
using System.Collections.ObjectModel;
using OpenQA.Selenium.Environment;

namespace OpenQA.Selenium
{
    [TestFixture]
    public class ElementPropertyTest : DriverTestFixture
    {
        [Test]
        [IgnoreBrowser(Browser.Chrome, "Chrome does not support get element property command")]
        [IgnoreBrowser(Browser.Opera)]
        [IgnoreBrowser(Browser.Remote)]
        [IgnoreBrowser(Browser.Safari)]
        public void ShouldReturnNullWhenGettingTheValueOfAPropertyThatIsNotListed()
        {
            driver.Url = simpleTestPage;
            IWebElement head = driver.FindElement(By.XPath("/html"));
            string attribute = head.GetProperty("cheese");
            Assert.IsNull(attribute);
        }

        [Test]
        [IgnoreBrowser(Browser.Chrome, "Chrome does not support get element property command")]
        [IgnoreBrowser(Browser.Opera)]
        [IgnoreBrowser(Browser.Remote)]
        [IgnoreBrowser(Browser.Safari)]
        public void CanRetrieveTheCurrentValueOfAProperty()
        {
            driver.Url = formsPage;
            IWebElement element = driver.FindElement(By.Id("working"));
            Assert.AreEqual(string.Empty, element.GetProperty("value"));
            element.SendKeys("hello world");
            Assert.AreEqual("hello world", element.GetProperty("value"));
        }
    }
}

Enable Get Element Property tests in Edge

Signed-off-by: Jim Evans <6d79d03c0573f3cb082d0037a63e1832cd69a278@gmail.com>


// 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.ComponentModel;
using osu.Framework.Input;

namespace osu.Game.Input
{
    /// <summary>
    /// Determines the situations in which the mouse cursor should be confined to the window.
    /// Expands upon <see cref="ConfineMouseMode"/> by providing the option to confine during gameplay.
    /// </summary>
    public enum OsuConfineMouseMode
    {
        /// <summary>
        /// The mouse cursor will be free to move outside the game window.
        /// </summary>
        Never,

        /// <summary>
        /// The mouse cursor will be locked to the window bounds while in fullscreen mode.
        /// </summary>
        Fullscreen,

        /// <summary>
        /// The mouse cursor will be locked to the window bounds during gameplay,
        /// but may otherwise move freely.
        /// </summary>
        [Description("During Gameplay")]
        DuringGameplay,

        /// <summary>
        /// The mouse cursor will always be locked to the window bounds while the game has focus.
        /// </summary>
        Always
    }
}

Add osu!-specific enum for confine mouse mode