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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AxosoftAPI.NET")]
[assembly: AssemblyDescription(".NET wrapper for the Axosoft API v4")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Axosoft")]
[assembly: AssemblyProduct("AxosoftAPI.NET")]
[assembly: AssemblyCopyright("Copyright ©  2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e9dab9c2-a84d-4572-9bc2-93347b5cdc8a")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("4.0.3.0")]
[assembly: AssemblyFileVersion("4.0.3.0")]

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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AxosoftAPI.NET")]
[assembly: AssemblyDescription(".NET wrapper for the Axosoft API v4")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Axosoft")]
[assembly: AssemblyProduct("AxosoftAPI.NET")]
[assembly: AssemblyCopyright("Copyright ©  2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e9dab9c2-a84d-4572-9bc2-93347b5cdc8a")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("4.0.4.0")]
[assembly: AssemblyFileVersion("4.0.4.0")]

Change project version based on lateset NuGet package.


namespace CertiPay.Common.Testing
{
    using ApprovalTests;
    using Newtonsoft.Json;
    using Ploeh.AutoFixture;

    public static class TestExtensions
    {
        private static readonly Fixture _fixture = new Fixture { };

        /// <summary>
        /// Runs ApprovalTests's VerifyJson against a JSON.net serialized representation of the provided object
        /// </summary>
        public static void VerifyMe(this object obj)
        {
            var json = JsonConvert.SerializeObject(obj);

            Approvals.VerifyJson(json);
        }

        public static T AutoGenerate<T>()
        {
            return _fixture.Create<T>();
        }
    }
}

namespace CertiPay.Common.Testing
{
    using ApprovalTests;
    using Newtonsoft.Json;
    using Ploeh.AutoFixture;

    public static class TestExtensions
    {
        private static readonly Fixture _fixture = new Fixture { };

        /// <summary>
        /// Runs ApprovalTests's VerifyJson against a JSON.net serialized representation of the provided object
        /// </summary>
        public static void VerifyMe(this object obj)
        {
            var json = JsonConvert.SerializeObject(obj);

            Approvals.VerifyJson(json);
        }

        /// <summary>
        /// Returns an auto-initialized instance of the type T, filled via mock
        /// data via AutoFixture.
        ///
        /// This will not work for interfaces, only concrete types.
        /// </summary>
        public static T AutoGenerate<T>()
        {
            return _fixture.Create<T>();
        }
    }
}

Update comments on test extensions

Update comments on test extensions


using MyDocs.Common.Contract.Storage;
using MyDocs.Common.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyDocs.Common.Contract.Service
{
    public interface IPageExtractor
    {
        IEnumerable<string> SupportedExtensions { get; }

        Task<IEnumerable<IFile>> ExtractPages(IFile file, Document document);
    }

    public class PageExtractorList : IPageExtractor
    {
        private readonly List<IPageExtractor> extractors;

        public PageExtractorList(IEnumerable<IPageExtractor> extractors)
        {
            this.extractors = extractors.ToList();
        }

        public IEnumerable<string> SupportedExtensions
        {
            get { return extractors.SelectMany(e => e.SupportedExtensions); }
        }

        public async Task<IEnumerable<IFile>> ExtractPages(IFile file, Document document)
        {
            var extension = Path.GetExtension(file.Name);
            return await extractors
                .Single(e => e.SupportedExtensions.Contains(extension))
                .ExtractPages(file, document);
        }
    }
}

using MyDocs.Common.Contract.Storage;
using MyDocs.Common.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyDocs.Common.Contract.Service
{
    public interface IPageExtractor
    {
        IEnumerable<string> SupportedExtensions { get; }

        Task<IEnumerable<IFile>> ExtractPages(IFile file, Document document);
    }

    public class PageExtractorList : IPageExtractor
    {
        private readonly IList<IPageExtractor> extractors;

        public PageExtractorList(IEnumerable<IPageExtractor> extractors)
        {
            this.extractors = extractors.ToList();
        }

        public IEnumerable<string> SupportedExtensions
        {
            get { return extractors.SelectMany(e => e.SupportedExtensions); }
        }

        public async Task<IEnumerable<IFile>> ExtractPages(IFile file, Document document)
        {
            var extension = Path.GetExtension(file.Name);
            return await extractors
                .Single(e => e.SupportedExtensions.Contains(extension))
                .ExtractPages(file, document);
        }
    }
}

Use interfaces instead of concrete types in file definition


using System;

namespace ExtensionMethods
{
    public static class MyExtensionMethods
    {
        public static DateTime Tomorrow(this DateTime date)
        {
            return date.AddDays(1);
        }
        public static DateTime Yesterday(this DateTime date)
        {
            return date.AddDays(-1);
        }
        public static int Age(this DateTime date)
        {
            var now = DateTime.Now;
            var age = now.Year - date.Year;
            if (now.Month > date.Month || (now.Month == date.Month && now.Day < date.Month))
                age -= 1;
            return age;

        }
        public static int AgeInDays(this DateTime date)
        {
            TimeSpan ts = DateTime.Now - date;
            return ts.Duration().Days;
        }
    }
}

using System;

namespace ExtensionMethods
{
    public static class MyExtensionMethods
    {
        public static DateTime Tomorrow(this DateTime date)
        {
            return date.AddDays(1);
        }
        public static DateTime Yesterday(this DateTime date)
        {
            return date.AddDays(-1);
        }
        public static int Age(this DateTime date)
        {
            var now = DateTime.Now;
            var age = now.Year - date.Year;
            if (now.Month > date.Month || (now.Month == date.Month && now.Day <= date.Day))
                age -= 1;
            return age;

        }
        public static int AgeInDays(this DateTime date)
        {
            TimeSpan ts = DateTime.Now - date;
            return ts.Duration().Days;
        }
    }
}

Adjust rule for Age Calc.

Adjust rule for Age Calc.


using UnityEngine;
using System.Collections;

public class TriggerDestroy : MonoBehaviour
{

	public Transform owner;
	public float ensureDestroyAfter = 5f;

	void Update()
	{
		ensureDestroyAfter -= Time.deltaTime;
	}

	void OnTriggerEnter(Collider other)
	{
		if (other.transform.name != owner.name)
		{
			return;
		}

		Destroy(gameObject);
	}
}

using UnityEngine;
using System.Collections;

public class TriggerDestroy : MonoBehaviour
{

	public Transform owner;
	public float ensureDestroyAfter = 2f;

	void Update()
	{
		ensureDestroyAfter -= Time.deltaTime;

		if (ensureDestroyAfter <= 0) {
			Destroy(gameObject);
		}
	}

	void OnTriggerEnter(Collider other)
	{
		if (other.transform.name != owner.name)
		{
			return;
		}

		Destroy(gameObject);
	}
}

Fix safety measures. Destroy missing.

Fix safety measures. Destroy missing.


#region Apache License 2.0

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

#endregion

using System;
using System.Reflection;
using Fasterflect;

namespace Org.Edgerunner.DotSerialize.Utilities
{
   public static class FieldInfoExtensions
   {
      #region Static Methods

      public static PropertyInfo GetEncapsulatingAutoProperty(this FieldInfo info)
      {
         var propertyName = NamingUtils.GetAutoPropertyName(info.Name);
         if (!string.IsNullOrEmpty(propertyName))
            return info.DeclaringType.Property(propertyName);

         return null;
      }

      public static bool IsBackingField(this FieldInfo info)
      {
         var propertyName = NamingUtils.GetAutoPropertyName(info.Name);
         return !string.IsNullOrEmpty(propertyName);
      }

      #endregion
   }
}

#region Apache License 2.0

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

#endregion

using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using Fasterflect;

namespace Org.Edgerunner.DotSerialize.Utilities
{
   public static class FieldInfoExtensions
   {
      #region Static Methods

      public static PropertyInfo GetEncapsulatingAutoProperty(this FieldInfo info)
      {
         var propertyName = NamingUtils.GetAutoPropertyName(info.Name);
         if (!string.IsNullOrEmpty(propertyName))
            return info.DeclaringType.Property(propertyName);

         return null;
      }

      public static bool IsBackingField(this FieldInfo info)
      {
         var propertyName = NamingUtils.GetAutoPropertyName(info.Name);
         if (string.IsNullOrEmpty(propertyName))
            return false;
         return info.HasAttribute<CompilerGeneratedAttribute>();
      }

      #endregion
   }
}

Improve accuracy of IsBackingField extension method.


using System;
using System.Collections.Generic;
using ClearMeasure.NumberCruncher;
using ClearMeasure.NumberCruncher.PrinterFormatters;

namespace TheTesst
{
    class Program
    {
        static void Main(string[] args)
        {
            var formatter = new DefaultPrinterFormatter(() => new FileResultStore(), new NumberToWord(), new FizzBuzz());
            var printer = new ConsolePrinter();
            var cruncher = new Cruncher(formatter, printer);

            var data = new List<int>() { 2, 3, 15, 7, 30, 104, 35465 };

            cruncher.Execute(data);

            Console.ReadLine();
        }
    }
}

using System;
using System.Collections.Generic;
using ClearMeasure.NumberCruncher;
using ClearMeasure.NumberCruncher.PrinterFormatters;

namespace TheTesst
{
    class Program
    {
        static void Main(string[] args)
        {
            var formatter = new DefaultPrinterFormatter(() => new StringBuilderResultStore(), new NumberToWord(), new FizzBuzz());
            var printer = new ConsolePrinter();
            var cruncher = new Cruncher(formatter, printer);

            var data = new List<int>() { 2, 3, 15, 7, 30, 104, 35465 };

            cruncher.Execute(data);

            Console.ReadLine();
        }
    }
}

Use StringBuilderResultStore in the console application


namespace Moya.Exceptions
{
    using System;

    public class MoyaException : Exception
    {
        public MoyaException(String message) : base(message)
        {

        }
    }
}

namespace Moya.Exceptions
{
    using System;

    /// <summary>
    /// Represents errors that occur during execution of Moya.
    /// </summary>
    public class MoyaException : Exception
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MoyaException"/> class
        /// with a specified error message.
        /// </summary>
        /// <param name="message">A message describing the error.</param>
        public MoyaException(String message) : base(message)
        {

        }
    }
}

Add xml documentation to moya exceptions


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

namespace ExtendedControls
{
    public class StatusStripCustom : StatusStrip
    {
        public const int WM_NCHITTEST = 0x84;
        public const int WM_NCLBUTTONDOWN = 0xA1;
        public const int WM_NCLBUTTONUP = 0xA2;
        public const int HT_CLIENT = 0x1;
        public const int HT_BOTTOMRIGHT = 0x11;
        public const int HT_TRANSPARENT = -1;

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);

            if (m.Msg == WM_NCHITTEST && (int)m.Result == HT_BOTTOMRIGHT)
            {
                // Tell the system to test the parent
                m.Result = (IntPtr)HT_TRANSPARENT;
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

namespace ExtendedControls
{
    public class StatusStripCustom : StatusStrip
    {
        public const int WM_NCHITTEST = 0x84;
        public const int WM_NCLBUTTONDOWN = 0xA1;
        public const int WM_NCLBUTTONUP = 0xA2;
        public const int HT_CLIENT = 0x1;
        public const int HT_BOTTOMRIGHT = 0x11;
        public const int HT_TRANSPARENT = -1;

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);

            if (m.Msg == WM_NCHITTEST)
            {
                if ((int)m.Result == HT_BOTTOMRIGHT)
                {
                    // Tell the system to test the parent
                    m.Result = (IntPtr)HT_TRANSPARENT;
                }
                else if ((int)m.Result == HT_CLIENT)
                {
                    // Work around the implementation returning HT_CLIENT instead of HT_BOTTOMRIGHT
                    int x = unchecked((short)((uint)m.LParam & 0xFFFF));
                    int y = unchecked((short)((uint)m.LParam >> 16));
                    Point p = PointToClient(new Point(x, y));

                    if (p.X >= this.ClientSize.Width - this.ClientSize.Height)
                    {
                        // Tell the system to test the parent
                        m.Result = (IntPtr)HT_TRANSPARENT;
                    }
                }
            }
        }
    }
}

Work around faulty StatusStrip implementations

Some StatusStrip implementations apparently return HT_CLIENT
for the sizing grip where they should return HT_BOTTOMRIGHT.


namespace ErikLieben.Data.Repository
{
    using System.Collections.Generic;

    public interface IRepository<T> : IEnumerable<T>
        where T : class
    {
        /// <summary>
        /// Adds the specified item.
        /// </summary>
        /// <param name="item">The item to add.</param>
        void Add(T item);

        /// <summary>
        /// Deletes the specified item.
        /// </summary>
        /// <param name="item">The item to delete.</param>
        void Delete(T item);

        /// <summary>
        /// Updates the specified item.
        /// </summary>
        /// <param name="item">The item to update.</param>
        void Update(T item);

        IEnumerable<T> Find(ISpecification<T> specification, IFetchingStrategy<T> fetchingStrategy);
    }
}

namespace ErikLieben.Data.Repository
{
    using System.Collections.Generic;

    public interface IRepository<T> : IEnumerable<T>
        where T : class
    {
        /// <summary>
        /// Adds the specified item.
        /// </summary>
        /// <param name="item">The item to add.</param>
        void Add(T item);

        /// <summary>
        /// Deletes the specified item.
        /// </summary>
        /// <param name="item">The item to delete.</param>
        void Delete(T item);

        /// <summary>
        /// Updates the specified item.
        /// </summary>
        /// <param name="item">The item to update.</param>
        void Update(T item);

        IEnumerable<T> Find(ISpecification<T> specification, IFetchingStrategy<T> fetchingStrategy);

        T FindFirstOrDefault(ISpecification<T> specification, IFetchingStrategy<T> fetchingStrategy);
    }
}

Add find first or default

Add find first or default


using MobileKidsIdApp.ViewModels;
using Xamarin.Forms;

namespace MobileKidsIdApp.Views
{
    public class MainPage : TabbedPage
    {
        private ApplicationBase CurrentApp => Application.Current as ApplicationBase;

        public MainPage()
        {
            Page childListPage = CurrentApp.CreatePage<ChildProfileListPage, ChildProfileListViewModel>(true).Result;
            Page instructionsPage = CurrentApp.CreatePage<InstructionIndexPage, InstructionIndexViewModel>(true).Result;

            if (childListPage is NavigationPage childNavPage)
            {
                childNavPage.Title = "My Kids";
                // TODO: set icon
            }

            if (instructionsPage is NavigationPage instructionNavPage)
            {
                instructionNavPage.Title = "Content";
                // TODO: set icon
            }

            Children.Add(childListPage);
            Children.Add(instructionsPage);
            // TODO: Add "logout" ability
        }
    }
}

using MobileKidsIdApp.ViewModels;
using Xamarin.Forms.PlatformConfiguration;
using Xamarin.Forms.PlatformConfiguration.AndroidSpecific;

namespace MobileKidsIdApp.Views
{
    public class MainPage : Xamarin.Forms.TabbedPage
    {
        private ApplicationBase CurrentApp => Xamarin.Forms.Application.Current as ApplicationBase;

        public MainPage()
        {
            On<Android>().SetToolbarPlacement(ToolbarPlacement.Bottom);

            Xamarin.Forms.Page childListPage = CurrentApp.CreatePage<ChildProfileListPage, ChildProfileListViewModel>(true).Result;
            Xamarin.Forms.Page instructionsPage = CurrentApp.CreatePage<InstructionIndexPage, InstructionIndexViewModel>(true).Result;

            if (childListPage is Xamarin.Forms.NavigationPage childNavPage)
            {
                childNavPage.Title = "My Kids";
                // TODO: set icon
            }

            if (instructionsPage is Xamarin.Forms.NavigationPage instructionNavPage)
            {
                instructionNavPage.Title = "Content";
                // TODO: set icon
            }

            Children.Add(childListPage);
            Children.Add(instructionsPage);
            // TODO: Add "logout" ability
        }
    }
}

Set tabs on Android to be on the bottom

Set tabs on Android to be on the bottom


using System;
using System.Collections.Generic;
using Microsoft.Framework.DependencyInjection;
using System.Threading.Tasks;

namespace Glimpse.Web
{
    public class MasterRequestRuntime
    {
        private readonly IDiscoverableCollection<IRequestRuntime> _requestRuntimes;
        private readonly IDiscoverableCollection<IRequestHandler> _requestHandlers;

        public MasterRequestRuntime(IServiceProvider serviceProvider)
        {
            // TODO: Switch these over to being injected and doing the serviceProvider resolve in the middleware
            _requestRuntimes = serviceProvider.GetService<IDiscoverableCollection<IRequestRuntime>>();
            _requestRuntimes.Discover();

            _requestHandlers = serviceProvider.GetService<IDiscoverableCollection<IRequestHandler>>();
            _requestHandlers.Discover();
        }

        public async Task Begin(IHttpContext context)
        {
            foreach (var requestRuntime in _requestRuntimes)
            {
                await requestRuntime.Begin(context);
            }
        }

        public bool TryGetHandle(IHttpContext context, out IRequestHandler handeler)
        {
            foreach (var requestHandler in _requestHandlers)
            {
                if (requestHandler.WillHandle(context))
                {
                    handeler = requestHandler;
                    return true;
                }
            }

            handeler = null;
            return false;
        }

        public async Task End(IHttpContext context)
        {
            foreach (var requestRuntime in _requestRuntimes)
            {
                await requestRuntime.End(context);
            }
        }
    }
}

using System;
using System.Collections.Generic;
using Microsoft.Framework.DependencyInjection;
using System.Threading.Tasks;

namespace Glimpse.Web
{
    public class MasterRequestRuntime
    {
        private readonly IDiscoverableCollection<IRequestRuntime> _requestRuntimes;
        private readonly IDiscoverableCollection<IRequestHandler> _requestHandlers;
        private readonly IDiscoverableCollection<IRequestAuthorizer> _requestAuthorizers;

        public MasterRequestRuntime(IServiceProvider serviceProvider)
        {
            // TODO: Switch these over to being injected and doing the serviceProvider resolve in the middleware
            _requestAuthorizers = serviceProvider.GetService<IDiscoverableCollection<IRequestAuthorizer>>();
            _requestAuthorizers.Discover();

            _requestRuntimes = serviceProvider.GetService<IDiscoverableCollection<IRequestRuntime>>();
            _requestRuntimes.Discover();

            _requestHandlers = serviceProvider.GetService<IDiscoverableCollection<IRequestHandler>>();
            _requestHandlers.Discover();
        }

        public bool Authorized(IHttpContext context)
        {
            foreach (var requestAuthorizer in _requestAuthorizers)
            {
                var allowed = requestAuthorizer.AllowUser(context);
                if (!allowed)
                {
                    return false;
                }
            }

            return true;
        }

        public async Task Begin(IHttpContext context)
        {
            foreach (var requestRuntime in _requestRuntimes)
            {
                await requestRuntime.Begin(context);
            }
        }

        public bool TryGetHandle(IHttpContext context, out IRequestHandler handeler)
        {
            foreach (var requestHandler in _requestHandlers)
            {
                if (requestHandler.WillHandle(context))
                {
                    handeler = requestHandler;
                    return true;
                }
            }

            handeler = null;
            return false;
        }

        public async Task End(IHttpContext context)
        {
            foreach (var requestRuntime in _requestRuntimes)
            {
                await requestRuntime.End(context);
            }
        }
    }
}

Add Request Authorizer to master request runtime


using System.Collections.Generic;
using System.IO;
using System.Text;
using CsvHelper;
using CsvHelper.Configuration;
using DereTore.Applications.StarlightDirector.Components;
using DereTore.Applications.StarlightDirector.Entities.Serialization;

namespace DereTore.Applications.StarlightDirector.Entities {
    public sealed class CompiledScore {

        public CompiledScore() {
            Notes = new InternalList<CompiledNote>();
        }

        public InternalList<CompiledNote> Notes { get; }

        public string GetCsvString() {
            var tempFileName = Path.GetTempFileName();
            using (var stream = File.Open(tempFileName, FileMode.Create, FileAccess.Write)) {
                using (var writer = new StreamWriter(stream, Encoding.UTF8)) {
                    var config = new CsvConfiguration();
                    config.RegisterClassMap<ScoreCsvMap>();
                    config.HasHeaderRecord = true;
                    config.TrimFields = false;
                    using (var csv = new CsvWriter(writer, config)) {
                        var newList = new List<CompiledNote>(Notes);
                        newList.Sort(CompiledNote.IDComparison);
                        csv.WriteRecords(newList);
                    }
                }
            }
            // BUG: WTF? Why can't all the data be written into a MemoryStream right after the csv.WriteRecords() call, but a FileStream?
            var text = File.ReadAllText(tempFileName, Encoding.UTF8);
            File.Delete(tempFileName);
            return text;
        }

    }
}

using System.Collections.Generic;
using System.IO;
using System.Text;
using CsvHelper;
using CsvHelper.Configuration;
using DereTore.Applications.StarlightDirector.Components;
using DereTore.Applications.StarlightDirector.Entities.Serialization;

namespace DereTore.Applications.StarlightDirector.Entities {
    public sealed class CompiledScore {

        public CompiledScore() {
            Notes = new InternalList<CompiledNote>();
        }

        public InternalList<CompiledNote> Notes { get; }

        public string GetCsvString() {
            var tempFileName = Path.GetTempFileName();
            using (var stream = File.Open(tempFileName, FileMode.Create, FileAccess.Write)) {
                using (var writer = new StreamWriter(stream, Encoding.UTF8)) {
                    var config = new CsvConfiguration();
                    config.RegisterClassMap<ScoreCsvMap>();
                    config.HasHeaderRecord = true;
                    config.TrimFields = false;
                    using (var csv = new CsvWriter(writer, config)) {
                        var newList = new List<CompiledNote>(Notes);
                        newList.Sort(CompiledNote.IDComparison);
                        csv.WriteRecords(newList);
                    }
                }
            }
            // BUG: WTF? Why can't all the data be written into a MemoryStream right after the csv.WriteRecords() call, but a FileStream?
            var text = File.ReadAllText(tempFileName, Encoding.UTF8);
            text = text.Replace("\r\n", "\n");
            File.Delete(tempFileName);
            return text;
        }

    }
}

Use Unix line feed for score exportation.


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

namespace EnigmaUtilities.Components
{
    /// <summary>
    /// An implementation of the plug board component for the enigma machine.
    /// </summary>
    public class Plugboard : Component
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Plugboard" /> class.
        /// </summary>
        /// <param name="plugs"> The plugs to be used. </param>
        public Plugboard(string[] plugs)
        {
            // Turn each plug connection into an encryption element in the dictionary
            this.EncryptionKeys = new Dictionary<char, char>();
            foreach (string plug in plugs)
            {
                // Add both ways round so its not required to look backwards across the plugboard during the encryption
                this.EncryptionKeys.Add(plug[0], plug[1]);
                this.EncryptionKeys.Add(plug[1], plug[0]);
            }
        }

        /// <summary>
        /// Encrypts a letter with the current plug board settings.
        /// </summary>
        /// <param name="c"> The character to encrypt. </param>
        /// <returns> The encrypted character. </returns>
        public override char Encrypt(char c)
        {
            return this.EncryptionKeys.Keys.Contains(c) ? this.EncryptionKeys[c] : c;
        }
    }
}

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

