/* -*- Mode: csharp; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: t -*- */
/***************************************************************************
 *  Utilities.cs
 *
 *  Copyright (C) 2005 Novell
 *  Written by Aaron Bockover (aaron@aaronbock.net)
 ****************************************************************************/

/*  THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
 *
 *  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.
 */

using System;

namespace MusicBrainz
{
    public class Utilities
    {
        public static DateTime StringToDateTime(string musicBrainzDate)
        {
            if(musicBrainzDate == null || musicBrainzDate == String.Empty) {
                return DateTime.MinValue;
            }

            // because the DateTime parser is *slow*

            string [] parts = musicBrainzDate.Split('-');

            if(parts.Length < 3) {
                return DateTime.MinValue;
            }

            try {
                return new DateTime(
                    Convert.ToInt32(parts[0]), // year
                    Convert.ToInt32(parts[1]), // month
                    Convert.ToInt32(parts[2])  // day
                );
            } catch(Exception) {
                return DateTime.MinValue;
            }
        }
    }
}

Convert a MusicBrainz date into a DateTime object

* src/MusicBrainz/Utilities.cs (StringToDateTime): Convert a MusicBrainz
    date into a DateTime object


using System;

namespace MitternachtWeb.Models {
	[Flags]
	public enum BotPagePermissions {
		None           = 0b00,
		ReadBotConfig  = 0b01,
		WriteBotConfig = 0b11,
	}

	[Flags]
	public enum GuildPagePermissions {
		None             = 0b_0000_0000,
		ReadGuildConfig  = 0b_0000_0001,
		WriteGuildConfig = 0b_0000_0011,
	}
}

Add initial page permission enums.

Add initial page permission enums.


namespace CSparse.Tests.Ordering
{
    using CSparse.Double;
    using CSparse.Ordering;
    using NUnit.Framework;
    using System;

    public class TestStronglyConnectedComponents
    {
        [Test]
        public void TestScc()
        {
            // https://en.wikipedia.org/wiki/Strongly_connected_component
            //
            // Adjacency list of directed graph with 8 nodes:
            //
            // [1] -> 2
            // [2] -> 3 -> 5 -> 6
            // [3] -> 4 -> 7
            // [4] -> 3 -> 8
            // [5] -> 1 -> 6
            // [6] -> 7
            // [7] -> 6
            // [8] -> 4 -> 7
            //
            // Adjacency matrix:

            var A = SparseMatrix.OfRowMajor(8, 8, new double[8 * 8]
            {
                1, 1, 0, 0, 0, 0, 0, 0,
                0, 1, 1, 0, 1, 1, 0, 0,
                0, 0, 1, 1, 0, 0, 1, 0,
                0, 0, 1, 1, 0, 0, 0, 1,
                1, 0, 0, 0, 1, 1, 0, 0,
                0, 0, 0, 0, 0, 1, 1, 0,
                0, 0, 0, 0, 0, 1, 1, 0,
                0, 0, 0, 1, 0, 0, 1, 1
            });

            int n = A.ColumnCount;

            var scc = StronglyConnectedComponents.Generate(A);

            var r = new int[] { 0, 3, 6, 8 };
            var p = new int[] { 0, 1, 4, 2, 3, 7, 5, 6 };

            Assert.AreEqual(scc.Blocks, 3);
            CollectionAssert.AreEqual(scc.BlockPointers, r);
            CollectionAssert.AreEqual(scc.Indices, p);
        }
    }
}

Add unit test for strongly connected components.


// 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.Numerics;
using System.Runtime.InteropServices;
using osu.Framework.Graphics;
using Veldrid.Sdl2;

// ReSharper disable InconsistentNaming

namespace osu.Framework.Platform
{
    public unsafe class Sdl2Functions
    {
        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        private delegate void SDL_GL_GetDrawableSize_t(SDL_Window window, int* w, int* h);

        private static readonly SDL_GL_GetDrawableSize_t s_glGetDrawableSize = Sdl2Native.LoadFunction<SDL_GL_GetDrawableSize_t>("SDL_GL_GetDrawableSize");

        public static Vector2 SDL_GL_GetDrawableSize(SDL_Window window)
        {
            int w, h;
            s_glGetDrawableSize(window, &w, &h);
            return new Vector2(w, h);
        }

        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        private delegate void SDL_GetWindowBordersSize_t(SDL_Window window, int* top, int* left, int* bottom, int* right);

        private static readonly SDL_GetWindowBordersSize_t s_glGetWindowBordersSize = Sdl2Native.LoadFunction<SDL_GetWindowBordersSize_t>("SDL_GetWindowBordersSize");

        public static MarginPadding SDL_GetWindowBordersSize(SDL_Window window)
        {
            int top, left, bottom, right;
            s_glGetWindowBordersSize(window, &top, &left, &bottom, &right);
            return new MarginPadding { Top = top, Left = left, Bottom = bottom, Right = right };
        }
    }
}

Add more SDL2 native functions

Add more SDL2 native functions

Veldrid does not expose all the functions we will need.


using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using Confuser.Core.Project;
using ConfuserEx.ViewModel;

namespace ConfuserEx {
	public partial class MainWindow : Window {
		public MainWindow() {
			InitializeComponent();

			var app = new AppVM();
			app.Project = new ProjectVM(new ConfuserProject());
			app.FileName = "Unnamed.crproj";

			app.Tabs.Add(new ProjectTabVM(app));
			app.Tabs.Add(new SettingsTabVM(app));
			app.Tabs.Add(new ProtectTabVM(app));
			app.Tabs.Add(new AboutTabVM(app));

			DataContext = app;
		}

		void OpenMenu(object sender, RoutedEventArgs e) {
			var btn = (Button)sender;
			ContextMenu menu = btn.ContextMenu;
			menu.PlacementTarget = btn;
			menu.Placement = PlacementMode.MousePoint;
			menu.IsOpen = true;
		}

		protected override void OnClosing(CancelEventArgs e) {
			base.OnClosing(e);
			e.Cancel = !((AppVM)DataContext).OnWindowClosing();
		}
	}
}

using System;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Xml;
using Confuser.Core.Project;
using ConfuserEx.ViewModel;

namespace ConfuserEx {
	public partial class MainWindow : Window {
		public MainWindow() {
			InitializeComponent();

			var app = new AppVM();
			app.Project = new ProjectVM(new ConfuserProject());
			app.FileName = "Unnamed.crproj";

			app.Tabs.Add(new ProjectTabVM(app));
			app.Tabs.Add(new SettingsTabVM(app));
			app.Tabs.Add(new ProtectTabVM(app));
			app.Tabs.Add(new AboutTabVM(app));

			LoadProj(app);

			DataContext = app;
		}

		void OpenMenu(object sender, RoutedEventArgs e) {
			var btn = (Button)sender;
			ContextMenu menu = btn.ContextMenu;
			menu.PlacementTarget = btn;
			menu.Placement = PlacementMode.MousePoint;
			menu.IsOpen = true;
		}

		void LoadProj(AppVM app) {
			var args = Environment.GetCommandLineArgs();
			if (args.Length != 2 || !File.Exists(args[1]))
				return;

			string fileName = args[1];
			try {
				var xmlDoc = new XmlDocument();
				xmlDoc.Load(fileName);
				var proj = new ConfuserProject();
				proj.Load(xmlDoc);
				app.Project = new ProjectVM(proj);
				app.FileName = fileName;
			}
			catch {
				MessageBox.Show("Invalid project!", "ConfuserEx", MessageBoxButton.OK, MessageBoxImage.Error);
			}
		}

		protected override void OnClosing(CancelEventArgs e) {
			base.OnClosing(e);
			e.Cancel = !((AppVM)DataContext).OnWindowClosing();
		}
	}
}

Add command line project loading

Add command line project loading

Fix #164


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

