using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace PickemApp
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode,
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using PickemApp.Models;
using PickemApp.Migrations;

namespace PickemApp
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode,
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<PickemDBContext, Configuration>());

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }
    }
}

Enable migrations on app start

Enable migrations on app start


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace Portfolio
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace Portfolio
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // Runs Code First database update on each restart...
            // handy for deploy via GitHub.
            #if !DEBUG
                var migrator = new DbMigrator(new Configuration());
                migrator.Update();
            #endif
        }
    }
}

Enable CF migrations on restart

Enable CF migrations on restart


using System;
using DemoDistributor.Endpoints.FileSystem;
using DemoDistributor.Endpoints.Sharepoint;
using Delivered;

namespace DemoDistributor
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            //Configure the distributor
            var distributor = new Distributor<File, Vendor>();
            //distributor.RegisterEndpointRepository(new FileSystemEndpointRepository());
            distributor.RegisterEndpointRepository(new SharepointEndpointRepository());
            distributor.RegisterEndpointDeliveryService(new FileSystemDeliveryService());
            distributor.RegisterEndpointDeliveryService(new SharepointDeliveryService());
            distributor.MaximumConcurrentDeliveries(3);

            //Distribute a file to a vendor
            try
            {
                var task = distributor.DistributeAsync(FakeFile, FakeVendor);
                task.Wait();

                Console.WriteLine("\nDistribution succeeded.");
            }
            catch(AggregateException aggregateException)
            {
                Console.WriteLine("\nDistribution failed.");

                foreach (var exception in aggregateException.Flatten().InnerExceptions)
                {
                    Console.WriteLine($"* {exception.Message}");
                }
            }

            Console.WriteLine("\nPress enter to exit.");

            Console.ReadLine();
        }

        private static File FakeFile => new File
        {
            Name = @"test.pdf",
            Contents = new byte[1024]
        };

        private static Vendor FakeVendor => new Vendor
        {
            Name = @"Mark's Pool Supplies"
        };

        private static Vendor FakeVendor2 => new Vendor
        {
            Name = @"Kevin's Art Supplies"
        };
    }
}

using System;
using DemoDistributor.Endpoints.FileSystem;
using DemoDistributor.Endpoints.Sharepoint;
using Delivered;

namespace DemoDistributor
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            //Configure the distributor
            var distributor = new Distributor<File, Vendor>();
            distributor.RegisterEndpointRepository(new FileSystemEndpointRepository());
            distributor.RegisterEndpointRepository(new SharepointEndpointRepository());
            distributor.RegisterEndpointDeliveryService(new FileSystemDeliveryService());
            distributor.RegisterEndpointDeliveryService(new SharepointDeliveryService());
            distributor.MaximumConcurrentDeliveries(3);

            //Distribute a file to a vendor
            try
            {
                var task = distributor.DistributeAsync(FakeFile, FakeVendor);
                task.Wait();

                Console.WriteLine("\nDistribution succeeded.");
            }
            catch(AggregateException aggregateException)
            {
                Console.WriteLine("\nDistribution failed.");

                foreach (var exception in aggregateException.Flatten().InnerExceptions)
                {
                    Console.WriteLine($"* {exception.Message}");
                }
            }

            Console.WriteLine("\nPress enter to exit.");

            Console.ReadLine();
        }

        private static File FakeFile => new File
        {
            Name = @"test.pdf",
            Contents = new byte[1024]
        };

        private static Vendor FakeVendor => new Vendor
        {
            Name = @"Mark's Pool Supplies"
        };

        private static Vendor FakeVendor2 => new Vendor
        {
            Name = @"Kevin's Art Supplies"
        };
    }
}

Fix demo by uncommenting line accidentally left commented


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Battlezeppelins.Models;

namespace Battlezeppelins.Controllers
{
    public abstract class BaseController : Controller
    {
        private static List<Player> playerList = new List<Player>();

        public Player GetPlayer()
        {
            if (Request.Cookies["userInfo"] != null)
            {
                string idStr = Server.HtmlEncode(Request.Cookies["userInfo"]["id"]);
                int id = Int32.Parse(idStr);

                Player player = SearchPlayer(id);
                if (player != null) return player;

                lock (playerList)
                {
                    player = SearchPlayer(id);
                    if (player != null) return player;

                    Player newPlayer = Player.GetInstance(id);
                    playerList.Add(newPlayer);
                    return newPlayer;
                }
            }
            return null;
        }