namespace EnigmaUtilities.Components
{
    /// <summary>
    /// An implementation of the plug board component for the enigma machine.
    /// </summary>
    public class Plugboard : Component
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Plugboard" /> class.
        /// </summary>
        /// <param name="plugs"> The plugs to be used. </param>
        public Plugboard(string[] plugs)
        {
            // Turn each plug connection into an encryption element in the dictionary
            this.EncryptionKeys = new Dictionary<char, char>();
            foreach (string plug in plugs)
            {
                // Only add to plugboard if its and length that won't create errors (2 or above)
                if (plug.Length >= 2)
                {
                    // Add both ways round so its not required to look backwards across the plugboard during the encryption
                    this.EncryptionKeys.Add(plug[0], plug[1]);
                    this.EncryptionKeys.Add(plug[1], plug[0]);
                }
            }
        }

        /// <summary>
        /// Encrypts a letter with the current plug board settings.
        /// </summary>
        /// <param name="c"> The character to encrypt. </param>
        /// <returns> The encrypted character. </returns>
        public override char Encrypt(char c)
        {
            return this.EncryptionKeys.Keys.Contains(c) ? this.EncryptionKeys[c] : c;
        }
    }
}

Stop errors if invalid plugboard settings and inputted into the constructor The constructor would throw errors if the length of a string in the string array of settings was of length 1 or 0. Now it only adds plug settings with a length of 2 or above