[assembly: AssemblyTitle("https://github.com/thekid/inotify-win")]
[assembly: AssemblyDescription("A port of the inotifywait tool for Windows")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Timm Friebe")]
[assembly: AssemblyProduct("inotify-win")]
[assembly: AssemblyCopyright("Copyright © 2012 - 2014 Timm Friebe")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.5.0.1")]
[assembly: ComVisible(false)]
[assembly: Guid("4254314b-ae21-4e2f-ba52-d6f3d83a86b5")]

Embed assembly info and version

Embed assembly info and version


namespace BatteryCommander.Web.Models
{
    public class Alert
    {
        // Id

        // SentAt

        // Recipients - IDs? - Pull Phone, Email from Soldier entity

        // Format - SMS? Email? Phone?

        // Message / Content

        // Status - Open, Closed -- Only one open at a time, all responses will be attributed to that alert
        // Responses - FROM, CONTENT

        // Request Ack T/F?
        // What about sending a short-URL to acknowledge receipt? https://abcd.red-leg-dev.com/Alert/{id}/Acknowledge
        // User enters name/identifying info, accessible from phones, can provide more context
        // OR, each user gets a custom URL based on receipient hash so that we don't even need more than a big ACK button?
    }
}

Add notes on the alert model

Add notes on the alert model


using System.Collections.Generic;
using DigitalOcean.API.Clients;
using DigitalOcean.API.Http;
using DigitalOcean.API.Models.Requests;
using DigitalOcean.API.Models.Responses;
using NSubstitute;
using RestSharp;
using Xunit;

namespace DigitalOcean.API.Tests.Clients {
    public class ProjectResourcesClientTest {
        [Fact]
        public void CorrectRequestForGetResources() {
            var factory = Substitute.For<IConnection>();
            var client = new ProjectResourcesClient(factory);

            client.GetResources("project:abc123");

            var parameters = Arg.Is<List<Parameter>>(list => (string)list[0].Value == "project:abc123");
            factory.Received().GetPaginated<ProjectResource>("projects/{project_id}/resources", parameters, "resources");
        }

        [Fact]
        public void CorrectRequestForGetDefaultResources() {
            var factory = Substitute.For<IConnection>();
            var client = new ProjectResourcesClient(factory);

            client.GetDefaultResources();

            factory.Received().GetPaginated<ProjectResource>("projects/default/resources", null, "resources");
        }

        [Fact]
        public void CorrectRequestForAssignResources() {
            var factory = Substitute.For<IConnection>();
            var client = new ProjectResourcesClient(factory);

            var resources = new AssignResourceNames() {
                Resources = new List<string>() { "do:droplet:9001", "do:droplet:9002" }
            };
            client.AssignResources("project:abc123", resources);

            var parameters = Arg.Is<List<Parameter>>(list => (string)list[0].Value == "project:abc123");
            factory.Received().ExecuteRequest<List<ProjectResource>>("projects/{project_id}/resources", parameters, resources, "resources", Method.POST);
        }

        [Fact]
        public void CorrectRequestForAssignDefaultResources() {
            var factory = Substitute.For<IConnection>();
            var client = new ProjectResourcesClient(factory);

            var resources = new AssignResourceNames() {
                Resources = new List<string>() { "do:droplet:9001", "do:droplet:9002" }
            };
            client.AssignDefaultResources(resources);

            factory.Received().ExecuteRequest<List<ProjectResource>>("projects/default/resources", null, resources, "resources", Method.POST);
        }
    }
}

Add tests for Project Resources.

Add tests for Project Resources.


using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using EventStore.ClientAPI;

namespace Edument.CQRS
{
    // An implementation of IEventStore in terms of EventStore, available from
    // http://geteventstore.com/
    public class ESEventStore : IEventStore
    {
        private IEventStoreConnection conn = EventStoreConnection
            .Create(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1113));

        public ESEventStore()
        {
            conn.Connect();
        }

        public IEnumerable LoadEventsFor<TAggregate>(Guid id)
        {
            StreamEventsSlice currentSlice;
            var nextSliceStart = StreamPosition.Start;
            do
            {
                currentSlice = conn.ReadStreamEventsForward(id.ToString(), nextSliceStart, 200, false);
                foreach (var e in currentSlice.Events)
                    yield return Deserialize(e.Event.EventType, e.Event.Data);
                nextSliceStart = currentSlice.NextEventNumber;
            } while (!currentSlice.IsEndOfStream);
        }

        private object Deserialize(string typeName, byte[] data)
        {
            var ser = new XmlSerializer(Type.GetType(typeName));
            var ms = new MemoryStream(data);
            ms.Seek(0, SeekOrigin.Begin);
            return ser.Deserialize(ms);
        }

        public void SaveEventsFor<TAggregate>(Guid? id, int eventsLoaded, ArrayList newEvents)
        {
            // Establish the aggregate ID to save the events under and ensure they
            // all have the correct ID.
            if (newEvents.Count == 0)
                return;
            Guid aggregateId = id ?? GetAggregateIdFromEvent(newEvents[0]);
            foreach (var e in newEvents)
                if (GetAggregateIdFromEvent(e) != aggregateId)
                    throw new InvalidOperationException(
                        "Cannot save events reporting inconsistent aggregate IDs");

            var expected = eventsLoaded == 0 ? ExpectedVersion.NoStream : eventsLoaded - 1;
            conn.AppendToStream(aggregateId.ToString(), expected, newEvents
                .Cast<dynamic>()
                .Select(e => new EventData(e.Id, e.GetType().AssemblyQualifiedName,
                    false, Serialize(e), null)));
        }

        private Guid GetAggregateIdFromEvent(object e)
        {
            var idField = e.GetType().GetField("Id");
            if (idField == null)
                throw new Exception("Event type " + e.GetType().Name + " is missing an Id field");
            return (Guid)idField.GetValue(e);
        }

        private byte[] Serialize(object obj)
        {
            var ser = new XmlSerializer(obj.GetType());
            var ms = new MemoryStream();
            ser.Serialize(ms, obj);
            ms.Seek(0, SeekOrigin.Begin);
            return ms.ToArray();
        }
    }
}

Add EventStore implementation of IEventStore.

Uses the EventStore from http://geteventstore.com/.


//----------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// 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.
//
//------------------------------------------------------------------------------

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.WsTrust;
using System.IO;
using System.Xml.Linq;

namespace Test.ADAL.NET.Unit
{
    [TestClass]
    [DeploymentItem("WsTrustResponse.xml")]
    public class WsTrustTests
    {
        [TestMethod]
        [TestCategory("WsTrustTests")]
        public void TestCreateFromResponseDocument_WhenInputContainsWhitespace_ShouldPreserveWhitespace()
        {
            string sample = File.ReadAllText("WsTrustResponse.xml");
            string characteristic = "\n        <saml:Assertion";
            StringAssert.Contains(sample, characteristic);
            WsTrustResponse resp = WsTrustResponse.CreateFromResponseDocument(
                XDocument.Parse(sample, LoadOptions.PreserveWhitespace), WsTrustVersion.WsTrust2005);
            StringAssert.Contains(resp.Token, characteristic);
        }
    }
}

Add a unit test for the new reserve-whitespace behavior


using System;
using System.Collections.Generic;
using Caliburn.Micro;
using CM.HelloUniversal.Views;
using CM.HelloUniversal.ViewModels;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml.Controls;

namespace CM.HelloUniversal
{
    public sealed partial class App
    {
        private WinRTContainer container;

        public App()
        {
            InitializeComponent();
        }

        protected override void Configure()
        {
            MessageBinder.SpecialValues.Add("$clickeditem", c => ((ItemClickEventArgs)c.EventArgs).ClickedItem);

            container = new WinRTContainer();

            container.RegisterWinRTServices();

            container.PerRequest<MainViewModel>();
        }

        protected override void PrepareViewFirst(Frame rootFrame)
        {
            container.RegisterNavigationService(rootFrame);
        }

        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            if (args.PreviousExecutionState == ApplicationExecutionState.Running)
                return;

            DisplayRootView<MainView>();
        }

        protected override object GetInstance(Type service, string key)
        {
            return container.GetInstance(service, key);
        }

        protected override IEnumerable<object> GetAllInstances(Type service)
        {
            return container.GetAllInstances(service);
        }

        protected override void BuildUp(object instance)
        {
            container.BuildUp(instance);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Diagnostics;
using Caliburn.Micro;
using CM.HelloUniversal.Views;
using CM.HelloUniversal.ViewModels;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml.Controls;

namespace CM.HelloUniversal
{
    public sealed partial class App
    {
        private WinRTContainer container;

        public App()
        {
            InitializeComponent();
        }

        protected override void Configure()
        {
            MessageBinder.SpecialValues.Add("$clickeditem", c => ((ItemClickEventArgs)c.EventArgs).ClickedItem);

            container = new WinRTContainer();

            container.RegisterWinRTServices();

            container.PerRequest<MainViewModel>();

            PrepareViewFirst();
        }

        protected override void PrepareViewFirst(Frame rootFrame)
        {
            container.RegisterNavigationService(rootFrame);
        }

        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            Initialize();

            if (args.PreviousExecutionState == ApplicationExecutionState.Running)
                return;

            if (RootFrame.Content == null)
                DisplayRootView<MainView>();
        }

        protected override object GetInstance(Type service, string key)
        {
            return container.GetInstance(service, key);
        }

        protected override IEnumerable<object> GetAllInstances(Type service)
        {
            return container.GetAllInstances(service);
        }

        protected override void BuildUp(object instance)
        {
            container.BuildUp(instance);
        }
    }
}

Fix for FAR in sample app

Fix for FAR in sample app


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

namespace System.Runtime.InteropServices
{
    // Stand-in type for low-level assemblies to obtain Win32 errors
    internal static class Marshal
    {
        public static int GetLastWin32Error()
        {
            // issue: https://github.com/dotnet/corefx/issues/6778
            // Need to define and implement this for Linux
            return 0;
        }

        unsafe public static String PtrToStringAnsi(IntPtr ptr)
        {
            if (IntPtr.Zero == ptr)
            {
                return null;
            }

            byte *pBytes = (byte *) ptr;
            int length = 0;

            while (*pBytes != 0)
            {
                pBytes++;
                length++;
            }

            if (length == 0)
            {
                return String.Empty;
            }

            char [] chars = new char[length];
            pBytes = (byte *) ptr;

            for (int i=0; i<length; i++)
            {
                chars[i] = (char) pBytes[i];
            }

            return new string(chars);
        }
    }
}

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

namespace System.Runtime.InteropServices
{
    // Stand-in type for low-level assemblies to obtain Win32 errors
    internal static class Marshal
    {
        public static int GetLastWin32Error()
        {
            // issue: https://github.com/dotnet/corefx/issues/6778
            // Need to define and implement this for Linux
            return 0;
        }

        unsafe public static String PtrToStringAnsi(IntPtr ptr)
        {
            if (IntPtr.Zero == ptr)
            {
                return null;
            }

            byte *pBytes = (byte *) ptr;
            int length = 0;

            while (pBytes[length] != 0)
            {
                length++;
            }

            return System.Text.Encoding.UTF8.GetString(pBytes, length);
        }
    }
}

Make Marshal.PtrToStringAnsi to use Utf8 on Linux

https://github.com/dotnet/corefx/issues/6834


using System;
using NUnit.Framework.Api;
using System.Xml.Linq;
using System.IO;

namespace GuiUnit
{
	public class XmlTestListener : ITestListener
	{
		TextWriter Writer {
			get; set;
		}

		public XmlTestListener (TextWriter writer)
		{
			Writer = writer;
		}

		public void TestStarted (ITest test)
		{
			if (test.HasChildren)
				Write (new XElement ("suite-started", new XAttribute ("name", test.FullName)));
			else
				Write (new XElement ("test-started", new XAttribute ("name", test.FullName)));
		}

		public void TestFinished (ITestResult result)
		{
			if (result.Test.HasChildren)
				Write (new XElement ("suite-finished", new XAttribute ("name", result.Test.FullName), new XAttribute ("result", ToXmlString (result.ResultState))));
			else
				Write (new XElement ("test-finished", new XAttribute ("name", result.Test.FullName), new XAttribute ("result", ToXmlString (result.ResultState))));
		}

		public void TestOutput (TestOutput testOutput)
		{
			// Ignore
		}

		object ToXmlString (ResultState resultState)
		{
			if (resultState == ResultState.Success)
				return "Success";
			else if (resultState == ResultState.Inconclusive)
				return "Inconclusive";
			else if (resultState == ResultState.Ignored)
				return "Ignored";
			else
				return "Failure";
		}

		void Write (XElement element)
		{
			try {
				Writer.WriteLine (element.ToString ());
			} catch {
			}
		}
	}
}

Add basic support for outputing on the fly updates


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

namespace log4net {

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

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

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

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

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

}

Make metadata accessible without reflection

git-svn-id: 223c0ba935819ffdcafdc68147dc609b4e469b1e@1159843 13f79535-47bb-0310-9956-ffa450edef68


using System;
using System.Threading.Tasks;
using NCrawler.Interfaces;

namespace NCrawler
{
    /// <summary>
    /// Implementation of pipeline steps which allow steps definition using simple functions
    /// </summary>
    public class SimpleStep : IPipelineStep
    {
        private Func<ICrawler, PropertyBag, Task> worker;

        public SimpleStep(Action worker)
            : this((crawler, properties) => worker())
        {
        }

        public SimpleStep(Action<ICrawler> worker)
            : this((crawler, properties) => worker(crawler))
        {
        }

        public SimpleStep(Action<ICrawler, PropertyBag> worker)
            : this((crawler, properties) =>
            {
                worker(crawler, properties);
                return Task.CompletedTask;
            })
        {
        }

        public SimpleStep(Func<Task> worker)
            : this((crawler, properties) => worker())
        {
        }

        public SimpleStep(Func<ICrawler, Task> worker)
            : this((crawler, properties) => worker(crawler))
        {
        }

        public SimpleStep(Func<ICrawler, PropertyBag, Task> worker) => this.worker = worker ?? throw new ArgumentNullException(nameof(worker));

        public Task ProcessAsync(ICrawler crawler, PropertyBag propertyBag)
        {
            return this.worker(crawler, propertyBag);
        }
    }
}

Add simple step which allow using delegates for defining steps


using JetBrains.Application.BuildScript.Application.Zones;
using JetBrains.ReSharper.Feature.Services.ExternalSources;

namespace JetBrains.ReSharper.Plugins.Unity.Feature.Services.ExternalSources
{
    [ZoneMarker]
    public class ZoneMarker : IRequire<ExternalSourcesZone>
    {
    }
}

Add zone marker to fix exceptions in inspectcode


using CLImber;
using SetIPLib;
using System;
using System.Linq;
using System.Net;

namespace SetIPCLI
{
    [CommandClass("edit", ShortDescription = "Updates a profile with the specified information. Updated info is specified using options: --ip=xxx.xxx.xxx.xxx")]
    class EditProfile
    {
        private Profile _editingProfile;

        private IPAddress _ip = null;
        [CommandOption("ip")]
        public IPAddress IP
        {
            get
            {
                return _ip ?? _editingProfile?.IP;
            }
            set
            {
                _ip = value;
            }
        }

        private IPAddress _subnet = null;
        [CommandOption("subnet")]
        public IPAddress Subnet
        {
            get
            {
                return _subnet ?? _editingProfile?.Subnet;
            }
            set
            {
                _subnet = value;
            }
        }

        private IPAddress _gateway = null;
        [CommandOption("gw")]
        [CommandOption("gateway")]
        public IPAddress Gateway
        {
            get
            {
                return _gateway ?? _editingProfile?.Gateway;
            }
            set
            {
                _gateway = value;
            }
        }

        private IPAddress _dns = null;
        [CommandOption("dns")]
        public IPAddress DNS
        {
            get
            {
                return _dns ?? _editingProfile?.DNSServers.DefaultIfEmpty(IPAddress.Any).FirstOrDefault();
            }
            set
            {
                _dns = value;
            }
        }

        private string _name = null;
        [CommandOption("name")]
        public string Name
        {
            get
            {
                return _name ?? _editingProfile?.Name;
            }
            set
            {
                _name = value;
            }
        }

        [CommandOption("dhcp")]
        public bool DHCP { get; set; } = false;

        private readonly IProfileStore _store;
        public EditProfile(IProfileStore profileStore)
        {
            _store = profileStore;
        }

        [CommandHandler(ShortDescription = "Update a profile with new values.")]
        public void Edit(string profileName)
        {
            var profiles = _store.Retrieve().ToList();
            var possibleProfiles = profiles.Where(p => p.Name.Equals(profileName, StringComparison.OrdinalIgnoreCase));

            if (possibleProfiles.Count() != 1)
            {
                return;
            }

            _editingProfile = possibleProfiles.First();
            Profile newProfile;
            if (DHCP)
            {
                newProfile = Profile.CreateDHCPProfile(Name);
            }
            if (DNS != IPAddress.Any)
            {
                newProfile = Profile.CreateStaticProfile(Name, IP, Subnet, Gateway, new IPAddress[] { DNS });
            }
            if (Gateway != IPAddress.Any)
            {
                newProfile = Profile.CreateStaticProfile(Name, IP, Subnet, Gateway);
            }
            else
            {
                newProfile = Profile.CreateStaticProfile(Name, IP, Subnet);
            }

            profiles.Remove(_editingProfile);
            profiles.Add(newProfile);
            _store.Store(profiles);
        }

    }
}

Add Command to Edit Profiles

Add Command to Edit Profiles

With CLImber's support for options, the Edit command can be implemented. Options are used to specify which part of the profile should be changed.


using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;

namespace Firehose.Web.Authors
{
    public class DavidOBrien : IFilterMyBlogPosts, IAmAMicrosoftMVP
    {
        public string FirstName => "David";
        public string LastName => "O'Brien";
        public string ShortBioOrTagLine => "is a Microsoft MVP, DevOps Consultant/Engineer, do AWS and a lot of Cloud.";
        public string StateOrRegion => "Melbourne, Australia";
        public string EmailAddress => "me@david-obrien.net";
        public string TwitterHandle => "david_obrien";
        public string GravatarHash => "c93bbf72255d38bab70895eb7c0b3f99";

        public Uri WebSite => new Uri("https://david-obrien.net/");

        public IEnumerable<Uri> FeedUris
        {
            get { yield return new Uri("https://david-obrien.net/feed.xml"); }
        }

        public string GitHubHandle => "davidobrien1985";

        public bool Filter(SyndicationItem item)
        {
            return item.Categories.Where(i => i.Name.Equals("powershell", StringComparison.OrdinalIgnoreCase)).Any();
        }

        DateTime IAmAMicrosoftMVP.FirstAwarded => new DateTime(2012, 10, 1);
    }
}

Add class for David OBrien

Add class for David OBrien


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

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

        protected override void InternalBuild()
        {
            Result = Build(Range.Start, Range.End, Range.Step);
        }

        public IEnumerable<string> Build(int start, int end, int step)
        {
            var list = new List<string>();
            for (int i = start; i <= end; i+=step)
                list.Add(i.ToString());

            return list;
        }
    }
}