        private Player SearchPlayer(int id)
        {
            if (!playerList.Any()) return null;

            foreach (Player listPlayer in playerList) {
                if (listPlayer.id == id) {
                    return listPlayer;
                }
            }
            return null;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Battlezeppelins.Models;

namespace Battlezeppelins.Controllers
{
    public abstract class BaseController : Controller
    {
        private static List<Player> playerList = new List<Player>();

        public Player GetPlayer()
        {
            if (Request.Cookies["userInfo"] != null)
            {
                string idStr = Server.HtmlEncode(Request.Cookies["userInfo"]["id"]);
                int id = Int32.Parse(idStr);

                Player player = SearchPlayer(id);
                if (player != null) return player;

                lock (playerList)
                {
                    player = SearchPlayer(id);
                    if (player != null) return player;

                    Player newPlayer = Player.GetInstance(id);
                    if (newPlayer != null) playerList.Add(newPlayer);
                    return newPlayer;
                }
            }
            return null;
        }

        private Player SearchPlayer(int id)
        {
            if (!playerList.Any()) return null;

            foreach (Player listPlayer in playerList) {
                if (listPlayer.id == id) {
                    return listPlayer;
                }
            }
            return null;
        }
    }
}

Fix null players in player list.

Fix null players in player list.


using System.Windows.Controls;

namespace PlantUmlEditor.View
{
    public partial class DiagramEditorView : UserControl
    {
        public DiagramEditorView()
        {
            InitializeComponent();
        }
    }
}

using System;
using System.Windows.Controls;

namespace PlantUmlEditor.View
{
    public partial class DiagramEditorView : UserControl
    {
        public DiagramEditorView()
        {
            InitializeComponent();

			ContentEditor.IsEnabledChanged += ContentEditor_IsEnabledChanged;
        }

		void ContentEditor_IsEnabledChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
		{
			// Maintain focus on the text editor.
			if ((bool)e.NewValue)
				Dispatcher.BeginInvoke(new Action(() => ContentEditor.Focus()));
		}
    }
}

Maintain focus on the text editor after saving.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using Caliburn.Micro;

namespace SharpGraphEditor.ViewModels
{
    public class TextViewerViewModel : PropertyChangedBase
    {
        private string _text;
        private bool _canCopy;
        private bool _canCancel;
        private bool _isReadOnly;

        public TextViewerViewModel(string text, bool canCopy, bool canCancel, bool isReadOnly)
        {
            Text = text;
            CanCopy = CanCopy;
            CanCancel = canCancel;
            IsReadOnly = isReadOnly;
        }

        public void Ok(IClose closableWindow)
        {
            closableWindow.TryClose(true);
        }

        public void Cancel(IClose closableWindow)
        {
            closableWindow.TryClose(false);
        }

        public void CopyText()
        {
            Clipboard.SetText(Text);
        }

        public string Text
        {
            get { return _text; }
            set
            {
                _text = value;
                NotifyOfPropertyChange(() => Text);
            }
        }

        public bool CanCopy
        {
            get { return _canCopy; }
            set
            {
                _canCopy = value;
                NotifyOfPropertyChange(() => CanCopy);
            }
        }

        public bool CanCancel
        {
            get { return _canCancel; }
            set
            {
                _canCancel = value;
                NotifyOfPropertyChange(() => CanCancel);
            }
        }

        public bool IsReadOnly
        {
            get { return _isReadOnly; }
            set
            {
                _isReadOnly = value;
                NotifyOfPropertyChange(() => IsReadOnly);
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using Caliburn.Micro;

namespace SharpGraphEditor.ViewModels
{
    public class TextViewerViewModel : PropertyChangedBase
    {
        private string _text;
        private bool _canCopy;
        private bool _canCancel;
        private bool _isReadOnly;

        public TextViewerViewModel(string text, bool canCopy, bool canCancel, bool isReadOnly)
        {
            Text = text;
            CanCopy = canCopy;
            CanCancel = canCancel;
            IsReadOnly = isReadOnly;
        }

        public void Ok(IClose closableWindow)
        {
            closableWindow.TryClose(true);
        }

        public void Cancel(IClose closableWindow)
        {
            closableWindow.TryClose(false);
        }

        public void CopyText()
        {
            Clipboard.SetText(Text);
        }

        public string Text
        {
            get { return _text; }
            set
            {
                _text = value;
                NotifyOfPropertyChange(() => Text);
            }
        }

        public bool CanCopy
        {
            get { return _canCopy; }
            set
            {
                _canCopy = value;
                NotifyOfPropertyChange(() => CanCopy);
            }
        }

        public bool CanCancel
        {
            get { return _canCancel; }
            set
            {
                _canCancel = value;
                NotifyOfPropertyChange(() => CanCancel);
            }
        }

        public bool IsReadOnly
        {
            get { return _isReadOnly; }
            set
            {
                _isReadOnly = value;
                NotifyOfPropertyChange(() => IsReadOnly);
            }
        }
    }
}

Fix bug: "Copy" button don't show in TextView during saving


// 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 UIKit;

namespace osu.iOS
{
    public class Application
    {
        public static void Main(string[] args)
        {
            UIApplication.Main(args, null, "AppDelegate");
        }
    }
}

// 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 UIKit;

namespace osu.iOS
{
    public class Application
    {
        public static void Main(string[] args)
        {
            UIApplication.Main(args, "GameUIApplication", "AppDelegate");
        }
    }
}

Fix iOS app entry for raw keyboard input


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

namespace Mindscape.Raygun4Net.Breadcrumbs
{
  internal class HttpBreadcrumbStorage : IRaygunBreadcrumbStorage
  {
    private const string ItemsKey = "Raygun.Breadcrumbs.Storage";

    public IEnumerator<RaygunBreadcrumb> GetEnumerator()
    {
      return GetList().GetEnumerator();
    }

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

    public void Store(RaygunBreadcrumb breadcrumb)
    {
      GetList().Add(breadcrumb);
    }

    public void Clear()
    {
      GetList().Clear();
    }

    private List<RaygunBreadcrumb> GetList()
    {
      SetupStorage();

      return (List<RaygunBreadcrumb>) HttpContext.Current.Items[ItemsKey];
    }

    private void SetupStorage()
    {
      if (HttpContext.Current != null && !HttpContext.Current.Items.Contains(ItemsKey))
      {
        HttpContext.Current.Items[ItemsKey] = new List<RaygunBreadcrumb>();
      }
    }
  }
}

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

namespace Mindscape.Raygun4Net.Breadcrumbs
{
  internal class HttpBreadcrumbStorage : IRaygunBreadcrumbStorage
  {
    private const string ItemsKey = "Raygun.Breadcrumbs.Storage";

    public IEnumerator<RaygunBreadcrumb> GetEnumerator()
    {
      return GetList().GetEnumerator();
    }

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

    public void Store(RaygunBreadcrumb breadcrumb)
    {
      GetList().Add(breadcrumb);
    }

    public void Clear()
    {
      GetList().Clear();
    }

    private List<RaygunBreadcrumb> GetList()
    {
      if (HttpContext.Current == null)
      {
        return new List<RaygunBreadcrumb>();
      }

      SetupStorage();

      return (List<RaygunBreadcrumb>) HttpContext.Current.Items[ItemsKey];
    }

    private void SetupStorage()
    {
      if (HttpContext.Current != null && !HttpContext.Current.Items.Contains(ItemsKey))
      {
        HttpContext.Current.Items[ItemsKey] = new List<RaygunBreadcrumb>();
      }
    }
  }
}

Return empty list if HttpContext.Current is null


using RimWorld;
using Verse;

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

namespace MTW_AncestorSpirits
{
    class RoomRoleWorker_ShrineRoom : RoomRoleWorker
    {
        public override float GetScore(Room room)
        {
            // I don't know if there should be some "If it's full of joy objects/work benches, *don't* classify it as
            // a Shrine - if you Shrine room wall gets broken down by a bug, this will probably push all the attached
            // rooms into the "Shrine Room" - is that a desired behaviour?

            Thing shrine = room.AllContainedThings.FirstOrDefault<Thing>(t => t is Building_Shrine);
            if (shrine == null)
            {
                return 0.0f;
            }
            else
            {
                return 9999.0f;
            }
        }
    }
}

using RimWorld;
using Verse;

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

namespace MTW_AncestorSpirits
{
    class RoomRoleWorker_ShrineRoom : RoomRoleWorker
    {
        public override float GetScore(Room room)
        {
            // I don't know if there should be some "If it's full of joy objects/work benches, *don't* classify it as
            // a Shrine - if you Shrine room wall gets broken down by a bug, this will probably push all the attached
            // rooms into the "Shrine Room" - is that a desired behaviour?

            var shrine = Find.Map.GetComponent<MapComponent_AncestorTicker>().CurrentSpawner;
            if (room.AllContainedThings.Contains<Thing>(shrine))
            {
                return 9999.0f;
            }
            else
            {
                return 0.0f;
            }
        }
    }
}

Fix ShrineRoom to always be current spawner


// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file

using EOLib.Data.Protocol;
using Microsoft.Practices.Unity;

namespace EOLib.Net.Translators
{
	public class PacketTranslatorContainer : IDependencyContainer
	{
		public void RegisterDependencies(IUnityContainer container)
		{
			container.RegisterType<IPacketTranslator<IInitializationData>, InitDataTranslator>();
		}
	}
}

// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file

using EOLib.Data.Login;
using EOLib.Data.Protocol;
using Microsoft.Practices.Unity;

namespace EOLib.Net.Translators
{
	public class PacketTranslatorContainer : IDependencyContainer
	{
		public void RegisterDependencies(IUnityContainer container)
		{
			container.RegisterType<IPacketTranslator<IInitializationData>, InitDataTranslator>();
			container.RegisterType<IPacketTranslator<IAccountLoginData>, AccountLoginPacketTranslator>();
		}
	}
}

Add IoC registration for login data translator


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Yio.Utilities;

namespace Yio
{
    public class Program
    {
        private static int _port { get; set; }

        public static void Main(string[] args)
        {
            Console.OutputEncoding = System.Text.Encoding.Unicode;

            StartupUtilities.WriteStartupMessage(StartupUtilities.GetRelease(), ConsoleColor.Cyan);

            if (!File.Exists("appsettings.json")) {
                StartupUtilities.WriteFailure("configuration is missing");
                Environment.Exit(1);
            }

            StartupUtilities.WriteInfo("setting port");
            if(args == null || args.Length == 0)
            {
                _port = 5100;
                StartupUtilities.WriteSuccess("port set to " + _port + " (default)");
            }
            else
            {
                _port = args[0] == null ? 5100 : Int32.Parse(args[0]);
                StartupUtilities.WriteSuccess("port set to " + _port + " (user defined)");
            }

            StartupUtilities.WriteInfo("starting App");
            BuildWebHost(args).Run();

            Console.ResetColor();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseUrls("http://0.0.0.0:" + _port.ToString() + "/")
                .UseStartup<Startup>()
                .Build();
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Yio.Utilities;

namespace Yio
{
    public class Program
    {
        private static int _port { get; set; }

        public static void Main(string[] args)
        {
            Console.OutputEncoding = System.Text.Encoding.Unicode;

            StartupUtilities.WriteStartupMessage(StartupUtilities.GetRelease(), ConsoleColor.Cyan);

            if (!File.Exists("appsettings.json")) {
                StartupUtilities.WriteFailure("configuration is missing");
                Environment.Exit(1);
            }

            StartupUtilities.WriteInfo("setting port");
            if(args == null || args.Length == 0)
            {
                _port = 5100;
                StartupUtilities.WriteSuccess("port set to " + _port + " (default)");
            }
            else
            {
                _port = args[0] == null ? 5100 : Int32.Parse(args[0]);
                StartupUtilities.WriteSuccess("port set to " + _port + " (user defined)");
            }

            StartupUtilities.WriteInfo("starting App");
            BuildWebHost().Run();

            Console.ResetColor();
        }

        public static IWebHost BuildWebHost() =>
            WebHost.CreateDefaultBuilder()
                .UseUrls("http://0.0.0.0:" + _port.ToString() + "/")
                .UseStartup<Startup>()
                .Build();
    }
}

Fix port in arguments crashing app

Fix port in arguments crashing app


using System;

namespace MarcelloDB.Helpers
{
    internal class DataHelper
    {
        internal static void CopyData(
            Int64 sourceAddress,
            byte[] sourceData,
            Int64 targetAddress,
            byte[] targetData)
        {
            var lengthToCopy = sourceData.Length;
            var sourceIndex = 0;
            var targetIndex = 0;

            if (sourceAddress < targetAddress)
            {
                sourceIndex = (int)(targetAddress - sourceAddress);
                lengthToCopy = sourceData.Length - sourceIndex;
            }

            if (sourceAddress > targetAddress)
            {
                targetIndex = (int)(sourceAddress - targetAddress);
                lengthToCopy = targetData.Length - targetIndex;
            }

            //max length to copy to not overrun the target array
            lengthToCopy = Math.Min(lengthToCopy, targetData.Length - targetIndex);
            //max length to copy to not overrrude the source array
            lengthToCopy = Math.Min(lengthToCopy, sourceData.Length - sourceIndex);

            if (lengthToCopy > 0)
            {
                Array.Copy(sourceData, sourceIndex, targetData, targetIndex, lengthToCopy);
            }

        }
    }
}

using System;

namespace MarcelloDB.Helpers
{
    internal class DataHelper
    {
        internal static void CopyData(
            Int64 sourceAddress,
            byte[] sourceData,
            Int64 targetAddress,
            byte[] targetData)
        {
            Int64 lengthToCopy = sourceData.Length;
            Int64 sourceIndex = 0;
            Int64 targetIndex = 0;

            if (sourceAddress < targetAddress)
            {
                sourceIndex = (targetAddress - sourceAddress);
                lengthToCopy = sourceData.Length - sourceIndex;
            }

            if (sourceAddress > targetAddress)
            {
                targetIndex = (sourceAddress - targetAddress);
                lengthToCopy = targetData.Length - targetIndex;
            }

            //max length to copy to not overrun the target array
            lengthToCopy = Math.Min(lengthToCopy, targetData.Length - targetIndex);
            //max length to copy to not overrrun the source array
            lengthToCopy = Math.Min(lengthToCopy, sourceData.Length - sourceIndex);

            if (lengthToCopy > 0)
            {
                Array.Copy(sourceData, (int)sourceIndex, targetData, (int)targetIndex, (int)lengthToCopy);
            }

        }
    }
}

Fix integer overflow on large collection files


using System.Html.Media;
using System.Runtime.CompilerServices;

namespace System.Html {
	public partial class Navigator {
		[InlineCode("(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozUserMedia || navigator.msGetUserMedia)({params}, {onsuccess})")]
		public static void GetUserMedia(MediaStreamOptions @params, Action<LocalMediaStream> onsuccess) {}

		[InlineCode("(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozUserMedia || navigator.msGetUserMedia)({params}, {onsuccess}, {onerror})")]
		public static void GetUserMedia(MediaStreamOptions @params, Action<LocalMediaStream> onsuccess, Action<string> onerror) {}
	}
}

using System.Html.Media;
using System.Runtime.CompilerServices;

namespace System.Html {
	public partial class Navigator {
		[InlineCode("(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia).call(navigator, {params}, {onsuccess})")]
		public static void GetUserMedia(MediaStreamOptions @params, Action<LocalMediaStream> onsuccess) {}

		[InlineCode("(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia).call(navigator, {params}, {onsuccess}, {onerror})")]
		public static void GetUserMedia(MediaStreamOptions @params, Action<LocalMediaStream> onsuccess, Action<string> onerror) {}
	}
}

Fix navigator.getUserMedia webkit(TypeError: Illegal invocation) + moz(typo)


using System;
using System.IO;
using System.Collections;

namespace DeviceMetadataInstallTool
{
    /// <summary>
    /// see https://support.microsoft.com/en-us/kb/303974
    /// </summary>
    class MetadataFinder
    {
        public System.Collections.Generic.List<String> Files = new System.Collections.Generic.List<String>();

        public void SearchDirectory(string dir)
        {
            try
            {
                foreach (var d in Directory.GetDirectories(dir))
                {
                    foreach (var f in Directory.GetFiles(d, "*.devicemetadata-ms"))
                    {
                        Files.Add(f);
                    }
                    SearchDirectory(d);
                }
            }
            catch (System.Exception excpt)
            {
                Console.WriteLine(excpt.Message);
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var files = new System.Collections.Generic.List<String>();
            //Console.WriteLine("Args size is {0}", args.Length);
            if (args.Length == 0)
            {
                var assemblyDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                var finder = new MetadataFinder();
                finder.SearchDirectory(assemblyDir);
                files = finder.Files;
            } else
            {
                files.AddRange(files);
            }

            var store = new Sensics.DeviceMetadataInstaller.MetadataStore();

            foreach (var fn in files)
            {
                var pkg = new Sensics.DeviceMetadataInstaller.MetadataPackage(fn);
                Console.WriteLine("{0} - {1} - Default locale: {2}", pkg.ExperienceGUID, pkg.ModelName, pkg.DefaultLocale);
                store.InstallPackage(pkg);
            }
        }
    }
}

using System;
using System.IO;
using System.Collections;

namespace DeviceMetadataInstallTool
{

    class Program
    {
        static void Main(string[] args)
        {
            var files = new System.Collections.Generic.List<String>();
            //Console.WriteLine("Args size is {0}", args.Length);
            if (args.Length == 0)
            {
                var assemblyDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                files = Sensics.DeviceMetadataInstaller.Util.GetMetadataFilesRecursive(assemblyDir);
            }
            else
            {
                files.AddRange(args);
            }

            var store = new Sensics.DeviceMetadataInstaller.MetadataStore();

            foreach (var fn in files)
            {
                var pkg = new Sensics.DeviceMetadataInstaller.MetadataPackage(fn);
                Console.WriteLine("{0} - {1} - Default locale: {2}", pkg.ExperienceGUID, pkg.ModelName, pkg.DefaultLocale);
                store.InstallPackage(pkg);
            }
        }
    }
}

Use glob-recurse and fix the program when you pass it file names


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

namespace osu.Framework.Platform.Linux
{
    using Native;

    public class LinuxGameHost : DesktopGameHost
    {
        internal LinuxGameHost(string gameName, bool bindIPC = false)
            : base(gameName, bindIPC)
        {
            Window = new LinuxGameWindow();
            Window.WindowStateChanged += (sender, e) =>
            {
                if (Window.WindowState != OpenTK.WindowState.Minimized)
                    OnActivated();
                else
                    OnDeactivated();
            };

            Library.Load("libbass.so", Library.LoadFlags.RTLD_LAZY | Library.LoadFlags.RTLD_GLOBAL);
        }

        protected override Storage GetStorage(string baseName) => new LinuxStorage(baseName, this);

        public override Clipboard GetClipboard() => new LinuxClipboard();
    }
}

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

using osu.Framework.Platform.Linux.Native;

namespace osu.Framework.Platform.Linux
{
    public class LinuxGameHost : DesktopGameHost
    {
        internal LinuxGameHost(string gameName, bool bindIPC = false)
            : base(gameName, bindIPC)
        {
            Window = new LinuxGameWindow();
            Window.WindowStateChanged += (sender, e) =>
            {
                if (Window.WindowState != OpenTK.WindowState.Minimized)
                    OnActivated();
                else
                    OnDeactivated();
            };

            Library.Load("libbass.so", Library.LoadFlags.RTLD_LAZY | Library.LoadFlags.RTLD_GLOBAL);
        }

        protected override Storage GetStorage(string baseName) => new LinuxStorage(baseName, this);

        public override Clipboard GetClipboard() => new LinuxClipboard();
    }
}

Use more standard namespace formatting

Use more standard namespace formatting


using System.IO;
using OpenSage.Network;

namespace OpenSage.Data.Sav
{
    internal static class GameStateMap
    {
        internal static void Load(SaveFileReader reader, Game game)
        {
            reader.ReadVersion(2);

            var mapPath1 = reader.ReadAsciiString();
            var mapPath2 = reader.ReadAsciiString();
            var gameType = reader.ReadEnum<GameType>();

            var mapSize = reader.BeginSegment();

            // TODO: Delete this temporary map when ending the game.
            var mapPathInSaveFolder = Path.Combine(
                game.ContentManager.UserMapsFileSystem.RootDirectory,
                mapPath1);
            using (var mapOutputStream = File.OpenWrite(mapPathInSaveFolder))
            {
                reader.ReadBytesIntoStream(mapOutputStream, (int)mapSize);
            }

            reader.EndSegment();

            var unknown2 = reader.ReadUInt32(); // 586
            var unknown3 = reader.ReadUInt32(); // 3220

            if (gameType == GameType.Skirmish)
            {
                game.SkirmishManager = new LocalSkirmishManager(game);
                game.SkirmishManager.Settings.Load(reader);

                game.SkirmishManager.Settings.MapName = mapPath1;

                game.SkirmishManager.StartGame();
            }
            else
            {
                game.StartSinglePlayerGame(mapPathInSaveFolder);
            }
        }
    }
}

using System.IO;
using OpenSage.Network;

namespace OpenSage.Data.Sav
{
    internal static class GameStateMap
    {
        internal static void Load(SaveFileReader reader, Game game)
        {
            reader.ReadVersion(2);

            var mapPath1 = reader.ReadAsciiString();
            var mapPath2 = reader.ReadAsciiString();
            var gameType = reader.ReadEnum<GameType>();

            var mapSize = reader.BeginSegment();

            // TODO: Delete this temporary map when ending the game.
            var mapPathInSaveFolder = Path.Combine(
                game.ContentManager.UserMapsFileSystem.RootDirectory,
                mapPath1);
            using (var mapOutputStream = File.OpenWrite(mapPathInSaveFolder))
            {
                reader.ReadBytesIntoStream(mapOutputStream, (int)mapSize);
            }

            reader.EndSegment();

            var unknown2 = reader.ReadUInt32(); // 586
            var unknown3 = reader.ReadUInt32(); // 3220

            if (gameType == GameType.Skirmish)
            {
                game.SkirmishManager = new LocalSkirmishManager(game);
                game.SkirmishManager.Settings.Load(reader);

                game.SkirmishManager.Settings.MapName = mapPath1;

                game.SkirmishManager.StartGame();
            }
            else
            {
                game.StartSinglePlayerGame(mapPath1);
            }
        }
    }
}

Fix map path for single player maps

Fix map path for single player maps


namespace Papyrus
{
    public static class EBookExtensions
    {

    }
}

using System;
using System.Threading.Tasks;
using Windows.Storage;

namespace Papyrus
{
    public static class EBookExtensions
    {
        public static async Task<bool> VerifyMimetypeAsync(this EBook ebook)
        {
            var mimetypeFile = await ebook._rootFolder.GetItemAsync("mimetype");

            if (mimetypeFile == null)                                           // Make sure file exists.
                return false;

            var fileContents = await FileIO.ReadTextAsync(mimetypeFile as StorageFile);

            if (fileContents != "application/epub+zip")                         // Make sure file contents are correct.
                return false;

            return true;
        }
    }
}

Add extension to verify mimetype.

Add extension to verify mimetype.


using System.Collections.Generic;
using System.Net;
using AppGet.Http;
using NLog;

namespace AppGet.PackageRepository
{
    public class AppGetServerClient : IPackageRepository
    {
        private readonly IHttpClient _httpClient;
        private readonly Logger _logger;
        private readonly HttpRequestBuilder _requestBuilder;

        private const string API_ROOT = "https://appget.net/api/v1/";

        public AppGetServerClient(IHttpClient httpClient, Logger logger)
        {
            _httpClient = httpClient;
            _logger = logger;

            _requestBuilder = new HttpRequestBuilder(API_ROOT);
        }

        public PackageInfo GetLatest(string name)
        {
            _logger.Info("Getting package " + name);

            var request = _requestBuilder.Build("packages/{package}/latest");
            request.AddSegment("package", name);

            try
            {
                var package = _httpClient.Get<PackageInfo>(request);
                return package.Resource;
            }
            catch (HttpException ex)
            {
                if (ex.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    return null;
                }
                throw;
            }
        }

        public List<PackageInfo> Search(string term)
        {
            _logger.Info("Searching for " + term);

            var request = _requestBuilder.Build("packages");

            request.UriBuilder.SetQueryParam("q", term.Trim());

            var package = _httpClient.Get<List<PackageInfo>>(request);
            return package.Resource;
        }
    }
}

using System.Collections.Generic;
using System.Net;
using AppGet.Http;
using NLog;

namespace AppGet.PackageRepository
{
    public class AppGetServerClient : IPackageRepository
    {
        private readonly IHttpClient _httpClient;
        private readonly Logger _logger;
        private readonly HttpRequestBuilder _requestBuilder;

        private const string API_ROOT = "https://appget.azurewebsites.net/v1/";

        public AppGetServerClient(IHttpClient httpClient, Logger logger)
        {
            _httpClient = httpClient;
            _logger = logger;

            _requestBuilder = new HttpRequestBuilder(API_ROOT);
        }

        public PackageInfo GetLatest(string name)
        {
            _logger.Info("Getting package " + name);

            var request = _requestBuilder.Build("packages/{package}/latest");
            request.AddSegment("package", name);

            try
            {
                var package = _httpClient.Get<PackageInfo>(request);
                return package.Resource;
            }
            catch (HttpException ex)
            {
                if (ex.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    return null;
                }
                throw;
            }
        }

        public List<PackageInfo> Search(string term)
        {
            _logger.Info("Searching for " + term);

            var request = _requestBuilder.Build("packages");

            request.UriBuilder.SetQueryParam("q", term.Trim());

            var package = _httpClient.Get<List<PackageInfo>>(request);
            return package.Resource;
        }
    }
}

Use azure hosted server for now

Use azure hosted server for now


using NUnit.Framework;
using System.Collections.Generic;

namespace FunWithNewtonsoft
{
    [TestFixture]
    public class ListTests
    {
        [Test]
        public void Deserialize_PartialList_ReturnsList()
        {
            // Assemble
            string json = @"
                {'Number':'1','Letter':'A'},
                {'Number':'2','Letter':'B'},
                {'Number':'3','Letter':'C'},";

            // Act
            List<Data> actual = null;

            // Assert
            Assert.AreEqual(1, actual[0].Number);
            Assert.AreEqual("A", actual[0].Letter);

            Assert.AreEqual(2, actual[1].Number);
            Assert.AreEqual("B", actual[1].Letter);

            Assert.AreEqual(3, actual[2].Number);
            Assert.AreEqual("C", actual[2].Letter);
        }
    }
}

using Newtonsoft.Json;
using NUnit.Framework;
using System.Collections.Generic;

namespace FunWithNewtonsoft
{
    [TestFixture]
    public class ListTests
    {
        [Test]
        public void DeserializeObject_JsonList_ReturnsList()
        {
            // Assemble
            string json = @"
                [
                    {'Number':'1','Letter':'A'},
                    {'Number':'2','Letter':'B'},
                    {'Number':'3','Letter':'C'}
                ]";

            // Act
            List<Data> actual = JsonConvert.DeserializeObject<List<Data>>(json);

            // Assert
            Assert.AreEqual(1, actual[0].Number);
            Assert.AreEqual("A", actual[0].Letter);

            Assert.AreEqual(2, actual[1].Number);
            Assert.AreEqual("B", actual[1].Letter);

            Assert.AreEqual(3, actual[2].Number);
            Assert.AreEqual("C", actual[2].Letter);
        }

        [Test]
        public void DeserializeObject_MissingSquareBracesAroundJsonList_Throws()
        {
            // Assemble
            string json = @"
                    {'Number':'1','Letter':'A'},
                    {'Number':'2','Letter':'B'},
                    {'Number':'3','Letter':'C'}";

            // Act
            Assert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<List<Data>>(json));
        }

        [Test]
        public void DeserializeObject_TrailingCommaAtEndOfJsonList_ReturnsList()
        {
            // Assemble
            string json = @"
                [
                    {'Number':'1','Letter':'A'},
                    {'Number':'2','Letter':'B'},
                    {'Number':'3','Letter':'C'},
                ]";

            // Act
            List<Data> actual = JsonConvert.DeserializeObject<List<Data>>(json);

            // Assert
            Assert.AreEqual(1, actual[0].Number);
            Assert.AreEqual("A", actual[0].Letter);

            Assert.AreEqual(2, actual[1].Number);
            Assert.AreEqual("B", actual[1].Letter);

            Assert.AreEqual(3, actual[2].Number);
            Assert.AreEqual("C", actual[2].Letter);
        }
    }
}

Add tests for json lists.

Add tests for json lists.


using System.Collections.Generic;
using System.Linq;
using GekkoAssembler.IntermediateRepresentation;

namespace GekkoAssembler.Optimizers
{
    public class IRMultiUnitOptimizer : IOptimizer
    {
        public IRCodeBlock Optimize(IRCodeBlock block)
        {
            var units = block.Units;

            var newUnits = units
                .Select(x => x is IRCodeBlock ? Optimize(x as IRCodeBlock) : x)
                .SelectMany(x => x is IRMultiUnit ? (x as IRMultiUnit).Inner : (IEnumerable<IIRUnit>)new[] { x });

            return new IRCodeBlock(newUnits);
        }
    }
}

using System.Collections.Generic;
using System.Linq;
using GekkoAssembler.IntermediateRepresentation;

namespace GekkoAssembler.Optimizers
{
    public class IRMultiUnitOptimizer : IOptimizer
    {
        public IRCodeBlock Optimize(IRCodeBlock block)
        {
            var units = block.Units;

            var newUnits = units
                .SelectMany(x => x is IRMultiUnit ? (x as IRMultiUnit).Inner : (IEnumerable<IIRUnit>)new[] { x })
                .Select(x => x is IRCodeBlock ? Optimize(x as IRCodeBlock) : x);

            return new IRCodeBlock(newUnits);
        }
    }
}

Change the Order for Inlining Multi Units


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

using System;
using osu.Framework.Graphics.Sprites;
using osu.Game.Overlays.Dialog;

namespace osu.Game.Collections
{
    public class DeleteCollectionDialog : PopupDialog
    {
        public DeleteCollectionDialog(BeatmapCollection collection, Action deleteAction)
        {
            HeaderText = "Confirm deletion of";
            BodyText = collection.Name.Value;

            Icon = FontAwesome.Regular.TrashAlt;

            Buttons = new PopupDialogButton[]
            {
                new PopupDialogOkButton
                {
                    Text = @"Yes. Go for it.",
                    Action = deleteAction
                },
                new PopupDialogCancelButton
                {
                    Text = @"No! Abort mission!",
                },
            };
        }
    }
}

// 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 Humanizer;
using osu.Framework.Graphics.Sprites;
using osu.Game.Overlays.Dialog;

namespace osu.Game.Collections
{
    public class DeleteCollectionDialog : PopupDialog
    {
        public DeleteCollectionDialog(BeatmapCollection collection, Action deleteAction)
        {
            HeaderText = "Confirm deletion of";
            BodyText = $"{collection.Name.Value} ({"beatmap".ToQuantity(collection.Beatmaps.Count)})";

            Icon = FontAwesome.Regular.TrashAlt;

            Buttons = new PopupDialogButton[]
            {
                new PopupDialogOkButton
                {
                    Text = @"Yes. Go for it.",
                    Action = deleteAction
                },
                new PopupDialogCancelButton
                {
                    Text = @"No! Abort mission!",
                },
            };
        }
    }
}

Add count to deletion dialog

Add count to deletion dialog


using UnityEngine;

public class Planet : MonoBehaviour {
    [SerializeField]
    private float _radius;

    public float Radius {
        get { return _radius; }
        set { _radius = value; }
    }

    public float Permieter {
        get { return 2 * Mathf.PI * Radius; }
    }

    public void SampleOrbit2D( float angle,
                               float distance,
                               out Vector3 position,
                               out Vector3 normal ) {

        // Polar to cartesian coordinates
        float x = Mathf.Cos( angle ) * distance;
        float y = Mathf.Sin( angle ) * distance;

        Vector3 dispalcement = new Vector3( x, 0, y );
        Vector3 center = transform.position;
        position = center + dispalcement;
        normal = dispalcement.normalized;
    }
}

using UnityEngine;

public class Planet : MonoBehaviour {
    [SerializeField]
    private float _radius;

    public float Radius {
        get { return _radius; }
        set { _radius = value; }
    }

    public float Permieter {
        get { return 2 * Mathf.PI * Radius; }
    }

    public void SampleOrbit2D( float angle,
                               float distance,
                               out Vector3 position,
                               out Vector3 normal ) {

        angle = angle * Mathf.Deg2Rad;

        // Polar to cartesian coordinates
        float x = Mathf.Cos( angle ) * distance;
        float y = Mathf.Sin( angle ) * distance;

        Vector3 dispalcement = new Vector3( x, 0, y );
        Vector3 center = transform.position;
        position = center + dispalcement;
        normal = dispalcement.normalized;
    }
}

Change orbit angles to degree

Change orbit angles to degree


using System;

namespace ExternalTemplates
{
	/// <summary>
	/// Default generator options.
	/// </summary>
	public class GeneratorOptions : IGeneratorOptions
	{
		/// <summary>
		/// Gets the path relative to the web root where the templates are stored.
		/// Default is "/Content/templates".
		/// </summary>
		public string VirtualPath { get; set; }

		/// <summary>
		/// Gets the extension of the templates.
		/// Default is ".tmpl.html".
		/// </summary>
		public string Extension { get; set; }

		/// <summary>
		/// Gets the post string to add to the end of the script tag's id following its name.
		/// Default is "-tmpl".
		/// </summary>
		public string PostString { get; set; }
	}
}

using System;

namespace ExternalTemplates
{
	/// <summary>
	/// Default generator options.
	/// </summary>
	public class GeneratorOptions : IGeneratorOptions
	{
		/// <summary>
		/// Gets the path relative to the web root where the templates are stored.
		/// Default is "/Content/templates".
		/// </summary>
		public string VirtualPath { get; set; } = "/Content/templates";

		/// <summary>
		/// Gets the extension of the templates.
		/// Default is ".tmpl.html".
		/// </summary>
		public string Extension { get; set; } = ".tmpl.html";

		/// <summary>
		/// Gets the post string to add to the end of the script tag's id following its name.
		/// Default is "-tmpl".
		/// </summary>
		public string PostString { get; set; } = "-tmpl";
	}
}

Add the defaults for GeneratorOptions

Add the defaults for GeneratorOptions


using FluentMigrator.Runner.Generators.Generic;

namespace FluentMigrator.Runner.Generators.MySql
{
    public class MySqlQuoter : GenericQuoter
    {
        public override string OpenQuote { get { return "`"; } }

        public override string CloseQuote { get { return "`"; } }

        public override string QuoteValue(object value)
        {
            return base.QuoteValue(value).Replace(@"\", @"\\");
        }

        public override string FromTimeSpan(System.TimeSpan value)
        {
            return System.String.Format("{0}{1}:{2}:{3}.{4}{0}"
                , ValueQuote
                , value.Hours + (value.Days * 24)
                , value.Minutes
                , value.Seconds
                , value.Milliseconds);
        }
    }
}

using FluentMigrator.Runner.Generators.Generic;

namespace FluentMigrator.Runner.Generators.MySql
{
    public class MySqlQuoter : GenericQuoter
    {
        public override string OpenQuote { get { return "`"; } }

        public override string CloseQuote { get { return "`"; } }

        public override string QuoteValue(object value)
        {
            return base.QuoteValue(value).Replace(@"\", @"\\");
        }

        public override string FromTimeSpan(System.TimeSpan value)
        {
            return System.String.Format("{0}{1:00}:{2:00}:{3:00}{0}"
                , ValueQuote
                , value.Hours + (value.Days * 24)
                , value.Minutes
                , value.Seconds);
        }
    }
}

Fix MySql do not support Milliseconds

Fix MySql do not support Milliseconds


using System;
using Dominion.Rules;
using Dominion.Rules.Activities;
using Dominion.Rules.CardTypes;

namespace Dominion.Cards.Actions
{
    public class Chancellor : Card, IActionCard
    {
        public Chancellor() : base(3)
        {
        }

        public void Play(TurnContext context)
        {
            context.MoneyToSpend += 2;
            context.AddEffect(new ChancellorEffect());
        }

        public class ChancellorEffect : CardEffectBase
        {
            public override void Resolve(TurnContext context)
            {
                _activities.Add(new ChancellorActivity(context.Game.Log, context.ActivePlayer, "Do you wish to put your deck into your discard pile?"));
            }

            public class ChancellorActivity : YesNoChoiceActivity
            {
                public ChancellorActivity(IGameLog log, Player player, string message)
                    : base(log, player, message)
                {
                }

                public override void Execute(bool choice)
                {
                    if (choice)
                    {
                        Log.LogMessage("{0} put his deck in his discard pile", Player.Name);
                        this.Player.Deck.MoveAll(this.Player.Discards);
                    }
                }
            }
        }

    }
}

using System;
using Dominion.Rules;
using Dominion.Rules.Activities;
using Dominion.Rules.CardTypes;

namespace Dominion.Cards.Actions
{
    public class Chancellor : Card, IActionCard
    {
        public Chancellor() : base(3)
        {
        }

        public void Play(TurnContext context)
        {
            context.MoneyToSpend += 2;
            context.AddEffect(new ChancellorEffect());
        }

        public class ChancellorEffect : CardEffectBase
        {
            public override void Resolve(TurnContext context)
            {
                if(context.ActivePlayer.Deck.CardCount > 0)
                    _activities.Add(new ChancellorActivity(context.Game.Log, context.ActivePlayer, "Do you wish to put your deck into your discard pile?"));
            }

            public class ChancellorActivity : YesNoChoiceActivity
            {
                public ChancellorActivity(IGameLog log, Player player, string message)
                    : base(log, player, message)
                {
                }

                public override void Execute(bool choice)
                {
                    if (choice)
                    {
                        Log.LogMessage("{0} put his deck in his discard pile", Player.Name);
                        this.Player.Deck.MoveAll(this.Player.Discards);
                    }
                }
            }
        }

    }
}

Stop chancellor from prompting the player when they have no cards in their deck.


using System;
using System.Collections.Specialized;
using Xunit;

namespace GV.AspNet.Configuration.ConfigurationManager.UnitTests
{
	public class AppSettingsConfigurationProviderTests
	{
		[Theory]
		[InlineData("Key1", "Value1")]
		[InlineData("Key2", "Value2")]
		public void LoadsKeyValuePairsFromAppSettings(string key, string value)
		{
			var appSettings = new NameValueCollection { { key, value } };
			var source = new AppSettingsConfigurationProvider(appSettings, ":", string.Empty);

			source.Load();

			string outValue;
			Assert.True(source.TryGet(key, out outValue));
			Assert.Equal(value, outValue);
		}
	}
}

using System;
using System.Collections.Specialized;
using Microsoft.Extensions.Configuration;
using Xunit;

namespace GV.AspNet.Configuration.ConfigurationManager.UnitTests
{
	public class AppSettingsConfigurationProviderTests
	{
		public class Load
		{
			[Theory]
			[InlineData("", "Value")]
			[InlineData("Key", "Value")]
			public void AddsAppSettings(string key, string value)
			{
				var appSettings = new NameValueCollection { { key, value } };
				var keyDelimiter = Constants.KeyDelimiter;
				var keyPrefix = string.Empty;
				var source = new AppSettingsConfigurationProvider(appSettings, keyDelimiter, keyPrefix);

				source.Load();

				string configurationValue;
				Assert.True(source.TryGet(key, out configurationValue));
				Assert.Equal(value, configurationValue);
			}

			[Theory]
			[InlineData("Parent.Key", "", "Parent.Key", "Value")]
			[InlineData("Parent.Key", ".", "Parent:Key", "Value")]
			public void ReplacesKeyDelimiter(string appSettingsKey, string keyDelimiter, string configurationKey, string value)
			{
				var appSettings = new NameValueCollection { { appSettingsKey, value } };
				var keyPrefix = string.Empty;
				var source = new AppSettingsConfigurationProvider(appSettings, keyDelimiter, keyPrefix);

				source.Load();

				string configurationValue;
				Assert.True(source.TryGet(configurationKey, out configurationValue));
				Assert.Equal(value, configurationValue);
			}
		}
	}
}

Add support for custom key delimiter

Add support for custom key delimiter


using System.Linq;
using Bugsnag.Payload;
using Xunit;

namespace Bugsnag.Tests.Payload
{
  public class ExceptionTests
  {
    [Fact]
    public void CorrectNumberOfExceptions()
    {
      var exception = new System.Exception("oh noes!");

      var exceptions = new Exceptions(exception, 5);

      Assert.Single(exceptions);
    }

    [Fact]
    public void IncludeInnerExceptions()
    {
      var innerException = new System.Exception();
      var exception = new System.Exception("oh noes!", innerException);

      var exceptions = new Exceptions(exception, 5);

      Assert.Equal(2, exceptions.Count());
    }
  }
}

using System.Linq;
using System.Threading.Tasks;
using Bugsnag.Payload;
using Xunit;

namespace Bugsnag.Tests.Payload
{
  public class ExceptionTests
  {
    [Fact]
    public void CorrectNumberOfExceptions()
    {
      var exception = new System.Exception("oh noes!");

      var exceptions = new Exceptions(exception, 5);

      Assert.Single(exceptions);
    }

    [Fact]
    public void IncludeInnerExceptions()
    {
      var innerException = new System.Exception();
      var exception = new System.Exception("oh noes!", innerException);

      var exceptions = new Exceptions(exception, 5);

      Assert.Equal(2, exceptions.Count());
    }

    [Fact]
    public void HandleAggregateExceptions()
    {
      Exceptions exceptions = null;
      var exceptionsToThrow = new[] { new System.Exception(), new System.DllNotFoundException() };
      var tasks = exceptionsToThrow.Select(e => Task.Run(() => { throw e; })).ToArray();

      try
      {
        Task.WaitAll(tasks);
      }
      catch (System.Exception exception)
      {
        exceptions = new Exceptions(exception, 0);
      }

      var results = exceptions.ToArray();

      Assert.Contains(results, exception => exception.ErrorClass == "System.DllNotFoundException");
      Assert.Contains(results, exception => exception.ErrorClass == "System.Exception");
      Assert.Contains(results, exception => exception.ErrorClass == "System.AggregateException");
    }
  }
}

Test for aggregate exception handling

Test for aggregate exception handling


using Umbraco.Core;
using Umbraco.Core.Components;

namespace Umbraco.Web.Routing
{
    /// <summary>
    /// Implements an Application Event Handler for managing redirect urls tracking.
    /// </summary>
    /// <remarks>
    /// <para>when content is renamed or moved, we want to create a permanent 301 redirect from it's old url</para>
    /// <para>not managing domains because we don't know how to do it - changing domains => must create a higher level strategy using rewriting rules probably</para>
    /// <para>recycle bin = moving to and from does nothing: to = the node is gone, where would we redirect? from = same</para>
    /// </remarks>
    [RuntimeLevel(MinLevel = RuntimeLevel.Run)]
    public class RedirectTrackingComposer : ComponentComposer<RelateOnCopyComponent>, ICoreComposer
    { }
}

using Umbraco.Core;
using Umbraco.Core.Components;

namespace Umbraco.Web.Routing
{
    /// <summary>
    /// Implements an Application Event Handler for managing redirect urls tracking.
    /// </summary>
    /// <remarks>
    /// <para>when content is renamed or moved, we want to create a permanent 301 redirect from it's old url</para>
    /// <para>not managing domains because we don't know how to do it - changing domains => must create a higher level strategy using rewriting rules probably</para>
    /// <para>recycle bin = moving to and from does nothing: to = the node is gone, where would we redirect? from = same</para>
    /// </remarks>
    [RuntimeLevel(MinLevel = RuntimeLevel.Run)]
    public class RedirectTrackingComposer : ComponentComposer<RedirectTrackingComponent>, ICoreComposer
    { }
}

Fix the redirect tracking composer

Fix the redirect tracking composer


using System;
using System.Collections.Generic;
using System.Drawing;
using PdfSharp.Pdf.Advanced;

// ReSharper disable once CheckNamespace
namespace PdfSharp.Pdf
{
  /// <summary>
  /// Extension methods for the PdfSharp library PdfItem object.
  /// </summary>
  public static class PdfPageExtensions
  {
    /// <summary>
    /// Get's all of the images from the specified page.
    /// </summary>
    /// <param name="page">The page to extract or retrieve images from.</param>
    /// <param name="filter">An optional filter to perform additional modifications or actions on the image.</param>
    /// <returns>An enumeration of images contained on the page.</returns>
    public static IEnumerable<Image> GetImages(this PdfPage page, Func<PdfPage, int, Image, Image> filter = null)
    {
      if (page == null) throw new ArgumentNullException("item", "The provided PDF page was null.");
      if (filter == null) filter = (pg, idx, img) => img;

      int index = 0;
      PdfDictionary resources = page.Elements.GetDictionary("/Resources");
      if (resources != null) {
        PdfDictionary xObjects = resources.Elements.GetDictionary("/XObject");
        if (xObjects != null) {
          ICollection<PdfItem> items = xObjects.Elements.Values;
          foreach (PdfItem item in items) {
            PdfReference reference = item as PdfReference;
            if (reference != null) {
              PdfDictionary xObject = reference.Value as PdfDictionary;
              if (xObject.IsImage()) {
                yield return filter.Invoke(page, index++, xObject.ToImage());
              }
            }
          }
        }
      }
    }
  }
}

using System;
using System.Collections.Generic;
using System.Drawing;
using PdfSharp.Pdf.Advanced;

// ReSharper disable once CheckNamespace
namespace PdfSharp.Pdf
{
  /// <summary>
  /// Extension methods for the PdfSharp library PdfItem object.
  /// </summary>
  public static class PdfPageExtensions
  {
    /// <summary>
    /// Get's all of the images from the specified page.
    /// </summary>
    /// <param name="page">The page to extract or retrieve images from.</param>
    /// <param name="filter">An optional filter to perform additional modifications or actions on the image.</param>
    /// <returns>An enumeration of images contained on the page.</returns>
    public static IEnumerable<Image> GetImages(this PdfPage page, Func<PdfPage, int, Image, Image> filter = null)
    {
      if (page == null) throw new ArgumentNullException("page", "The provided PDF page was null.");
      if (filter == null) filter = (pg, idx, img) => img;

      int index = 0;
      var resources = page.Elements.GetDictionary("/Resources");
      if (resources != null) {
        var xObjects = resources.Elements.GetDictionary("/XObject");
        if (xObjects != null) {
          var items = xObjects.Elements.Values;
          foreach (PdfItem item in items) {
            var reference = item as PdfReference;
            if (reference != null) {
              var xObject = reference.Value as PdfDictionary;
              if (xObject.IsImage()) {
                yield return filter.Invoke(page, index++, xObject.ToImage());
              }
            }
          }
        }
      }
    }
  }
}

Use var declaration. Fix ArgumentNullException parameter name.


@model Portal.CMS.Web.Areas.Admin.ViewModels.Dashboard.QuickAccessViewModel

    @foreach (var category in Model.Categories)
    {
        @category.DesktopText@category.MobileText
    }

    @foreach (var category in Model.Categories)
    {

                @foreach (var action in category.Actions)
                {
                    @action.Text
                }

    }

Bring Attention to the Quick Access Panel On Page Load


using System;
using MyTrips.DataObjects;
using MyTrips.DataStore.Abstractions;
using System.Threading.Tasks;
using MyTrips.Utils;
using System.Collections.Generic;

namespace MyTrips.DataStore.Azure.Stores
{
    public class TripStore : BaseStore<Trip>, ITripStore
    {
        IPhotoStore photoStore;
        public TripStore()
        {
            photoStore = ServiceLocator.Instance.Resolve<IPhotoStore>();
        }

        public override async Task<IEnumerable<Trip>> GetItemsAsync(int skip = 0, int take = 100, bool forceRefresh = false)
        {
            var items = await base.GetItemsAsync(skip, take, forceRefresh);
            foreach (var item in items)
            {
                item.Photos = new List<Photo>();
                var photos = await photoStore.GetTripPhotos(item.Id);
                foreach(var photo in photos)
                    item.Photos.Add(photo);
            }

            return items;
        }

        public override async Task<Trip> GetItemAsync(string id)
        {
            var item = await base.GetItemAsync(id);

            if (item.Photos == null)
                item.Photos = new List<Photo>();
            else
                item.Photos.Clear();

            var photos = await photoStore.GetTripPhotos(item.Id);
            foreach(var photo in photos)
                item.Photos.Add(photo);

            return item;
        }
    }
}

using System;
using MyTrips.DataObjects;
using MyTrips.DataStore.Abstractions;
using System.Threading.Tasks;
using MyTrips.Utils;
using System.Collections.Generic;
using System.Linq;

namespace MyTrips.DataStore.Azure.Stores
{
    public class TripStore : BaseStore<Trip>, ITripStore
    {
        IPhotoStore photoStore;
        public TripStore()
        {
            photoStore = ServiceLocator.Instance.Resolve<IPhotoStore>();
        }

        public override async Task<IEnumerable<Trip>> GetItemsAsync(int skip = 0, int take = 100, bool forceRefresh = false)
        {
            var items = await base.GetItemsAsync(skip, take, forceRefresh);
            foreach (var item in items)
            {
                item.Photos = new List<Photo>();
                var photos = await photoStore.GetTripPhotos(item.Id);
                foreach(var photo in photos)
                    item.Photos.Add(photo);
            }

            return items;
        }

        public override async Task<Trip> GetItemAsync(string id)
        {
            var item = await base.GetItemAsync(id);

            if (item.Photos == null)
                item.Photos = new List<Photo>();
            else
                item.Photos.Clear();

            var photos = await photoStore.GetTripPhotos(item.Id);
            foreach(var photo in photos)
                item.Photos.Add(photo);

            item.Points = item.Points.OrderBy(p => p.Sequence).ToArray();

            return item;
        }
    }
}

Make sure we order by sequence

Make sure we order by sequence


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

namespace NuGet.VisualStudio {
    public static class AggregatePackageSource {
        public static readonly PackageSource Instance = new PackageSource("(Aggregate source)", Resources.VsResources.AggregateSourceName);

        public static bool IsAggregate(this PackageSource source) {
            return source == Instance;
        }

        public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate(this IPackageSourceProvider provider) {
            return Enumerable.Repeat(Instance, 1).Concat(provider.LoadPackageSources());
        }

        public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate() {
            return GetPackageSourcesWithAggregate(ServiceLocator.GetInstance<IVsPackageSourceProvider>());
        }
    }
}

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

namespace NuGet.VisualStudio {
    public static class AggregatePackageSource {
        public static readonly PackageSource Instance = new PackageSource("(Aggregate source)", Resources.VsResources.AggregateSourceName);

        public static bool IsAggregate(this PackageSource source) {
            return source == Instance;
        }

        public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate(this IPackageSourceProvider provider) {
            return new[] { Instance }.Concat(provider.LoadPackageSources());
        }

        public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate() {
            return GetPackageSourcesWithAggregate(ServiceLocator.GetInstance<IVsPackageSourceProvider>());
        }
    }
}

Replace Enumerable.Repeat call with an one-element array.


using static System.Console;
using System.Linq;
using CIV.Ccs;
using CIV.Hml;

namespace CIV
{
    class Program
    {
        static void Main(string[] args)
        {
  			var text = System.IO.File.ReadAllText(args[0]);

			var processes = CcsFacade.ParseAll(text);
            var hmlText = "[[ack]][[ack]][[ack]](<<ack>>tt and [[freeAll]]ff)";
            var prova = HmlFacade.ParseAll(hmlText);
            WriteLine(prova.Check(processes["Prison"]));
        }
    }
}

using static System.Console;
using CIV.Ccs;
using CIV.Interfaces;

namespace CIV
{
    class Program
    {
        static void Main(string[] args)
        {
  			var text = System.IO.File.ReadAllText(args[0]);

			var processes = CcsFacade.ParseAll(text);
            var trace = CcsFacade.RandomTrace(processes["Prison"], 450);
            foreach (var action in trace)
            {
                WriteLine(action);
            }
        }
    }
}

Revert "Remove RandomTrace stuff from main"

This reverts commit f4533db6c2eb955d5433cf52e85d32a223a7bba8.


using EOBot.Interpreter.Extensions;
using System.Collections.Generic;
using System.Linq;

namespace EOBot.Interpreter.States
{
    public class StatementEvaluator : IScriptEvaluator
    {
        private readonly IEnumerable<IScriptEvaluator> _evaluators;

        public StatementEvaluator(IEnumerable<IScriptEvaluator> evaluators)
        {
            _evaluators = evaluators;
        }

        public bool Evaluate(ProgramState input)
        {
            while (input.Current().TokenType == BotTokenType.NewLine)
                input.Expect(BotTokenType.NewLine);

            return (Evaluate<AssignmentEvaluator>(input)
                    || Evaluate<KeywordEvaluator>(input)
                    || Evaluate<LabelEvaluator>(input)
                    || Evaluate<FunctionEvaluator>(input))
                    && input.Expect(BotTokenType.NewLine);
        }

        private bool Evaluate<T>(ProgramState input)
            where T : IScriptEvaluator
        {
            return _evaluators
                .OfType<T>()
                .Single()
                .Evaluate(input);
        }
    }
}

using EOBot.Interpreter.Extensions;
using System.Collections.Generic;
using System.Linq;

namespace EOBot.Interpreter.States
{
    public class StatementEvaluator : IScriptEvaluator
    {
        private readonly IEnumerable<IScriptEvaluator> _evaluators;

        public StatementEvaluator(IEnumerable<IScriptEvaluator> evaluators)
        {
            _evaluators = evaluators;
        }

        public bool Evaluate(ProgramState input)
        {
            while (input.Current().TokenType == BotTokenType.NewLine)
                input.Expect(BotTokenType.NewLine);

            return (Evaluate<AssignmentEvaluator>(input)
                    || Evaluate<KeywordEvaluator>(input)
                    || Evaluate<LabelEvaluator>(input)
                    || Evaluate<FunctionEvaluator>(input))
                    && (input.Expect(BotTokenType.NewLine) || input.Expect(BotTokenType.EOF));
        }

        private bool Evaluate<T>(ProgramState input)
            where T : IScriptEvaluator
        {
            return _evaluators
                .OfType<T>()
                .Single()
                .Evaluate(input);
        }
    }
}

Allow statements to end with EOF instead of forcing a newline for every evaluated statement


namespace Sharpy.Core {
    /// <summary>
    ///     <para>Represent a generator which can generate any amount of elements by invoking method <see cref="Generate" />.</para>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface IGenerator<out T>  {
        /// <summary>
        ///     <para>Generate next element.</para>
        /// </summary>
        /// <returns>
        ///     A generated element.
        /// </returns>
        new T Generate();
    }

}

namespace Sharpy.Core {
    /// <summary>
    ///     <para>Represent a generator which can generate any amount of elements by invoking method <see cref="Generate" />.</para>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface IGenerator<out T> {
        /// <summary>
        ///     <para>Generate next element.</para>
        /// </summary>
        /// <returns>
        ///     A generated element.
        /// </returns>
        T Generate();
    }
}

Remove new keyword from interface

Remove new keyword from interface

Former-commit-id: e271328ab161d18c97babd8a011a6806ce7b1981


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

using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;

namespace osu.Game.Screens.Edit.Screens
{
    public class EditorScreen : Container
    {
        public readonly Bindable<WorkingBeatmap> Beatmap = new Bindable<WorkingBeatmap>();

        protected override Container<Drawable> Content => content;
        private readonly Container content;

        public EditorScreen()
        {
            Anchor = Anchor.Centre;
            Origin = Anchor.Centre;
            RelativeSizeAxes = Axes.Both;

            InternalChild = content = new Container { RelativeSizeAxes = Axes.Both };
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();

            this.ScaleTo(0.75f).FadeTo(0)
                .Then()
                .ScaleTo(1f, 500, Easing.OutQuint).FadeTo(1f, 250, Easing.OutQuint);
        }

        public void Exit()
        {
            this.ScaleTo(1.25f, 500).FadeOut(250).Expire();
        }
    }
}

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

using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;

namespace osu.Game.Screens.Edit.Screens
{
    public class EditorScreen : Container
    {
        public readonly Bindable<WorkingBeatmap> Beatmap = new Bindable<WorkingBeatmap>();

        protected override Container<Drawable> Content => content;
        private readonly Container content;

        public EditorScreen()
        {
            Anchor = Anchor.Centre;
            Origin = Anchor.Centre;
            RelativeSizeAxes = Axes.Both;

            InternalChild = content = new Container { RelativeSizeAxes = Axes.Both };
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();

            this.FadeTo(0)
                .Then()
                .FadeTo(1f, 250, Easing.OutQuint);
        }

        public void Exit()
        {
            this.FadeOut(250).Expire();
        }
    }
}

Remove scale effect on editor screen switches


using System.Configuration;

namespace SchemaZen.test {
	public class ConfigHelper {
		public static string TestDB {
			get { return ConfigurationManager.AppSettings["testdb"]; }
		}

		public static string TestSchemaDir {
			get { return ConfigurationManager.AppSettings["test_schema_dir"]; }
		}

		public static string SqlDbDiffPath {
			get { return ConfigurationManager.AppSettings["SqlDbDiffPath"]; }
		}
	}
}

using System;
using System.Configuration;

namespace SchemaZen.test {
	public class ConfigHelper {
		public static string TestDB {
			get { return GetSetting("testdb"); }
		}

		public static string TestSchemaDir {
			get { return GetSetting("test_schema_dir"); }
		}

		public static string SqlDbDiffPath {
			get { return GetSetting("SqlDbDiffPath"); }
		}

		private static string GetSetting(string key) {
			var val = Environment.GetEnvironmentVariable(key);
			return val ?? ConfigurationManager.AppSettings[key];
		}
	}
}

Read environment variables for test settings.

Allows me to specify a different testdb on the build server.


using System;
using System.Collections.Generic;
using System.Text;
using MiX.Integrate.Shared.Entities.Communications;

namespace MiX.Integrate.Shared.Entities.Messages
{
	public class SendJobMessageCarrier
	{
		public SendJobMessageCarrier() { }

		public short VehicleId { get; set; }
		public string Description { get; set; }
		public string UserDescription { get; set; }
		public string Body { get; set; }
		public DateTime? StartDate { get; set; }
		public DateTime? ExpiryDate { get; set; }
		public bool RequiresAddress { get; set; }
		public bool AddAddressSummary { get; set; }
		public bool UseFirstAddressForSummary { get; set; }
		public JobMessageActionNotifications NotificationSettings { get; set; }
		public long[] AddressList { get; set; }
		public CommsTransports Transport { get; set; }
		public bool Urgent { get; set; }
	}
}

using System;
using System.Collections.Generic;
using System.Text;
using MiX.Integrate.Shared.Entities.Communications;

namespace MiX.Integrate.Shared.Entities.Messages
{
	public class SendJobMessageCarrier
	{
		public SendJobMessageCarrier() { }

		public short VehicleId { get; set; }
		public string Description { get; set; }
		public string UserDescription { get; set; }
		public string Body { get; set; }
		public DateTime? StartDate { get; set; }
		public DateTime? ExpiryDate { get; set; }
		public bool RequiresAddress { get; set; }
		public bool AddAddressSummary { get; set; }
		public bool UseFirstAddressForSummary { get; set; }
		public JobMessageActionNotifications NotificationSettings { get; set; }
		public int[] AddressList { get; set; }
		public long[] LocationList { get; set; }
		public CommsTransports Transport { get; set; }
		public bool Urgent { get; set; }
	}
}

Add extra property to use new long Id's

FLEET-9992: Add extra property to use new long Id's


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

namespace SpotiPeek.App
{
    class TrackModel
    {
        public string SongTitle;
        public string ArtistName;
        public string AlbumTitle;
        public string AlbumYear;
    }
}

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

namespace SpotiPeek.App
{
    class TrackModel
    {
        public string SongTitle;
        public string ArtistName;
        public string AlbumTitle;
    }
}

Remove unused property from Track model

Remove unused property from Track model


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

using System.ComponentModel;

namespace osu.Game.GameModes.Play
{
    public enum PlayMode
    {
        [Description(@"osu!")]
        Osu = 0,
        [Description(@"taiko")]
        Taiko = 1,
        [Description(@"catch")]
        Catch = 2,
        [Description(@"mania")]
        Mania = 3
    }
}

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

using System.ComponentModel;

namespace osu.Game.GameModes.Play
{
    public enum PlayMode
    {
        [Description(@"osu!")]
        Osu = 0,
        [Description(@"osu!taiko")]
        Taiko = 1,
        [Description(@"osu!catch")]
        Catch = 2,
        [Description(@"osu!mania")]
        Mania = 3
    }
}

Add osu! prefix to mode descriptions.

Add osu! prefix to mode descriptions.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Giles.Core.Runners;
using Giles.Core.Utility;
using NUnit.Core;
using NUnit.Core.Filters;

namespace Giles.Runner.NUnit
{
    public class NUnitRunner : IFrameworkRunner
    {
        IEnumerable<string> filters;

        public SessionResults RunAssembly(Assembly assembly, IEnumerable<string> filters)
        {
            this.filters = filters;
            var remoteTestRunner = new RemoteTestRunner(0);
            var package = SetupTestPackager(assembly);
            remoteTestRunner.Load(package);
            var listener = new GilesNUnitEventListener();
            remoteTestRunner.Run(listener, GetFilters());
            return listener.SessionResults;
        }

        ITestFilter GetFilters()
        {
            var simpleNameFilter = new SimpleNameFilter(filters.ToArray());
            return simpleNameFilter;
        }

        public IEnumerable<string> RequiredAssemblies()
        {
            return new[]
                       {
                           Assembly.GetAssembly(typeof(NUnitRunner)).Location,
                           "nunit.core.dll", "nunit.core.interfaces.dll"
                       };
        }

        private static TestPackage SetupTestPackager(Assembly assembly)
        {
            return new TestPackage(assembly.FullName, new[] { assembly.Location });
        }
    }
}

using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Giles.Core.Runners;
using NUnit.Core;
using NUnit.Core.Filters;

namespace Giles.Runner.NUnit
{
    public class NUnitRunner : IFrameworkRunner
    {
        IEnumerable<string> filters;

        public SessionResults RunAssembly(Assembly assembly, IEnumerable<string> filters)
        {
            this.filters = filters;
            var remoteTestRunner = new RemoteTestRunner(0);
            var package = SetupTestPackager(assembly);
            remoteTestRunner.Load(package);
            var listener = new GilesNUnitEventListener();
            if (filters.Count() == 0)
                remoteTestRunner.Run(listener);
            else
                remoteTestRunner.Run(listener, GetFilters());
            return listener.SessionResults;
        }

        ITestFilter GetFilters()
        {
            var simpleNameFilter = new SimpleNameFilter(filters.ToArray());
            return simpleNameFilter;
        }

        public IEnumerable<string> RequiredAssemblies()
        {
            return new[]
                       {
                           Assembly.GetAssembly(typeof(NUnitRunner)).Location,
                           "nunit.core.dll", "nunit.core.interfaces.dll"
                       };
        }

        private static TestPackage SetupTestPackager(Assembly assembly)
        {
            return new TestPackage(assembly.FullName, new[] { assembly.Location });
        }
    }
}

Fix to not use a test filter in NUnit when no filters has been declared in Giles. This was causing NUnit to not run the tests


using System.Text;
using dot10.IO;

namespace dot10.dotNET {
	/// <summary>
	/// Represents the #Strings stream
	/// </summary>
	public class StringsStream : DotNetStream {
		/// <inheritdoc/>
		public StringsStream(IImageStream imageStream, StreamHeader streamHeader)
			: base(imageStream, streamHeader) {
		}

		/// <summary>
		/// Read a <see cref="string"/>
		/// </summary>
		/// <param name="offset">Offset of string</param>
		/// <returns>The UTF-8 decoded string or null if invalid offset</returns>
		public string Read(uint offset) {
			var data = imageStream.ReadBytesUntilByte(0);
			if (data == null)
				return null;
			return Encoding.UTF8.GetString(data);
		}
	}
}

using System.Text;
using dot10.IO;

namespace dot10.dotNET {
	/// <summary>
	/// Represents the #Strings stream
	/// </summary>
	public class StringsStream : DotNetStream {
		/// <inheritdoc/>
		public StringsStream(IImageStream imageStream, StreamHeader streamHeader)
			: base(imageStream, streamHeader) {
		}

		/// <summary>
		/// Read a <see cref="string"/>
		/// </summary>
		/// <param name="offset">Offset of string</param>
		/// <returns>The UTF-8 decoded string or null if invalid offset</returns>
		public string Read(uint offset) {
			if (offset >= imageStream.Length)
				return null;
			imageStream.Position = offset;
			var data = imageStream.ReadBytesUntilByte(0);
			if (data == null)
				return null;
			return Encoding.UTF8.GetString(data);
		}
	}
}

Return null if invalid offset and seek to the offset


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

namespace osu.Game.Online.Multiplayer
{
    public enum RoomCategory
    {
        Normal,
        Spotlight
    }
}

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

namespace osu.Game.Online.Multiplayer
{
    public enum RoomCategory
    {
        Normal,
        Spotlight,
        Realtime,
    }
}

Add realtime to room categories

Add realtime to room categories


using System;

namespace Satrabel.OpenContent.Components.TemplateHelpers
{
    public class Ratio
    {
        private readonly float _ratio;

        public int Width { get; private set; }
        public int Height { get; private set; }
        public float AsFloat
        {
            get { return (float)Width / (float)Height); }
        }

        public Ratio(string ratioString)
        {
            Width = 1;
            Height = 1;
            var elements = ratioString.ToLowerInvariant().Split('x');
            if (elements.Length == 2)
            {
                int leftPart;
                int rightPart;
                if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart))
                {
                    Width = leftPart;
                    Height = rightPart;
                }
            }
            _ratio = AsFloat;
        }
        public Ratio(int width, int height)
        {
            if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger");
            if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger");
            Width = width;
            Height = height;
            _ratio = AsFloat;
        }

        public void SetWidth(int newWidth)
        {
            Width = newWidth;
            Height = Convert.ToInt32(newWidth / _ratio);
        }
        public void SetHeight(int newHeight)
        {
            Width = Convert.ToInt32(newHeight * _ratio);
            Height = newHeight;
        }
    }
}

using System;

namespace Satrabel.OpenContent.Components.TemplateHelpers
{
    public class Ratio
    {
        private readonly float _ratio;

        public int Width { get; private set; }
        public int Height { get; private set; }
        public float AsFloat
        {
            get { return (float)Width / (float)Height; }
        }

        public Ratio(string ratioString)
        {
            Width = 1;
            Height = 1;
            var elements = ratioString.ToLowerInvariant().Split('x');
            if (elements.Length == 2)
            {
                int leftPart;
                int rightPart;
                if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart))
                {
                    Width = leftPart;
                    Height = rightPart;
                }
            }
            _ratio = AsFloat;
        }
        public Ratio(int width, int height)
        {
            if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger");
            if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger");
            Width = width;
            Height = height;
            _ratio = AsFloat;
        }

        public void SetWidth(int newWidth)
        {
            Width = newWidth;
            Height = Convert.ToInt32(newWidth / _ratio);
        }
        public void SetHeight(int newHeight)
        {
            Width = Convert.ToInt32(newHeight * _ratio);
            Height = newHeight;
        }
    }
}

Fix issue where ratio was always returning "1"


using System;

namespace Stratis.Bitcoin.Features.Wallet
{
    /// <summary>
    /// An indicator on how fast a transaction will be accepted in a block
    /// </summary>
    public enum FeeType
    {
        /// <summary>
        /// Slow.
        /// </summary>
        Low = 0,

        /// <summary>
        /// Avarage.
        /// </summary>
        Medium = 1,

        /// <summary>
        /// Fast.
        /// </summary>
        High = 105
    }

    public static class FeeParser
    {
        public static FeeType Parse(string value)
        {
            if (Enum.TryParse<FeeType>(value, true, out var ret))
                return ret;

            return FeeType.Medium;
        }

        /// <summary>
        /// Map a fee type to the number of confirmations
        /// </summary>
        public static int ToConfirmations(this FeeType fee)
        {
            switch (fee)
            {
                case FeeType.Low:
                    return 50;
                case FeeType.Medium:
                    return 20;
                case FeeType.High:
                    return 5;

            }

            throw new WalletException("Invalid fee");
        }
    }
}

using System;

namespace Stratis.Bitcoin.Features.Wallet
{
    /// <summary>
    /// An indicator of how fast a transaction will be accepted in a block.
    /// </summary>
    public enum FeeType
    {
        /// <summary>
        /// Slow.
        /// </summary>
        Low = 0,

        /// <summary>
        /// Avarage.
        /// </summary>
        Medium = 1,

        /// <summary>
        /// Fast.
        /// </summary>
        High = 105
    }

    public static class FeeParser
    {
        public static FeeType Parse(string value)
        {
            bool isParsed = Enum.TryParse<FeeType>(value, true, out var result);
            if (!isParsed)
            {
                throw new FormatException($"FeeType {value} is not a valid FeeType");
            }

            return result;
        }

        /// <summary>
        /// Map a fee type to the number of confirmations
        /// </summary>
        public static int ToConfirmations(this FeeType fee)
        {
            switch (fee)
            {
                case FeeType.Low:
                    return 50;
                case FeeType.Medium:
                    return 20;
                case FeeType.High:
                    return 5;

            }

            throw new WalletException("Invalid fee");
        }
    }
}

Make FeeParser throw if the fee parsed is not low, medium or high (previously defaulted to medium0


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

namespace Infusion.EngineScripts
{
    public sealed class ScriptEngine
    {
        private readonly IScriptEngine[] engines;
        private string scriptRootPath;

        public ScriptEngine(params IScriptEngine[] engines)
        {
            this.engines = engines;
        }

        public string ScriptRootPath
        {
            get => scriptRootPath;
            set
            {
                scriptRootPath = value;
                ForeachEngine(engine => engine.ScriptRootPath = value);
            }
        }

        public async Task ExecuteScript(string scriptPath, CancellationTokenSource cancellationTokenSource)
        {
            await ForeachEngineAsync(engine => engine.ExecuteScript(scriptPath, cancellationTokenSource));
        }

        public void Reset() => ForeachEngine(engine => engine.Reset());

        private void ForeachEngine(Action<IScriptEngine> engineAction)
        {
            foreach (var engine in engines)
                engineAction(engine);
        }

        private async Task ForeachEngineAsync(Func<IScriptEngine, Task> engineAction)
        {
            foreach (var engine in engines)
                await engineAction(engine);
        }
    }
}

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

namespace Infusion.EngineScripts
{
    public sealed class ScriptEngine
    {
        private readonly IScriptEngine[] engines;
        private string scriptRootPath;

        public ScriptEngine(params IScriptEngine[] engines)
        {
            this.engines = engines;
        }

        public string ScriptRootPath
        {
            get => scriptRootPath;
            set
            {
                scriptRootPath = value;
                ForeachEngine(engine => engine.ScriptRootPath = value);
            }
        }

        public Task ExecuteInitialScript(string scriptPath, CancellationTokenSource cancellationTokenSource)
        {
            var currentRoot = Path.GetDirectoryName(scriptPath);
            Directory.SetCurrentDirectory(currentRoot);
            ScriptRootPath = currentRoot;

            return ExecuteScript(scriptPath, cancellationTokenSource);
        }

        public async Task ExecuteScript(string scriptPath, CancellationTokenSource cancellationTokenSource)
        {
            if (!File.Exists(scriptPath))
                throw new FileNotFoundException($"Script file not found: {scriptPath}", scriptPath);
            await ForeachEngineAsync(engine => engine.ExecuteScript(scriptPath, cancellationTokenSource));
        }

        public void Reset() => ForeachEngine(engine => engine.Reset());

        private void ForeachEngine(Action<IScriptEngine> engineAction)
        {
            foreach (var engine in engines)
                engineAction(engine);
        }

        private async Task ForeachEngineAsync(Func<IScriptEngine, Task> engineAction)
        {
            foreach (var engine in engines)
                await engineAction(engine);
        }
    }
}

Set current directory for initial script.


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

namespace LazyLibrary.Storage.Memory
{
    internal class MemoryRepository<T> : IRepository<T> where T : IStorable
    {
        private List<T> repository = new List<T>();

        public T GetById(int id)
        {
            return this.repository.Where(x => x.Id == id).SingleOrDefault();
        }

        public IQueryable<T> Get(System.Func<T, bool> exp = null)
        {
            return exp != null ? repository.Where(exp).AsQueryable<T>() : repository.AsQueryable<T>();
        }

        public void Upsert(T item)
        {
            var obj = GetById(item.Id);

            if (obj != null)
            {
                // Update
                this.repository.Remove(obj);
                this.repository.Add(item);
            }
            else
            {
                // Insert
                var nextId = this.repository.Any() ? this.repository.Max(x => x.Id) + 1 : 1;
                item.Id = nextId;
                this.repository.Add(item);
            }
        }

        public void Delete(T item)
        {
            var obj = GetById(item.Id);
            this.repository.Remove(obj);
        }
    }
}

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

namespace LazyLibrary.Storage.Memory
{
    internal class MemoryRepository<T> : IRepository<T> where T : IStorable
    {
        private List<T> repository = new List<T>();

        public T GetById(int id)
        {
            return this.repository.SingleOrDefault(x => x.Id == id);
        }

        public IQueryable<T> Get(System.Func<T, bool> exp = null)
        {
            return exp != null ? repository.Where(exp).AsQueryable<T>() : repository.AsQueryable<T>();
        }

        public void Upsert(T item)
        {
            if (repository.Contains(item))
            {
                // Update
                var obj = repository.Single(x => x.Equals(item));
                this.repository.Remove(obj);
                this.repository.Add(item);
            }
            else
            {
                // Insert
                var nextId = this.repository.Any() ? this.repository.Max(x => x.Id) + 1 : 1;
                item.Id = nextId;
                this.repository.Add(item);
            }
        }

        public void Delete(T item)
        {
            var obj = GetById(item.Id);
            this.repository.Remove(obj);
        }
    }
}

Check for objects existing using their equals operation rather than Ids


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using Microsoft.Experimental.Azure.Spark;
using System.Collections.Immutable;
using System.IO;
using Microsoft.Experimental.Azure.CommonTestUtilities;

namespace Shark
{
	public class WorkerRole : SharkNodeBase
	{
		protected override ImmutableDictionary<string, string> GetHadoopConfigProperties()
		{
			return WasbConfiguration.GetWasbConfigKeys();
		}
	}
}

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using Microsoft.Experimental.Azure.Spark;
using System.Collections.Immutable;
using System.IO;
using Microsoft.Experimental.Azure.CommonTestUtilities;

namespace Shark
{
	public class WorkerRole : SharkNodeBase
	{
		protected override ImmutableDictionary<string, string> GetHadoopConfigProperties()
		{
			var rootFs = String.Format("wasb://shark@{0}.blob.core.windows.net",
					WasbConfiguration.ReadWasbAccountsFile().First());
			return WasbConfiguration.GetWasbConfigKeys()
				.Add("hive.exec.scratchdir", rootFs + "/scratch")
				.Add("hive.metastore.warehouse.dir", rootFs + "/warehouse");
		}
	}
}

Put the scratch and warehouse directories up on WASB in the Shark test service. This gets CTAS to work.