using System;
using System.Threading;

namespace JetBrains.ReSharper.Plugins.Unity.Rider.iOS.ListUsbDevices
{
    internal static class Program
    {
        private static bool ourFinished;

        private static int Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usage: ios-list-usb-devices dllFolderPath sleepInMs");
                Console.WriteLine("  Type 'stop' to finish");
                return -1;
            }

            var thread = new Thread(ThreadFunc);
            thread.Start(args);

            while (true)
            {
                if (Console.ReadLine()?.Equals("stop", StringComparison.OrdinalIgnoreCase) == true)
                {
                    ourFinished = true;
                    break;
                }
            }

            thread.Join();

            return 0;
        }

        private static void ThreadFunc(object state)
        {
            var args = (string[]) state;
            var sleepTimeMs = int.Parse(args[1]);
            using (var api = new ListDevices(args[0]))
            {
                while (!ourFinished)
                {
                    var devices = api.GetDevices();

                    Console.WriteLine($"{devices.Count}");
                    foreach (var device in devices)
                        Console.WriteLine($"{device.productId:X} {device.udid}");

                    Thread.Sleep(sleepTimeMs);
                }
            }
        }
    }
}

using System;
using System.Net.Sockets;
using System.Threading;

namespace JetBrains.ReSharper.Plugins.Unity.Rider.iOS.ListUsbDevices
{
    internal static class Program
    {
        private static bool ourFinished;

        private static int Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usage: ios-list-usb-devices dllFolderPath sleepInMs");
                Console.WriteLine("  Type 'stop' to finish");
                return -1;
            }

            InitialiseWinSock();

            var thread = new Thread(ThreadFunc);
            thread.Start(args);

            while (true)
            {
                if (Console.ReadLine()?.Equals("stop", StringComparison.OrdinalIgnoreCase) == true)
                {
                    ourFinished = true;
                    break;
                }
            }

            thread.Join();

            return 0;
        }

        private static void InitialiseWinSock()
        {
            // Small hack to force WinSock to initialise on Windows. If we don't do this, the C based socket APIs in the
            // native dll will fail, because no-one has bothered to initialise sockets.
            try
            {
                var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
                socket.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to create socket (force initialising WinSock on Windows)");
                Console.WriteLine(e);
            }
        }

        private static void ThreadFunc(object state)
        {
            var args = (string[]) state;
            var sleepTimeMs = int.Parse(args[1]);
            using (var api = new ListDevices(args[0]))
            {
                while (!ourFinished)
                {
                    var devices = api.GetDevices();

                    Console.WriteLine($"{devices.Count}");
                    foreach (var device in devices)
                        Console.WriteLine($"{device.productId:X} {device.udid}");

                    Thread.Sleep(sleepTimeMs);
                }
            }
        }
    }
}

Fix listing iOS devices on Windows

Fix listing iOS devices on Windows


using System;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;

namespace Daisy.SaveAsDAISY.Addins.Word2007 {
    public partial class ExceptionReport : Form {
        private Exception ExceptionRaised { get;  }
        public ExceptionReport(Exception raised) {
            InitializeComponent();
            this.ExceptionRaised = raised;
            this.ExceptionMessage.Text = raised.Message + "\r\nStacktrace:\r\n" + raised.StackTrace;
        }

        private void SendReport_Click(object sender, EventArgs e) {
            StringBuilder message = new StringBuilder("The following exception was reported by a user using the saveAsDaisy addin:\r\n");
            message.AppendLine(this.ExceptionRaised.Message);
            message.AppendLine();
            message.Append(this.ExceptionRaised.StackTrace);

            string mailto = string.Format(
                "mailto:{0}?Subject={1}&Body={2}",
                "daisy-pipeline@mail.daisy.org",
                "Unhandled exception report in the SaveAsDAISY addin",
                message.ToString()
                );
            mailto = Uri.EscapeUriString(mailto);
            //MessageBox.Show(message.ToString());
            Process.Start(mailto);
        }
    }
}