Add the builder for an Integer range

Add the builder for an Integer range


using System.Collections.Generic;
using System.Linq;
using CppSharp.Passes;

namespace CppSharp
{
    /// <summary>
    /// This class is used to build passes that will be run against the AST
    /// that comes from C++.
    /// </summary>
    public class PassBuilder<T>
    {
        public List<T> Passes { get; private set; }
        public Driver Driver { get; private set; }

        public PassBuilder(Driver driver)
        {
            Passes = new List<T>();
            Driver = driver;
        }

        /// <summary>
        /// Adds a new pass to the builder.
        /// </summary>
        public void AddPass(T pass)
        {
            Passes.Add(pass);
        }

        /// <summary>
        /// Finds a previously-added pass of the given type.
        /// </summary>
        public T FindPass<T>() where T : TranslationUnitPass
        {
            return Passes.OfType<T>().Select(pass => pass as T).FirstOrDefault();
        }
    }
}

using System.Collections.Generic;
using System.Linq;
using CppSharp.Passes;

namespace CppSharp
{
    /// <summary>
    /// This class is used to build passes that will be run against the AST
    /// that comes from C++.
    /// </summary>
    public class PassBuilder<T>
    {
        public List<T> Passes { get; private set; }
        public Driver Driver { get; private set; }

        public PassBuilder(Driver driver)
        {
            Passes = new List<T>();
            Driver = driver;
        }

        /// <summary>
        /// Adds a new pass to the builder.
        /// </summary>
        public void AddPass(T pass)
        {
            Passes.Add(pass);
        }

        /// <summary>
        /// Finds a previously-added pass of the given type.
        /// </summary>
        public U FindPass<U>() where U : TranslationUnitPass
        {
            return Passes.OfType<U>().Select(pass => pass as U).FirstOrDefault();
        }
    }
}

Use a different generic type variable name that does not conflict with the parent one.


namespace Skeleton.Web.Tests.Conventions.Responses
{
    using System;
    using Web.Conventions.Responses;
    using Xunit;

