using MobileKidsIdApp.Services;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
using MobileKidsIdApp.Models;

namespace MobileKidsIdApp.ViewModels
{
    public class BasicDetails : ViewModelBase<Models.ChildDetails>
    {
        private ContactInfo _contact;

        public ICommand ChangeContactCommand { get; private set; }

        public BasicDetails(Models.ChildDetails details)
        {
            ChangeContactCommand = new Command(async () =>
            {
                ContactInfo contact = await DependencyService.Get<IContactPicker>().GetSelectedContactInfo();
                if (contact == null)
                {
                    //Do nothing, user must have cancelled.
                }
                else
                {
                    _contact = contact;
                    Model.ContactId = contact.Id;

                    //Only overwrite name fields if they were blank.
                    if (string.IsNullOrEmpty(Model.FamilyName))
                        Model.FamilyName = contact.FamilyName;
                    if (string.IsNullOrEmpty(Model.AdditionalName))
                        Model.AdditionalName = contact.AdditionalName;
                    if (string.IsNullOrEmpty(Model.GivenName))
                        Model.GivenName = contact.GivenName;

                    OnPropertyChanged(nameof(Contact));
                }
            });

            Model = details;
        }

        protected override async Task<ChildDetails> DoInitAsync()
        {
            _contact = await DependencyService.Get<IContactPicker>().GetContactInfoForId(Model.ContactId);
            return Model;
        }

        public ContactInfo Contact { get { return _contact; } }
    }
}

using MobileKidsIdApp.Services;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
using MobileKidsIdApp.Models;

namespace MobileKidsIdApp.ViewModels
{
    public class BasicDetails : ViewModelBase<Models.ChildDetails>
    {
        private ContactInfo _contact;

        public ICommand ChangeContactCommand { get; private set; }

        public BasicDetails(Models.ChildDetails details)
        {
            ChangeContactCommand = new Command(async () =>
            {
                PrepareToShowModal();
                ContactInfo contact = await DependencyService.Get<IContactPicker>().GetSelectedContactInfo();
                if (contact == null)
                {
                    //Do nothing, user must have cancelled.
                }
                else
                {
                    _contact = contact;
                    Model.ContactId = contact.Id;

                    //Only overwrite name fields if they were blank.
                    if (string.IsNullOrEmpty(Model.FamilyName))
                        Model.FamilyName = contact.FamilyName;
                    if (string.IsNullOrEmpty(Model.AdditionalName))
                        Model.AdditionalName = contact.AdditionalName;
                    if (string.IsNullOrEmpty(Model.GivenName))
                        Model.GivenName = contact.GivenName;

                    OnPropertyChanged(nameof(Contact));
                }
            });

            Model = details;
        }

        protected override async Task<ChildDetails> DoInitAsync()
        {
            _contact = await DependencyService.Get<IContactPicker>().GetContactInfoForId(Model.ContactId);
            return Model;
        }

        public ContactInfo Contact { get { return _contact; } }
    }
}

Make sure the model isn't lost when navigating to/from the contact picker


<!DOCTYPE html>

        <title>@ViewData["Title"]</title>
        <link rel="icon" type="image/png" href="favicon.png">
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <link rel="stylesheet" href="~/style.css"/>

Logs

Resources

                @RenderBody()

            © 2014–2018 codingteam

<!DOCTYPE html>

        <title>@ViewData["Title"]</title>
        <link rel="icon" type="image/png" href="favicon.png">
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <link rel="stylesheet" href="~/style.css"/>

Logs

Resources

                @RenderBody()

            © 2019 codingteam

Update copyright year in template

Update copyright year in template

The year of first publication was removed as per #69 it's not necessary.

Closes #69.


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

using System.Linq;
using NUnit.Framework;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics.Containers;
using osu.Framework.Screens;
using osu.Framework.Testing;
using osu.Game.Screens.Play.HUD;
using osu.Game.Skinning;
using osu.Game.Tests.Visual;
using osuTK;

namespace osu.Game.Rulesets.Catch.Tests
{
    [TestFixture]
    public class TestSceneCatchPlayerLegacySkin : LegacySkinPlayerTestScene
    {
        protected override Ruleset CreatePlayerRuleset() => new CatchRuleset();

        [Test]
        [Ignore("HUD components broken, remove when fixed.")]
        public void TestLegacyHUDComboCounterHidden([Values] bool withModifiedSkin)
        {
            if (withModifiedSkin)
            {
                AddStep("change component scale", () => Player.ChildrenOfType<LegacyScoreCounter>().First().Scale = new Vector2(2f));
                AddStep("update target", () => Player.ChildrenOfType<SkinnableTargetContainer>().ForEach(LegacySkin.UpdateDrawableTarget));
                AddStep("exit player", () => Player.Exit());
                CreateTest(null);
            }

            AddAssert("legacy HUD combo counter hidden", () =>
            {
                return Player.ChildrenOfType<LegacyComboCounter>().All(c => !c.ChildrenOfType<Container>().Single().IsPresent);
            });
        }
    }
}

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

using System.Linq;
using NUnit.Framework;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics.Containers;
using osu.Framework.Screens;
using osu.Framework.Testing;
using osu.Game.Screens.Play.HUD;
using osu.Game.Skinning;
using osu.Game.Tests.Visual;
using osuTK;

namespace osu.Game.Rulesets.Catch.Tests
{
    [TestFixture]
    public class TestSceneCatchPlayerLegacySkin : LegacySkinPlayerTestScene
    {
        protected override Ruleset CreatePlayerRuleset() => new CatchRuleset();

        [Test]
        public void TestLegacyHUDComboCounterHidden([Values] bool withModifiedSkin)
        {
            if (withModifiedSkin)
            {
                AddStep("change component scale", () => Player.ChildrenOfType<LegacyScoreCounter>().First().Scale = new Vector2(2f));
                AddStep("update target", () => Player.ChildrenOfType<SkinnableTargetContainer>().ForEach(LegacySkin.UpdateDrawableTarget));
                AddStep("exit player", () => Player.Exit());
                CreateTest(null);
            }

            AddAssert("legacy HUD combo counter hidden", () =>
            {
                return Player.ChildrenOfType<LegacyComboCounter>().All(c => c.ChildrenOfType<Container>().Single().Alpha == 0f);
            });
        }
    }
}

Remove ignore attribute from now fixed test scene


using System;
using System.IO;
using System.Runtime.InteropServices;

namespace JemlemlacuLemjakarbabo
{
    class Program
    {
        static void Main(string[] args)
        {
            CheckHResult(UnsafeNativeMethods.WICCodec.CreateImagingFactory(UnsafeNativeMethods.WICCodec.WINCODEC_SDK_VERSION,
                out var pImagingFactory));

            using var fs = new FileStream("image.jpg",
                FileMode.Open,
                FileAccess.Read,
                FileShare.Read,
                4096,
                FileOptions.Asynchronous);

            Guid vendorMicrosoft = new Guid(MILGuidData.GUID_VendorMicrosoft);
            UInt32 metadataFlags = (uint)WICMetadataCacheOptions.WICMetadataCacheOnDemand;

            CheckHResult
            (
                UnsafeNativeMethods.WICImagingFactory.CreateDecoderFromFileHandle
                (
                    pImagingFactory,
                    fs.SafeFileHandle,
                    ref vendorMicrosoft,
                    metadataFlags,
                    out var decoder
                )
            );
        }

        static void CheckHResult(int hr)
        {
            if (hr < 0)
            {
                Exception exceptionForHR = Marshal.GetExceptionForHR(hr, (IntPtr)(-1));

                throw exceptionForHR;
            }
        }
    }
}

using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;

namespace JemlemlacuLemjakarbabo
{
    class Program
    {
        static void Main(string[] args)
        {
            CheckHResult(UnsafeNativeMethods.WICCodec.CreateImagingFactory(UnsafeNativeMethods.WICCodec.WINCODEC_SDK_VERSION,
                out var pImagingFactory));

            using var fs = new FileStream("image.jpg",
                FileMode.Open,
                FileAccess.Read,
                FileShare.Read,
                4096,
                FileOptions.Asynchronous);
            var stream = fs;
            SafeFileHandle safeFilehandle

            System.IO.FileStream filestream = stream as System.IO.FileStream;
            try
            {
                if (filestream.IsAsync is false)
                {
                    safeFilehandle = filestream.SafeFileHandle;
                }
                else
                {
                    // If Filestream is async that doesn't support IWICImagingFactory_CreateDecoderFromFileHandle_Proxy, then revert to old code path.
                    safeFilehandle = null;
                }
            }
            catch
            {
                // If Filestream doesn't support SafeHandle then revert to old code path.
                // See https://github.com/dotnet/wpf/issues/4355
                safeFilehandle = null;
            }

            Guid vendorMicrosoft = new Guid(MILGuidData.GUID_VendorMicrosoft);
            UInt32 metadataFlags = (uint)WICMetadataCacheOptions.WICMetadataCacheOnDemand;

            CheckHResult
            (
                UnsafeNativeMethods.WICImagingFactory.CreateDecoderFromFileHandle
                (
                    pImagingFactory,
                    fs.SafeFileHandle,
                    ref vendorMicrosoft,
                    metadataFlags,
                    out var decoder
                )
            );
        }

        static void CheckHResult(int hr)
        {
            if (hr < 0)
            {
                Exception exceptionForHR = Marshal.GetExceptionForHR(hr, (IntPtr)(-1));

                throw exceptionForHR;
            }
        }
    }
}

Fix create BitmapDecoder with async file stream.