using System;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;

namespace Daisy.SaveAsDAISY.Addins.Word2007 {
    public partial class ExceptionReport : Form {
        private Exception ExceptionRaised { get;  }
        public ExceptionReport(Exception raised) {
            InitializeComponent();
            this.ExceptionRaised = raised;
            this.ExceptionMessage.Text = raised.Message + "\r\nStacktrace:\r\n" + raised.StackTrace;
        }

        private void SendReport_Click(object sender, EventArgs evt) {
            StringBuilder message = new StringBuilder("The following exception was reported by a user using the saveAsDaisy addin:\r\n");
            message.AppendLine(this.ExceptionRaised.Message);
            message.AppendLine();
            message.Append(this.ExceptionRaised.StackTrace);
            Exception e = ExceptionRaised;
            while (e.InnerException != null) {
                e = e.InnerException;
                message.AppendLine(" - Inner exception : " + e.Message);
                message.AppendLine();
                message.Append(this.ExceptionRaised.StackTrace);
            }

            string mailto = string.Format(
                "mailto:{0}?Subject={1}&Body={2}",
                "daisy-pipeline@mail.daisy.org",
                "Unhandled exception report in the SaveAsDAISY addin",
                message.ToString()
                );
            mailto = Uri.EscapeUriString(mailto);
            //MessageBox.Show(message.ToString());
            Process.Start(mailto);
        }
    }
}

Improve exception report to also get inner exceptions if possible


using System.Collections.Generic;

namespace kafka4net.Metadata
{
    class BrokerMeta
    {
        public int NodeId;
        public string Host;
        public int Port;

        // Not serialized, just a link to connection associated with this broker
        internal Connection Conn;

        public override string ToString()
        {
            return string.Format("{0}:{1} Id:{2}", Host, Port, NodeId);
        }

        #region comparer
        public static readonly IEqualityComparer<BrokerMeta> NodeIdComparer = new ComparerImpl();
        class ComparerImpl : IEqualityComparer<BrokerMeta>
        {
            public bool Equals(BrokerMeta x, BrokerMeta y)
            {
                return x.NodeId == y.NodeId;
            }

            public int GetHashCode(BrokerMeta obj)
            {
                return obj.NodeId;
            }
        }
        #endregion
    }
}

using System;
using System.Collections.Generic;

namespace kafka4net.Metadata
{
    class BrokerMeta
    {
        public int NodeId;
        public string Host;
        public int Port;

        // Not serialized, just a link to connection associated with this broker
        internal Connection Conn;

        public override string ToString()
        {
            return string.Format("{0}:{1} Id:{2}", Host, Port, NodeId);
        }

        #region comparer
        public static readonly IEqualityComparer<BrokerMeta> NodeIdComparer = new ComparerImpl();
        class ComparerImpl : IEqualityComparer<BrokerMeta>
        {
            public bool Equals(BrokerMeta x, BrokerMeta y)
            {
                if(x.NodeId != -99 || y.NodeId != -99)
                    return x.NodeId == y.NodeId;

                // If those are non-resolved seed brokers, do property comparison, because they all have NodeId==-99
                return string.Equals(x.Host, y.Host, StringComparison.OrdinalIgnoreCase) && x.Port == y.Port;
            }

            public int GetHashCode(BrokerMeta obj)
            {
                return obj.NodeId;
            }
        }
        #endregion
    }
}

Fix comparer. Seed node all have NodeId=-99, so need to compare their fields.

Fix #16.


using System.Drawing;

public struct FBAdSize {
    SizeF size;
}

public struct FBAdStarRating {
    float value;
    int scale;
}

using System.Drawing;

public struct FBAdSize {
    public SizeF size;
}

public struct FBAdStarRating {
    public float value;
    public int scale;
}

Fix the access level on the size and rating structs

Test Plan: manual

Reviewers: justin, srimoyee, tberman

Reviewed By: tberman

Subscribers: tberman, peter, justin, stephan, serdar

Differential Revision: http://phabricator.thefactory.com/D3824


using System;

namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World, I was created by my father, Bigsby, in an unidentified evironment!");
            Console.WriteLine("Bigsby Gates was here!");
            Console.WriteLine("Bigsby Trovalds was here!");
        }
    }
}

using System;

namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World, I was created by my father, Bigsby, in an unidentified evironment!");
            Console.WriteLine("Bigsby Gates was here!");
            Console.WriteLine("Bigsby Trovalds was here!");
            Console.WriteLine("Bigsby Jobs was here!");
        }
    }
}

Add Bigsby Jobs was here

Add Bigsby Jobs was here


using System;
using Microsoft.SPOT;

namespace IntervalTimer
{
    public class IntervalReachedEventArgs : EventArgs
    {
        public String Message { get; set; }

        public IntervalReachedEventArgs(String message)
        {
            Message = message;
        }
    }
}

using System;
using Microsoft.SPOT;

namespace IntervalTimer
{
    public class IntervalReachedEventArgs : EventArgs
    {
        public int DurationNumber { get; set; }

        public IntervalReachedEventArgs(int durationNumber)
        {
            DurationNumber = durationNumber;
        }
    }
}

Change IntervalReached event to contain duration position.


// 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.Bindables;
using osu.Game.Configuration;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.UI;

namespace osu.Game.Rulesets.Osu.Mods
{
    public class OsuModBarrelRoll : Mod, IUpdatableByPlayfield
    {
        [SettingSource("Roll speed", "Speed at which things rotate")]
        public BindableNumber<double> SpinSpeed { get; } = new BindableDouble(1)
        {
            MinValue = 0.1,
            MaxValue = 20,
            Precision = 0.1,
        };

        public override string Name => "Barrel Roll";
        public override string Acronym => "BR";
        public override double ScoreMultiplier => 1;

        public void Update(Playfield playfield)
        {
            playfield.Rotation = (float)(playfield.Time.Current / 1000 * SpinSpeed.Value);
        }
    }
}

// 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.Bindables;
using osu.Game.Configuration;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.UI;
using osu.Game.Rulesets.UI;
using osuTK;

namespace osu.Game.Rulesets.Osu.Mods
{
    public class OsuModBarrelRoll : Mod, IUpdatableByPlayfield, IApplicableToDrawableRuleset<OsuHitObject>
    {
        [SettingSource("Roll speed", "Speed at which things rotate")]
        public BindableNumber<double> SpinSpeed { get; } = new BindableDouble(1)
        {
            MinValue = 0.1,
            MaxValue = 20,
            Precision = 0.1,
        };

        public override string Name => "Barrel Roll";
        public override string Acronym => "BR";
        public override double ScoreMultiplier => 1;

        public void Update(Playfield playfield)
        {
            playfield.Rotation = (float)(playfield.Time.Current / 1000 * SpinSpeed.Value);
        }

        public void ApplyToDrawableRuleset(DrawableRuleset<OsuHitObject> drawableRuleset)
        {
            // scale the playfield to allow all hitobjects to stay within the visible region.
            drawableRuleset.Playfield.Scale = new Vector2(OsuPlayfield.BASE_SIZE.Y / OsuPlayfield.BASE_SIZE.X);
        }
    }
}

Scale the playfield to avoid off-screen objects


using System.Dynamic;
using System.Xml.Serialization;
using com.esendex.sdk.core;
using com.esendex.sdk.messaging;
using com.esendex.sdk.utilities;
using NUnit.Framework;

namespace com.esendex.sdk.test.messaging
{
    [TestFixture]
    public class SmsMessageSerializationTests
    {
        [Test]
        public void WhenCharacterSetIsDefaultItIsNotSerialised()
        {
            var message = new SmsMessage();
            var serialiser = new XmlSerialiser();
            var serialisedMessage = serialiser.Serialise(message);

            Assert.That(serialisedMessage, Is.Not.StringContaining("characterset"));
        }

        [Test]
        public void WhenCharacterSetIsSetShouldBeSerialised([Values(CharacterSet.Auto, CharacterSet.GSM, CharacterSet.Unicode)] CharacterSet characterSet)
        {
            var message = new SmsMessage();
            message.CharacterSet = characterSet;

            var serialiser = new XmlSerialiser();
            var serialisedMessage = serialiser.Serialise(message);

            Assert.That(serialiser.Deserialise<SmsMessage>(serialisedMessage).CharacterSet, Is.EqualTo(characterSet));
        }
    }
}

using com.esendex.sdk.core;
using com.esendex.sdk.messaging;
using com.esendex.sdk.utilities;
using NUnit.Framework;

namespace com.esendex.sdk.test.messaging
{
    [TestFixture]
    public class SmsMessageSerializationTests
    {
        [TestCase(CharacterSet.Auto, @"<?xml version=""1.0"" encoding=""utf-8""?><message><type>SMS</type><validity>0</validity><characterset>Auto</characterset></message>")]
        [TestCase(CharacterSet.GSM, @"<?xml version=""1.0"" encoding=""utf-8""?><message><type>SMS</type><validity>0</validity><characterset>GSM</characterset></message>")]
        [TestCase(CharacterSet.Unicode, @"<?xml version=""1.0"" encoding=""utf-8""?><message><type>SMS</type><validity>0</validity><characterset>Unicode</characterset></message>")]
        [TestCase(CharacterSet.Default, @"<?xml version=""1.0"" encoding=""utf-8""?><message><type>SMS</type><validity>0</validity></message>")]
        public void WhenSmsMessageIsSerializedThenTheCharacterSetIsSerialisedAsExpected(CharacterSet characterSet, string expectedXml)
        {
            var message = new SmsMessage {CharacterSet = characterSet};

            var serialiser = new XmlSerialiser();
            var serialisedMessage = serialiser.Serialise(message);

            Assert.That(serialisedMessage, Is.EqualTo(expectedXml));
        }
    }
}