    public class ExceptionDescriptionTests
    {
        [Fact]
        public void ShouldCollectInformation()
        {
            // Given
            const string message = "<Message>";
            const string innerMessage = "<Inner_Message>";

            void Action()
            {
                void InnerAction() => throw new ArgumentException(innerMessage);
                try
                {
                    InnerAction();
                }
                catch (Exception e)
                {
                    throw new InvalidOperationException(message, e);
                }
            }

            //When
            Exception exception = null;
            try
            {
                Action();
            }
            catch (Exception e)
            {
                exception = e;
            }
            var exceptionStringDescription = new ExceptionDescription(exception).ToString();

            // Then
            Assert.Contains(message, exceptionStringDescription, StringComparison.InvariantCultureIgnoreCase);
            Assert.Contains(exception.GetType().ToString(), exceptionStringDescription, StringComparison.InvariantCultureIgnoreCase);
            Assert.Contains(exception.StackTrace, exceptionStringDescription, StringComparison.InvariantCultureIgnoreCase);

            Assert.Contains(innerMessage, exceptionStringDescription, StringComparison.InvariantCultureIgnoreCase);
            Assert.Contains(exception.InnerException.GetType().ToString(), exceptionStringDescription, StringComparison.InvariantCultureIgnoreCase);
            Assert.Contains(exception.InnerException.StackTrace, exceptionStringDescription, StringComparison.InvariantCultureIgnoreCase);
        }
    }
}

Test was added for ExceptionDescription

Test was added for ExceptionDescription


using System;
using CoreGraphics;
using UIKit;
using Foundation;

namespace TableEditing
{
	[Register ("AppDelegate")]
	public class AppDelegate : UIApplicationDelegate
	{
		#region -= main =-

		public static void Main (string[] args)
		{
			try {
				UIApplication.Main (args, null, "AppDelegate");
			} catch (Exception e) {
				Console.WriteLine (e.ToString ());
			}
		}

		#endregion

		#region -= declarations and properties =-

		protected UIWindow window;
		protected TableEditing.Screens.HomeScreen iPhoneHome;

		#endregion

		public override bool FinishedLaunching (UIApplication app, NSDictionary options)
		{
			//---- create our window
			window = new UIWindow (UIScreen.MainScreen.Bounds);
			window.MakeKeyAndVisible ();

			//---- create the home screen
			iPhoneHome = new TableEditing.Screens.HomeScreen ();
			iPhoneHome.View.Frame = new CGRect (0, UIApplication.SharedApplication.StatusBarFrame.Height,
				UIScreen.MainScreen.ApplicationFrame.Width,
				UIScreen.MainScreen.ApplicationFrame.Height);

			window.AddSubview (iPhoneHome.View);

			return true;
		}
	}
}

using System;
using CoreGraphics;
using UIKit;
using Foundation;

namespace TableEditing
{
	[Register ("AppDelegate")]
	public class AppDelegate : UIApplicationDelegate
	{
		#region -= main =-

		public static void Main (string[] args)
		{
			try {
				UIApplication.Main (args, null, "AppDelegate");
			} catch (Exception e) {
				Console.WriteLine (e.ToString ());
			}
		}

		#endregion

		#region -= declarations and properties =-

		protected UIWindow window;
		protected TableEditing.Screens.HomeScreen iPhoneHome;

		#endregion

		public override bool FinishedLaunching (UIApplication app, NSDictionary options)
		{
			//---- create our window
			window = new UIWindow (UIScreen.MainScreen.Bounds);
			window.MakeKeyAndVisible ();

			//---- create the home screen
			iPhoneHome = new TableEditing.Screens.HomeScreen ();
			iPhoneHome.View.Frame = new CGRect (0, UIApplication.SharedApplication.StatusBarFrame.Height,
				UIScreen.MainScreen.ApplicationFrame.Width,
				UIScreen.MainScreen.ApplicationFrame.Height);

			var navigationController = new UINavigationController (iPhoneHome);
			window.RootViewController = navigationController;
			window.MakeKeyAndVisible ();

			return true;
		}
	}
}

Set root view controller for window

[TableEditing] Set root view controller for window


using Certify.Locales;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace Certify.UI.Utils
{
    public class UpdateCheckUtils
    {
        public async Task<Models.UpdateCheck> UpdateWithDownload()
        {
            Mouse.OverrideCursor = Cursors.Wait;
            var updateCheck = await new Management.Util().DownloadUpdate();
            if (!string.IsNullOrEmpty(updateCheck.UpdateFilePath))
            {
                if (MessageBox.Show(SR.Update_ReadyToApply, ConfigResources.AppName, MessageBoxButton.YesNoCancel) == MessageBoxResult.Yes)
                {
                    // file has been downloaded and verified
                    System.Diagnostics.Process p = new System.Diagnostics.Process();
                    p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                    p.StartInfo.FileName = updateCheck.UpdateFilePath;
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.RedirectStandardError = true;
                    p.Start();

                    //stop certify.service
                    /*ServiceController service = new ServiceController("ServiceName");
                    service.Stop();
                    service.WaitForStatus(ServiceControllerStatus.Stopped);*/

                    Application.Current.Shutdown();
                }
            }
            Mouse.OverrideCursor = Cursors.Arrow;
            return updateCheck;
        }
    }
}

using Certify.Locales;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace Certify.UI.Utils
{
    public class UpdateCheckUtils
    {
        public async Task<Models.UpdateCheck> UpdateWithDownload()
        {
            Mouse.OverrideCursor = Cursors.Wait;
            var updateCheck = await new Management.Util().DownloadUpdate();
            if (!string.IsNullOrEmpty(updateCheck.UpdateFilePath))
            {
                if (MessageBox.Show(SR.Update_ReadyToApply, ConfigResources.AppName, MessageBoxButton.YesNoCancel) == MessageBoxResult.Yes)
                {
                    // file has been downloaded and verified
                    System.Diagnostics.Process p = new System.Diagnostics.Process();
                    p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                    p.StartInfo.FileName = updateCheck.UpdateFilePath;
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.RedirectStandardError = true;
                    p.StartInfo.Arguments = "/SILENT";
                    p.Start();

                    //stop certify.service
                    /*ServiceController service = new ServiceController("ServiceName");
                    service.Stop();
                    service.WaitForStatus(ServiceControllerStatus.Stopped);*/

                    Application.Current.Shutdown();
                }
            }
            Mouse.OverrideCursor = Cursors.Arrow;
            return updateCheck;
        }
    }
}

Use "silent" install (no prompts) when running optional auto apply update


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

using System;
using gaxgrpc = Google.Api.Gax.Grpc;
using grpccore = Grpc.Core;
using sys = System;

namespace Google.Cloud.Speech.V1
{
    // This is a partial class introduced for backward compatibility with earlier versions.
    public partial class SpeechSettings
    {
        /// <summary>
        /// In previous releases, this property returned a filter used by default for "Idempotent" RPC methods.
        /// It is now unused, and may not represent the current default behavior.
        /// </summary>
        [Obsolete("This member is no longer called by other code in this library. Please use the individual CallSettings properties.")]
        public static sys::Predicate<grpccore::RpcException> IdempotentRetryFilter { get; } =
            gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Unavailable);

        /// <summary>
        /// In previous releases, this property returned a filter used by default for "NonIdempotent" RPC methods.
        /// It is now unused, and may not represent the current default behavior.
        /// </summary>
        [Obsolete("This member is no longer called by other code in this library. Please use the individual CallSettings properties.")]
        public static sys::Predicate<grpccore::RpcException> NonIdempotentRetryFilter { get; } =
            gaxgrpc::RetrySettings.FilterForStatusCodes();

        /// <summary>
        /// In previous releases, this method returned the backoff used by default for "Idempotent" RPC methods.
        /// It is now unused, and may not represent the current default behavior.
        /// </summary>
        [Obsolete("This member is no longer called by other code in this library. Please use the individual CallSettings properties.")]
        public static gaxgrpc::BackoffSettings GetDefaultRetryBackoff() => new gaxgrpc::BackoffSettings(
            delay: sys::TimeSpan.FromMilliseconds(100),
            maxDelay: sys::TimeSpan.FromMilliseconds(60000),
            delayMultiplier: 1.3
        );

        /// <summary>
        /// In previous releases, this method returned the backoff used by default for "NonIdempotent" RPC methods.
        /// It is now unused, and may not represent the current default behavior.
        /// </summary>
        [Obsolete("This member is no longer called by other code in this library. Please use the individual CallSettings properties.")]
        public static gaxgrpc::BackoffSettings GetDefaultTimeoutBackoff() => new gaxgrpc::BackoffSettings(
            delay: sys::TimeSpan.FromMilliseconds(20000),
            maxDelay: sys::TimeSpan.FromMilliseconds(20000),
            delayMultiplier: 1.0
        );
    }
}

Add partial class for retry settings (compatibility)


using System;

namespace Tellurium.VisualAssertions.Screenshots.Utils
{
    static class DateTimeExtensions
    {
        public static DateTime TrimToMiliseconds(this DateTime dateTime)
        {
            return Trim(dateTime, TimeSpan.TicksPerMillisecond);
        }

        static DateTime Trim(DateTime date, long roundTicks)
        {
            return new DateTime(date.Ticks - date.Ticks % roundTicks);
        }
    }
}

Fix issue with persisting DateTime

Fix issue with persisting DateTime


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Stranne.BooliLib.Models;
using Xunit;

namespace Stranne.BooliLib.Tests
{
    public class LibraryVisabilityTest
    {
        private readonly IEnumerable<Type> _publicClasses = new List<Type>
        {
            typeof(BooliService),
            typeof(IBooliService),
            typeof(Address),
            typeof(Area),
            typeof(AreaSearchOption),
            typeof(BaseObjectSearchOptions),
            typeof(BaseResult),
            typeof(BaseSearchOptions),
            typeof(BooliResult<,>),
            typeof(BoxCoordinates),
            typeof(Dimension),
            typeof(Distance),
            typeof(IBooliId),
            typeof(ListedObject),
            typeof(ListedSearchOption),
            typeof(LocationResult),
            typeof(Position),
            typeof(PositionResult),
            typeof(Region),
            typeof(SoldObject),
            typeof(SoldSearchOption),
            typeof(Source)
        };