[BitmapDecoder.Create does not handle FileStream with FileOptions.Asynchronous · Issue #4355 · dotnet/wpf](https://github.com/dotnet/wpf/issues/4355 )


using System.Linq;
using ITCO.SboAddon.Framework.Helpers;
using SAPbobsCOM;

namespace ITCO.SboAddon.Framework.Extensions
{
    public static class UserQueryExtensions
    {
        public static string GetOrCreateUserQuery(this Company company, string userQueryName, string userQueryDefaultQuery)
        {
            using (var userQuery = new SboRecordsetQuery<UserQueries>(
                $"SELECT [IntrnalKey] FROM [OUQR] WHERE [QName] = '{userQueryName}'", BoObjectTypes.oUserQueries))
            {
                if (userQuery.Count == 0)
                {
                    userQuery.BusinessObject.QueryDescription = userQueryName;
                    userQuery.BusinessObject.Query = userQueryDefaultQuery;
                    userQuery.BusinessObject.QueryCategory = -1;
                    var response = userQuery.BusinessObject.Add();

                    ErrorHelper.HandleErrorWithException(response, $"Could not create User Query '{userQueryName}'");

                    return userQueryDefaultQuery;
                }

                return userQuery.Result.First().Query;
            }
        }
    }
}

using System.Linq;
using System.Text.RegularExpressions;
using ITCO.SboAddon.Framework.Helpers;
using SAPbobsCOM;

namespace ITCO.SboAddon.Framework.Extensions
{
    public static class UserQueryExtensions
    {
        /// <summary>
        /// Get or create User Query
        /// </summary>
        /// <param name="company">Company Object</param>
        /// <param name="userQueryName">User Query Name</param>
        /// <param name="userQueryDefaultQuery">Query</param>
        /// <param name="formatToSqlParams">Replace [%0] to @p0</param>
        /// <returns></returns>
        public static string GetOrCreateUserQuery(this Company company, string userQueryName, string userQueryDefaultQuery, bool formatToSqlParams = false)
        {
            var userQuery = userQueryDefaultQuery;

            using (var userQueryObject = new SboRecordsetQuery<UserQueries>(
                $"SELECT [IntrnalKey] FROM [OUQR] WHERE [QName] = '{userQueryName}'", BoObjectTypes.oUserQueries))
            {
                if (userQueryObject.Count == 0)
                {
                    userQueryObject.BusinessObject.QueryDescription = userQueryName;
                    userQueryObject.BusinessObject.Query = userQueryDefaultQuery;
                    userQueryObject.BusinessObject.QueryCategory = -1;
                    var response = userQueryObject.BusinessObject.Add();

                    ErrorHelper.HandleErrorWithException(response, $"Could not create User Query '{userQueryName}'");
                }
                else
                {
                    userQuery = userQueryObject.Result.First().Query;
                }
            }

            if (formatToSqlParams)
                userQuery = Regex.Replace(userQuery, @"\[%([0-9])\]", "@p$1");

            return userQuery;
        }
    }
}

Add formatToSqlParams param to GetOrCreateUserQuery


using System.Runtime.InteropServices;
using System.Windows.Forms;
using ExcelDna.Integration.CustomUI;

namespace Ribbon
{
    [ComVisible(true)]
    public class RibbonController : ExcelRibbon
    {
        public override string GetCustomUI(string RibbonID)
        {
            return @"
      <customUI xmlns='http://schemas.microsoft.com/office/2006/01/customui' loadImage='LoadImage'>
      <ribbon>
        <tabs>
          <tab id='tab1' label='My Tab'>
            <group id='group1' label='My Group'>
              <button id='button1' label='My Button' onAction='OnButtonPressed'/>
            </group >
          </tab>
        </tabs>
      </ribbon>
    </customUI>";
        }

        public void OnButtonPressed(IRibbonControl control)
        {
            MessageBox.Show("Hello from control " + control.Id);
            DataWriter.WriteData();
        }
    }
}

using System.Runtime.InteropServices;
using System.Windows.Forms;
using ExcelDna.Integration.CustomUI;

namespace Ribbon
{
    [ComVisible(true)]
    public class RibbonController : ExcelRibbon
    {
        public override string GetCustomUI(string RibbonID)
        {
            return @"
      <customUI xmlns='http://schemas.microsoft.com/office/2006/01/customui'>
      <ribbon>
        <tabs>
          <tab id='tab1' label='My Tab'>
            <group id='group1' label='My Group'>
              <button id='button1' label='My Button' onAction='OnButtonPressed'/>
            </group >
          </tab>
        </tabs>
      </ribbon>
    </customUI>";
        }

        public void OnButtonPressed(IRibbonControl control)
        {
            MessageBox.Show("Hello from control " + control.Id);
            DataWriter.WriteData();
        }
    }
}

Ribbon: Remove extra loadImage callback until we discuss it


namespace ClojSharp.Core.Tests
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using ClojSharp.Core.Compiler;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class EvaluateTests
    {
        private Machine machine;

        [TestInitialize]
        public void Setup()
        {
            this.machine = new Machine();
        }

        [TestMethod]
        public void EvaluateInteger()
        {
            Assert.AreEqual(123, this.Evaluate("123", null));
        }

        [TestMethod]
        public void EvaluateSymbolInContext()
        {
            Context context = new Context();
            context.SetValue("one", 1);
            Assert.AreEqual(1, this.Evaluate("one", context));
        }

        [TestMethod]
        public void EvaluateAddTwoIntegers()
        {
            Assert.AreEqual(3, this.Evaluate("(+ 1 2)", this.machine.RootContext));
        }

        [TestMethod]
        public void EvaluateAddThreeIntegers()
        {
            Assert.AreEqual(6, this.Evaluate("(+ 1 2 3)", this.machine.RootContext));
        }

        [TestMethod]
        public void EvaluateOneInteger()
        {
            Assert.AreEqual(5, this.Evaluate("(+ 5)", this.machine.RootContext));
        }

        [TestMethod]
        public void EvaluateNoInteger()
        {
            Assert.AreEqual(0, this.Evaluate("(+)", this.machine.RootContext));
        }

        private object Evaluate(string text, Context context)
        {
            Parser parser = new Parser(text);
            var expr = parser.ParseExpression();
            Assert.IsNull(parser.ParseExpression());
            return this.machine.Evaluate(expr, context);
        }
    }
}

namespace ClojSharp.Core.Tests
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using ClojSharp.Core.Compiler;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class EvaluateTests
    {
        private Machine machine;

        [TestInitialize]
        public void Setup()
        {
            this.machine = new Machine();
        }

        [TestMethod]
        public void EvaluateInteger()
        {
            Assert.AreEqual(123, this.Evaluate("123", null));
        }

        [TestMethod]
        public void EvaluateSymbolInContext()
        {
            Context context = new Context();
            context.SetValue("one", 1);
            Assert.AreEqual(1, this.Evaluate("one", context));
        }

        [TestMethod]
        public void EvaluateAdd()
        {
            Assert.AreEqual(3, this.Evaluate("(+ 1 2)", this.machine.RootContext));
            Assert.AreEqual(6, this.Evaluate("(+ 1 2 3)", this.machine.RootContext));
            Assert.AreEqual(5, this.Evaluate("(+ 5)", this.machine.RootContext));
            Assert.AreEqual(0, this.Evaluate("(+)", this.machine.RootContext));
        }

        private object Evaluate(string text, Context context)
        {
            Parser parser = new Parser(text);
            var expr = parser.ParseExpression();
            Assert.IsNull(parser.ParseExpression());
            return this.machine.Evaluate(expr, context);
        }
    }
}

Test Refactor, consolidate Evaluate Add tests


using System;
using System.Diagnostics;
using StreamCompanionTypes.DataTypes;
using StreamCompanionTypes.Enums;

namespace OsuMemoryEventSource
{
    public class LiveToken
    {
        public IToken Token { get; set; }
        public Func<object> Updater;
        public bool IsLazy { get; set; }
        protected Lazy<object> Lazy = new Lazy<object>();
        public LiveToken(IToken token, Func<object> updater)
        {
            Token = token;
            Updater = updater;
            _ = Lazy.Value;
        }

        public void Update(OsuStatus status = OsuStatus.All)
        {
            if (!Token.CanSave(status) || Updater == null)
            {
                return;
            }

            if (IsLazy)
            {
                if (Lazy.IsValueCreated)
                {
                    Token.Value = Lazy = new Lazy<object>(Updater);
                }
            }
            else
            {
                Token.Value = Updater();
            }
        }
    }
}

using System;
using System.Diagnostics;
using StreamCompanionTypes.DataTypes;
using StreamCompanionTypes.Enums;

namespace OsuMemoryEventSource
{
    public class LiveToken
    {
        public IToken Token { get; set; }
        public Func<object> Updater;
        public bool IsLazy { get; set; }
        protected Lazy<object> Lazy = new Lazy<object>();
        public LiveToken(IToken token, Func<object> updater)
        {
            Token = token;
            Updater = updater;
            _ = Lazy.Value;
        }

        public void Update(OsuStatus status = OsuStatus.All)
        {
            if (!Token.CanSave(status) || Updater == null)
            {
                Token.Reset();
                return;
            }

            if (IsLazy)
            {
                if (Lazy.IsValueCreated)
                {
                    Token.Value = Lazy = new Lazy<object>(Updater);
                }
            }
            else
            {
                Token.Value = Updater();
            }
        }
    }
}

Fix: Reset live tokens value when it can not be saved

aka. clear token values after finishing play/exiting results screen


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

    public class SettingsParser
    {
        public T Parse<T>(FileInfo file, string commandLine, string environment) where T : new()
        {
            return (T)Parse(typeof (T), file, commandLine, environment);
        }

        public object Parse(Type t, FileInfo file, string commandLine, string environment)
        {
            var binder = ConfigurationBinderFactory.New(c =>
            {
                //c.AddJsonFile("global.conf");
                //c.AddJsonFile("{0}.conf".FormatWith(environment));
                //c.AddJsonFile(file.FullName);
                var content = File.ReadAllText(file.FullName);
                c.AddJson(content);
                //c.AddCommandLine(commandLine);
            });

            object result = binder.Bind(t);

            return result;
        }
    }
}

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

    public class SettingsParser
    {
        public T Parse<T>(FileInfo file, string commandLine, string environment) where T : new()
        {
            return (T)Parse(typeof (T), file, commandLine, environment);
        }

        public object Parse(Type t, FileInfo file, string commandLine, string environment)
        {
            var binder = ConfigurationBinderFactory.New(c =>
            {
                //c.AddJsonFile("global.conf");
                //c.AddJsonFile("{0}.conf".FormatWith(environment));
                //c.AddJsonFile(file.FullName);
                var content = File.ReadAllText(file.FullName);
                c.AddJson(content);
                c.AddCommandLine(commandLine);
            });

            object result = binder.Bind(t);

            return result;
        }
    }
}

Enable overriding of settings via command line arguments in the formats: /SettingName=value /SettingName:value


using System;
using System.Collections.Generic;
using Arango.Client;
using Arango.fastJSON;