Make characterset serialisation test explicit


using UnityEngine;
using System.Collections;

/**
 * Use Keyboard to switch between all scenes in build
 * Wraps from last Scene back to first and vice versa
 */

namespace mmm {

    public class SceneSwitcher : MonoBehaviour {

        public KeyCode keyNext = KeyCode.Equals;
        public KeyCode keyPrevious = KeyCode.Minus;

	    void Update () {

            // Trigger Scene Switch with Keyboard Commands
            if (Input.GetKeyDown(keyNext))
            {
                // Increment Scene
                int nextLevel = Application.loadedLevel;
                nextLevel++;
                if (nextLevel >= Application.levelCount)
                {
                    nextLevel = 0;
                }
                Application.LoadLevel(nextLevel);
            }

            if (Input.GetKeyDown(keyPrevious))
            {
                // Decrement Scene
                int nextLevel = Application.loadedLevel;
                nextLevel--;
                if (nextLevel < 0)
                {
                    nextLevel = Application.levelCount;
                }
                Application.LoadLevel(nextLevel);
            }

	    }

    }

}

using UnityEngine;
using System.Collections;

/**
 * Use Keyboard to switch between all scenes in build
 * Wraps from last Scene back to first and vice versa
 */

namespace mmm {

    public class SceneSwitcher : MonoBehaviour {

        public KeyCode keyNext = KeyCode.Equals;
        public KeyCode keyPrevious = KeyCode.Minus;

	    void Update () {

            // Trigger Scene Switch with Keyboard Commands
            if (Input.GetKeyDown(keyNext))
            {
                // Increment Scene
                int nextLevel = Application.loadedLevel;
                nextLevel++;
                if (nextLevel >= Application.levelCount)
                {
                    nextLevel = 0;
                }
                Application.LoadLevel(nextLevel);
            }

            if (Input.GetKeyDown(keyPrevious))
            {
                // Decrement Scene
                int nextLevel = Application.loadedLevel;
                nextLevel--;
                if (nextLevel < 0)
                {
                    nextLevel = Application.levelCount - 1;
                }
                Application.LoadLevel(nextLevel);
            }

	    }

    }

}

Fix for Scene Switcher negative wraparound


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

namespace QueueDataGraphic
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();

			List<string> TestList = new List<string>();
			TestList.Add("Channel1");
			TestList.Add("Channel2");
			TestList.Add("Channel3");

			CSharpFiles.QueueDataGraphic QueueDataGraphic1 = new CSharpFiles.QueueDataGraphic(TestList);

			for(int Loopnum = 0; Loopnum < 500; Loopnum++)
			{
				QueueDataGraphic1.AddData("Channel1", Loopnum*2);
			}

			panel1.Paint += new PaintEventHandler(QueueDataGraphic1.DrawGraph);
			panel1.Refresh();

		}
	}
}

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

namespace QueueDataGraphic
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();

			List<string> TestList = new List<string>();
			TestList.Add("Channel1");
			TestList.Add("Channel2");
			TestList.Add("Channel3");

			CSharpFiles.QueueDataGraphic QueueDataGraphic1 = new CSharpFiles.QueueDataGraphic(TestList);

			for(int Loopnum = 0; Loopnum < 500; Loopnum++)
			{
				QueueDataGraphic1.AddData("Channel1", Loopnum*2);
			}

			QueueDataGraphic1.SetWidth(panel1.Size.Width);
			QueueDataGraphic1.SetHeight(panel1.Size.Height);

			panel1.Paint += new PaintEventHandler(QueueDataGraphic1.DrawGraph);
			panel1.Refresh();

		}
	}
}

Call SetWidth and SetHeight method

Call SetWidth and SetHeight method

Call SetWidth and SetHeight method


Remove duplicate attribute that fails the build


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

public class ControlDisplay : MonoBehaviour
{

#pragma warning disable 0649   //Serialized Fields
    [SerializeField]
    private SpriteRenderer controlRenderer;
    [SerializeField]
    private Text controlText;
#pragma warning restore 0649

    public void setControlScheme(MicrogameTraits.ControlScheme controlScheme)
    {
        //TODO re-enable command warnings?
        controlRenderer.sprite = GameController.instance.getControlSprite(controlScheme);
        controlText.text = TextHelper.getLocalizedTextNoWarnings("control." + controlScheme.ToString().ToLower(), getDefaultControlString(controlScheme));
    }

    string getDefaultControlString(MicrogameTraits.ControlScheme controlScheme)
    {
        switch (controlScheme)
        {
            case (MicrogameTraits.ControlScheme.Key):
                return "USE DA KEYZ";
            case (MicrogameTraits.ControlScheme.Mouse):
                return "USE DA MOUSE";
            default:
                return "USE SOMETHING";
        }
    }
}

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

public class ControlDisplay : MonoBehaviour
{

#pragma warning disable 0649   //Serialized Fields
    [SerializeField]
    private SpriteRenderer controlRenderer;
    [SerializeField]
    private Text controlText;
#pragma warning restore 0649

    public void setControlScheme(MicrogameTraits.ControlScheme controlScheme)
    {
        //TODO re-enable command warnings?
        controlRenderer.sprite = GameController.instance.getControlSprite(controlScheme);
        controlText.text = TextHelper.getLocalizedTextNoWarnings("stage.control." + controlScheme.ToString().ToLower(), getDefaultControlString(controlScheme));
    }

    string getDefaultControlString(MicrogameTraits.ControlScheme controlScheme)
    {
        switch (controlScheme)
        {
            case (MicrogameTraits.ControlScheme.Key):
                return "USE DA KEYZ";
            case (MicrogameTraits.ControlScheme.Mouse):
                return "USE DA MOUSE";
            default:
                return "USE SOMETHING";
        }
    }
}

Fix incorrect control display key

Fix incorrect control display key


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

using System;
using System.Collections.Generic;

namespace Stormpath.Owin.Common.Views.Precompiled
{
    public static class ViewResolver
    {
        private static readonly Dictionary<string, Func<IView>> LookupTable =
            new Dictionary<string, Func<IView>>(StringComparer.OrdinalIgnoreCase)
        {
            ["change"] = () => new Change(),
            ["forgot"] = () => new Forgot(),
            ["login"] = () => new Login(),
            ["register"] = () => new Register(),
            ["verify"] = () => new Verify(),
        };

        public static IView GetView(string name)
        {
            Func<IView> foundViewFactory = null;
            LookupTable.TryGetValue(name, out foundViewFactory);

            return foundViewFactory == null
                ? null
                : foundViewFactory();
        }
    }
}

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

using System;
using System.Collections.Generic;

namespace Stormpath.Owin.Common.Views.Precompiled
{
    public static class ViewResolver
    {
        private static readonly Dictionary<string, Func<IView>> LookupTable =
            new Dictionary<string, Func<IView>>(StringComparer.OrdinalIgnoreCase)
        {
            ["change-password"] = () => new Change(),
            ["forgot-password"] = () => new Forgot(),
            ["login"] = () => new Login(),
            ["register"] = () => new Register(),
            ["verify"] = () => new Verify(),
        };

        public static IView GetView(string name)
        {
            Func<IView> foundViewFactory = null;
            LookupTable.TryGetValue(name, out foundViewFactory);

            return foundViewFactory == null
                ? null
                : foundViewFactory();
        }
    }
}

Fix incorrect default view names

Fix incorrect default view names


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

namespace Sandra.UI.WF
{
    public partial class SettingsTextBox
    {
        public const string SettingsTextBoxUIActionPrefix = nameof(RichTextBoxBase) + ".";

        public static readonly DefaultUIActionBinding SaveToFile = new DefaultUIActionBinding(
            new UIAction(SettingsTextBoxUIActionPrefix + nameof(SaveToFile)),
            new UIActionBinding()
            {
                ShowInMenu = true,
                IsFirstInGroup = true,
                MenuCaptionKey = LocalizedStringKeys.Save,
                Shortcuts = new ShortcutKeys[] { new ShortcutKeys(KeyModifiers.Control, ConsoleKey.S), },
            });

        public UIActionState TrySaveToFile(bool perform)
        {
            if (ReadOnly) return UIActionVisibility.Hidden;
            return UIActionVisibility.Enabled;
        }
    }
}

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

namespace Sandra.UI.WF
{
    public partial class SettingsTextBox
    {
        public const string SettingsTextBoxUIActionPrefix = nameof(RichTextBoxBase) + ".";

        public static readonly DefaultUIActionBinding SaveToFile = new DefaultUIActionBinding(
            new UIAction(SettingsTextBoxUIActionPrefix + nameof(SaveToFile)),
            new UIActionBinding()
            {
                ShowInMenu = true,
                IsFirstInGroup = true,
                MenuCaptionKey = LocalizedStringKeys.Save,
                Shortcuts = new ShortcutKeys[] { new ShortcutKeys(KeyModifiers.Control, ConsoleKey.S), },
            });

        public UIActionState TrySaveToFile(bool perform)
        {
            if (ReadOnly) return UIActionVisibility.Hidden;
            if (perform) File.WriteAllText(settingsFile.AbsoluteFilePath, Text);
            return UIActionVisibility.Enabled;
        }
    }
}