        [Fact]
        public void VerifyPublicClasses()
        {
            var publicClasses = new List<Type>(_publicClasses);

            var booliLibAssembly = typeof(BooliService).GetTypeInfo().Assembly;
            booliLibAssembly.GetTypes()
                .Where(type => type.GetTypeInfo().IsPublic)
                .ToList()
                .ForEach(type =>
                {
                    Assert.Contains(type, publicClasses);
                    publicClasses.Remove(type);
                });

            Assert.Empty(publicClasses);
        }

        [Fact]
        public void VerifyBooliServiceClassVariables()
        {
            Assert.True(new BooliService(TestConstants.CallerId, TestConstants.Key).BaseService.GetType().GetTypeInfo().IsNotPublic);
        }
    }
}

Add test to verify library class visability

Ensure that no unintended classes are set to public, vice versa.


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

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

        [HttpGet]
        /// <summary>
        /// Gets all questions
        /// </summary>
        /// <returns>Questions list</returns>
        public IActionResult GetQuestions()
        {
            var questions = _questionsRepository.GetAllQuestions();
            return Json(questions);
        }

        [HttpPost]
        /// <summary>
        /// Add single multiple answer question into SingleMultipleAnswerQuestion model
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        /// <returns></returns>
        public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
        {
            _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion);
            return Ok();
        }

        /// <summary>
        /// Add options of single multiple answer question to SingleMultipleAnswerQuestionOption model
        /// </summary>
        /// <param name="singleMultipleAnswerQuestionOption"></param>
        /// <returns></returns>
        public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
        {
            _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption);
            return Ok();
        }
    }
}

Update server side API for single multiple answer question


using UnityEngine;
using System.Collections;

public class AccelerometerReader : MonoBehaviour {
    public float Filter = 5.0f;
    public GUIText Label;
    private Vector3 accel;

    void Start() {
        accel = Input.acceleration;
    }

    void Update() {
        // filter the jerky acceleration in the variable accel:
        accel = Vector3.Lerp(accel, Input.acceleration, Filter * Time.deltaTime);

        var dir = new Vector3(accel.x, accel.y, 0);
        // limit dir vector to magnitude 1:
        if (dir.sqrMagnitude > 1) dir.Normalize();

        // sync to framerate
        Label.text = (dir * Time.deltaTime * 100).ToString();
    }
}

Add accelerometer reader example script

Add accelerometer reader example script


// http://careercup.com/question?id=5690323227377664
//
// Write a function which takes an integer and convert to string as:
// 1 - A         0001
// 2 - B         0010
// 3 - AA        0011
// 4 - AB        0100
// 5 - BA        0101
// 6 - BB        0110
// 7 - AAA       0111
// 8 - AAB       1000
// 9 - ABA       1001
// 10 - ABB
// 11 - BAA
// 12 - BAB
// 13 - BBA
// 14 - BBB
// 15 - AAAA

using System;

static class Program
{
    static String ToS(this int i)
    {
        String result = String.Empty;
        while (i > 0)
        {
            if ((i & 1) == 0)
            {
                result += "B";
                i -= 1;
            }
            else
            {
                result += "A";
            }

            i >>= 1;
        }

        return result;
    }

    static void Main()
    {
        for (int i = 1; i < 16; i++)
        {
            Console.WriteLine("{0} - {1}", i, i.ToS());
        }
    }
}

Convert int to string column

Convert int to string column


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

namespace open3mod
{
    // Zip() was added in .NET 4.0.
    // http://blogs.msdn.com/b/ericlippert/archive/2009/05/07/zip-me-up.aspx
    public static class LinqZipNet4Backport
    {
        public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult> (this IEnumerable<TFirst> first,
            IEnumerable<TSecond> second,
            Func<TFirst, TSecond, TResult> resultSelector)
        {
            if (first == null)
                throw new ArgumentNullException("first");
            if (second == null)
                throw new ArgumentNullException("second");
            if (resultSelector == null)
                throw new ArgumentNullException("resultSelector");
            return ZipIterator(first, second, resultSelector);
        }

        private static IEnumerable<TResult> ZipIterator<TFirst, TSecond, TResult>
            (IEnumerable<TFirst> first,
            IEnumerable<TSecond> second,
            Func<TFirst, TSecond, TResult> resultSelector)
        {
            using (IEnumerator<TFirst> e1 = first.GetEnumerator())
            using (IEnumerator<TSecond> e2 = second.GetEnumerator())
                while (e1.MoveNext() && e2.MoveNext())
                    yield return resultSelector(e1.Current, e2.Current);
        }
    }
}

Add Eric Lippert's backport of Zip() to .NET 3.5.


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

using NUnit.Framework;
using osu.Game.Utils;

namespace osu.Game.Tests.NonVisual
{
    [TestFixture]
    public class FormatUtilsTest
    {
        [TestCase(0, "0.00%")]
        [TestCase(0.01, "1.00%")]
        [TestCase(0.9899, "98.99%")]
        [TestCase(0.989999, "99.00%")]
        [TestCase(0.99, "99.00%")]
        [TestCase(0.9999, "99.99%")]
        [TestCase(0.999999, "99.99%")]
        [TestCase(1, "100.00%")]
        public void TestAccuracyFormatting(double input, string expectedOutput)
        {
            Assert.AreEqual(expectedOutput, input.FormatAccuracy());
        }
    }
}

Add test coverage of accuracy formatting function


// TooFewPlayersException.cs
// <copyright file="TooFewPlayersException.cs"> This code is protected under the MIT License. </copyright>
using System;

namespace CardGames
{
    /// <summary>
    /// An exception raised when TooFewPlayers are added to a game.
    /// </summary>
    [Serializable]
    public class TooFewPlayersException : Exception
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="TooFewPlayersException" /> class.
        /// </summary>
        public TooFewPlayersException()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="TooFewPlayersException" /> class.
        /// </summary>
        /// <param name="message"> The message to explain the exception. </param>
        public TooFewPlayersException(string message) : base(message)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="TooFewPlayersException" /> class.
        /// </summary>
        /// <param name="message"> The message to explain the exception. </param>
        /// <param name="inner"> The exception that caused the TooFewPlayersException. </param>
        public TooFewPlayersException(string message, Exception inner)
            : base(message, inner)
        {
        }
    }
}

Add too few players exception

Add too few players exception


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

namespace TimeNetSync.Services
{
    public interface IResultsOutput
    {
    }
}

Set up results output interface

Set up results output interface


using JetBrains.Annotations;
using JetBrains.Application.changes;
using JetBrains.Application.FileSystemTracker;
using JetBrains.Application.Threading;
using JetBrains.DocumentManagers;
using JetBrains.DocumentModel;
using JetBrains.Lifetimes;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Host.Features.Documents;
using JetBrains.ReSharper.Plugins.Unity.ProjectModel;
using JetBrains.Rider.Model;
using JetBrains.Util;

namespace JetBrains.ReSharper.Plugins.Unity.Rider
{
    [SolutionComponent]
    public class RiderUnityDocumentOperationsImpl : RiderDocumentOperationsImpl
    {
        [NotNull] private readonly ILogger myLogger;

        public RiderUnityDocumentOperationsImpl(Lifetime lifetime,
            [NotNull] SolutionModel solutionModel,
            [NotNull] SettingsModel settingsModel,
            [NotNull] ISolution solution,
            [NotNull] IShellLocks locks,
            [NotNull] ChangeManager changeManager,
            [NotNull] DocumentToProjectFileMappingStorage documentToProjectFileMappingStorage,
            [NotNull] IFileSystemTracker fileSystemTracker,
            [NotNull] ILogger logger)
            : base(lifetime, solutionModel, settingsModel, solution, locks, changeManager,
                documentToProjectFileMappingStorage, fileSystemTracker, logger)
        {
            myLogger = logger;
        }

        public override void SaveDocumentAfterModification(IDocument document, bool forceSaveOpenDocuments)
        {
            Locks.Dispatcher.AssertAccess();

            if (forceSaveOpenDocuments)
            {
                var projectFile = DocumentToProjectFileMappingStorage.TryGetProjectFile(document);
                var isUnitySharedProjectFile = projectFile != null
                                               && projectFile.IsShared()
                                               && projectFile.GetProject().IsUnityProject();
                if (isUnitySharedProjectFile)
                {
                    myLogger.Info($"Trying to save document {document.Moniker}. Force = true");
                    myLogger.Verbose("File is shared and contained in Unity project. Skip saving.");
                    return;
                }
            }

            base.SaveDocumentAfterModification(document, forceSaveOpenDocuments);
        }
    }
}

Fix autosave and refresh on shared projects


// Copyright 2013 J.C. Moyer
//
// 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 Newtonsoft.Json;

namespace Yeena.PathOfExile {
    [JsonObject]
    public class PoEStashTabInfo {
        [JsonProperty("n")] private readonly string _name;
        [JsonProperty("i")] private readonly int _index;
        // colour { r, g, b }
        // src

        public string Name {
            get { return _name; }
        }

        public int Index {
            get { return _index; }
        }
    }
}

Add missing file for named tabs

Add missing file for named tabs


namespace MassTransit.Tests
{
    using System;
    using System.Threading.Tasks;
    using MassTransit.Testing;
    using Microsoft.Extensions.DependencyInjection;
    using Middleware;
    using NUnit.Framework;
    using TestFramework.Messages;