namespace Arango.ConsoleTests
{
    class Program
    {
        public static void Main(string[] args)
        {
            var performance = new Performance();

            //performance.TestSimpleSequentialHttpPostRequests();
            //performance.TestRestSharpHttpPostRequests();
            //performance.TestSimpleParallelHttpPostRequests();

            performance.Dispose();

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}

using System;
using System.Collections.Generic;
using Arango.Client;
using Arango.fastJSON;

namespace Arango.ConsoleTests
{
    class Program
    {
        public static void Main(string[] args)
        {
            //PerformanceTests();

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }

        static void PerformanceTests()
        {
            var performance = new Performance();

            //performance.TestSimpleSequentialHttpPostRequests();
            //performance.TestRestSharpHttpPostRequests();
            //performance.TestSimpleParallelHttpPostRequests();

            performance.Dispose();
        }
    }
}

Put performance test into separate method in console.


// Copyright (c) PocketCampus.Org 2014-15
// See LICENSE file for more details
// File author: Solal Pirelli

using System;
using Windows.ApplicationModel;
using Windows.System;

namespace PocketCampus.Main.Services
{
    public sealed class AppRatingService : IAppRatingService
    {
        public async void RequestRating()
        {
            await Launcher.LaunchUriAsync( new Uri( "ms-windows-store:REVIEW?PFN=" + Package.Current.Id.FamilyName ) );
        }
    }
}

// Copyright (c) PocketCampus.Org 2014-15
// See LICENSE file for more details
// File author: Solal Pirelli

using System;
using Windows.System;

namespace PocketCampus.Main.Services
{
    public sealed class AppRatingService : IAppRatingService
    {
        private const string AppId = "28f8300e-8a84-4e3e-8d68-9a07c5b2a83a";

        public async void RequestRating()
        {
            // FRAMEWORK BUG: This seems to be the only correct way to do it.
            // Despite MSDN documentation, other ways (e.g. reviewapp without appid, or REVIEW?PFN=) open Xbox Music...
            await Launcher.LaunchUriAsync( new Uri( "ms-windows-store:reviewapp?appid=" + AppId, UriKind.Absolute ) );
        }
    }
}

[main.wp] Fix "rate app" button in the about page.


@model BatteryCommander.Web.Commands.UpdateSUTARequest

@using (Html.BeginForm("Edit", "SUTA", new { Model.Id }, FormMethod.Post, true, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()

        @Html.DisplayNameFor(model => model.Body.Supervisor)
        @Html.DropDownListFor(model => model.Body.Supervisor, (IEnumerable<SelectListItem>)ViewBag.Supervisors)

        @Html.DisplayNameFor(model => model.Body.StartDate)
        @Html.EditorFor(model => model.Body.StartDate)

        @Html.DisplayNameFor(model => model.Body.EndDate)
        @Html.EditorFor(model => model.Body.EndDate)

        @Html.DisplayNameFor(model => model.Body.Reasoning)
        @Html.TextAreaFor(model => model.Body.Reasoning, new { cols="40", rows="5" })

        @Html.DisplayNameFor(model => model.Body.MitigationPlan)
        @Html.TextAreaFor(model => model.Body.MitigationPlan, new { cols="40", rows="5" })

    <button type="submit">Save</button>
}

Make the SUTA edit text form bigger

Make the SUTA edit text form bigger


using UnityEngine;
using System.Collections;

namespace UDBase.Components.Log {
	public class LogTags {
		public const int Common = 1;
		public const int UI     = 2;

		string[] _names = new string[]{"Common", "UI"};

		public virtual string GetName(int index) {
			switch( index ) {
				case Common: {
						return "Common";
				}

				case UI: {
						return "UI";
				}
			}
			return "Unknown";
		}

		public virtual string[] GetNames() {
			return _names;
		}
	}
}

using UnityEngine;
using System.Collections;

namespace UDBase.Components.Log {
	public class LogTags {
		public const int Common = 1;
		public const int UI     = 2;
		public const int Scene  = 3;

		string[] _names = new string[]{"Common", "UI", "Scene"};

		public virtual string GetName(int index) {
			switch( index ) {
				case Common : return "Common";
				case UI     : return "UI";
				case Scene  : return "Scene";
			}
			return "Unknown";
		}

		public virtual string[] GetNames() {
			return _names;
		}
	}
}

Add tag for Scene logs; Code alignment;

Add tag for Scene logs; Code alignment;


using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;

namespace Nowin
{
    public class IpIsLocalChecker : IIpIsLocalChecker
    {
        readonly Dictionary<IPAddress, bool> _dict;

        public IpIsLocalChecker()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            _dict=host.AddressList.Where(
                a => a.AddressFamily == AddressFamily.InterNetwork || a.AddressFamily == AddressFamily.InterNetworkV6).
                ToDictionary(p => p, p => true);
            _dict.Add(IPAddress.Loopback,true);
            _dict.Add(IPAddress.IPv6Loopback,true);
        }

        public bool IsLocal(IPAddress address)
        {
            return _dict.ContainsKey(address);
        }
    }
}

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;

namespace Nowin
{
    public class IpIsLocalChecker : IIpIsLocalChecker
    {
        readonly Dictionary<IPAddress, bool> _dict;

        public IpIsLocalChecker()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            _dict = host.AddressList.Where(
                a => a.AddressFamily == AddressFamily.InterNetwork || a.AddressFamily == AddressFamily.InterNetworkV6).
                ToDictionary(p => p, p => true);
            _dict[IPAddress.Loopback] = true;
            _dict[IPAddress.IPv6Loopback] = true;
        }

        public bool IsLocal(IPAddress address)
        {
            return _dict.ContainsKey(address);
        }
    }
}

Fix of LocalChecker sometimes loopback could be already part of dictionary throwing exception on duplicate add.


using System;
using System.Collections.Generic;
using System.Diagnostics;
using FubuCore;
using FubuCore.Descriptions;
using FubuCore.Logging;
using FubuCore.Util;
using NLog;
using Logger = NLog.Logger;

namespace FubuMVC.NLog
{
    public class NLogListener : ILogListener
    {
        private readonly Cache<Type, Logger> _logger;

        public NLogListener()
        {
            _logger = new Cache<Type, Logger>(x => LogManager.GetLogger(x.FullName));
        }

        public bool IsDebugEnabled
        {
            get { return true; }
        }

        public bool IsInfoEnabled
        {
            get { return true; }
        }

        public void Debug(string message)
        {
            DebugMessage(message);
        }

        public void DebugMessage(object message)
        {
            _logger[message.GetType()].Debug(Description.For(message));
        }

        public void Error(string message, Exception ex)
        {
            _logger[message.GetType()].ErrorException(message, ex);
        }

        public void Error(object correlationId, string message, Exception ex)
        {
            Error(message, ex);
        }

        public void Info(string message)
        {
            InfoMessage(message);
        }

        public void InfoMessage(object message)
        {
            _logger[message.GetType()].Info(Description.For(message));
        }