Implement TrySaveToFile() by using File.WriteAllText().


using System;
using System.Collections.Generic;

namespace Glimpse.Server
{
    public class GlimpseServerWebOptions
    {
        public GlimpseServerWebOptions()
        {
            AllowedUserRoles = new List<string>();
        }

        public bool AllowRemote { get; set; }

        public IList<string> AllowedUserRoles { get; }
    }
}

using System;

namespace Glimpse.Server
{
    public class GlimpseServerWebOptions
    {
        public bool AllowRemote { get; set; }
    }
}

Revert "Add option for allowed user roles"

This reverts commit afa31ac8b25d9ed3fac1d5531cb83c897e876b4f.


using System;
using System.Collections.Generic;
using System.Windows.Forms;
using UniProgramGen.Data;

namespace UniProgramGen
{
    public partial class ResultsTab : UserControl
    {
        public ResultsTab()
        {
            InitializeComponent();
        }

        private List<Teacher> teachers;
        private List<Room> rooms;
        private List<Group> groups;
        private List<Subject> subjects;

        internal void InitializeBindingSources(
            BindingSource teachersBS,
            BindingSource roomsBS,
            BindingSource groupsBS,
            BindingSource subjectsBS)
        {
            teachers = (List<Teacher>)teachersBS.DataSource;
            rooms = (List<Room>)roomsBS.DataSource;
            groups = (List<Group>)groupsBS.DataSource;
            subjects = (List<Subject>)subjectsBS.DataSource;

            listBoxTeachers.DataSource = teachersBS;
            listBoxRooms.DataSource = roomsBS;
            listBoxGroups.DataSource = groupsBS;
        }

        private void buttonGenerate_Click(object sender, EventArgs e)
        {
            //new Generator.ProgramGenerator().GenerateProgram();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using UniProgramGen.Data;

namespace UniProgramGen
{
    public partial class ResultsTab : UserControl
    {
        public ResultsTab()
        {
            InitializeComponent();
        }

        private List<Teacher> teachers;
        private List<Room> rooms;
        private List<Group> groups;
        private List<Subject> subjects;

        internal void InitializeBindingSources(
            BindingSource teachersBS,
            BindingSource roomsBS,
            BindingSource groupsBS,
            BindingSource subjectsBS)
        {
            teachers = (List<Teacher>)teachersBS.DataSource;
            rooms = (List<Room>)roomsBS.DataSource;
            groups = (List<Group>)groupsBS.DataSource;
            subjects = (List<Subject>)subjectsBS.DataSource;

            listBoxTeachers.DataSource = teachersBS;
            listBoxRooms.DataSource = roomsBS;
            listBoxGroups.DataSource = groupsBS;
        }

        private void buttonGenerate_Click(object sender, EventArgs e)
        {
            DumpExampleSolution();
            return;

            var generator = new Generator.ProgramGenerator();
            var program = generator.GenerateProgram(rooms, subjects, teachers, groups);
        }

        private void DumpExampleSolution()
        {
            Data.DBManager db = new DBManager();
            db.getTestData();
            var program = new Generator.ProgramGenerator().GenerateProgram(db.rooms, db.subjects, db.teachers, db.groups);
            var firstSolution = program.First();

            string firstSolutionJson = Newtonsoft.Json.JsonConvert.SerializeObject(firstSolution);
            System.IO.File.WriteAllText("../../datafiles/example_solution.json", firstSolutionJson);
        }
    }
}

Add dumping of solution based on dummy data


using System.Collections.Generic;
using Newtonsoft.Json.Linq;

namespace template_designer
{
    public class JsonToDictionaryConverter
    {
        public static Dictionary<string, object> DeserializeJsonToDictionary(string json)
        {

            var jObject = JObject.Parse(json);

            var dict = ParseObject(jObject);

            return dict;
        }

        private static Dictionary<string, object> ParseObject(JObject jObject)
        {
            var dict = new Dictionary<string, object>();
            foreach (var property in jObject.Properties())
            {
                if (property.Value.Type == JTokenType.Array)
                {
                    dict.Add(property.Name, ParseArray(property.Value.ToObject<JArray>()));
                }
                else if (property.Value.Type == JTokenType.Object)
                {
                    dict.Add(property.Name, ParseObject(property.Value.ToObject<JObject>()));
                }
                else
                {
                    dict.Add(property.Name, property.Value.ToString());
                }

            }
            return dict;
        }

        private static List<object> ParseArray(JArray value)
        {
            var list = new List<object>();
            foreach (var child in value.Children())
            {
                if (child.Type == JTokenType.Array)
                {
                    list.Add(ParseArray(child.ToObject<JArray>()));
                }
                else if (child.Type == JTokenType.Object)
                {
                    list.Add(ParseObject(child.ToObject<JObject>()));
                }
                else
                {
                    list.Add(child.ToString());
                }
            }
            return list;
        }
    }
}

using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;

namespace template_designer
{
    public class JsonToDictionaryConverter
    {
        public static Dictionary<string, object> DeserializeJsonToDictionary(string json)
        {
            var jObject = JObject.Parse(json);

            return ParseJObject(jObject);
        }

        private static Dictionary<string, object> ParseJObject(JObject jObject)
        {
            return jObject.Properties().ToDictionary(property => property.Name, property => ParseValue(property.Value));
        }

        private static object ParseValue(JToken value)
        {
            switch (value.Type)
            {
                case JTokenType.Array:
                    return ParseJArray(value.ToObject<JArray>());
                case JTokenType.Object:
                    return ParseJObject(value.ToObject<JObject>());
                case JTokenType.Boolean:
                    return value.ToObject<bool>();
                case JTokenType.Integer:
                    return value.ToObject<int>();
                case JTokenType.Float:
                    return value.ToObject<float>();
                default:
                    return value.ToString();
            }
        }

        private static List<object> ParseJArray(JArray value)
        {
            return value.Children().Select(ParseValue).ToList();
        }
    }
}

Improve json conversion: support more types + cleanup code


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

namespace Microsoft.CodeAnalysis.CodeStyle
{
    internal partial class CodeStyleOption2<T>
    {
        public static explicit operator CodeStyleOption<T>(CodeStyleOption2<T> option)
        {
            if (option == null)
            {
                return null;
            }

            return new CodeStyleOption<T>(option.Value, (NotificationOption)option.Notification);
        }

        public static explicit operator CodeStyleOption2<T>(CodeStyleOption<T> option)
        {
            if (option == null)
            {
                return null;
            }

            return new CodeStyleOption2<T>(option.Value, (NotificationOption2)option.Notification);
        }
    }
}

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

namespace Microsoft.CodeAnalysis.CodeStyle
{
    internal partial class CodeStyleOption2<T>
    {
        public static implicit operator CodeStyleOption<T>(CodeStyleOption2<T> option)
        {
            if (option == null)
            {
                return null;
            }

            return new CodeStyleOption<T>(option.Value, (NotificationOption)option.Notification);
        }

        public static implicit operator CodeStyleOption2<T>(CodeStyleOption<T> option)
        {
            if (option == null)
            {
                return null;
            }

            return new CodeStyleOption2<T>(option.Value, (NotificationOption2)option.Notification);
        }
    }
}

Switch back to implicit operators for conversions to and from CodeStyleOption and CodeStyleOption2 respectively. These are needed to prevent InvalidCastException when user invokes `optionSet.WithChangedOption(..., new CodeStyleOption<bool>(...))` and any of our internal code base tries to fetch the option value with `optionSet.GetOption<T>(...)` where T is ` CodeStyleOption2<bool>`, and this helper attempts a direct cast from object to `T`.


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

[AddComponentMenu("Plantain/Trigger/Propagator")]
public class TriggerPropagator : Trigger {
    /// <summary>
    /// A list of GameObjects that will have the current GameObject's triggers passed on to.
    /// </summary>
    public List<GameObject> targets;

    /// <summary>
    /// Used to prevent infinite propagation by allowing only 1 pass on.
    /// </summary>
    protected bool procced = false;

    public void PerformTrigger(TriggerOption tOption) {
        if(!procced && isActive) {
            procced = true;
            foreach(GameObject gameObj in targets) {
                gameObj.SendMessage("PerformTrigger", tOption, SendMessageOptions.DontRequireReceiver);
            }
            procced = false;
        }
    }

    void OnDrawGizmos() {
        TriggerGizmos("Propagator");

        Gizmos.color = Color.cyan;
        GizmoTargetedObjects(targets);
    }
}

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

[AddComponentMenu("Plantain/Trigger/Propagator")]
public class TriggerPropagator : Trigger {
    /// <summary>
    /// Prevent a trigger from hopping any further than the targeted objects.
    /// </summary>
    public bool preventPropigation = false;

    /// <summary>
    /// A list of GameObjects that will have the current GameObject's triggers passed on to.
    /// </summary>
    public List<GameObject> targets;

    /// <summary>
    /// Used to prevent propigation for infinite loops, among other senarios.
    /// </summary>
    protected bool procced = false;

    public void PerformTrigger(TriggerOption tOption) {
        if(!procced && isActive) {
            procced = true;
            foreach(GameObject gameObj in targets) {
                if(preventPropigation) {
                    TriggerPropagator[] propagators = gameObj.GetComponents<TriggerPropagator>();
                    foreach(TriggerPropagator propigator in propagators) {
                        propigator.procced = true;
                    }

                    gameObj.SendMessage("PerformTrigger", tOption, SendMessageOptions.DontRequireReceiver);

                    foreach(TriggerPropagator propigator in propagators) {
                        propigator.procced = false;
                    }

                } else {
                    gameObj.SendMessage("PerformTrigger", tOption, SendMessageOptions.DontRequireReceiver);
                }
            }
            procced = false;
        }
    }

    void OnDrawGizmos() {
        TriggerGizmos("Propagator");

        Gizmos.color = Color.cyan;
        GizmoTargetedObjects(targets);
    }
}

Add option for only 1 hop propagation

Add option for only 1 hop propagation

Sometimes, you don't want to go to the end of the line of propagators.


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

namespace Samesound
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
        }
    }
}

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