    [TestFixture]
    public class Using_a_request_filter_with_request_client
    {
        [Test]
        public async Task Should_fault_instead_of_timeout()
        {
            await using var provider = new ServiceCollection()
                .AddMassTransitTestHarness(x =>
                {
                    x.AddConsumer<PingConsumer>();

                    x.UsingInMemory((context, cfg) =>
                    {
                        cfg.UseConsumeFilter(typeof(RequestValidationScopedFilter<>), context);

                        cfg.ConfigureEndpoints(context);
                    });
                })
                .BuildServiceProvider(true);

            var harness = provider.GetTestHarness();

            harness.TestInactivityTimeout = TimeSpan.FromSeconds(1);

            await harness.Start();

            IRequestClient<PingMessage> client = harness.GetRequestClient<PingMessage>();

            Assert.That(async () =>
                await client.GetResponse<PongMessage>(new
                {
                    CorrelationId = InVar.Id,
                }), Throws.TypeOf<RequestFaultException>());
        }

        public class PingConsumer :
            IConsumer<PingMessage>
        {
            public Task Consume(ConsumeContext<PingMessage> context)
            {
                return context.RespondAsync(new PongMessage(context.Message.CorrelationId));
            }
        }

        public class RequestValidationScopedFilter<T> :
            IFilter<ConsumeContext<T>>
            where T : class
        {
            public void Probe(ProbeContext context)
            {
                context.CreateFilterScope("RequestValidationScopedFilter<TMessage> scope");
            }

            public async Task Send(ConsumeContext<T> context, IPipe<ConsumeContext<T>> next)
            {
                try
                {
                    throw new IntentionalTestException("Failed to validate request");
                }
                catch (Exception exception)
                {
                    await context.NotifyFaulted(context.ReceiveContext.ElapsedTime, TypeCache<RequestValidationScopedFilter<T>>.ShortName, exception)
                        .ConfigureAwait(false);

                    throw;
                }
            }
        }
    }
}

Verify NotifyFault called will properly fail a filter execution


using System;

namespace CompetitionPlatform.Models
{
    public class Initiative
    {
        public string FirstName { get; set; }
        public string ProjectId { get; set; }
        public DateTime ProjectCreatedDate { get; set; }
        public string ProjectAuthorName { get; set; }
        public string ProjectName { get; set; }
        public string ProjectStatus { get; set; }
        public string ProjectDescription { get; set; }
        public double ProjectFirstPrize { get; set; }
        public double ProjectSecondPrize { get; set; }
    }

    public class Competition
    {
        public string FirstName { get; set; }
        public string ProjectId { get; set; }
        public DateTime ProjectCreatedDate { get; set; }
        public DateTime ProjectCompetitionDeadline { get; set; }
        public string ProjectAuthorName { get; set; }
        public string ProjectName { get; set; }
        public string ProjectStatus { get; set; }
        public string ProjectDescription { get; set; }
        public double ProjectFirstPrize { get; set; }
        public double ProjectSecondPrize { get; set; }
    }

    public class Implementation
    {
        public string FirstName { get; set; }
        public string ProjectId { get; set; }
        public DateTime ProjectCreatedDate { get; set; }
        public DateTime ProjectImplementationDeadline { get; set; }
        public string ProjectAuthorName { get; set; }
        public string ProjectName { get; set; }
        public string ProjectStatus { get; set; }
        public string ProjectDescription { get; set; }
        public double ProjectFirstPrize { get; set; }
        public double ProjectSecondPrize { get; set; }
    }

    public class Voting
    {
        public string FirstName { get; set; }
        public string ProjectId { get; set; }
        public DateTime ProjectCreatedDate { get; set; }
        public DateTime ProjectVotingDeadline { get; set; }
        public string ProjectAuthorName { get; set; }
        public string ProjectName { get; set; }
        public string ProjectStatus { get; set; }
        public string ProjectDescription { get; set; }
        public double ProjectFirstPrize { get; set; }
        public double ProjectSecondPrize { get; set; }
    }
}

Add models for notification emails.

Add models for notification emails.


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

using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.UI.Scrolling;
using osuTK;

namespace osu.Game.Rulesets.Catch.Edit
{
    /// <summary>
    /// Utility functions used by the editor.
    /// </summary>
    public static class CatchHitObjectUtils
    {
        /// <summary>
        /// Get the position of the hit object in the playfield based on <see cref="CatchHitObject.OriginalX"/> and <see cref="HitObject.StartTime"/>.
        /// </summary>
        public static Vector2 GetStartPosition(ScrollingHitObjectContainer hitObjectContainer, CatchHitObject hitObject)
        {
            return new Vector2(hitObject.OriginalX, hitObjectContainer.PositionAtTime(hitObject.StartTime));
        }
    }
}

Add a function to compute hit object position in catch editor


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using Microsoft.Kinect;
using System.IO;

namespace MultipleKinectsPlatform.MultipleKinectsPlatform.Data
{
    [DataContract(Name="Skeleton")]
    public class Skeleton
    {
        [DataMember(Name="Joints")]
        public List<Joint> Joints;

        [DataMember]
        public float pos_x;

        [DataMember]
        public float pos_y;

        [DataMember]
        public float pos_z;

        public Skeleton(List<Joint> givenJoints,float i_x,float i_y,float i_z)
        {
            Joints = givenJoints;
            pos_x = i_x;
            pos_y = i_y;
            pos_z = i_z;
        }

        public static List<Skeleton> ConvertKinectSkeletons(Microsoft.Kinect.Skeleton[] obtainedSkeletons)
        {
            List<Skeleton> convertedSkeletons = new List<Skeleton>();

            foreach (Microsoft.Kinect.Skeleton skeleton in obtainedSkeletons)
            {
                /* Get all joints of the skeleton */

                List<Joint> convertedJoints = new List<Joint>();

                foreach (Microsoft.Kinect.Joint joint in skeleton.Joints)
                {
                    SkeletonPoint points  = joint.Position;

                    MultipleKinectsPlatform.Data.Joint convertedJoint = new MultipleKinectsPlatform.Data.Joint(points.X,points.Y,points.Z);

                    convertedJoints.Add(convertedJoint);
                }

                /* Get the position of the skeleton */

                SkeletonPoint skeletonPos = skeleton.Position;

                MultipleKinectsPlatform.Data.Skeleton convertedSkeleton = new Skeleton(convertedJoints,skeletonPos.X,skeletonPos.Y,skeletonPos.Z);

                convertedSkeletons.Add(convertedSkeleton);
            }

            return convertedSkeletons;
        }

        public static string ConvertToJSON(List<MultipleKinectsPlatform.Data.Skeleton> skeletonsToBeSerialise)
        {
            MemoryStream memStream = new MemoryStream();

            DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(List<MultipleKinectsPlatform.Data.Skeleton>));

            jsonSer.WriteObject(memStream, skeletonsToBeSerialise);

            string json = System.Text.Encoding.UTF8.GetString(memStream.GetBuffer(), 0, Convert.ToInt32(memStream.Length));

            return json;
        }
    }
}

Add a new datatype for skeletons

Add a new datatype for skeletons


using System;
using GamesWithGravitas.Extensions;
using Xunit;

namespace GamesWithGravitas
{
    public class NotifyPropertyChangedBaseTests
    {
        [Theory]
        [InlineData("Foo")]
        [InlineData("Bar")]
        public void SettingAPropertyWorks(string propertyValue)
        {
            var notifier = new Notifier();
            var listener = notifier.ListenForPropertyChanged(nameof(Notifier.StringProperty));

            notifier.StringProperty = propertyValue;

            Assert.Equal(propertyValue, notifier.StringProperty);
            Assert.True(listener.AllTrue);
        }

        [Theory]
        [InlineData("Foo")]
        [InlineData("Bar")]
        public void SettingADependentPropertyWorks(string propertyValue)
        {
            var notifier = new Notifier();
            var listener = notifier.ListenForPropertyChanged(nameof(Notifier.DependentProperty), nameof(Notifier.DerivedProperty));

            notifier.DependentProperty = propertyValue;

            Assert.Equal(propertyValue, notifier.DependentProperty);
            Assert.Equal(propertyValue + "!", notifier.DerivedProperty);
            Assert.True(listener.AllTrue);
        }
    }

    public class Notifier : NotifyPropertyChangedBase
    {
        private string _stringProperty;
        public string StringProperty
        {
            get => _stringProperty;
            set => SetProperty(ref _stringProperty, value);
        }

        private string _dependentProperty;
        public string DependentProperty
        {
            get => _dependentProperty;
            set => SetProperty(ref _dependentProperty, value, otherProperties: nameof(DerivedProperty));
        }

        public string DerivedProperty => DependentProperty + "!";
    }
}

Add some simple test cases for SetProperty.


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

namespace osu.Game.Rulesets.Mods
{
    /// <summary>
    /// Represents a mod which can override (and block) a fail.
    /// </summary>
    public interface IApplicableRestartOnFail : IApplicableMod
    {
        /// <summary>
        /// Whether we allow restarting
        /// </summary>
        bool AllowRestart { get; }
    }
}

Add new interface that allows restarts

Add new interface that allows restarts


// 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.Threading;
using NUnit.Framework;
using osu.Framework.IO.Stores;
using osu.Framework.Threading;

namespace osu.Framework.Tests.Audio
{
    /// <remarks>
    /// This unit will ALWAYS SKIP if the system does not have a physical audio device!!!
    /// A physical audio device is required to simulate the "loss" of it during playback.
    /// </remarks>
    [TestFixture]
    public class DeviceLosingAudioTest
    {
        private AudioThread thread;
        private NamespacedResourceStore<byte[]> store;
        private AudioManagerWithDeviceLoss manager;

        [SetUp]
        public void SetUp()
        {
            thread = new AudioThread();
            store = new NamespacedResourceStore<byte[]>(new DllResourceStore(@"osu.Framework.Tests.dll"), @"Resources");

            manager = new AudioManagerWithDeviceLoss(thread, store, store);

            thread.Start();

            // wait for any device to be initialized
            manager.WaitForDeviceChange(-1);

            // if the initialized device is "No sound", it indicates that no other physical devices are available, so this unit should be ignored
            if (manager.CurrentDevice == 0)
                Assert.Ignore("Physical audio devices are required for this unit.");

            // we don't want music playing in unit tests :)
            manager.Volume.Value = 0;
        }