        public bool ListensFor(Type type)
        {
            return true;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Diagnostics;
using FubuCore;
using FubuCore.Descriptions;
using FubuCore.Logging;
using FubuCore.Util;
using NLog;
using Logger = NLog.Logger;

namespace FubuMVC.NLog
{
    public class NLogListener : ILogListener
    {
        private readonly Cache<Type, Logger> _logger;

        public NLogListener()
        {
            _logger = new Cache<Type, Logger>(x => LogManager.GetLogger(x.FullName));
        }

        public bool IsDebugEnabled
        {
            get { return true; }
        }

        public bool IsInfoEnabled
        {
            get { return true; }
        }

        public void Debug(string message)
        {
            DebugMessage(message);
        }

        public void DebugMessage(object message)
        {
            _logger[message.GetType()].Debug(Description.For(message));
        }

        public void Error(string message, Exception ex)
        {
            var loggerType = ex != null ? ex.GetType() : message.GetType();
            _logger[loggerType].ErrorException(message, ex);
        }

        public void Error(object correlationId, string message, Exception ex)
        {
            Error(message, ex);
        }

        public void Info(string message)
        {
            InfoMessage(message);
        }

        public void InfoMessage(object message)
        {
            _logger[message.GetType()].Info(Description.For(message));
        }

        public bool ListensFor(Type type)
        {
            return true;
        }
    }
}

Change logger type for NLog error messages to be based on exception if possible


namespace Moya.Runner.Factories
{
    using System;
    using System.Collections.Generic;
    using Attributes;
    using Exceptions;
    using Extensions;
    using Moya.Utility;
    using Runners;

    public class TestRunnerFactory : ITestRunnerFactory
    {
        private readonly IDictionary<Type, Type> attributeTestRunnerMapping = new Dictionary<Type, Type>
        {
            { typeof(StressAttribute), typeof(StressTestRunner) }
        };

        public ITestRunner GetTestRunnerForAttribute(Type type)
        {
            if (!Reflection.TypeIsMoyaAttribute(type))
            {
                throw new MoyaException("Unable to provide moya test runner for type {0}".FormatWith(type));
            }

            Type typeOfTestRunner = attributeTestRunnerMapping[type];
            ITestRunner instance = (ITestRunner)Activator.CreateInstance(typeOfTestRunner);
            ITestRunner timerDecoratedInstance = new TimerDecorator(instance);
            return timerDecoratedInstance;
        }
    }
}

namespace Moya.Runner.Factories
{
    using System;
    using System.Collections.Generic;
    using Attributes;
    using Exceptions;
    using Extensions;
    using Moya.Utility;
    using Runners;

    public class TestRunnerFactory : ITestRunnerFactory
    {
        private readonly IDictionary<Type, Type> attributeTestRunnerMapping = new Dictionary<Type, Type>
        {
            { typeof(StressAttribute), typeof(StressTestRunner) },
            { typeof(WarmupAttribute), typeof(WarmupTestRunner) },
        };

        public ITestRunner GetTestRunnerForAttribute(Type type)
        {
            if (!Reflection.TypeIsMoyaAttribute(type))
            {
                throw new MoyaException("Unable to provide moya test runner for type {0}".FormatWith(type));
            }

            Type typeOfTestRunner = attributeTestRunnerMapping[type];
            ITestRunner instance = (ITestRunner)Activator.CreateInstance(typeOfTestRunner);
            ITestRunner timerDecoratedInstance = new TimerDecorator(instance);
            return timerDecoratedInstance;
        }
    }
}

Add warmup attribute to test runner factory


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

using System;
using osu.Game.Online.Multiplayer;
using osu.Game.Screens.Multi;

namespace osu.Game.Screens.Select
{
    public class MatchSongSelect : SongSelect, IMultiplayerScreen
    {
        public Action<PlaylistItem> Selected;

        public string ShortTitle => "song selection";

        protected override bool OnStart()
        {
            var item = new PlaylistItem
            {
                Beatmap = Beatmap.Value.BeatmapInfo,
                Ruleset = Ruleset.Value,
                RulesetID = Ruleset.Value.ID ?? 0
            };

            item.RequiredMods.AddRange(SelectedMods.Value);

            Selected?.Invoke(item);

            if (IsCurrentScreen)
                Exit();

            return true;
        }
    }
}

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

using System;
using Humanizer;
using osu.Game.Online.Multiplayer;
using osu.Game.Screens.Multi;

namespace osu.Game.Screens.Select
{
    public class MatchSongSelect : SongSelect, IMultiplayerScreen
    {
        public Action<PlaylistItem> Selected;

        public string ShortTitle => "song selection";
        public override string Title => ShortTitle.Humanize();

        protected override bool OnStart()
        {
            var item = new PlaylistItem
            {
                Beatmap = Beatmap.Value.BeatmapInfo,
                Ruleset = Ruleset.Value,
                RulesetID = Ruleset.Value.ID ?? 0
            };

            item.RequiredMods.AddRange(SelectedMods.Value);

            Selected?.Invoke(item);

            if (IsCurrentScreen)
                Exit();

            return true;
        }
    }
}

Fix title of match song select

Fix title of match song select


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

using osu.Game.Users;
using osu.Game.Rulesets;

namespace osu.Game.Online.API.Requests
{
    public class GetUserRequest : APIRequest<User>
    {
        private readonly string userIdentifier;
        public readonly RulesetInfo Ruleset;

        /// <summary>
        /// Gets the currently logged-in user.
        /// </summary>
        public GetUserRequest()
        {
        }

        /// <summary>
        /// Gets a user from their ID.
        /// </summary>
        /// <param name="userId">The user to get.</param>
        /// <param name="ruleset">The ruleset to get the user's info for.</param>
        public GetUserRequest(long? userId = null, RulesetInfo ruleset = null)
        {
            this.userIdentifier = userId.ToString();
            Ruleset = ruleset;
        }

        /// <summary>
        /// Gets a user from their username.
        /// </summary>
        /// <param name="username">The user to get.</param>
        /// <param name="ruleset">The ruleset to get the user's info for.</param>
        public GetUserRequest(string username = null, RulesetInfo ruleset = null)
        {
            this.userIdentifier = username;
            Ruleset = ruleset;
        }

        protected override string Target => userIdentifier != null ? $@"users/{userIdentifier}/{Ruleset?.ShortName}" : $@"me/{Ruleset?.ShortName}";
    }
}

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

using osu.Game.Users;
using osu.Game.Rulesets;

namespace osu.Game.Online.API.Requests
{
    public class GetUserRequest : APIRequest<User>
    {
        private readonly string lookup;
        public readonly RulesetInfo Ruleset;
        private readonly LookupType lookupType;

        /// <summary>
        /// Gets the currently logged-in user.
        /// </summary>
        public GetUserRequest()
        {
        }

        /// <summary>
        /// Gets a user from their ID.
        /// </summary>
        /// <param name="userId">The user to get.</param>
        /// <param name="ruleset">The ruleset to get the user's info for.</param>
        public GetUserRequest(long? userId = null, RulesetInfo ruleset = null)
        {
            lookup = userId.ToString();
            lookupType = LookupType.Id;
            Ruleset = ruleset;
        }

        /// <summary>
        /// Gets a user from their username.
        /// </summary>
        /// <param name="username">The user to get.</param>
        /// <param name="ruleset">The ruleset to get the user's info for.</param>
        public GetUserRequest(string username = null, RulesetInfo ruleset = null)
        {
            lookup = username;
            lookupType = LookupType.Username;
            Ruleset = ruleset;
        }

        protected override string Target => lookup != null ? $@"users/{lookup}/{Ruleset?.ShortName}?k={lookupType.ToString().ToLower()}" : $@"me/{Ruleset?.ShortName}";

        private enum LookupType
        {
            Id,
            Username
        }
    }
}

Use correct lookup type to ensure username based lookups always prefer username


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ploeh.AutoFixture.Kernel;

namespace Ploeh.AutoFixture
{
    /// <summary>
    /// Decorates an <see cref="ISpecimenBuilder" /> with a
    /// <see cref="OmitOnRecursionGuard" />.
    /// </summary>
    public class OmitOnRecursionBehavior : ISpecimenBuilderTransformation
    {
        /// <summary>
        /// Decorates the supplied <see cref="ISpecimenBuilder" /> with an
        /// <see cref="OmitOnRecursionGuard"/>.
        /// </summary>
        /// <param name="builder">The builder to decorate.</param>
        /// <returns>
        /// <paramref name="builder" /> decorated with an
        /// <see cref="RecursionGuard" />.
        /// </returns>
        public ISpecimenBuilder Transform(ISpecimenBuilder builder)
        {
            if (builder == null)
                throw new ArgumentNullException("builder");

            return new RecursionGuard(builder, new OmitOnRecursionHandler());
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ploeh.AutoFixture.Kernel;

namespace Ploeh.AutoFixture
{
    /// <summary>
    /// Decorates an <see cref="ISpecimenBuilder" /> with a
    /// <see cref="RecursionGuard" />.
    /// </summary>
    public class OmitOnRecursionBehavior : ISpecimenBuilderTransformation
    {
        /// <summary>
        /// Decorates the supplied <see cref="ISpecimenBuilder" /> with an
        /// <see cref="RecursionGuard"/>.
        /// </summary>
        /// <param name="builder">The builder to decorate.</param>
        /// <returns>
        /// <paramref name="builder" /> decorated with an
        /// <see cref="RecursionGuard" />.
        /// </returns>
        public ISpecimenBuilder Transform(ISpecimenBuilder builder)
        {
            if (builder == null)
                throw new ArgumentNullException("builder");

            return new RecursionGuard(builder, new OmitOnRecursionHandler());
        }
    }
}

Replace two xml comment instances of 'OmitOnRecursionGuard' with 'RecursionGuard'

The use of OmitOnRecursionGuard class seems to have been replaced with the combined use of RecursionGuard and OmitOnRecursionHandler. The class level xml comments for the OmitOnRecursionBehavior class, as well as its Transform method are updated with this commit to replace the word 'OmitOnRecursionGuard' with 'RecursionGuard' in a total of [2] places.


using System;
using System.Threading.Tasks;
namespace DanTup.DartAnalysis
{
	class VersionRequest : Request<Response<VersionResponse>>
	{
		public string method = "server.getVersion";
	}

	class VersionResponse
	{
		public string version = null;
	}

	public static class VersionRequestImplementation
	{
		public static async Task<Version> GetServerVersion(this DartAnalysisService service)
		{
			var response = await service.Service.Send(new VersionRequest());

			return Version.Parse(response.result.version);
		}
	}
}

using System;
using System.Threading.Tasks;
namespace DanTup.DartAnalysis
{
	class ServerVersionRequest : Request<Response<ServerVersionResponse>>
	{
		public string method = "server.getVersion";
	}

	class ServerVersionResponse
	{
		public string version = null;
	}

	public static class ServerVersionRequestImplementation
	{
		public static async Task<Version> GetServerVersion(this DartAnalysisService service)
		{
			var response = await service.Service.Send(new ServerVersionRequest());

			return Version.Parse(response.result.version);
		}
	}
}

Rename some classes to better match the service API.


using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace LiteDB.Tests
{
    public class LargeDoc
    {
        public ObjectId Id { get; set; }
        public Guid Guid { get; set; }
        public string Lorem { get; set; }
    }

    [TestClass]
    public class ShrinkDatabaseTest
    {
        [TestMethod]
        public void ShrinkDatabaseTest_Test()
        {
            using (var file = new TempFile())
            using (var db = new LiteDatabase(file.Filename))
            {
                var col = db.GetCollection<LargeDoc>("col");

                col.Insert(GetDocs(1, 10000));

                db.DropCollection("col");

                // full disk usage
                var size = file.Size;

                var r = db.Shrink();

                // only header page
                Assert.AreEqual(4096, size - r);
            }
        }

        private IEnumerable<LargeDoc> GetDocs(int initial, int count)
        {
            for (var i = initial; i < initial + count; i++)
            {
                yield return new LargeDoc
                {
                    Guid = Guid.NewGuid(),
                    Lorem = TempFile.LoremIpsum(10, 15, 2, 3, 3)
                };
            }
        }
    }
}

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace LiteDB.Tests
{
    public class LargeDoc
    {
        public ObjectId Id { get; set; }
        public Guid Guid { get; set; }
        public string Lorem { get; set; }
    }

    [TestClass]
    public class ShrinkDatabaseTest
    {
        [TestMethod]
        public void ShrinkDatabaseTest_Test()
        {
            using (var file = new TempFile())
            using (var db = new LiteDatabase(file.Filename))
            {
                var col = db.GetCollection<LargeDoc>("col");

                col.Insert(GetDocs(1, 10000));

                db.DropCollection("col");

                // full disk usage
                var size = file.Size;

                var r = db.Shrink();

                // only header page
                Assert.AreEqual(8192, size - r);
            }
        }

        private IEnumerable<LargeDoc> GetDocs(int initial, int count)
        {
            for (var i = initial; i < initial + count; i++)
            {
                yield return new LargeDoc
                {
                    Guid = Guid.NewGuid(),
                    Lorem = TempFile.LoremIpsum(10, 15, 2, 3, 3)
                };
            }
        }
    }
}

Fix unit test for 2 pages initial data

Fix unit test for 2 pages initial data


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

using System;
using System.Threading.Tasks;

namespace Microsoft.Fx.Portability
{
    public interface IObjectCache<TObject> : IDisposable
    {
        TObject Value { get; }
        DateTimeOffset LastUpdated { get; }
        Task UpdateAsync();
    }
}

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

using System;
using System.Threading.Tasks;

namespace Microsoft.Fx.Portability
{
    public interface IObjectCache : IDisposable
    {
        Task UpdateAsync();

        DateTimeOffset LastUpdated { get; }
    }

    public interface IObjectCache<TObject> : IObjectCache
    {
        TObject Value { get; }
    }
}

Add a non-generic object cache

Add a non-generic object cache


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

public class PlayerMovement : MonoBehaviour {

    public float movementSpeed = 1.0f;

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {
        var x = Input.GetAxis("Horizontal") * Time.deltaTime * movementSpeed;
        var z = Input.GetAxis("Vertical") * Time.deltaTime * movementSpeed;

        transform.Translate(x, 0, z);
    }

}

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

public class PlayerMovement : MonoBehaviour {

    public float movementSpeed = 1.0f;

    private bool isMovementLocked = false;

	// Use this for initialization
	void Start () {
	}

	// Update is called once per frame
	void Update () {
        look();
        if (isMovementLocked)
        {
            movement();
        }
    }

    private void look()
    {
        var ray = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Debug.DrawRay(Camera.main.transform.position, ray, Color.yellow);

        transform.LookAt(ray, new Vector3(0, 0, -1));
        transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);
    }

    private void movement()
    {
        var x = Input.GetAxis("Horizontal") * Time.deltaTime * movementSpeed;
        var z = Input.GetAxis("Vertical") * Time.deltaTime * movementSpeed;

        transform.Translate(x, 0, z, Space.World);
    }
}

Add Mouse Look Tracking to player character


using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Backend.Models;
using WalletWasabi.Interfaces;

namespace WalletWasabi.WebClients.SmartBit
{
	public class SmartBitExchangeRateProvider : IExchangeRateProvider
	{
		private SmartBitClient _client;

		public SmartBitExchangeRateProvider(SmartBitClient smartBitClient)
		{
			_client = smartBitClient;
		}

		public async Task<List<ExchangeRate>> GetExchangeRateAsync()
		{
			var rates = await _client.GetExchangeRatesAsync(CancellationToken.None);
			var rate = rates.Single(x => x.Code == "USD");

			var exchangeRates = new List<ExchangeRate>
			{
				new ExchangeRate { Rate = rate.Rate, Ticker = "USD" },
			};

			return exchangeRates;
		}
	}
}

using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Backend.Models;
using WalletWasabi.Interfaces;

namespace WalletWasabi.WebClients.SmartBit
{
	public class SmartBitExchangeRateProvider : IExchangeRateProvider
	{
		private SmartBitClient Client { get; }

		public SmartBitExchangeRateProvider(SmartBitClient smartBitClient)
		{
			Client = smartBitClient;
		}

		public async Task<List<ExchangeRate>> GetExchangeRateAsync()
		{
			var rates = await Client.GetExchangeRatesAsync(CancellationToken.None);
			var rate = rates.Single(x => x.Code == "USD");

			var exchangeRates = new List<ExchangeRate>
			{
				new ExchangeRate { Rate = rate.Rate, Ticker = "USD" },
			};

			return exchangeRates;
		}
	}
}

Use property instead of member

[skip ci] Use property instead of member


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

using osu.Framework.Timing;

namespace osu.Framework.Audio.Track
{
    public class TrackVirtual : Track
    {
        private readonly StopwatchClock clock = new StopwatchClock();

        private double seekOffset;

        public override bool Seek(double seek)
        {
            double current = CurrentTime;

            seekOffset = seek;
            lock (clock) clock.Restart();

            if (Length > 0 && seekOffset > Length)
                seekOffset = Length;

            return current != seekOffset;
        }

        public override void Start()
        {
            lock (clock) clock.Start();
        }

        public override void Reset()
        {
            lock (clock) clock.Reset();
            seekOffset = 0;

            base.Reset();
        }

        public override void Stop()
        {
            lock (clock) clock.Stop();
        }

        public override bool IsRunning
        {
            get
            {
                lock (clock) return clock.IsRunning;
            }
        }

        public override bool HasCompleted
        {
            get
            {
                lock (clock) return base.HasCompleted || IsLoaded && !IsRunning && CurrentTime >= Length;
            }
        }

        public override double CurrentTime
        {
            get
            {
                lock (clock) return seekOffset + clock.CurrentTime;
            }
        }

        public override void Update()
        {
            lock (clock)
            {
                if (CurrentTime >= Length)
                    Stop();
            }
        }
    }
}

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

using osu.Framework.Timing;

namespace osu.Framework.Audio.Track
{
    public class TrackVirtual : Track
    {
        private readonly StopwatchClock clock = new StopwatchClock();

        private double seekOffset;

        public TrackVirtual()
        {
            Length = double.MaxValue;
        }

        public override bool Seek(double seek)
        {
            double current = CurrentTime;

            seekOffset = seek;
            lock (clock) clock.Restart();

            if (Length > 0 && seekOffset > Length)
                seekOffset = Length;

            return current != seekOffset;
        }

        public override void Start()
        {
            lock (clock) clock.Start();
        }

        public override void Reset()
        {
            lock (clock) clock.Reset();
            seekOffset = 0;

            base.Reset();
        }

        public override void Stop()
        {
            lock (clock) clock.Stop();
        }

        public override bool IsRunning
        {
            get
            {
                lock (clock) return clock.IsRunning;
            }
        }

        public override bool HasCompleted
        {
            get
            {
                lock (clock) return base.HasCompleted || IsLoaded && !IsRunning && CurrentTime >= Length;
            }
        }

        public override double CurrentTime
        {
            get
            {
                lock (clock) return seekOffset + clock.CurrentTime;
            }
        }

        public override void Update()
        {
            lock (clock)
            {
                if (CurrentTime >= Length)
                    Stop();
            }
        }
    }
}

Make virtual tracks reeeeeeeaaally long

Make virtual tracks reeeeeeeaaally long


namespace Adaptive.ReactiveTrader.Client.UI.SpotTiles
{
    public static class PriceFormatter
    {
        public static FormattedPrice GetFormattedPrice(decimal rate, int precision, int pipsPosition)
        {
            var rateAsString = rate.ToString("0." + new string('0', precision));

            var dotIndex = rateAsString.IndexOf('.');

            var bigFigures = rateAsString.Substring(0, dotIndex + pipsPosition - 1);
            var pips = rateAsString.Substring(dotIndex + pipsPosition - 1, 2);

            var tenthOfPips = "";

            if (precision > pipsPosition)
            {
                tenthOfPips = rateAsString.Substring(dotIndex + pipsPosition + 1, rateAsString.Length - (dotIndex + pipsPosition + 1));
            }

            return new FormattedPrice(bigFigures, pips, tenthOfPips);
        }

        public static string GetFormattedSpread(decimal spread, int precision, int pipsPosition)
        {
            var delta = precision - pipsPosition;
            if (delta > 0)
            {
                return spread.ToString("0." + new string('0', delta));
            }
            return spread.ToString("0");
        }
    }
}

using System.Globalization;

namespace Adaptive.ReactiveTrader.Client.UI.SpotTiles
{
    public static class PriceFormatter
    {
        public static FormattedPrice GetFormattedPrice(decimal rate, int precision, int pipsPosition)
        {
            var rateAsString = rate.ToString("0." + new string('0', precision), CultureInfo.InvariantCulture);

            var dotIndex = rateAsString.IndexOf('.');

            var bigFigures = rateAsString.Substring(0, dotIndex + pipsPosition - 1);
            var pips = rateAsString.Substring(dotIndex + pipsPosition - 1, 2);

            var tenthOfPips = "";

            if (precision > pipsPosition)
            {
                tenthOfPips = rateAsString.Substring(dotIndex + pipsPosition + 1, rateAsString.Length - (dotIndex + pipsPosition + 1));
            }

            return new FormattedPrice(bigFigures, pips, tenthOfPips);
        }

        public static string GetFormattedSpread(decimal spread, int precision, int pipsPosition)
        {
            var delta = precision - pipsPosition;
            if (delta > 0)
            {
                return spread.ToString("0." + new string('0', delta), CultureInfo.InvariantCulture);
            }
            return spread.ToString("0");
        }
    }
}

Fix number format for locales that don't use . as decimal mark


using System.Windows;
using System.Windows.Shell;
using GitMind.ApplicationHandling.SettingsHandling;

namespace GitMind.Common
{
	public class JumpListService
	{
		private static readonly int MaxTitleLength = 25;

		public void Add(string workingFolder)
		{
			JumpList jumpList = JumpList.GetJumpList(Application.Current) ?? new JumpList();

			string title = workingFolder.Length < MaxTitleLength
				? workingFolder
				: "..." + workingFolder.Substring(workingFolder.Length - MaxTitleLength);

			JumpTask jumpTask = new JumpTask();
			jumpTask.Title = title;
			jumpTask.ApplicationPath = ProgramPaths.GetInstallFilePath();
			jumpTask.Arguments = $"/d:\"{workingFolder}\"";
			jumpTask.IconResourcePath = ProgramPaths.GetInstallFilePath();
			jumpTask.Description = workingFolder;

			jumpList.ShowRecentCategory = true;

			JumpList.AddToRecentCategory(jumpTask);
			JumpList.SetJumpList(Application.Current, jumpList);
		}
	}
}

using System.IO;
using System.Windows;
using System.Windows.Shell;
using GitMind.ApplicationHandling.SettingsHandling;

namespace GitMind.Common
{
	public class JumpListService
	{
		private static readonly int MaxTitleLength = 25;

		public void Add(string workingFolder)
		{
			JumpList jumpList = JumpList.GetJumpList(Application.Current) ?? new JumpList();

			string folderName = Path.GetFileName(workingFolder) ?? workingFolder;

			string title = folderName.Length < MaxTitleLength
				? folderName
				: folderName.Substring(0, MaxTitleLength) + "...";

			JumpTask jumpTask = new JumpTask();
			jumpTask.Title = title;
			jumpTask.ApplicationPath = ProgramPaths.GetInstallFilePath();
			jumpTask.Arguments = $"/d:\"{workingFolder}\"";
			jumpTask.IconResourcePath = ProgramPaths.GetInstallFilePath();
			jumpTask.Description = workingFolder;

			jumpList.ShowRecentCategory = true;

			JumpList.AddToRecentCategory(jumpTask);
			JumpList.SetJumpList(Application.Current, jumpList);
		}
	}
}

Make taskbar jump list show last part of path (folder name)


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

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

Use the .Data propertry as opposed to GetData in this PartialView


@model InfinysBreakfastOrders.Web.InputModels.Orders.OrderInputModel
@{
    ViewBag.Title = "Post New Order";
}

@ViewBag.Title

@using (Html.BeginForm("NewOrder", "Orders", FormMethod.Post))
{

        @Html.LabelFor(model => model.OrderDate)
        @Html.TextBoxFor(model => model.OrderDate, new { id = "date-picker" })

        @Html.LabelFor(model => model.OrderText)
        @Html.EditorFor(model => model.OrderText)

        <input type="submit" value="Post New Order" class="btn btn-primary btn-lg"/>

}

@model InfinysBreakfastOrders.Web.InputModels.Orders.OrderInputModel
@{
    ViewBag.Title = "Post New Order";
}

@ViewBag.Title

@using (Html.BeginForm("NewOrder", "Orders", FormMethod.Post))
{

        @Html.LabelFor(model => model.OrderDate)
        @Html.TextBoxFor(model => model.OrderDate, new { id = "date-picker", @Value = DateTime.Now.Date })

        @Html.LabelFor(model => model.OrderText)
        @Html.EditorFor(model => model.OrderText)

        <input type="submit" value="Post New Order" class="btn btn-primary btn-lg"/>

}

Fix date in date pickuper

Fix date in date pickuper


@model WuzlStats.ViewModels.Player.TeamPlayerStats

Teams

                Games played:

@Model.WinsCount    @Model.LossesCount

                Favorite partner:

@Model.FavoritePartner

                Favorite team:

@Model.FavoriteTeam

                Favorite position:

@Model.FavoritePosition

Fix whitespace in team player stats view.


using System.Web;
using Newtonsoft.Json;
using System;

namespace TropoCSharp.Tropo
{
    /// <summary>
    /// A utility class to render a Tropo object as JSON.
    /// </summary>
    public static class TropoJSONExtensions
    {
        public static void RenderJSON(this Tropo tropo, HttpResponse response)
        {
            tropo.Language = null;
            tropo.Voice = null;
            JsonSerializerSettings settings = new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore };
            response.AddHeader("WebAPI-Lang-Ver", "CSharp V15.8.0 SNAPSHOT");
            response.Write(JsonConvert.SerializeObject(tropo, Formatting.None, settings).Replace("\\", "").Replace("\"{", "{").Replace("}\"", "}"));

        }
    }

}

using System.Web;
using Newtonsoft.Json;
using System;

namespace TropoCSharp.Tropo
{
    /// <summary>
    /// A utility class to render a Tropo object as JSON.
    /// </summary>
    public static class TropoJSONExtensions
    {
        public static void RenderJSON(this Tropo tropo, HttpResponse response)
        {
            tropo.Language = null;
            tropo.Voice = null;
            JsonSerializerSettings settings = new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore };
            response.AddHeader("WebAPI-Lang-Ver", "CSharp V15.8.0 2017-05-22");
            response.Write(JsonConvert.SerializeObject(tropo, Formatting.None, settings).Replace("\\", "").Replace("\"{", "{").Replace("}\"", "}"));

        }
    }

}

Make a tag V15.8.0 2017-05-22

Make a tag V15.8.0 2017-05-22


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

using osu.Framework.Platform;

namespace osu.Game.Tests
{
    /// <summary>
    /// A headless host which cleans up before running (removing any remnants from a previous execution).
    /// </summary>
    public class CleanRunHeadlessGameHost : HeadlessGameHost
    {
        public CleanRunHeadlessGameHost(string gameName = @"", bool bindIPC = false, bool realtime = true)
            : base(gameName, bindIPC, realtime)
        {
            Storage.DeleteDirectory(string.Empty);
        }
    }
}

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

using osu.Framework.Platform;

namespace osu.Game.Tests
{
    /// <summary>
    /// A headless host which cleans up before running (removing any remnants from a previous execution).
    /// </summary>
    public class CleanRunHeadlessGameHost : HeadlessGameHost
    {
        public CleanRunHeadlessGameHost(string gameName = @"", bool bindIPC = false, bool realtime = true)
            : base(gameName, bindIPC, realtime)
        {
        }

        protected override void SetupForRun()
        {
            base.SetupForRun();
            Storage.DeleteDirectory(string.Empty);
        }
    }
}

Fix remaining game host regressions

Fix remaining game host regressions


using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.Owin.Builder;
using Owin;

namespace CefSharp.Owin.Example.Wpf
{
    //Shorthand for Owin pipeline func
    using AppFunc = Func<IDictionary<string, object>, Task>;

    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            var appBuilder = new AppBuilder();
            appBuilder.UseNancy();
            var appFunc = (AppFunc)appBuilder.Build(typeof (AppFunc));

            var settings = new CefSettings();
            settings.RegisterOwinSchemeHandlerFactory("owin", appFunc);
            Cef.Initialize(settings);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.Owin.Builder;
using Owin;

namespace CefSharp.Owin.Example.Wpf
{
    //Shorthand for Owin pipeline func
    using AppFunc = Func<IDictionary<string, object>, Task>;

    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            var appBuilder = new AppBuilder();
            appBuilder.UseNancy();
            var appFunc = appBuilder.Build<AppFunc>();

            var settings = new CefSettings();
            settings.RegisterOwinSchemeHandlerFactory("owin", appFunc);
            Cef.Initialize(settings);
        }
    }
}

Switch to the Build<AppFunc> extension method - nicer syntax


namespace LibGit2Sharp.Core
{
    internal enum GitErrorCategory
    {
        Unknown = -1,
        NoMemory,
        Os,
        Invalid,
        Reference,
        Zlib,
        Repository,
        Config,
        Regex,
        Odb,
        Index,
        Object,
        Net,
        Tag,
        Tree,
        Indexer,
        Ssl,
        Submodule,
        Thread,
        Stash,
        Checkout,
        FetchHead,
        Merge,
        Ssh,
        Filter,
    }
}

namespace LibGit2Sharp.Core
{
    internal enum GitErrorCategory
    {
        Unknown = -1,
        None,
        NoMemory,
        Os,
        Invalid,
        Reference,
        Zlib,
        Repository,
        Config,
        Regex,
        Odb,
        Index,
        Object,
        Net,
        Tag,
        Tree,
        Indexer,
        Ssl,
        Submodule,
        Thread,
        Stash,
        Checkout,
        FetchHead,
        Merge,
        Ssh,
        Filter,
        Revert,
        Callback,
    }
}

Update error categories to match libgit2


using BatteryCommander.Web.Models;
using System;
using System.Collections.Generic;
using Xunit;

namespace BatteryCommander.Tests
{
    public class FiscalYearTests
    {
        [Fact]