namespace Samesound
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            Database.SetInitializer<SamesoundContext>(null);
        }
    }
}

Add Database initializer to Global

Add Database initializer to Global


@using Microsoft.AspNet.Identity

            @ViewBag.Title

                @ViewBag.Lead

            @if (Request.IsAuthenticated)
            {
                using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
                {
                    @Html.AntiForgeryToken()

Home

                        @Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })

Log off

                }
            }
            else
            {

Home

@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })

@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })

            }

@using Microsoft.AspNet.Identity

@using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
    @Html.AntiForgeryToken()
}

            @ViewBag.Title

                @ViewBag.Lead

            @if (Request.IsAuthenticated)
            {

Home

                    @Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })

                    Log off

            }
            else
            {

Home

@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })

@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })

            }

Fix logout form input button

Fix logout form input button


using System;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace TcpSocketDataSender
{
    public class TcpSocketManager : IDisposable
    {
        private TcpClient _tcpClient;
        BinaryWriter _writer = null;

        public int ServerPort = 7839;
        public string ServerIp = "127.0.0.1";
        public bool AutoReconnect = false;
        public bool Connect()
        {
            if (_writer != null)
                return true;
            _tcpClient = new TcpClient();
            try
            {
                _tcpClient.Connect(IPAddress.Parse(ServerIp), ServerPort);
                _writer = new BinaryWriter(_tcpClient.GetStream());
            }
            catch (SocketException)
            {
                //No server avaliable, or it is busy/full.
                return false;
            }
            return true;
        }

        public void Write(string data)
        {
            bool written = false;
            try
            {
                if (_tcpClient?.Connected ?? false)
                {
                    _writer?.Write(data);
                    written = true;
                }
            }
            catch (IOException)
            {
                //connection most likely closed
                _writer?.Dispose();
                _writer = null;
                ((IDisposable)_tcpClient)?.Dispose();
            }
            if (!written && AutoReconnect)
            {
                if(Connect())
                    Write(data);
            }
        }

        public void Dispose()
        {
            ((IDisposable)_tcpClient)?.Dispose();
            _writer?.Dispose();
        }
    }
}

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;

namespace TcpSocketDataSender
{
    public class TcpSocketManager : IDisposable
    {
        private TcpClient _tcpClient;
        BinaryWriter _writer = null;

        public int ServerPort = 7839;
        public string ServerIp = "127.0.0.1";
        public bool AutoReconnect = false;
        public async Task<bool> Connect()
        {
            if (_writer != null)
                return true;
            _tcpClient = new TcpClient();
            try
            {
                await _tcpClient.ConnectAsync(IPAddress.Parse(ServerIp), ServerPort);
                _writer = new BinaryWriter(_tcpClient.GetStream());
            }
            catch (SocketException)
            {
                //No server avaliable, or it is busy/full.
                return false;
            }
            return true;
        }

        public async Task Write(string data)
        {
            bool written = false;
            try
            {
                if (_tcpClient?.Connected ?? false)
                {
                    _writer?.Write(data);
                    written = true;
                }
            }
            catch (IOException)
            {
                //connection most likely closed
                _writer?.Dispose();
                _writer = null;
                ((IDisposable)_tcpClient)?.Dispose();
            }
            if (!written && AutoReconnect)
            {
                if(await Connect())
                    await Write(data);
            }
        }

        public void Dispose()
        {
            ((IDisposable)_tcpClient)?.Dispose();
            _writer?.Dispose();
        }
    }
}

Fix: Make tcpSocketManager writes async to avoid blocking everything else

Fixes #40


// 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.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Screens.Play;
using osu.Game.Screens.Play.HUD;
using osuTK;

namespace osu.Game.Skinning
{
    public class LegacyAccuracyCounter : PercentageCounter, IAccuracyCounter
    {
        private readonly ISkin skin;

        public LegacyAccuracyCounter(ISkin skin)
        {
            Anchor = Anchor.TopRight;
            Origin = Anchor.TopRight;

            Scale = new Vector2(0.75f);
            Margin = new MarginPadding(10);

            this.skin = skin;
        }

        [Resolved(canBeNull: true)]
        private HUDOverlay hud { get; set; }

        protected sealed override OsuSpriteText CreateSpriteText() =>
            new LegacySpriteText(skin, "score" /*, true*/)
            {
                Anchor = Anchor.TopRight,
                Origin = Anchor.TopRight,
            };

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

            if (hud?.ScoreCounter.Drawable is LegacyScoreCounter score)
            {
                // for now align with the score counter. eventually this will be user customisable.
                Y = Parent.ToLocalSpace(score.ScreenSpaceDrawQuad.BottomRight).Y;
            }
        }
    }
}

// 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.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Screens.Play;
using osu.Game.Screens.Play.HUD;
using osuTK;

namespace osu.Game.Skinning
{
    public class LegacyAccuracyCounter : PercentageCounter, IAccuracyCounter
    {
        private readonly ISkin skin;

        public LegacyAccuracyCounter(ISkin skin)
        {
            Anchor = Anchor.TopRight;
            Origin = Anchor.TopRight;

            Scale = new Vector2(0.6f);
            Margin = new MarginPadding(10);

            this.skin = skin;
        }

        [Resolved(canBeNull: true)]
        private HUDOverlay hud { get; set; }

        protected sealed override OsuSpriteText CreateSpriteText() =>
            new LegacySpriteText(skin, "score" /*, true*/)
            {
                Anchor = Anchor.TopRight,
                Origin = Anchor.TopRight,
            };

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

            if (hud?.ScoreCounter.Drawable is LegacyScoreCounter score)
            {
                // for now align with the score counter. eventually this will be user customisable.
                Y = Parent.ToLocalSpace(score.ScreenSpaceDrawQuad.BottomRight).Y;
            }
        }
    }
}

Adjust accuracy display to match stable

Adjust accuracy display to match stable


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

namespace Cams
{
	class Program
	{
		static void Main(string[] args)
		{
			string rawDir = Path.Combine(Settings.Path, "raw");
			string processedDir = Path.Combine(Settings.Path, "processed");

			var cameras = Directory.GetDirectories(rawDir).Select(BuildCamera);
			foreach (var cam in cameras)
				cam.Process(processedDir);

			var dates = Directory.GetDirectories(processedDir).Select(p => new VideoDate(p));
			foreach (var date in dates)
				date.Summarize();

#if DEBUG
			Console.ReadKey();
#endif
		}

		static Camera BuildCamera(string path)
		{
			bool isAmcrest = File.Exists(Path.Combine(path, "DVRWorkDirectory"));

			if (isAmcrest)
				return new AmcrestCamera(path);

			return new FoscamCamera(path);
		}
	}
}

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

namespace Cams
{
	class Program
	{
		static void Main(string[] args)
		{
			string rawDir = Path.Combine(Settings.Path, "raw");
			string processedDir = Path.Combine(Settings.Path, "processed");

			var cameras = Directory.GetDirectories(rawDir).Select(BuildCamera);
			foreach (var cam in cameras)
				cam.Process(processedDir);

			var dates = Directory.GetDirectories(processedDir).Select(p => new VideoDate(p));
			foreach (var date in dates)
				date.Summarize();

#if DEBUG
			Console.WriteLine();
			Console.WriteLine("Press any key to exit");
			Console.ReadKey();
#endif
		}

		static Camera BuildCamera(string path)
		{
			bool isAmcrest = File.Exists(Path.Combine(path, "DVRWorkDirectory"));

			if (isAmcrest)
				return new AmcrestCamera(path);

			return new FoscamCamera(path);
		}
	}
}

Add message to exit in debug mode

Add message to exit in debug mode


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

[assembly: AssemblyTitle("GitHubFeeds")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Bradley Grainger")]
[assembly: AssemblyProduct("GitHubFeeds")]
[assembly: AssemblyCopyright("Copyright 2012 Bradley Grainger")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.*")]

Allow compiler to set assembly version.

Allow compiler to set assembly version.

If the AssemblyFileVersion attribute is omitted, both it and
AssemblyVersion will be set to an automatically-generated version.


Regular Poller?

        Register for more config options. It's free!

    <form name="quickPollForm">

            Your Question

            <input id="question" placeholder="E.g. Where should we go for lunch?" ng-model="pollQuestion" required />

            <button type="submit" class="inactive-btn shadowed" ng-click="createPoll(pollQuestion)" ng-disabled="quickPollForm.$invalid">Quick Poll</button>

    </form>

or

        <button class="active-btn shadowed" ng-click="openLoginDialog()">Sign In</button>
        <button class="active-btn shadowed" ng-click="openRegisterDialog()">Register</button>

Regular Poller?

        Register for more config options. It's free!

    <form name="quickPollForm" ng-submit="createPoll(pollQuestion)">

            Your Question

            <input id="question" placeholder="E.g. Where should we go for lunch?" ng-model="pollQuestion" required />

            <button type="submit" class="inactive-btn shadowed" ng-disabled="quickPollForm.$invalid">Quick Poll</button>

    </form>

or

        <button class="active-btn shadowed" ng-click="openLoginDialog()">Sign In</button>
        <button class="active-btn shadowed" ng-click="openRegisterDialog()">Register</button>

Return now submits quick poll

Return now submits quick poll

Change ng-click on button to ng-submit on form to allow Return key to
submit form.


@using GiveCRM.Web.Infrastructure
@if (ConfigurationSettings.IsUserVoiceIntegrationEnabled)
{
    <script type="text/javascript">
        var uvOptions = { };
        (function() {
            var uv = document.createElement('script');
            uv.type = 'text/javascript';
            uv.async = true;
            uv.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'widget.uservoice.com/XMFifLxGL4npm6SHybYvtw.js';
            var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(uv, s);
        })();
    </script>
}

Add UserVoice widget to global footer.

Add UserVoice widget to global footer.

The widget is placed on the right hand side of the window, half-way down
the vertical space.  It is "fixed" to the window, so it will remain in
place as the user scrolls the page.

The widget might be better placed at the very bottom of the <body> tag in
_Layout.cshtml to improve page rendering.


@if (Request.IsAuthenticated) {
     @Session["DisplayName"]

@Html.ActionLink("Profile", "Profile", "User")

@Html.ActionLink("Log Out", "Logout", "User")

} else {
     Log In

Log in with Google

Log in with Facebook

Log in with Twitter

Log in with an OpenID

@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })

}