        [TearDown]
        public void TearDown()
        {
            Assert.IsFalse(thread.Exited);

            thread.Exit();

            Thread.Sleep(500);

            Assert.IsTrue(thread.Exited);
        }

        [Test]
        public void TestPlaybackWithDeviceLoss() => testPlayback(manager.SimulateDeviceRestore, manager.SimulateDeviceLoss);

        [Test]
        public void TestPlaybackWithDeviceRestore() => testPlayback(manager.SimulateDeviceLoss, manager.SimulateDeviceRestore);

        private void testPlayback(Action preparation, Action simulate)
        {
            preparation();

            var track = manager.Tracks.Get("Tracks.sample-track.mp3");

            // start track
            track.Restart();

            Thread.Sleep(100);

            Assert.IsTrue(track.IsRunning);
            Assert.That(track.CurrentTime, Is.GreaterThan(0));

            var timeBeforeLosing = track.CurrentTime;

            // simulate change (loss/restore)
            simulate();

            Assert.IsTrue(track.IsRunning);

            Thread.Sleep(100);

            // playback should be continuing after device change
            Assert.IsTrue(track.IsRunning);
            Assert.That(track.CurrentTime, Is.GreaterThan(timeBeforeLosing));

            // stop track
            track.Stop();

            Thread.Sleep(100);

            Assert.IsFalse(track.IsRunning);

            // seek track
            track.Seek(0);

            Thread.Sleep(100);

            Assert.IsFalse(track.IsRunning);
            Assert.AreEqual(track.CurrentTime, 0);
        }
    }
}

Add tests for losing audio devices

Add tests for losing audio devices


using Amadevus.RecordGenerator.TestsBase;
using Xunit;

namespace Amadevus.RecordGenerator.Test
{
    public class RecordClassTests : RecordTestsBase
    {
        [Fact]
        public void ReflectedClass_HasNo_RecordAttribute()
        {
            var recordType = typeof(Item);

            var recordAttributes = recordType.GetCustomAttributes(typeof(RecordAttribute), false);

            Assert.Empty(recordAttributes);
        }
    }
}

Add test that asserts records don't have RecordAttribute in reflection


public class DifficultyHandler : BaseBehaviour {

	private int difficultyLevel;

	void OnSetDifficulty(int difficulty)
	{
		switch (difficulty)
		{
			case NORMAL:
				EventKit.Broadcast("set difficulty damage modifier", 1);
				break;
			case HARD:
				EventKit.Broadcast("set difficulty damage modifier", 2);
				break;
			case EPIC:
				EventKit.Broadcast("set difficulty damage modifier", 3);
				break;
		}
	}

	void OnEnable()
	{
		EventKit.Subscribe<int>("set difficulty", OnSetDifficulty);
	}

	void OnDestroy()
	{
		EventKit.Unsubscribe<int>("set difficulty", OnSetDifficulty);
	}
}

Update to use EventKit messaging

Update to use EventKit messaging


using Windows.UI.Xaml.Controls;

namespace WeatherDataReporter
{
    public sealed partial class MainPage : Page
    {
        static string iotHubUri = "{replace}";
        static string deviceKey = "{replace}";
        static string deviceId = "{replace}";
    }
}

Move connection strings to separate file


using System;
using System.Runtime.InteropServices;

namespace PepperSharp
{
    public partial struct PPCompletionCallback
    {

        public PPCompletionCallback(PPCompletionCallbackFunc func)
        {
            this.func = func;
            this.user_data = IntPtr.Zero;
            this.flags = (int)PPCompletionCallbackFlag.None;
        }

        public PPCompletionCallback(PPCompletionCallbackFunc func, object userData)
        {
            this.func = func;
            if (userData == null)
                this.user_data = IntPtr.Zero;
            else
            {
                GCHandle userHandle = GCHandle.Alloc(userData);
                this.user_data = (IntPtr)userHandle;
            }
            this.flags = (int)PPCompletionCallbackFlag.None;
        }

        public static object GetUserDataAsObject(IntPtr userData)
        {
            if (userData == IntPtr.Zero)
                return null;

            // back to object (in callback function):
            GCHandle userDataHandle = (GCHandle)userData;
            return userDataHandle.Target as object;

        }

        public static T GetUserData<T>(IntPtr userData)
        {
            if (userData == IntPtr.Zero)
                return default(T);

            GCHandle userDataHandle = (GCHandle)userData;
            return (T)userDataHandle.Target;

        }

    }
}

Add partial implementation to PPCompletionCallback

- Add constructors which make it easier to create callback functions to be used.
- Add static helper methods for working with user data that is passed around with the callback
+ public static object GetUserDataAsObject(IntPtr userData)
+ public static T GetUserData<T>(IntPtr userData)


using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace Tera.Analytics
{
    public static class DataCenterExtensions
    {
        private static XStreamingElement ToXStreamingElement(DataCenterElement element)
        {
            var xElement = new XStreamingElement(element.Name);
            xElement.Add(element.Attributes.Select(attribute => new XAttribute(attribute.Name, attribute.Value)));
            xElement.Add(element.Children.Select(ToXStreamingElement));
            return xElement;
        }

        /// <summary>
        ///     Exports the content of the specified element in XML format.
        /// </summary>
        /// <param name="element">The element to export.</param>
        /// <param name="outputPath">The path of the file that will contain the exported content.</param>
        public static void Export(this DataCenterElement element, string outputPath)
        {
            var xElement = ToXStreamingElement(element);
            using (var file = File.CreateText(outputPath))
            {
                xElement.Save(file);
            }
        }

        /// <summary>
        ///     Exports the contents of the Data Center in XML format.
        /// </summary>
        /// <param name="dataCenter">The Data Center to export.</param>
        /// <param name="outputPath">The path of the directory that will contain the exported content.</param>
        public static void Export(this DataCenter dataCenter, string outputPath)
        {
            var directory = Directory.CreateDirectory(outputPath);
            var groups = dataCenter.Root.Children.GroupBy(child => child.Name);
            foreach (var group in groups)
                if (group.Count() > 1)
                {
                    var groupDirectory = directory.CreateSubdirectory(group.Key);
                    var elementsAndFileNames = group.Select((element, index) => new
                    {
                        element,
                        fileName = $"{element.Name}_{index}.xml"
                    });
                    foreach (var o in elementsAndFileNames)
                    {
                        var fileName = Path.Combine(groupDirectory.FullName, o.fileName);
                        o.element.Export(fileName);
                    }
                }
                else
                {
                    var element = group.Single();
                    var fileName = Path.Combine(directory.FullName, $"{element.Name}.xml");
                    element.Export(fileName);
                }
        }
    }
}

Add extension methods to export the Data Center's content.


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

using NUnit.Framework;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osuTK.Input;

namespace osu.Game.Tests.Visual.Editing
{
    /// <summary>
    /// Test editor hotkeys at a high level to ensure they all work well together.
    /// </summary>
    public class TestSceneEditorBindings : EditorTestScene
    {
        protected override Ruleset CreateEditorRuleset() => new OsuRuleset();

        [Test]
        public void TestBeatDivisorChangeHotkeys()
        {
            AddStep("hold shift", () => InputManager.PressKey(Key.LShift));

            AddStep("press 4", () => InputManager.Key(Key.Number4));
            AddAssert("snap updated to 4", () => EditorBeatmap.BeatmapInfo.BeatDivisor, () => Is.EqualTo(4));

            AddStep("press 6", () => InputManager.Key(Key.Number6));
            AddAssert("snap updated to 6", () => EditorBeatmap.BeatmapInfo.BeatDivisor, () => Is.EqualTo(6));

            AddStep("release shift", () => InputManager.ReleaseKey(Key.LShift));
        }
    }
}

Add top level test coverage of editor shortcuts


using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;

namespace Tgstation.Server.Host.Core.Tests
{
	[TestClass]
	public sealed class TestApplication
	{
		[TestMethod]
		public void TestMethodThrows()
		{
			Assert.ThrowsException<ArgumentNullException>(() => new Application(null, null));
			var mockConfiguration = new Mock<IConfiguration>();
			Assert.ThrowsException<ArgumentNullException>(() => new Application(mockConfiguration.Object, null));

			var mockHostingEnvironment = new Mock<IHostingEnvironment>();

			var app = new Application(mockConfiguration.Object, mockHostingEnvironment.Object);

			Assert.ThrowsException<ArgumentNullException>(() => app.ConfigureServices(null));
			Assert.ThrowsException<ArgumentNullException>(() => app.Configure(null, null, null));

			var mockAppBuilder = new Mock<IApplicationBuilder>();
			Assert.ThrowsException<ArgumentNullException>(() => app.Configure(mockAppBuilder.Object, null, null));

			var mockLogger = new Mock<ILogger<Application>>();
			Assert.ThrowsException<ArgumentNullException>(() => app.Configure(mockAppBuilder.Object, mockLogger.Object, null));
		}
	}
}

Add a basic application test

Add a basic application test


// http://careercup.com/question?id=5693863291256832
//
// Rearrange chars in a String so that no adjacent chars repeat
//

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

static class Program
{
    static Random random = new Random();

    static String Rearrange(this String s)
    {
        return null;
    }

    static String GenerateString()
    {
        return String.Join(String.Empty, Enumerable.Repeat(0, random.Next(20, 30)).Select(x => (char)random.Next('a', 'z')));
    }

    static void Main()
    {
        for (int i = 0; i < 10; i++)
        {
            String s = GenerateString();
            String p = s.Rearrange();
            Console.WriteLine("{0} = {1}", s, p == null? "Not possible" : p);
        }
    }
}

Rearrange chars - prep work

Rearrange chars - prep work


// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.

namespace Narvalo.Finance
{
    using System.Globalization;