        public void Check_FY_2017_Start()
        {

        }
    }
}

using BatteryCommander.Web.Models;
using System;
using System.Collections.Generic;
using Xunit;
using BatteryCommander.Web.Services;

namespace BatteryCommander.Tests
{
    public class FiscalYearTests
    {
        [Fact]

        public void Check_FY_2017_Start()
        {
            Assert.Equal(new DateTime(2016, 10, 1), FiscalYear.FY2017.Start());
        }

        [Fact]
        public void Check_FY_2017_Next()
        {
            Assert.Equal(FiscalYear.FY2018, FiscalYear.FY2017.Next());
        }

        [Fact]
        public void Check_FY_2017_End()
        {
            Assert.Equal(new DateTime(2017, 9, 30), FiscalYear.FY2017.End());
        }
    }
}

Add tests for FY handling

Add tests for FY handling


// 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.

#nullable disable

using osu.Framework.Localisation;
using osu.Game.Resources.Localisation.Web;

namespace osu.Game.Overlays.BeatmapListing
{
    public enum SortCriteria
    {
        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingTitle))]
        Title,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingArtist))]
        Artist,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingDifficulty))]
        Difficulty,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingRanked))]
        Ranked,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingRating))]
        Rating,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingPlays))]
        Plays,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingFavourites))]
        Favourites,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingRelevance))]
        Relevance
    }
}