@if (Request.IsAuthenticated) {
     @Session["DisplayName"]

@Html.ActionLink("Profile", "Profile", "User")

@Html.ActionLink("Log Out", "Logout", "User", new { Area = string.Empty }, htmlAttributes: null)

} else {
     Log In

Log in with Google

Log in with Facebook

Log in with Twitter

Log in with an OpenID

@Html.ActionLink("Register", "Register", "Account", htmlAttributes: new { id = "registerLink" })

}

Fix Log Out link so it works everywhere.

No more 404 if trying to log out from the admin area.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using fitSharp.Machine.Engine;
using fitSharp.Machine.Model;
using NUnit.Framework;
using fitSharp.Samples.Fit;
using fitSharp.Fit.Operators;

namespace fitSharp.Test.NUnit.Fit {
    public class ParseOperatorTest<ParseOperatorType>
        where ParseOperatorType : CellOperator, ParseOperator<Cell>, new() {
        ParseOperatorType parser;

        public ParseOperatorTest() {
            // Parse operators are stateless, so no need to use SetUp.
            parser = new ParseOperatorType { Processor = Builder.CellProcessor() };
        }

        protected bool CanParse<T>(string cellContent) {
            return parser.CanParse(typeof(T), TypedValue.Void, new CellTreeLeaf(cellContent));
        }

        protected T Parse<T>(string cellContent) where T : class {
            return Parse<T>(cellContent, TypedValue.Void);
        }

        protected T Parse<T>(string cellContent, TypedValue instance) where T : class {
            TypedValue result = parser.Parse(typeof(string), TypedValue.Void, new CellTreeLeaf(cellContent));
            return result.GetValueAs<T>();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using fitSharp.Machine.Engine;
using fitSharp.Machine.Model;
using NUnit.Framework;
using fitSharp.Samples.Fit;
using fitSharp.Fit.Operators;

namespace fitSharp.Test.NUnit.Fit {
    public class ParseOperatorTest<ParseOperatorType>
        where ParseOperatorType : CellOperator, ParseOperator<Cell>, new() {

        public ParseOperatorType Parser { get; private set; }

        [SetUp]
        public void SetUp() {
            // Parse operators are stateless, but the processor may be mutated
            // by Parse(), so recreate for every test
            Parser = new ParseOperatorType { Processor = Builder.CellProcessor() };
        }

        protected bool CanParse<T>(string cellContent) {
            return Parser.CanParse(typeof(T), TypedValue.Void, new CellTreeLeaf(cellContent));
        }

        protected T Parse<T>(string cellContent) where T : class {
            return Parse<T>(cellContent, TypedValue.Void);
        }

        protected T Parse<T>(string cellContent, TypedValue instance) where T : class {
            TypedValue result = Parser.Parse(typeof(string), TypedValue.Void, new CellTreeLeaf(cellContent));
            return result.GetValueAs<T>();
        }
    }
}

Refactor Expose parse operator to deriving tests. Use [SetUp] attribute to recreate parser for every test.


using System;
using System.Data;

namespace Gigobyte.Daterpillar.Data
{
    public class SQLiteSchemaAggregator : SchemaAggregatorBase
    {
        public SQLiteSchemaAggregator(IDbConnection connection) : base(connection)
        {
        }

        protected override string GetColumnInfoQuery(string tableName)
        {
            throw new NotImplementedException();
        }

        protected override string GetForeignKeyInfoQuery(string tableName)
        {
            throw new NotImplementedException();
        }

        protected override string GetIndexColumnsQuery(string indexIdentifier)
        {
            throw new NotImplementedException();
        }

        protected override string GetIndexInfoQuery(string tableName)
        {
            throw new NotImplementedException();
        }

        protected override string GetTableInfoQuery()
        {
            throw new NotImplementedException();
        }
    }
}

using System;
using System.Data;
using Gigobyte.Daterpillar.Transformation;
using System.Text.RegularExpressions;

namespace Gigobyte.Daterpillar.Data
{
    public class SQLiteSchemaAggregator : SchemaAggregatorBase
    {
        public SQLiteSchemaAggregator(IDbConnection connection) : base(connection)
        {
        }

        protected override void LoadColumnInformationIntoSchema(Table table, DataTable columnInfo)
        {
            foreach (DataRow row in columnInfo.Rows)
            {
                string temp;

                string typeName = Convert.ToString(row[ColumnName.Type]);
                typeName = (typeName == "INTEGER" ? "int" : typeName.ToLower());

                temp = _dataTypeRegex.Match(typeName)?.Groups["scale"]?.Value;
                int scale = Convert.ToInt32((string.IsNullOrEmpty(temp) ? "0" : temp));

                temp = _dataTypeRegex.Match(typeName)?.Groups["precision"]?.Value;
                int precision = Convert.ToInt32((string.IsNullOrEmpty(temp) ? "0" : temp));

                string defaultValue = Convert.ToString(row["dflt_value"]);

                var newColumn = new Column();
                newColumn.Name = Convert.ToString(row[ColumnName.Name]);
                newColumn.DataType = new DataType(typeName, scale, precision);
                //newColumn.AutoIncrement = Convert.ToBoolean(row[ColumnName.Auto]);
                newColumn.IsNullable = !Convert.ToBoolean(row["notnull"]);
                if (!string.IsNullOrEmpty(defaultValue)) newColumn.Modifiers.Add(defaultValue);

                table.Columns.Add(newColumn);
            }
        }

        protected override void LoadForeignKeyInformationIntoSchema(Table table, DataTable foreignKeyInfo)
        {
            base.LoadForeignKeyInformationIntoSchema(table, foreignKeyInfo);
        }

        protected override string GetColumnInfoQuery(string tableName)
        {
            return $"PRAGMA table_info('{tableName}');";
        }

        protected override string GetForeignKeyInfoQuery(string tableName)
        {
            return $"PRAGMA foreign_key_list('{tableName}');";
        }

        protected override string GetIndexColumnsQuery(string indexIdentifier)
        {
            throw new NotImplementedException();
        }

        protected override string GetIndexInfoQuery(string tableName)
        {
            throw new NotImplementedException();
        }

        protected override string GetTableInfoQuery()
        {
            return $"select sm.tbl_name AS [Name], '' AS [Comment] from sqlite_master sm WHERE sm.sql IS NOT NULL AND sm.name <> 'sqlite_sequence' AND sm.type = 'table';";
        }

        #region Private Members
        private Regex _dataTypeRegex = new Regex(@"\((?<scale>\d+),? ?(?<precision>\d+)\)", RegexOptions.Compiled);
        #endregion
    }
}

Add implementation details to SQLiteSchema Aggregator


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;

namespace Psistats.App
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.ThreadException +=
              new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

            // Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainScreen2());
        }

        static void CurrentDomain_UnhandledException (object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                Exception ex = (Exception)e.ExceptionObject;

                MessageBox.Show("CurrentDomain: Whoops! Please contact the developers with the following"
                      + " information:\n\n" + ex.Message + ex.StackTrace,
                      "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            finally
            {
                Application.Exit();
            }
        }

        public static void Application_ThreadException (object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            DialogResult result = DialogResult.Abort;
            try
            {
                result = MessageBox.Show("Application: Whoops! Please contact the developers with the"
                  + " following information:\n\n" + e.Exception.Message + e.Exception.StackTrace,
                  "Application Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
            }
            finally
            {
                if (result == DialogResult.Abort)
                {
                    Application.Exit();
                }
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;

namespace Psistats.App
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.ThreadException +=
              new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainScreen2());
        }

        static void CurrentDomain_UnhandledException (object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                Exception ex = (Exception)e.ExceptionObject;

                MessageBox.Show("CurrentDomain: Whoops! Please contact the developers with the following"
                      + " information:\n\n" + ex.Message + ex.StackTrace,
                      "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            finally
            {
                Application.Exit();
            }
        }

        public static void Application_ThreadException (object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            DialogResult result = DialogResult.Abort;
            try
            {
                result = MessageBox.Show("Application: Whoops! Please contact the developers with the"
                  + " following information:\n\n" + e.Exception.Message + e.Exception.StackTrace,
                  "Application Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
            }
            finally
            {
                if (result == DialogResult.Abort)
                {
                    Application.Exit();
                }
            }
        }
    }
}

Fix last remaining critical issue in sonar