    public static class RegionInfoExtensions
    {
        public static bool IsUsing(this RegionInfo @this, Currency currency)
        {
            Require.NotNull(@this, nameof(@this));

            return @this.ISOCurrencySymbol == currency.Code;
        }

        public static bool IsUsing<TCurrency>(this RegionInfo @this, TCurrency currency)
            where TCurrency : CurrencyUnit<TCurrency>
        {
            Require.NotNull(@this, nameof(@this));

            return @this.ISOCurrencySymbol == currency.Code;
        }
    }
}

Add two extensions for RegionInfo.

Add two extensions for RegionInfo.


using Newtonsoft.Json;

namespace CompetitionPlatform.Helpers
{
    public static class NotificationMessageHelper
    {
        public static string ProjectCreatedMessage(string userEmail, string userName, string projectName)
        {
            var messageData = new MessageData
            {
                Subject = "New Project Created - " + projectName,
                Text = "User " + userName + " (" + userEmail + ") " + "Has Created a new project - " + projectName
            };

            var data = new Data
            {
                BroadcastGroup = 600,
                MessageData = messageData
            };

            var plainTextBroadCast = new PlainTextBroadcast { Data = data };

            return "PlainTextBroadcast:" + JsonConvert.SerializeObject(plainTextBroadCast);
        }
    }

    public class PlainTextBroadcast
    {
        public Data Data { get; set; }
    }

    public class Data
    {
        public int BroadcastGroup { get; set; }
        public MessageData MessageData { get; set; }
    }

    public class MessageData
    {
        public string Subject { get; set; }
        public string Text { get; set; }
    }
}

Add a helper class to compose broadcasted messages.


namespace AngleSharp.Core.Tests.Io
{
    using AngleSharp.Io;
    using NUnit.Framework;

    [TestFixture]
    public class MimeTypeNameTests
    {
        [Test]
        public void CommonMimeTypesAreCorrectlyDefined()
        {
            Assert.AreEqual("image/avif", MimeTypeNames.FromExtension(".avif"));
            Assert.AreEqual("image/gif", MimeTypeNames.FromExtension(".gif"));
            Assert.AreEqual("image/jpeg", MimeTypeNames.FromExtension(".jpeg"));
            Assert.AreEqual("image/jpeg", MimeTypeNames.FromExtension(".jpg"));
            Assert.AreEqual("image/png", MimeTypeNames.FromExtension(".png"));
            Assert.AreEqual("image/svg+xml", MimeTypeNames.FromExtension(".svg"));
            Assert.AreEqual("image/webp", MimeTypeNames.FromExtension(".webp"));
        }
    }
}

Add test coverage for common mime types

Add test coverage for common mime types


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

namespace MartinCostello.LondonTravel.Site.Models
{
    using MartinCostello.LondonTravel.Site.Options;
    using Shouldly;
    using Xunit;

    /// <summary>
    /// A class containing unit tests for the <see cref="MetaModel"/> class.
    /// </summary>
    public static class MetaModelTests
    {
        [Fact]
        public static void MetaModel_Create_Handles_Null_Options()
        {
            // Arrange
            var options = null as MetadataOptions;

            // Act
            MetaModel actual = MetaModel.Create(options);

            // Assert
            actual.ShouldNotBeNull();
        }

        [Fact]
        public static void MetaModel_Create_Handles_Null_Author()
        {
            // Arrange
            var options = new MetadataOptions();

            // Act
            MetaModel actual = MetaModel.Create(options);

            // Assert
            actual.ShouldNotBeNull();
        }
    }
}

Add unit tests for MetaModel

Add unit tests for MetaModel

Add very basic unit tests for null handling in MetaModel.Create().


using AutoMapper;
using Diploms.Core;
using Diploms.Dto.Departments;

namespace Diploms.Services.Departments
{
    public class DepartmentsMappings : Profile
    {
        public DepartmentsMappings()
        {
            CreateMap<DepartmentEditDto, Department>();
        }
    }
}

Add mapping profile for departments

Add mapping profile for departments


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

namespace BitCommitment
{
    /// <summary>
    /// A class to perform bit commitment. It does not care what the input is; it's just a
    /// facility for exchanging bit commitment messages.
    /// </summary>
    public class BitCommitmentEngine
    {
        #region properties

        public Byte[] BobRandBytesR { get; set; }
        public Byte[] AliceEncryptedMessage { get; set; }

        #endregion
    }
}

Add separate facility for bit commitment


using System;
using System.Text;
using System.Threading.Tasks;
using Confluent.Kafka;
using Confluent.Kafka.SyncOverAsync;
using Newtonsoft.Json;

namespace Jasper.ConfluentKafka.Serialization
{
    internal class DefaultJsonSerializer<T> : IAsyncSerializer<T>
    {
        public Task<byte[]> SerializeAsync(T data, SerializationContext context)
        {
            var json = JsonConvert.SerializeObject(data);
            return Task.FromResult(Encoding.UTF8.GetBytes(json));
        }

        public ISerializer<T> AsSyncOverAsync()
        {
            return new SyncOverAsyncSerializer<T>(this);
        }
    }

    internal class DefaultJsonDeserializer<T> : IAsyncDeserializer<T>
    {
        public IDeserializer<T> AsSyncOverAsync()
        {
            return new SyncOverAsyncDeserializer<T>(this);
        }

        public Task<T> DeserializeAsync(ReadOnlyMemory<byte> data, bool isNull, SerializationContext context)
        {
            return Task.FromResult(JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(data.ToArray())));
        }
    }
}

Add a basic kafka serilaizer

Add a basic kafka serilaizer


using System;
using System.Threading;
using System.Threading.Tasks;
using Binance.WebSocket;
using Xunit;

namespace Binance.Tests.WebSocket
{
    public class DefaultWebSocketClientTest
    {
        [Fact]
        public async Task Throws()
        {
            var uri = new Uri("wss://stream.binance.com:9443");

            var client = new DefaultWebSocketClient();

            using (var cts = new CancellationTokenSource())
            {
                await Assert.ThrowsAsync<ArgumentNullException>("uri", () => client.StreamAsync(null, cts.Token));
                await Assert.ThrowsAsync<ArgumentException>("token", () => client.StreamAsync(uri, CancellationToken.None));
            }
        }

        [Fact]
        public async Task StreamAsync()
        {
            var uri = new Uri("wss://stream.binance.com:9443");

            var client = new DefaultWebSocketClient();

            using (var cts = new CancellationTokenSource())
            {
                cts.Cancel();
                await client.StreamAsync(uri, cts.Token);
            }
        }
    }
}

Add default web socket client unit tests


using System;
using System.Runtime.InteropServices;

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

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

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

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

        // set parameters
        [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern int SetProducerNameServerAddress(IntPtr producer, string nameServer);

        [DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
        public static extern int SetProducerLogPath(IntPtr producer, string logPath);

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

        //send
        [DllImport(ConstValues.RocketMQDriverDllName,CallingConvention = CallingConvention.Cdecl)]
        public static extern int SendMessageSync(IntPtr producer, IntPtr message, [Out]out CSendResult result);
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct CSendResult
    {
        public int sendStatus;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
        public string msgId;

        public long offset;
    }

    public enum CLogLevel
    {
        E_LOG_LEVEL_FATAL = 1,
        E_LOG_LEVEL_ERROR = 2,
        E_LOG_LEVEL_WARN = 3,
        E_LOG_LEVEL_INFO = 4,
        E_LOG_LEVEL_DEBUG = 5,
        E_LOG_LEVEL_TRACE = 6,
        E_LOG_LEVEL_LEVEL_NUM = 7
    }
}

Add the producer wrap to donet

Add the producer wrap to donet


namespace NBench.VisualStudio.TestAdapter
{
    using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
    using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
    using System;
    using System.Collections.Generic;

    public class NBenchTestDiscoverer : ITestDiscoverer
    {
        public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
        {
            throw new NotImplementedException();
        }
    }
}

Add the NBench visual studio test adapter project.


using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class TextureTilingController : MonoBehaviour {

	// Give us the texture so that we can scale proportianally the width according to the height variable below
	// We will grab it from the meshRenderer
	//public Texture texture;
	//public float textureToMeshZ = 2f; // Use this to contrain texture to a certain size

	//Vector3 prevScale = Vector3.one;
	//float prevTextureToMeshZ = -1f;

	// Use this for initialization
	void Start () {
		//this.prevScale = gameObject.transform.lossyScale;
		//this.prevTextureToMeshZ = this.textureToMeshZ;

		this.UpdateTiling();
	}

	// Update is called once per frame
	void Update () {
		// If something has changed
		//if(gameObject.transform.lossyScale != prevScale || !Mathf.Approximately(this.textureToMeshZ, prevTextureToMeshZ))
			this.UpdateTiling();

		// Maintain previous state variables
		//this.prevScale = gameObject.transform.lossyScale;
		//this.prevTextureToMeshZ = this.textureToMeshZ;
	}

	[ContextMenu("UpdateTiling")]
	void UpdateTiling()
	{
		// A Unity plane is 10 units x 10 units
		//float planeSizeX = gameObject.renderer.material.mainTextureScale.x;
		//float planeSizeZ = gameObject.renderer.material.mainTextureScale.y;

		// Figure out texture-to-mesh width based on user set texture-to-mesh height
		//float textureToMeshX = ((float)this.texture.width/this.texture.height)*this.textureToMeshZ;

		// gameObject.renderer.material.SetTextureScale ("", new Vector2 (1.0f .x, 1.0f / gameObject.transform.lossyScale.z));
		gameObject.renderer.sharedMaterial.mainTextureScale = gameObject.transform.lossyScale * -1;
		//transform.renderer.material.mainTextureScale = new Vector2(XScale , YScale );
		// gameObject.renderer.material.mainTextureScale = new Vector2(1.0f,1.0f);
	}
}

Add script for fixing tecture scaling

Add script for fixing tecture scaling