// 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.

#nullable disable

using osu.Framework.Localisation;
using osu.Game.Resources.Localisation.Web;

namespace osu.Game.Overlays.BeatmapListing
{
    public enum SortCriteria
    {
        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingTitle))]
        Title,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingArtist))]
        Artist,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingDifficulty))]
        Difficulty,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingUpdated))]
        Updated,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingRanked))]
        Ranked,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingRating))]
        Rating,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingPlays))]
        Plays,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingFavourites))]
        Favourites,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingRelevance))]
        Relevance,

        [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingNominations))]
        Nominations,
    }
}

Add "Nominations" and "Updated" sorting criteria in beatmap listing


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

// TODO: Hide header when no items in dropdown
namespace osu.Framework.Graphics.UserInterface.Tab
{
    public abstract class TabDropDownMenu<T> : DropDownMenu<T>
    {
        protected TabDropDownMenu()
        {
            RelativeSizeAxes = Axes.X;
            Header.Anchor = Anchor.TopRight;
            Header.Origin = Anchor.TopRight;
            ContentContainer.Anchor = Anchor.TopRight;
            ContentContainer.Origin = Anchor.TopRight;
        }

        internal float HeaderHeight
        {
            get { return Header.DrawHeight; }
            set { Header.Height = value; }
        }

        internal float HeaderWidth
        {
            get { return Header.DrawWidth; }
            set { Header.Width = value; }
        }

        internal void HideItem(T val)
        {
            int index;
            if (ItemDictionary.TryGetValue(val, out index))
                ItemList[index]?.Hide();
        }

        internal void ShowItem(T val)
        {
            int index;
            if (ItemDictionary.TryGetValue(val, out index))
                ItemList[index]?.Show();
        }
    }
}

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

using System.Linq;

namespace osu.Framework.Graphics.UserInterface.Tab
{
    public abstract class TabDropDownMenu<T> : DropDownMenu<T>
    {
        protected TabDropDownMenu()
        {
            RelativeSizeAxes = Axes.X;
            Header.Anchor = Anchor.TopRight;
            Header.Origin = Anchor.TopRight;
            ContentContainer.Anchor = Anchor.TopRight;
            ContentContainer.Origin = Anchor.TopRight;
        }

        internal float HeaderHeight
        {
            get { return Header.DrawHeight; }
            set { Header.Height = value; }
        }

        internal float HeaderWidth
        {
            get { return Header.DrawWidth; }
            set { Header.Width = value; }
        }

        internal void HideItem(T val)
        {
            int index;
            if (ItemDictionary.TryGetValue(val, out index))
                ItemList[index]?.Hide();

            updateAlphaVisibility();
        }

        internal void ShowItem(T val)
        {
            int index;
            if (ItemDictionary.TryGetValue(val, out index))
                ItemList[index]?.Show();

            updateAlphaVisibility();
        }

        private void updateAlphaVisibility() => Header.Alpha = ItemList.Any(i => i.IsPresent) ? 1 : 0;
    }
}

Hide TabControl's dropdown's header when no items are inside the dropdown.


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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Game.Configuration;
using osu.Game.Localisation;

namespace osu.Game.Overlays.Settings.Sections.Gameplay
{
    public class HUDSettings : SettingsSubsection
    {
        protected override LocalisableString Header => GameplaySettingsStrings.HUDHeader;

        [BackgroundDependencyLoader]
        private void load(OsuConfigManager config)
        {
            Children = new Drawable[]
            {
                new SettingsEnumDropdown<HUDVisibilityMode>
                {
                    LabelText = GameplaySettingsStrings.HUDVisibilityMode,
                    Current = config.GetBindable<HUDVisibilityMode>(OsuSetting.HUDVisibilityMode)
                },
                new SettingsCheckbox
                {
                    LabelText = GameplaySettingsStrings.ShowDifficultyGraph,
                    Current = config.GetBindable<bool>(OsuSetting.ShowProgressGraph)
                },
                new SettingsCheckbox
                {
                    LabelText = GameplaySettingsStrings.ShowHealthDisplayWhenCantFail,
                    Current = config.GetBindable<bool>(OsuSetting.ShowHealthDisplayWhenCantFail),
                    Keywords = new[] { "hp", "bar" }
                },
                new SettingsCheckbox
                {
                    LabelText = GameplaySettingsStrings.AlwaysShowKeyOverlay,
                    Current = config.GetBindable<bool>(OsuSetting.KeyOverlay)
                },
            };
        }
    }
}

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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Game.Configuration;
using osu.Game.Localisation;

namespace osu.Game.Overlays.Settings.Sections.Gameplay
{
    public class HUDSettings : SettingsSubsection
    {
        protected override LocalisableString Header => GameplaySettingsStrings.HUDHeader;

        [BackgroundDependencyLoader]
        private void load(OsuConfigManager config)
        {
            Children = new Drawable[]
            {
                new SettingsEnumDropdown<HUDVisibilityMode>
                {
                    LabelText = GameplaySettingsStrings.HUDVisibilityMode,
                    Current = config.GetBindable<HUDVisibilityMode>(OsuSetting.HUDVisibilityMode)
                },
                new SettingsCheckbox
                {
                    LabelText = GameplaySettingsStrings.ShowDifficultyGraph,
                    Current = config.GetBindable<bool>(OsuSetting.ShowProgressGraph)
                },
                new SettingsCheckbox
                {
                    LabelText = GameplaySettingsStrings.ShowHealthDisplayWhenCantFail,
                    Current = config.GetBindable<bool>(OsuSetting.ShowHealthDisplayWhenCantFail),
                    Keywords = new[] { "hp", "bar" }
                },
                new SettingsCheckbox
                {
                    LabelText = GameplaySettingsStrings.AlwaysShowKeyOverlay,
                    Current = config.GetBindable<bool>(OsuSetting.KeyOverlay),
                    Keywords = new[] { "counter" },
                },
            };
        }
    }
}

Add "counter" keyword for key overlay setting


using System;
using Autofac.Builder;
using Hangfire.Annotations;

namespace Hangfire
{
    /// <summary>
    /// Adds registration syntax to the <see cref="Autofac.ContainerBuilder"/> type.
    /// </summary>
    public static class RegistrationExtensions
    {
        /// <summary>
        /// Share one instance of the component within the context of a single
        /// processing background job instance.
        /// </summary>
        /// <typeparam name="TLimit">Registration limit type.</typeparam>
        /// <typeparam name="TActivatorData">Activator data type.</typeparam>
        /// <typeparam name="TStyle">Registration style.</typeparam>
        /// <param name="registration">The registration to configure.</param>
        /// <returns>A registration builder allowing further configuration of the component.</returns>
        /// <exception cref="ArgumentNullException">
        /// Thrown when <paramref name="registration"/> is <see langword="null"/>.
        /// </exception>
        public static IRegistrationBuilder<TLimit, TActivatorData, TStyle>
            InstancePerBackgroundJob<TLimit, TActivatorData, TStyle>(
            [NotNull] this IRegistrationBuilder<TLimit, TActivatorData, TStyle> registration)
        {
            if (registration == null) throw new ArgumentNullException("registration");
            return registration.InstancePerMatchingLifetimeScope(AutofacJobActivator.LifetimeScopeTag);
        }
    }
}

using System;
using System.Linq;
using Autofac.Builder;
using Hangfire.Annotations;

namespace Hangfire
{
    /// <summary>
    /// Adds registration syntax to the <see cref="Autofac.ContainerBuilder"/> type.
    /// </summary>
    public static class RegistrationExtensions
    {
        /// <summary>
        /// Share one instance of the component within the context of a single
        /// processing background job instance.
        /// </summary>
        /// <typeparam name="TLimit">Registration limit type.</typeparam>
        /// <typeparam name="TActivatorData">Activator data type.</typeparam>
        /// <typeparam name="TStyle">Registration style.</typeparam>
        /// <param name="registration">The registration to configure.</param>
        /// <param name="lifetimeScopeTags">Additional tags applied for matching lifetime scopes.</param>
        /// <returns>A registration builder allowing further configuration of the component.</returns>
        /// <exception cref="ArgumentNullException">
        /// Thrown when <paramref name="registration"/> is <see langword="null"/>.
        /// </exception>
        public static IRegistrationBuilder<TLimit, TActivatorData, TStyle>
            InstancePerBackgroundJob<TLimit, TActivatorData, TStyle>(
            [NotNull] this IRegistrationBuilder<TLimit, TActivatorData, TStyle> registration,
            params object[] lifetimeScopeTags)
        {
            if (registration == null) throw new ArgumentNullException("registration");

            var tags = new[] { AutofacJobActivator.LifetimeScopeTag }.Concat(lifetimeScopeTags).ToArray();
            return registration.InstancePerMatchingLifetimeScope(tags);
        }
    }
}

Allow combining lifetime scope tags

Allow combining lifetime scope tags

Autofac's lifetimeScope registration methods such as `InstancePerRequest` and `InstancePerMatchingLifetimeScope` take a `params object[] lifetimeScopeTags` at the end allowing easy combining of allowed scopes. I've added this parameter to `InstancePerBackgroundJob`.

This lets people call `InstancePerBackgroundJob(Autofac.Core.Lifetime.MatchingScopeLifetimeTags.RequestLifetimeScopeTag)` allowing for proper registration of a component for either webrequests or background jobs, as well as allowing people to bring in their own tags if needed.


using System;
using System.Collections.Generic;

namespace website_performance.Entities
{
    public class Robots
    {
        private readonly List<Uri> _sitemaps = new List<Uri>();

        public Robots(string url)
        {
            if (Uri.TryCreate(url, UriKind.Absolute, out var robotsUrl))
                Url = robotsUrl;
            else
                throw new UriFormatException($"Fail to parse URL \"{url}\"");
        }

        public Uri Url { get; }

        public IReadOnlyCollection<Uri> Sitemaps => _sitemaps;

        public void AddSitemap(string sitemapUrl)
        {
            if (Uri.TryCreate(sitemapUrl, UriKind.Absolute, out var sitemap))
            {
                if (_sitemaps.Contains(sitemap) == false)
                    _sitemaps.Add(sitemap);
            }
            else
            {
                throw new UriFormatException($"Fail to parse URL \"{sitemapUrl}\"");
            }
        }

        // New code
        public void GeneratePerformanceReport()
        {
            throw new NotImplementedException();
        }
    }
}

using System;
using System.Collections.Generic;
using website_performance.Infrastructure;

namespace website_performance.Entities
{
    public class Robots
    {
        private readonly IHttpMessageHandlerFactory _httpMessageHandlerFactory;
        private readonly List<Uri> _sitemaps = new List<Uri>();

        public Robots(string url)
        {
            if (Uri.TryCreate(url, UriKind.Absolute, out var robotsUrl))
                Url = robotsUrl;
            else
                throw new UriFormatException($"Fail to parse URL \"{url}\"");
        }

        public Robots(string url, IHttpMessageHandlerFactory httpMessageHandlerFactory)
        {
            _httpMessageHandlerFactory = httpMessageHandlerFactory ?? throw new ArgumentNullException(nameof(httpMessageHandlerFactory));

            if (Uri.TryCreate(url, UriKind.Absolute, out var robotsUrl))
                Url = robotsUrl;
            else
                throw new UriFormatException($"Fail to parse URL \"{url}\"");
        }

        public Uri Url { get; }

        public IReadOnlyCollection<Uri> Sitemaps => _sitemaps;

        public void AddSitemap(string sitemapUrl)
        {
            if (Uri.TryCreate(sitemapUrl, UriKind.Absolute, out var sitemap))
            {
                if (_sitemaps.Contains(sitemap) == false)
                    _sitemaps.Add(sitemap);
            }
            else
            {
                throw new UriFormatException($"Fail to parse URL \"{sitemapUrl}\"");
            }
        }

        // New code
        public void GeneratePerformanceReport()
        {
            throw new NotImplementedException();
        }
    }
}

Add ctor to pipe the http factory

Add ctor to pipe the http factory


using Microsoft.Extensions.Options;
using SendGrid.Helpers.Mail;
using System.Threading.Tasks;

namespace BatteryCommander.Web.Services
{
    public interface IEmailService
    {
        Task Send(SendGridMessage message);
    }

    public class EmailService : IEmailService
    {
        public static readonly EmailAddress FROM_ADDRESS = new EmailAddress("BatteryCommander@red-leg-dev.com");

        private readonly IOptions<SendGridSettings> settings;

        private SendGrid.ISendGridClient client => new SendGrid.SendGridClient(apiKey: settings.Value.APIKey);

        public EmailService(IOptions<SendGridSettings> settings)
        {
            this.settings = settings;
        }

        public virtual async Task Send(SendGridMessage message)
        {
            // TODO Add logging
            // TODO Handle if it doesn't send successfully

            var response = await client.SendEmailAsync(message);
        }
    }
}

using Microsoft.Extensions.Options;
using SendGrid.Helpers.Mail;
using System.Threading.Tasks;

namespace BatteryCommander.Web.Services
{
    public interface IEmailService
    {
        Task Send(SendGridMessage message);
    }

    public class EmailService : IEmailService
    {
        public static readonly EmailAddress FROM_ADDRESS = new EmailAddress("BatteryCommander@redleg.app");

        private readonly IOptions<SendGridSettings> settings;

        private SendGrid.ISendGridClient client => new SendGrid.SendGridClient(apiKey: settings.Value.APIKey);

        public EmailService(IOptions<SendGridSettings> settings)
        {
            this.settings = settings;
        }

        public virtual async Task Send(SendGridMessage message)
        {
            // TODO Add logging
            // TODO Handle if it doesn't send successfully

            var response = await client.SendEmailAsync(message);
        }
    }
}

Change the FROM address to redleg.app

Change the FROM address to redleg.app


namespace TraktApiSharp.Objects.Get.Shows.Seasons
{
    using Newtonsoft.Json;

    /// <summary>
    /// A collection of ids for various web services for a Trakt season.
    /// </summary>
    public class TraktSeasonIds
    {
        /// <summary>
        /// The Trakt numeric id for the season.
        /// </summary>
        [JsonProperty(PropertyName = "trakt")]
        public int Trakt { get; set; }

        /// <summary>
        /// The numeric id for the season from thetvdb.com
        /// </summary>
        [JsonProperty(PropertyName = "tvdb")]
        public int? Tvdb { get; set; }

        /// <summary>
        /// The numeric id for the season from themoviedb.org
        /// </summary>
        [JsonProperty(PropertyName = "tmdb")]
        public int? Tmdb { get; set; }

        /// <summary>
        /// The numeric id for the season from tvrage.com
        /// </summary>
        [JsonProperty(PropertyName = "tvrage")]
        public int? TvRage { get; set; }

        /// <summary>
        /// Tests, if at least one id has been set.
        /// </summary>
        [JsonIgnore]
        public bool HasAnyId => Trakt > 0 || Tvdb > 0 || Tvdb > 0 || TvRage > 0;
    }
}

namespace TraktApiSharp.Objects.Get.Shows.Seasons
{
    using Newtonsoft.Json;

    /// A collection of ids for various web services, including the Trakt id, for a Trakt season.
    public class TraktSeasonIds
    {
        /// Gets or sets the Trakt numeric id.
        [JsonProperty(PropertyName = "trakt")]
        public int Trakt { get; set; }

        /// Gets or sets the numeric id from thetvdb.com
        [JsonProperty(PropertyName = "tvdb")]
        public int? Tvdb { get; set; }

        /// Gets or sets the numeric id from themoviedb.org
        [JsonProperty(PropertyName = "tmdb")]
        public int? Tmdb { get; set; }

        /// Gets or sets the numeric id from tvrage.com
        [JsonProperty(PropertyName = "tvrage")]
        public int? TvRage { get; set; }

        /// Returns, whether any id has been set.
        [JsonIgnore]
        public bool HasAnyId => Trakt > 0 || Tvdb > 0 || Tvdb > 0 || TvRage > 0;
    }
}

Update existing documentation for season ids.


using SnakeApp.Models;
using System;

namespace SnakeApp.Controllers
{
	public class GameController
	{
		public void StartNewGame()
		{
			PrepareConsole();

			var game = new Game(80, 25, 5, 100);
			game.StartAsync();

			ConsoleKeyInfo userInput = new ConsoleKeyInfo();
			do
			{
				userInput = Console.ReadKey(true);
				game.ReceiveInput(userInput.Key);
			} while (userInput.Key != ConsoleKey.Q);

			RestoreConsole();
		}

		private void PrepareConsole()
		{
			// getting the current cursor visibility is not supported on linux, so just hide then restore it
			Console.Clear();
			Console.CursorVisible = false;
		}

		private void RestoreConsole()
		{
			Console.Clear();
			Console.CursorVisible = true;
		}
	}
}

using SnakeApp.Models;
using System;

namespace SnakeApp.Controllers
{
	public class GameController
	{
		private byte MAX_WIDTH = 80;
		private byte MAX_HEIGHT = 25;

		public void StartNewGame()
		{
			PrepareConsole();

			var game = new Game(Math.Min((byte)(Console.WindowWidth - 1), MAX_WIDTH), Math.Min((byte)(Console.WindowHeight - 1), MAX_HEIGHT), 5, 100);
			game.StartAsync();

			ConsoleKeyInfo userInput = new ConsoleKeyInfo();
			do
			{
				userInput = Console.ReadKey(true);
				game.ReceiveInput(userInput.Key);
			} while (userInput.Key != ConsoleKey.Q);

			RestoreConsole();
		}

		private void PrepareConsole()
		{
			// getting the current cursor visibility is not supported on linux, so just hide then restore it
			Console.Clear();
			Console.CursorVisible = false;
		}

		private void RestoreConsole()
		{
			Console.Clear();
			Console.CursorVisible = true;
		}
	}
}

Set the the game width and height to the console window size or to a maximum value.


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

namespace osu.Game.Screens.Select
{
    public class MatchSongSelect : SongSelect
    {
        protected override bool OnSelectionFinalised()
        {
            Exit();
            return true;
        }
    }
}

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

namespace osu.Game.Screens.Select
{
    public class MatchSongSelect : SongSelect
    {
        protected override bool OnSelectionFinalised()
        {
            Schedule(() =>
            {
                // needs to be scheduled else we enter an infinite feedback loop.
                if (IsCurrentScreen) Exit();
            });

            return true;
        }
    }
}

Fix an endless feedback loop

Fix an endless feedback loop


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

namespace Microsoft.DotNet.Cli.Build
{
    public class DotNetTest : DotNetTool
    {
        protected override string Command
        {
            get { return "test"; }
        }

        protected override string Args
        {
            get { return $"{GetProjectPath()} {GetConfiguration()} {GetLogger()} {GetNoBuild()}"; }
        }

        public string Configuration { get; set; }

        public string Logger { get; set; }

        public string ProjectPath { get; set; }

        public bool NoBuild { get; set; }

        private string GetConfiguration()
        {
            if (!string.IsNullOrEmpty(Configuration))
            {
                return $"--configuration {Configuration}";
            }

            return null;
        }

        private string GetLogger()
        {
            if (!string.IsNullOrEmpty(Logger))
            {
                return $"--logger:{Logger}";
            }

            return null;
        }

        private string GetProjectPath()
        {
            if (!string.IsNullOrEmpty(ProjectPath))
            {
                return $"{ProjectPath}";
            }

            return null;
        }

        private string GetNoBuild()
        {
            if (NoBuild)
            {
                return "--noBuild";
            }

            return null;
        }
    }
}

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

namespace Microsoft.DotNet.Cli.Build
{
    public class DotNetTest : DotNetTool
    {
        protected override string Command
        {
            get { return "test"; }
        }

        protected override string Args
        {
            get { return $"{GetProjectPath()} {GetConfiguration()} {GetLogger()} {GetNoBuild()}"; }
        }

        public string Configuration { get; set; }

        public string Logger { get; set; }

        public string ProjectPath { get; set; }

        public bool NoBuild { get; set; }

        private string GetConfiguration()
        {
            if (!string.IsNullOrEmpty(Configuration))
            {
                return $"--configuration {Configuration}";
            }

            return null;
        }

        private string GetLogger()
        {
            if (!string.IsNullOrEmpty(Logger))
            {
                return $"--logger:{Logger}";
            }

            return null;
        }

        private string GetProjectPath()
        {
            if (!string.IsNullOrEmpty(ProjectPath))
            {
                return $"{ProjectPath}";
            }

            return null;
        }

        private string GetNoBuild()
        {
            if (NoBuild)
            {
                return "--no-build";
            }

            return null;
        }
    }
}

Fix no build option in dotnet test task

Fix no build option in dotnet test task


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

using System;
using Microsoft.Owin.Infrastructure;
using Microsoft.Owin.Security.Infrastructure;

namespace Microsoft.Owin.Security.OAuth
{
    public class OAuthAuthorizationServerOptions : AuthenticationOptions
    {
        public OAuthAuthorizationServerOptions() : base("Bearer")
        {
            AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(5);
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14);
            SystemClock = new SystemClock();
        }

        public string AuthorizeEndpointPath { get; set; }
        public string TokenEndpointPath { get; set; }

        public IOAuthAuthorizationServerProvider Provider { get; set; }

        public ISecureDataFormat<AuthenticationTicket> AuthorizationCodeFormat { get; set; }
        public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; set; }
        public ISecureDataFormat<AuthenticationTicket> RefreshTokenFormat { get; set; }

        public TimeSpan AuthorizationCodeExpireTimeSpan { get; set; }
        public TimeSpan AccessTokenExpireTimeSpan { get; set; }

        public IAuthenticationTokenProvider AuthorizationCodeProvider { get; set; }
        public IAuthenticationTokenProvider AccessTokenProvider { get; set; }
        public IAuthenticationTokenProvider RefreshTokenProvider { get; set; }

        public bool AuthorizeEndpointDisplaysError { get; set; }

        public ISystemClock SystemClock { get; set; }
    }
}

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

using System;
using Microsoft.Owin.Infrastructure;
using Microsoft.Owin.Security.Infrastructure;

namespace Microsoft.Owin.Security.OAuth
{
    public class OAuthAuthorizationServerOptions : AuthenticationOptions
    {
        public OAuthAuthorizationServerOptions() : base("Bearer")
        {
            AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(5);
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20);
            SystemClock = new SystemClock();
        }

        public string AuthorizeEndpointPath { get; set; }
        public string TokenEndpointPath { get; set; }

        public IOAuthAuthorizationServerProvider Provider { get; set; }

        public ISecureDataFormat<AuthenticationTicket> AuthorizationCodeFormat { get; set; }
        public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; set; }
        public ISecureDataFormat<AuthenticationTicket> RefreshTokenFormat { get; set; }

        public TimeSpan AuthorizationCodeExpireTimeSpan { get; set; }
        public TimeSpan AccessTokenExpireTimeSpan { get; set; }

        public IAuthenticationTokenProvider AuthorizationCodeProvider { get; set; }
        public IAuthenticationTokenProvider AccessTokenProvider { get; set; }
        public IAuthenticationTokenProvider RefreshTokenProvider { get; set; }

        public bool AuthorizeEndpointDisplaysError { get; set; }

        public ISystemClock SystemClock { get; set; }
    }
}

Reduce default access token expiration timespan

20 minutes by default