Added aggregated hash/id extension methods

--- Source/RoaringFangs/Utility/Collections.cs
+++ Source/RoaringFangs/Utility/Collections.cs
@@ -23,6 +23,7 @@
 */

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

 namespace RoaringFangs.Utility
 {
@@ -64,5 +65,25 @@
                 return value;
             return default(TValue);
         }
+
+        public static int AggregatedHashCode<T>(this ICollection<T> self)
+        {
+            var hashes = self
+                .Where(s => s != null)
+                .Select(s => s.GetHashCode());
+            if (hashes.Any())
+                return hashes.Aggregate((a, b) => a ^ b);
+            return 0;
+        }
+
+        public static int AggregatedInstanceIDs<T>(this ICollection<T> self) where T : UnityEngine.Object
+        {
+            var ids = self
+                .Where(s => s != null)
+                .Select(s => s.GetInstanceID());
+            if (ids.Any())
+                return ids.Aggregate((a, b) => a ^ b);
+            return 0;
+        }
     }
 }


Missing a fairly critical log entry

Missing a fairly critical log entry

--- src/Umbraco.Web/umbraco.presentation/content.cs
+++ src/Umbraco.Web/umbraco.presentation/content.cs
@@ -1024,7 +1024,7 @@
                 catch (Exception e)
                 {
                     // This is really bad, loading from cache file failed for some reason, now fallback to loading from database
-                    Debug.WriteLine("Content file cache load failed: " + e);
+                    LogHelper.Error<content>("Content file cache load failed", e);
                     DeleteXmlCache();
                 }
             }


Return the root element instead of document node

--- src/Umbraco.Web/umbraco.presentation/library.cs
+++ src/Umbraco.Web/umbraco.presentation/library.cs
@@ -251,13 +251,13 @@
                     json = "{\"arrayitem\":" + json + "}";
                 }
                 var xml = JsonConvert.DeserializeXmlNode(json, "json", false);
-                return xml.CreateNavigator().Select("/");
+                return xml.CreateNavigator().Select("/json");
             }
             catch (Exception ex)
             {
                 var xd = new XmlDocument();
                 xd.LoadXml(string.Format("<error>Could not convert json to xml. Error: {0}</error>", ex));
-                return xd.CreateNavigator().Select("/");
+                return xd.CreateNavigator().Select("/error");
             }
         }


BugFix

BugFix

--- CoCSharp/Networking/NetworkManager.cs
+++ CoCSharp/Networking/NetworkManager.cs
@@ -87,6 +87,7 @@
             packet.WritePacket(new PacketWriter(tempStream));
             byte[] buffer = new byte[tempStream.Length];
             tempStream.Read(buffer, 0, buffer.Length);
+            buffer = (buffer.Skip(HeaderSize).ToArray());
             CoCCrypto.Encrypt(buffer);
             CoCStream.Write(buffer, 0, buffer.Length);
         }


Fix window titlebar button foreground colors (#35)

--- src/UwCore/Hamburger/HamburgerView16299.xaml.cs
+++ src/UwCore/Hamburger/HamburgerView16299.xaml.cs
@@ -43,9 +43,13 @@
             // Blur background
             this.PopupOverlay.RegisterPropertyChangedCallback(PopupOverlay.IsOpenProperty, this.OnPopupOverlayIsOpenChanged);
             this.LoadingOverlay.RegisterPropertyChangedCallback(LoadingOverlay.IsActiveProperty, this.OnLoadingOverlayIsActiveChanged);
-        }
-
-        #region Navigation
+
+            //Theme changes
+            var settings = new UISettings();
+            settings.ColorValuesChanged += (s, e) => this.UpdateTitleBarButtonForegroundColors();
+        }
+
+        #region ViewModel integration
         private void HamburgerView16299_OnDataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
         {
             this.ViewModel.PropertyChanged += this.ViewModelOnPropertyChanged;
@@ -55,8 +59,25 @@

             this.UpdateNavigationItems();
             this.UpdateSelectedItem();
-        }
-
+            this.UpdateTitleBarButtonForegroundColors();
+        }
+
+        private void ViewModelOnPropertyChanged(object sender, PropertyChangedEventArgs e)
+        {
+            if (e.PropertyName == nameof(this.ViewModel.SelectedAction) ||
+                e.PropertyName == nameof(this.ViewModel.SelectedSecondaryAction))
+            {
+                this.UpdateSelectedItem();
+            }
+
+            if (e.PropertyName == nameof(this.ViewModel.Theme))
+            {
+                this.UpdateTitleBarButtonForegroundColors();
+            }
+        }
+        #endregion
+
+        #region Navigation
         private void OnActionsChanged(NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
         {
             this.UpdateNavigationItems();
@@ -102,16 +123,6 @@
         }

         private bool _updatingSelectedItemFromViewModel = false;
-
-        private void ViewModelOnPropertyChanged(object sender, PropertyChangedEventArgs e)
-        {
-            if (e.PropertyName == nameof(this.ViewModel.SelectedAction) ||
-                e.PropertyName == nameof(this.ViewModel.SelectedSecondaryAction))
-            {
-                this.UpdateSelectedItem();
-            }
-        }
-
         private void UpdateSelectedItem()
         {
             var selectedAction = this.ViewModel.SelectedAction ?? this.ViewModel.SelectedSecondaryAction;
@@ -175,6 +186,32 @@
             //If its inset, make it show BEHIND the navigation view
             Canvas.SetZIndex(this.AppTitle, isMini || isCompact || expandedButNotOpen ? -1 : 0);
             this.AppTitle.Margin = new Thickness(inset + 12, 8, 0, 0);
+        }
+        #endregion
+
+        #region Window shell button foreground colors
+        private void UpdateTitleBarButtonForegroundColors()
+        {
+            bool IsDarkThemeCurrently()
+            {
+                if (this.ViewModel == null)
+                    return false; // Whatever, doesnt really matter because we will update again once we have a ViewModel
+
+                if (this.ViewModel.Theme == ElementTheme.Default)
+                {
+                    var settings = new UISettings();
+                    return settings.GetColorValue(UIColorType.Background) == Colors.Black;
+                }
+
+                return this.ViewModel.Theme == ElementTheme.Dark;
+            }
+
+            Color color = IsDarkThemeCurrently()
+                ? Colors.White
+                : Colors.Black;
+
+            ApplicationViewTitleBar titleBar = ApplicationView.GetForCurrentView().TitleBar;
+            titleBar.ButtonForegroundColor = color;
         }
         #endregion


Improved files commit info loading

Improved files commit info loading

--- CodeHub/Services/RepositoryUtility.cs
+++ CodeHub/Services/RepositoryUtility.cs
@@ -148,8 +148,11 @@
                         != null) // There must be a node with these specs if the HTML loading failed
                     ?.Descendants("div") // Get the inner <div/> nodes
                     ?.FirstOrDefault(node => node.Attributes?.AttributesWithName("class")?.FirstOrDefault() // Check the class name
-                        ?.Value?.Equals("loader-error") == true) != null) // Make sure there was in fact a loading error
-                {
+                        ?.Value?.Equals("loader-error") == true) != null || // Make sure there was in fact a loading error
+                        html.Contains("class=\"warning include - fragment - error\"") ||
+                        html.Contains("Failed to load latest commit information"))
+                {
+                    System.Diagnostics.Debug.WriteLine("[DEBUG] Fallback");
                     // Use the Oktokit APIs to get the info
                     IEnumerable<Task<IReadOnlyList<GitHubCommit>>> tasks = contents.Select(r => client.Repository.Commit.GetAll(repoId,
                         new CommitRequest { Path = r.Path, Sha = branch }, // Only get the commits that edited the current file
@@ -165,6 +168,7 @@
                             : new RepositoryContentWithCommitInfo(file);
                     });
                 }
+                System.Diagnostics.Debug.WriteLine("[DEBUG] HTML parsing");

                 /* ================
                  * HTML STRUCTURE


getting there with keeping old code that you want to keep

--- CodeRecycler/DestinationProjParser.cs
+++ CodeRecycler/DestinationProjParser.cs
@@ -234,37 +234,35 @@
       if (startPlaceHolder != null && endPlaceHolder != null && startPlaceHolder.IsBefore(endPlaceHolder))
       {
         XNode startNode = startPlaceHolder;
+        while (startNode.NextNode != endPlaceHolder)
+        {
+          oldXmlBuilder.Append(startNode.NextNode.ToString());
+          if (remove) startNode.NextNode.Remove();
+          else startNode = startNode.NextNode;
+        }
+        string oldXml = oldXmlBuilder.ToString();
+
         List<XElement> keepers = new List<XElement>();
-        while (startNode != endPlaceHolder)
-        {
-          if (startNode == null)
+        Log.WriteLine(oldXml);
+
+        if (oldXml.Contains("ItemGroup"))
+        {
+          XElement xElement = XElement.Parse(oldXml);
+
+          foreach (XElement descendant in xElement.Elements().Where(e => e.Attribute("Include") != null) )
           {
-            startNode = startNode.NextNode;
-            continue;
+            if (!descendant.Attribute("Include").Value.StartsWith("..")) { keepers.Add(descendant); }
           }
-          oldXmlBuilder.Append(startNode.NextNode);
-
-          if (startNode.NextNode != null && startNode.NextNode.NodeType == XmlNodeType.Element)
+
+          if (remove && keepers.Any())
           {
-          XElement xElement = XElement.Parse(startNode.NextNode.ToString());
-
-          foreach (XElement descendant in xElement.Elements("Include"))
-            if (!descendant.Value.StartsWith("..")) keepers.Add(descendant);
+            XElement newItemGroup = new XElement("ItemGroup");
+            foreach (XElement keeper in keepers) { newItemGroup.Add(keeper); }
+            endPlaceHolder.AddAfterSelf(newItemGroup);
           }
-
-          if (remove && startNode.NextNode  != null) startNode.NextNode.Remove();
-          else startNode = startNode.NextNode;
-        }
-        if (remove && keepers.Any())
-        {
-          XElement newItemGroup = new XElement("ItemGroup");
-          foreach (XElement keeper in keepers)
-          {
-            newItemGroup.Add(keeper);
-          }
-          endPlaceHolder.AddAfterSelf(newItemGroup);
-        }
-        return oldXmlBuilder.ToString();
+        }
+
+        return oldXml;
       }
       Recycler.Crash("Error: cannot get old Recycled Code from " + DestProjAbsolutePath);
       return "you'll never get this";


Only allow college names for colleges supported by commencement

--- Commencement/Resources/SelectLists.cs
+++ Commencement/Resources/SelectLists.cs
@@ -23,13 +23,13 @@
             new SelectListItem() {Value = "AE", Text = "Agricultural and Environmental Science"},
             new SelectListItem() {Value = "BI", Text = "Biological Science"},
             new SelectListItem() {Value = "EN", Text = "Engineering"},
-            new SelectListItem() {Value = "GS", Text = "Graduate Studies"},
+            //new SelectListItem() {Value = "GS", Text = "Graduate Studies"},
             new SelectListItem() {Value = "LS", Text = "Letters & Science"},
-            new SelectListItem() {Value = "LW", Text = "Law"},
-            new SelectListItem() {Value = "MD", Text = "Medicine"},
-            new SelectListItem() {Value = "SM", Text = "School of Management"},
-            new SelectListItem() {Value = "UE", Text = "University Extension"},
-            new SelectListItem() {Value = "VM", Text = "Veterinary Medicine"},
+            //new SelectListItem() {Value = "LW", Text = "Law"},
+            //new SelectListItem() {Value = "MD", Text = "Medicine"},
+            //new SelectListItem() {Value = "SM", Text = "School of Management"},
+            //new SelectListItem() {Value = "UE", Text = "University Extension"},
+            //new SelectListItem() {Value = "VM", Text = "Veterinary Medicine"},
         };

         public static List<SelectListItem> DegreeType = new List<SelectListItem>()


Add French language into LanguageSelector

French language was disabled into language selector for some reason.
As the translation is done, it makes sens to enable it again

--- ConfigurationPage/LanguageSelector.cs
+++ ConfigurationPage/LanguageSelector.cs
@@ -37,7 +37,7 @@
 			languageDict["Default"] = "EN";
 			languageDict["English"] = "EN";
 			languageDict["Español"] = "ES";
-			//languageDict["Français"] = "FR";
+			languageDict["Français"] = "FR";
 			languageDict["Deutsch"] = "DE";
 			languageDict["Polski"] = "PL";
 			languageDict["Türkçe"] = "TR";


Added Releases

Added Releases

--- Controllers/RepositoriesController.cs
+++ Controllers/RepositoriesController.cs
@@ -214,6 +214,11 @@
 		{
 			return GitHubRequest.Get<ContentModel>(Uri + "/contents" + path, new { Ref = branch });
 		}
+
+        public GitHubRequest<List<ReleaseModel>> GetReleases(int page = 1, int perPage = 100)
+        {
+            return GitHubRequest.Get<List<ReleaseModel>>(Uri + "/releases", new { page = page, per_page = perPage });
+        }

 		public GitHubRequest<ContentUpdateModel> UpdateContentFile(string path, string message, string content, string sha, string branch = "master")
 		{


improve timer test ranges

improve timer test ranges

--- CoreAPM.NET.Agent.Tests/TimerTests.cs
+++ CoreAPM.NET.Agent.Tests/TimerTests.cs
@@ -42,14 +42,14 @@
             var stopwatch = Substitute.For<Stopwatch>();
             var timer = new Timer(stopwatch);
             timer.Start();
-            Thread.Sleep(5);
+            Thread.Sleep(1);
             timer.Stop();

             //act
             var result = timer.CurrentTime;

             //assert
-            Assert.InRange(result, 5, 10);
+            Assert.InRange(result, 1, 10);
         }

         [Fact]
@@ -60,10 +60,10 @@
             var timer = new Timer(stopwatch);

             //act
-            var result = timer.Time(() => Thread.Sleep(5));
+            var result = timer.Time(() => Thread.Sleep(1));

             //assert
-            Assert.InRange(result, 5, 10);
+            Assert.InRange(result, 1, 10);
         }
     }
-}+}


[変更]EllipseCollider.Contains：計算式の簡略化

[変更]EllipseCollider.Contains：計算式の簡略化

--- CoreCode/Collision/EllipseCollider.cs
+++ CoreCode/Collision/EllipseCollider.cs
@@ -25,12 +25,15 @@
             }

             // 楕円侵入判定をまじめにやるべきケース
-            var centerX = (Left + Right) * 0.5;
-            var centerY = (Top + Bottom) * 0.5;
-            var radiusX = (Right - Left) * 0.5;
-            var radiusY = (Bottom - Top) * 0.5;
-            var normalizedPointX = (x - centerX) / radiusX;
-            var normalizedPointY = (y - centerY) / radiusY;
+            //var centerX = (Left + Right) * 0.5;
+            //var centerY = (Top + Bottom) * 0.5;
+            //var radiusX = (Right - Left) * 0.5;
+            //var radiusY = (Bottom - Top) * 0.5;
+            //var normalizedPointX = (x - centerX) / radiusX;
+            //var normalizedPointY = (y - centerY) / radiusY;
+            // 上式をまとめて簡略化
+            var normalizedPointX = (x * 2.0 - (Left + Right)) / (Right - Left);
+            var normalizedPointY = (y * 2.0 - (Top + Bottom)) / (Bottom - Top);
             var normalizedDistanceSquare = normalizedPointX * normalizedPointX + normalizedPointY * normalizedPointY;

             return normalizedDistanceSquare <= 1;


Handle drag and drop of folder. Fix  #15

Handle drag and drop of folder. Fix  #15

--- CountPages/ViewModel/MainViewModel.cs
+++ CountPages/ViewModel/MainViewModel.cs
@@ -1,4 +1,7 @@
 using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
 using System.IO;
 using System.Linq;
 using System.Threading.Tasks;
@@ -34,26 +37,25 @@
 		private async void ExecuteDropped(object o)
 		{
 			var e = o as DragEventArgs;
-			if (e != null)
-				await ReadFiles(e);
+			if (e != null && e.Data.GetDataPresent(DataFormats.FileDrop, false))
+				await ReadFiles((string[])e.Data.GetData(DataFormats.FileDrop));
 		}

-		private async Task ReadFiles(DragEventArgs e)
+		private async Task ReadFiles(IEnumerable<string> droppedPaths)
 		{
-			if (!e.Data.GetDataPresent(DataFormats.FileDrop)) return;
 			//try
 			//{
-			var paths = (string[])e.Data.GetData(DataFormats.FileDrop);
+
+			var paths = droppedPaths.SelectMany(path => path.GetAllFiles()).ToArray();

 			var tasks = new Task<Document>[paths.Length];
 			for (var i = 0; i < paths.Length; i++)
 			{
 				var path = paths[i];
-				var stream = new FileStream(path, FileMode.Open);
-				tasks[i] = Task.Run<Document>(() =>
-					new Document(path, stream));
+				var stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
+				tasks[i] = Task.Run(() => new Document(path, stream));
 			}
-			var documents =  await Task.WhenAll(tasks);
+			var documents = await Task.WhenAll(tasks);

 			PageCount = Convert.ToUInt32(documents.Sum(doc => doc.Count));

@@ -73,4 +75,44 @@
 			RaisePropertyChanged("LoaderVisibility");
 		}
 	}
+
+
+	public static class TreeReader
+	{
+		public static IEnumerable<string> GetAllFiles(this string path)
+		{
+			var queue = new Queue<string>();
+			queue.Enqueue(path);
+			while (queue.Count > 0)
+			{
+				path = queue.Dequeue();
+				if (String.IsNullOrEmpty(Path.GetExtension(path)))
+				{
+					try
+					{
+						foreach (var subDir in Directory.GetDirectories(path))
+							queue.Enqueue(subDir);
+					}
+					catch (Exception ex)
+					{
+						Console.Error.WriteLine(ex);
+					}
+					string[] files = null;
+					try
+					{
+						files = Directory.GetFiles(path);
+					}
+					catch (Exception ex)
+					{
+						Console.Error.WriteLine(ex);
+					}
+					if (files != null)
+						foreach (var t in files)
+							yield return t;
+				}
+				else
+					yield return path;
+			}
+		}
+	}
 }


ReadOnlySpan` hash fix

ReadOnlySpan` hash fix

--- src/Peachpie.Library/Hash.cs
+++ src/Peachpie.Library/Hash.cs
@@ -1218,8 +1218,9 @@
             /// </summary>
             /// <param name="newData">New pack of data to be appended to the buffered ones.</param>
             /// <param name="blockSize">Block size, when buffered data fits this, they are returned.</param>
+            /// <param name="callback">Called for each block.</param>
             /// <returns>Packs of block, as a pair of byte array and index of first element.</returns>
-            internal IEnumerable<(byte[] Block, int ElementIndex)> ProcessBlocked(ReadOnlySpan<byte>/*!*/newData, int blockSize)
+            internal void ProcessBlocked(ReadOnlySpan<byte>/*!*/newData, int blockSize, Action<byte[], int> callback)
             {
                 Debug.Assert(blockSize > 0);

@@ -1237,11 +1238,11 @@
                     {
                         newData.CopyTo(buffer.AsSpan(bufferUsage, newData.Length));
                         bufferUsage += newData.Length;
-                        yield break;
+                        return;
                     }

                     newData.CopyTo(buffer.AsSpan(bufferUsage, bytesToFitBuffer));
-                    yield return (buffer, 0); // use the data from buffer
+                    callback(buffer, 0); // use the data from buffer

                     bufferUsage = 0;            // buffer is empty now
                     index += bytesToFitBuffer;  // part of newData was used
@@ -1250,7 +1251,7 @@
                 // returns blocks from the newData
                 while (index + blockSize <= newData.Length)
                 {
-                    yield return (newData.ToArray(), index);
+                    callback(newData.ToArray(), index);
                     index += blockSize;
                 }

@@ -1762,8 +1763,10 @@

                 public override bool Update(ReadOnlySpan<byte> data)
                 {
-                    foreach (var block in ProcessBlocked(data, 16))
-                        TransformBlock(block.Block, block.ElementIndex);
+                    ProcessBlocked(data, 16, (block, index) =>
+                    {
+                        TransformBlock(block, index);
+                    });

                     return true;
                 }
@@ -1945,8 +1948,10 @@
                         ++count[1];
                     count[1] += ((uint)data.Length >> 29);

-                    foreach (var block in ProcessBlocked(data, 64))
-                        MD4Transform(block.Block, block.ElementIndex);
+                    ProcessBlocked(data, 64, (block, index) =>
+                    {
+                        MD4Transform(block, index);
+                    });

                     return true;
                 }
@@ -2229,8 +2234,10 @@
                     count[1] += ((uint)data.Length >> 29);

                     // Transform blocks of 64 bytes
-                    foreach (var block in ProcessBlocked(data, 64))
-                        MD5Transform(block.Block, block.ElementIndex);
+                    ProcessBlocked(data, 64, (block, index) =>
+                    {
+                        MD5Transform(block, index);
+                    });

                     return true;
                 }


Updated flashcard model

Updated flashcard model

--- StudyBox/StudyBox.Core/Models/Flashcard.cs
+++ StudyBox/StudyBox.Core/Models/Flashcard.cs
@@ -6,10 +6,6 @@
     {
         [JsonProperty(PropertyName = "id")]
         public string Id { get; set; }
-
-        //Need to delete this
-        [JsonProperty(PropertyName = "deck")]
-        public Deck Deck { get; set; }

         [JsonProperty(PropertyName = "deckId")]
         public string DeckID { get; set; }
@@ -20,22 +16,22 @@
         [JsonProperty(PropertyName = "answer")]
         public string Answer { get; set; }

+        [JsonProperty(PropertyName = "isHidden")]
+        public bool IsHidden { get; set; }
+
         [JsonProperty(PropertyName = "tipsCount")]
         public int TipsCount { get; set; }

-        //Need to delete this
-        [JsonProperty(PropertyName = "hint")]
-        public string Hint { get; set; }
-
         public Flashcard() { }

-        public Flashcard(string id, Deck deck, string question, string answer, string hint)
+        public Flashcard(string id, string deckId, string question, string answer, bool idHidden, int tipsCount)
         {
             Id = id;
-            Deck = deck;
+            DeckID = deckId;
             Question = question;
             Answer = answer;
-            Hint = hint;
+            IsHidden = IsHidden;
+            TipsCount = tipsCount;
         }
     }
 }


fixes

fixes

--- Styx/Aegir/GeoCoordinates/GeoCoordinate.cs
+++ Styx/Aegir/GeoCoordinates/GeoCoordinate.cs
@@ -283,6 +283,50 @@

         #endregion

+        #region fromLatLng(Latitude, Longitude, Altitude = null)
+
+        /// <summary>
+        /// Create a new geographical coordinate or position on a map.
+        /// </summary>
+        /// <param name="Latitude">The Latitude (south to nord).</param>
+        /// <param name="Longitude">The Longitude (parallel to equator).</param>
+        /// <param name="Altitude">The (optional) Altitude.</param>
+        public static GeoCoordinate fromLatLng(Double   Latitude,
+                                               Double   Longitude,
+                                               Double?  Altitude = null)
+
+            => new GeoCoordinate(
+                   Aegir.Latitude. Parse(Latitude),
+                   Aegir.Longitude.Parse(Longitude),
+                   Altitude.HasValue
+                       ? new Aegir.Altitude?(Aegir.Altitude.Parse(Altitude.Value))
+                       : null
+               );
+
+        #endregion
+
+        #region fromLngLat(Longitude, Latitude, Altitude = null)
+
+        /// <summary>
+        /// Create a new geographical coordinate or position on a map.
+        /// </summary>
+        /// <param name="Longitude">The Longitude (parallel to equator).</param>
+        /// <param name="Latitude">The Latitude (south to nord).</param>
+        /// <param name="Altitude">The (optional) Altitude.</param>
+        public static GeoCoordinate fromLngLat(Double   Longitude,
+                                               Double   Latitude,
+                                               Double?  Altitude = null)
+
+            => new GeoCoordinate(
+                   Aegir.Latitude. Parse(Latitude),
+                   Aegir.Longitude.Parse(Longitude),
+                   Altitude.HasValue
+                       ? new Aegir.Altitude?(Aegir.Altitude.Parse(Altitude.Value))
+                       : null
+               );
+
+        #endregion
+

         #region Parse   (LatitudeString, LongitudeString, AltitudeString = null)


Parse BG in an async-friendly way.

Parse BG in an async-friendly way.

--- src/BibleBot.Backend/Services/Providers/BibleGatewayProvider.cs
+++ src/BibleBot.Backend/Services/Providers/BibleGatewayProvider.cs
@@ -1,10 +1,12 @@
+using System.IO;
+using System.Linq;
 using System.Net.Http;
-using System.Linq;
+using System.Threading;
 using System.Threading.Tasks;
 using System.Collections.Generic;
 using System.Text.RegularExpressions;

-using AngleSharp;
+using AngleSharp.Html.Parser;

 using BibleBot.Lib;
 using BibleBot.Backend.Models;
@@ -14,7 +16,9 @@
     public class BibleGatewayProvider : IBibleProvider
     {
         public string Name { get; set; }
+        private readonly CancellationTokenSource _cancellationToken;
         private readonly HttpClient _httpClient;
+        private readonly HtmlParser _htmlParser;
         private readonly string _baseURL = "https://www.biblegateway.com";
         private readonly string _getURI = "/passage/?search={0}&version={1}&interface=print";
         private readonly string _votdURI = "/reading-plans/verse-of-the-day/next";
@@ -22,7 +26,10 @@
         public BibleGatewayProvider()
         {
             Name = "bg";
+
+            _cancellationToken = new CancellationTokenSource();
             _httpClient = new HttpClient();
+            _htmlParser = new HtmlParser();
         }

         public async Task<Verse> GetVerse(Reference reference, bool titlesEnabled, bool verseNumbersEnabled)
@@ -33,9 +40,16 @@
             }

             string url = _baseURL + System.String.Format(_getURI, reference.AsString, reference.Version.Abbreviation);
-            string resp = await _httpClient.GetStringAsync(url);
+
+            HttpResponseMessage req = await _httpClient.GetAsync(url);
+            _cancellationToken.Token.ThrowIfCancellationRequested();

-            var document = await BrowsingContext.New().OpenAsync(req => req.Content(resp));
+            Stream resp = await req.Content.ReadAsStreamAsync();
+            _cancellationToken.Token.ThrowIfCancellationRequested();
+
+            var document = await _htmlParser.ParseDocumentAsync(resp);
+            _cancellationToken.Token.ThrowIfCancellationRequested();
+
             var container = document.QuerySelector(".result-text-style-normal");

             if (container == null)
@@ -118,9 +132,15 @@
         public async Task<string> GetDailyVerse()
         {
             string url = _baseURL + _votdURI;
-            string resp = await _httpClient.GetStringAsync(url);
+
+            HttpResponseMessage req = await _httpClient.GetAsync(url);
+            _cancellationToken.Token.ThrowIfCancellationRequested();

-            var document = await BrowsingContext.New().OpenAsync(req => req.Content(resp));
+            Stream resp = await req.Content.ReadAsStreamAsync();
+            _cancellationToken.Token.ThrowIfCancellationRequested();
+
+            var document = await _htmlParser.ParseDocumentAsync(resp);
+            _cancellationToken.Token.ThrowIfCancellationRequested();

             return document.GetElementsByClassName("rp-passage-display").FirstOrDefault().TextContent;
         }


Add skips to prime factors test suite

Add skips to prime factors test suite

--- exercises/prime-factors/PrimeFactorsTest.cs
+++ exercises/prime-factors/PrimeFactorsTest.cs
@@ -10,37 +10,37 @@
         Assert.Empty(PrimeFactors.Factors(1));
     }

-    [Fact]
+    [Fact(Skip = "Remove to run test")]
     public void Prime_number()
     {
         Assert.Equal(new[] { 2 }, PrimeFactors.Factors(2));
     }

-    [Fact]
+    [Fact(Skip = "Remove to run test")]
     public void Square_of_a_prime()
     {
         Assert.Equal(new[] { 3, 3 }, PrimeFactors.Factors(9));
     }

-    [Fact]
+    [Fact(Skip = "Remove to run test")]
     public void Cube_of_a_prime()
     {
         Assert.Equal(new[] { 2, 2, 2 }, PrimeFactors.Factors(8));
     }

-    [Fact]
+    [Fact(Skip = "Remove to run test")]
     public void Product_of_primes_and_non_primes()
     {
         Assert.Equal(new[] { 2, 2, 3 }, PrimeFactors.Factors(12));
     }

-    [Fact]
+    [Fact(Skip = "Remove to run test")]
     public void Product_of_primes()
     {
         Assert.Equal(new[] { 5, 17, 23, 461 }, PrimeFactors.Factors(901255));
     }

-    [Fact]
+    [Fact(Skip = "Remove to run test")]
     public void Factors_include_a_large_prime()
     {
         Assert.Equal(new[] { 11, 9539, 894119 }, PrimeFactors.Factors(93819012551));


Fix tests.

Fix tests.

--- src/EditorFeatures/Test/CallHierarchy/CallHierarchyTestState.cs
+++ src/EditorFeatures/Test/CallHierarchy/CallHierarchyTestState.cs
@@ -15,6 +15,7 @@
 using Microsoft.CodeAnalysis.Editor.SymbolMapping;
 using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
 using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
+using Microsoft.CodeAnalysis.FindSymbols;
 using Microsoft.CodeAnalysis.Notification;
 using Microsoft.VisualStudio.Language.CallHierarchy;
 using Microsoft.VisualStudio.Text;
@@ -124,6 +125,7 @@
                 .WithPart(typeof(CallHierarchyProvider))
                 .WithPart(typeof(SymbolMappingServiceFactory))
                 .WithPart(typeof(EditorNotificationServiceFactory))
+                .WithPart(typeof(DefaultSymbolFinderEngineService))
                 .WithParts(additionalTypes);

             return MinimalTestExportProvider.CreateExportProvider(catalog);


Improved archive pack output #97

Improved archive pack output #97

--- Tailviewer.Archiver/Applications/Packer.cs
+++ Tailviewer.Archiver/Applications/Packer.cs
@@ -28,8 +28,10 @@
 			var archiveFilename = _options.ArchiveFileName ?? Path.GetFileNameWithoutExtension(_options.InputFileName);
 			if (!archiveFilename.EndsWith(PluginArchive.PluginExtension, StringComparison.InvariantCultureIgnoreCase))
 				archiveFilename = string.Format("{0}.{1}", archiveFilename, PluginArchive.PluginExtension);
+			if (!Path.IsPathRooted(archiveFilename))
+				archiveFilename = Path.Combine(Directory.GetCurrentDirectory(), archiveFilename);

-			Console.WriteLine("Creating plugin archive {0}...", archiveFilename);
+			Console.WriteLine("Creating Tailviewer plugin...");

 			using (var pluginStream = new MemoryStream())
 			{
@@ -44,7 +46,7 @@
 							return -1;

 						case ".dll":
-							Console.Write("Adding plugin assembly {0}... ", _options.InputFileName);
+							Console.Write("Adding {0}... ", _options.InputFileName);
 							packer.AddPluginAssembly(_options.InputFileName);
 							Console.WriteLine("OK");
 							break;
@@ -56,20 +58,21 @@

 					foreach (var filename in _options.Files)
 					{
-						Console.Write("Adding file {0}... ", filename);
+						Console.Write("Adding {0}... ", filename);
 						AddFile(packer, filename);
 						Console.WriteLine("OK");
 					}
 				}

 				pluginStream.Position = 0;
+				Console.Write("Saving plugin => {0}... ", archiveFilename);
 				using (var fileStream = File.Create(archiveFilename))
 				{
 					pluginStream.CopyTo(fileStream);
 				}
+				Console.WriteLine("OK");
 			}

-			Console.WriteLine("Finished!");
 			return 0;
 		}


regression tester

regression tester

--- Testing/RegressionTesting/CompilerSuite.cs
+++ Testing/RegressionTesting/CompilerSuite.cs
@@ -77,11 +77,11 @@
                         Process proc;
                         if (Environment == "Microsoft")
                         {
-                            proc = ExecuteProcess(poly, '"' + filename + '"' + ' ' + '"' + output + '"');
+                            proc = ExecuteProcess(poly, '"' + filename + '"' + " --out=" + '"' + output + '"');
                         }
                         else if (Environment == "Mono")
                         {
-                            proc = ExecuteProcess(mono, poly + " \"" + filename + '"' + ' ' + '"' + output + '"');
+                            proc = ExecuteProcess(mono, poly + " \"" + filename + '"' + " --out=" + '"' + output + '"');
                         }
                         else
                         {
@@ -108,7 +108,7 @@
                         }
                         else if (Environment == "Mono")
                         {
-                            proc = ExecuteProcess(gcc, "-m32 \"" + filename.Replace(@"\", "/") + '"' + " -c -o " + '"' + output.Replace(@"\", "/") + '"' + " -I ../Runtime");
+                            proc = ExecuteProcess(gcc, " \"" + filename.Replace(@"\", "/") + '"' + " -c -o " + '"' + output.Replace(@"\", "/") + '"' + " -I ../Runtime");

                         }
                         else
@@ -136,7 +136,7 @@
                         }
                         else if (Environment == "Mono")
                         {
-                            proc = ExecuteProcess(gcc, "-m32 " + filename.Replace(@"\", "/") + ' ' + " runtime.a -o " + '"' + output.Replace(@"\", "/") + '"');
+                            proc = ExecuteProcess(gcc, " " + filename.Replace(@"\", "/") + ' ' + " runtime.a -o " + '"' + output.Replace(@"\", "/") + '"');
                         }
                         else
                         {


Tests: add basic logic for MockServerLoopNode

--- Tests/Mocks/DataLoop/MockServerLoopNode.cs
+++ Tests/Mocks/DataLoop/MockServerLoopNode.cs
@@ -23,7 +23,9 @@
 // SOFTWARE.
 //
 using System;
+using System.Threading;
 using System.Threading.Tasks;
+using DarkCaster.Async;
 using DarkCaster.DataTransfer.Server;
 using DarkCaster.DataTransfer.Config;

@@ -31,39 +33,93 @@
 {
 	public sealed class MockServerLoopNode : INode
 	{
+		private readonly Random random;
+		private readonly AsyncRunner newConnRunner = new AsyncRunner();
+		private readonly ITunnelConfigFactory configFactory;
+		private readonly INode upstreamNode;
+		private volatile INode downstreamNode;

-		public void NewConnection(Storage readStorage, Storage writeStorage)
+		private readonly int minBlockSize;
+		private readonly int maxBlockSize;
+		private readonly int readTimeout;
+		private readonly float nodeFailProb;
+		private int noFailOpsCount;
+
+		private int initCount;
+		private int ncCount;
+		private int regDsCount;
+		private int shutdownCount;
+		private int disposeCount;
+
+		public MockServerLoopNode(ITunnelConfig serverConfig, INode upstream, ITunnelConfigFactory configFactory,
+															int defaultMinBlockSize = 16, int defaultMaxBlockSize = 4096, int defaultReadTimeout = 5000,
+															int defaultNoFailOpsCount = 1, float defaultNodeFailProb = 0.0f)
 		{
+			minBlockSize = serverConfig.Get<int>("mock_min_block_size");
+			maxBlockSize = serverConfig.Get<int>("mock_max_block_size");
+			readTimeout = serverConfig.Get<int>("mock_read_timeout");
+			nodeFailProb = serverConfig.Get<float>("mock_fail_prob");
+			noFailOpsCount = serverConfig.Get<int>("mock_nofail_ops_count");
+			if(minBlockSize <= 0)
+				minBlockSize = defaultMinBlockSize;
+			if(maxBlockSize <= 0)
+				maxBlockSize = defaultMaxBlockSize;
+			if(readTimeout <= 0)
+				readTimeout = defaultReadTimeout;
+			if(nodeFailProb <= 0.001f)
+				nodeFailProb = defaultNodeFailProb;
+			if(noFailOpsCount <= 0)
+				noFailOpsCount = defaultNoFailOpsCount;
+			this.upstreamNode = upstream;
+			this.configFactory = configFactory;
+			this.random = new Random();
+		}
+
+		public void NewConnection(Storage clientReadStorage, Storage clientWriteStorage)
+		{
+			Interlocked.Increment(ref ncCount);
+			//simulate fail
+			if(--noFailOpsCount <= 0 && (float)random.NextDouble() < nodeFailProb)
+			{
+				newConnRunner.ExecuteTask(() => downstreamNode.NodeFailAsync(new Exception("Expected fail")));
+				throw new Exception("Expected fail triggered");
+			}
+			var tunnel = new MockServerLoopTunnel(minBlockSize, maxBlockSize, clientWriteStorage, readTimeout, clientReadStorage);
+			var config = configFactory.CreateNew();
+			newConnRunner.ExecuteTask(() => downstreamNode.OpenTunnelAsync(config, tunnel));
 		}

 		public Task InitAsync()
 		{
-			throw new NotImplementedException("TODO");
+			Interlocked.Increment(ref initCount);
+			return Task.FromResult(true);
 		}

 		public void RegisterDownstream(INode downstream)
 		{
-			throw new NotImplementedException("TODO");
+			Interlocked.Increment(ref regDsCount);
+			this.downstreamNode = downstream;
 		}

 		public Task OpenTunnelAsync(ITunnelConfig config, ITunnel upstream)
 		{
-			throw new NotImplementedException("TODO");
+			throw new NotSupportedException("THIS IS A ROOT SERVER NODE");
 		}

 		public Task NodeFailAsync(Exception ex)
 		{
-			throw new NotImplementedException("TODO");
+			throw new NotSupportedException("THIS IS A ROOT SERVER NODE");
 		}

 		public Task ShutdownAsync()
 		{
-			throw new NotImplementedException("TODO");
+			Interlocked.Increment(ref shutdownCount);
+			return Task.FromResult(true);
 		}

 		public void Dispose()
 		{
-
+			Interlocked.Increment(ref disposeCount);
 		}
 	}
 }


Increased physical time for user program running

--- src/JoyOI.OnlineJudge.WebApi/Controllers/Api/JudgeController.cs
+++ src/JoyOI.OnlineJudge.WebApi/Controllers/Api/JudgeController.cs
@@ -186,7 +186,7 @@
                     Id = await MgmtSvc.PutBlobAsync("limit.json", Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new
                     {
                         UserTime = problem.TimeLimitationPerCaseInMs,
-                        PhysicalTime = problem.TimeLimitationPerCaseInMs * 2,
+                        PhysicalTime = problem.TimeLimitationPerCaseInMs * 4,
                         Memory = problem.MemoryLimitationPerCaseInByte
                     }))),
                     Name = "limit.json",


Mintmanga download test.

Mintmanga download test.

--- Tests/Tests.Entities/Download/Readmanga.cs
+++ Tests/Tests.Entities/Download/Readmanga.cs
@@ -40,6 +40,29 @@
       Assert.AreEqual(100, lastPercent);
     }

+    [Test]
+    public async Task DownloadMintmanga()
+    {
+      var rm = Mangas.CreateFromWeb(new Uri(@"http://mintmanga.com/haruka_na_receive"));
+      var sw = new Stopwatch();
+      sw.Start();
+      rm.PropertyChanged += RmOnDownloadChanged;
+      DirectoryHelpers.DeleteDirectory(rm.GetAbsoulteFolderPath());
+      await rm.Download();
+      sw.Stop();
+      Log.Add($"manga loaded {sw.Elapsed.TotalSeconds}, iscompleted = {rm.IsDownloaded}, lastpercent = {lastPercent}");
+      Assert.IsTrue(Directory.Exists(rm.GetAbsoulteFolderPath()));
+      var files = Directory.GetFiles(rm.GetAbsoulteFolderPath(), "*", SearchOption.AllDirectories);
+      Assert.AreEqual(11, files.Length);
+      var fileInfos = files.Select(f => new FileInfo(f)).ToList();
+      Assert.AreEqual(3474445, fileInfos.Sum(f => f.Length));
+
+      // Количество повторяющихся картинок на мангу - не больше одной на главу.
+      Assert.IsTrue(rm.Volumes.Sum(v => v.Container.Count()) >= fileInfos.GroupBy(f => f.Length).Max(g => g.Count()));
+      Assert.IsTrue(rm.IsDownloaded);
+      Assert.AreEqual(100, lastPercent);
+    }
+
     private void RmOnDownloadChanged(object sender, PropertyChangedEventArgs args)
     {
       if (args.PropertyName == nameof(IManga.Downloaded))


Refactor

Refactor

--- Tests/ViewModel/SpecLogTransformerTests.cs
+++ Tests/ViewModel/SpecLogTransformerTests.cs
@@ -15,11 +15,17 @@
     [Test]
     public void Transform_NullPathToSpecLogFile_ThrowsArgumentNullExceptionForPathToSpecLogFile()
     {
-      var transformer = new SpecLogTransformer(new MockFileSystem());
+      var transformer = CreateSpecLogTransformer();

       Check.ThatCode(() => transformer.Transform(null, null))
         .Throws<ArgumentNullException>()
         .WithProperty("ParamName", "pathToSpecLogFile");
     }
+
+    private static SpecLogTransformer CreateSpecLogTransformer()
+    {
+      var transformer = new SpecLogTransformer(new MockFileSystem());
+      return transformer;
+    }
   }
 }


fix LinFx.Threading.Timer

fix LinFx.Threading.Timer

--- src/LinFx/Extensions/RabbitMQ/DefaultRabbitMqMessageConsumer.cs
+++ src/LinFx/Extensions/RabbitMQ/DefaultRabbitMqMessageConsumer.cs
@@ -1,10 +1,10 @@
-using Microsoft.Extensions.Logging;
+using LinFx.Threading;
+using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging.Abstractions;
 using RabbitMQ.Client;
 using RabbitMQ.Client.Events;
 using System;
 using System.Collections.Concurrent;
-using System.Threading;
 using System.Threading.Tasks;

 namespace LinFx.Extensions.RabbitMQ
@@ -37,11 +37,12 @@
             QueueBindCommands = new ConcurrentQueue<QueueBindCommand>();
             Callbacks = new ConcurrentBag<Func<IModel, BasicDeliverEventArgs, Task>>();

-            Timer = new Timer(Timer_Elapsed, null, Timeout.Infinite, Timeout.Infinite);
-            //Timer.Change(0, null, Timeout.Infinite, Timeout.Infinite);
-            //Timer.Period = 5000; //5 sec.
-            //Timer.Elapsed += Timer_Elapsed;
-            //Timer.RunOnStart = true;
+            Timer = new Timer
+            {
+                Period = 5000, //5 sec.
+                RunOnStart = true
+            };
+            Timer.Elapsed += Timer_Elapsed;
         }

         public void Initialize(
@@ -52,8 +53,7 @@
             Exchange = Check.NotNull(exchange, nameof(exchange));
             Queue = Check.NotNull(queue, nameof(queue));
             ConnectionName = connectionName;
-            //Timer.Start();
-            TryCreateChannel();
+            Timer.StartAsync().Wait();
         }

         public virtual async Task BindAsync(string routingKey)
@@ -120,7 +120,7 @@
             Callbacks.Add(callback);
         }

-        protected virtual void Timer_Elapsed(object state)
+        protected virtual void Timer_Elapsed(object sender, EventArgs e)
         {
             if (Channel == null || Channel.IsOpen == false)
             {


Fix issue with LD_LIBRARY_PATH that prevented MRO from loading.

--- src/Linux/Host/Broker/Impl/Services/LinuxRHostProcessService.cs
+++ src/Linux/Host/Broker/Impl/Services/LinuxRHostProcessService.cs
@@ -45,6 +45,15 @@
             return new UnixProcess(process);
         }

+        private string GetLoadLibraryPath(string binPath) {
+            string value = Environment.GetEnvironmentVariable("LD_LIBRARY_PATH");
+            if (string.IsNullOrEmpty(value)) {
+                return binPath;
+            }
+
+            return $"{binPath}:{value}";
+        }
+
         private IDictionary<string, string> GetHostEnvironment(Interpreter interpreter, string profilePath, string userName) {
             // set required environment variables.
             Dictionary<string, string> environment = new Dictionary<string, string>() {
@@ -53,15 +62,15 @@
                 { "PWD"                     , profilePath},
                 { "R_HOME"                  , interpreter.RInterpreterInfo.InstallPath},
                 { "USER"                    , Utility.GetUnixUserName(userName)},
+                { "LD_LIBRARY_PATH"         , GetLoadLibraryPath(interpreter.RInterpreterInfo.BinPath)}
             };

             // set optional environment variables if available
-            string[] optionalVariables = { "LD_LIBRARY_PATH", "LN_S", "R_ARCH", "R_BROWSER", "R_BZIPCMD", "R_GZIPCMD", "R_LIBS_SITE", "R_INCLUDE_DIR", "R_DOC_DIR", "R_PAPERSIZE", "R_PAPERSIZE_USER", "R_PDFVIEWER", "R_PRINTCMD", "R_RD4PDF", "R_SHARE_DIR", "R_TEXI2DVICMD", "R_UNZIPCMD", "R_ZIPCMD", "SED", "SHELL", "SHLVL", "TAR" };
+            string[] optionalVariables = { "LN_S", "R_ARCH", "R_BROWSER", "R_BZIPCMD", "R_GZIPCMD", "R_LIBS_SITE", "R_INCLUDE_DIR", "R_DOC_DIR", "R_PAPERSIZE", "R_PAPERSIZE_USER", "R_PDFVIEWER", "R_PRINTCMD", "R_RD4PDF", "R_SHARE_DIR", "R_TEXI2DVICMD", "R_UNZIPCMD", "R_ZIPCMD", "SED", "SHELL", "SHLVL", "TAR" };
             foreach(string key in optionalVariables) {
                 SetEnvironmentVaraibleIfAvailable(environment, key);
             }

-            // TODO: provide RTVS_LD_LIBRARY_PATH
             return environment;
         }


Fixed failing test

Fixed failing test

--- src/Marten.Testing/Events/Projections/lazy_loaded_projection.cs
+++ src/Marten.Testing/Events/Projections/lazy_loaded_projection.cs
@@ -79,7 +79,7 @@
             theSession.SaveChanges();

             var document2 = theSession.Load<PersistedView>(streamId);
-            document.Events.Count.ShouldBe(3);
+            document2.Events.Count.ShouldBe(3);

             logger.Logs.Count.ShouldBe(1);
         }


added namespace mappings to Xamarin.Forms project

--- src/MvvmScarletToolkit.Xamarin.Forms/Properties/AssemblyInfo.cs
+++ src/MvvmScarletToolkit.Xamarin.Forms/Properties/AssemblyInfo.cs
@@ -1,5 +1,7 @@
 using System.Reflection;
 using System.Runtime.InteropServices;
+using Xamarin.Forms;
+using Xamarin.Forms.Internals;

 // General Information about an assembly is controlled through the following
 // set of attributes. Change these attribute values to modify the information
@@ -16,3 +18,6 @@

 // The following GUID is for the ID of the typelib if this project is exposed to COM
 [assembly: Guid("9bd9b759-8c12-4e08-971b-9ba21d8247ff")]
+[assembly: Preserve(AllMembers = true)]
+[assembly: XmlnsPrefix("http://SoftThorn.MvvmScarletToolkit.com/winfx/xaml/shared", "mvvm")]
+[assembly: XmlnsDefinition("http://SoftThorn.MvvmScarletToolkit.com/winfx/xaml/shared", "MvvmScarletToolkit")]


Remove unnecessary function abstraction

Remove unnecessary function abstraction

--- src/NUnitFramework/framework/Attributes/TestFixtureAttribute.cs
+++ src/NUnitFramework/framework/Attributes/TestFixtureAttribute.cs
@@ -252,7 +252,7 @@
         /// </summary>
         public IEnumerable<TestSuite> BuildFrom(ITypeInfo typeInfo)
         {
-            yield return this.BuildFrom(typeInfo, PreFilter.Empty, this);
+            return this.BuildFrom(typeInfo, PreFilter.Empty);
         }

         #endregion
@@ -266,15 +266,10 @@
         /// <param name="filter">Filter used to select methods as tests.</param>
         public IEnumerable<TestSuite> BuildFrom(ITypeInfo typeInfo, IPreFilter filter)
         {
-            yield return this.BuildFrom(typeInfo, filter, this);
-        }
-
-        private TestSuite BuildFrom(ITypeInfo typeInfo, IPreFilter filter, ITestFixtureData testFixtureData)
-        {
-            var fixture = _builder.BuildFrom(typeInfo, filter, testFixtureData);
+            var fixture = _builder.BuildFrom(typeInfo, filter, this);
             fixture.ApplyAttributesToTest(typeInfo.Type.GetTypeInfo());

-            return fixture;
+            yield return fixture;
         }

         #endregion


Force resave of IPublishedContentExtensions

--- src/Our.Umbraco.Vorto/Extensions/IPublishedContentExtensions.cs
+++ src/Our.Umbraco.Vorto/Extensions/IPublishedContentExtensions.cs
@@ -136,7 +136,7 @@
             var result = content.DoGetVortoValue<T>(propertyAlias, cultureName, recursive, default(T));
             if (result == null && !string.IsNullOrEmpty(fallbackCultureName) && !fallbackCultureName.Equals(cultureName))
                 result = content.DoGetVortoValue<T>(propertyAlias, fallbackCultureName, recursive, defaultValue);
-
+
             return result;
         }


Remove ToList

Remove ToList

--- src/SlackUserChangeAlerts.Function/CheckUserListChanges/run.csx
+++ src/SlackUserChangeAlerts.Function/CheckUserListChanges/run.csx
@@ -38,7 +38,7 @@
 }

 private static IEnumerable<Member> DeserializeMembers(string json) =>
-    JsonConvert.DeserializeObject<UserCollection>(json).Members.Where(m => !m.Deleted).ToList();
+    JsonConvert.DeserializeObject<UserCollection>(json).Members.Where(m => !m.Deleted);

 private static string Env(string name) => System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);


U4-9077 - in addition, deal with N+1 for relations

--- src/Umbraco.Core/Persistence/Repositories/RelationRepository.cs
+++ src/Umbraco.Core/Persistence/Repositories/RelationRepository.cs
@@ -42,6 +42,47 @@
                 throw new Exception(string.Format("RelationType with Id: {0} doesn't exist", dto.RelationType));

             var factory = new RelationFactory(relationType);
+            return DtoToEntity(dto, factory);
+        }
+
+        protected override IEnumerable<IRelation> PerformGetAll(params int[] ids)
+        {
+            var sql = GetBaseQuery(false);
+            if (ids.Length > 0)
+                sql.WhereIn<RelationDto>(x => x.Id, ids);
+            sql.OrderBy<RelationDto>(x => x.RelationType);
+            var dtos = Database.Fetch<RelationDto>(sql);
+            return DtosToEntities(dtos);
+        }
+
+        protected override IEnumerable<IRelation> PerformGetByQuery(IQuery<IRelation> query)
+        {
+            var sqlClause = GetBaseQuery(false);
+            var translator = new SqlTranslator<IRelation>(sqlClause, query);
+            var sql = translator.Translate();
+            sql.OrderBy<RelationDto>(x => x.RelationType);
+            var dtos = Database.Fetch<RelationDto>(sql);
+            return DtosToEntities(dtos);
+        }
+
+        private IEnumerable<IRelation> DtosToEntities(IEnumerable<RelationDto> dtos)
+        {
+            // in most cases, the relation type will be the same for all of them,
+            // plus we've ordered the relations by type, so try to allocate as few
+            // factories as possible - bearing in mind that relation types are cached
+            RelationFactory factory = null;
+            var relationTypeId = -1;
+
+            return dtos.Select(x =>
+            {
+                if (relationTypeId != x.RelationType)
+                    factory = new RelationFactory(_relationTypeRepository.Get(relationTypeId = x.RelationType));
+                return DtoToEntity(x, factory);
+            });
+        }
+
+        private static IRelation DtoToEntity(RelationDto dto, RelationFactory factory)
+        {
             var entity = factory.BuildEntity(dto);

             //on initial construction we don't want to have dirty properties tracked
@@ -49,41 +90,6 @@
             ((TracksChangesEntityBase)entity).ResetDirtyProperties(false);

             return entity;
-        }
-
-        //TODO: Fix N+1 !
-
-        protected override IEnumerable<IRelation> PerformGetAll(params int[] ids)
-        {
-            if (ids.Any())
-            {
-                foreach (var id in ids)
-                {
-                    yield return Get(id);
-                }
-            }
-            else
-            {
-                var dtos = Database.Fetch<RelationDto>("WHERE id > 0");
-                foreach (var dto in dtos)
-                {
-                    yield return Get(dto.Id);
-                }
-            }
-        }
-
-        protected override IEnumerable<IRelation> PerformGetByQuery(IQuery<IRelation> query)
-        {
-            var sqlClause = GetBaseQuery(false);
-            var translator = new SqlTranslator<IRelation>(sqlClause, query);
-            var sql = translator.Translate();
-
-            var dtos = Database.Fetch<RelationDto>(sql);
-
-            foreach (var dto in dtos)
-            {
-                yield return Get(dto.Id);
-            }
         }

         #endregion


notes

notes

--- src/Umbraco.Web.Website/Routing/UmbracoRouteValueTransformer.cs
+++ src/Umbraco.Web.Website/Routing/UmbracoRouteValueTransformer.cs
@@ -122,7 +122,6 @@
             httpContext.Features.Set(umbracoRouteValues);

             // publish an event that we've routed a request
-            // TODO: does this occur on 404 or have we already returned?
             await _eventAggregator.PublishAsync(new UmbracoRoutedRequest(_umbracoContextAccessor.UmbracoContext));

             // Need to check if there is form data being posted back to an Umbraco URL


Fixing focus typo

Fixing focus typo

--- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/TreeControl.cs
+++ src/UnityExtension/Assets/Editor/GitHub.Unity/UI/TreeControl.cs
@@ -210,9 +210,10 @@
             {
                 int directionY = Event.current.keyCode == KeyCode.UpArrow ? -1 : Event.current.keyCode == KeyCode.DownArrow ? 1 : 0;
                 int directionX = Event.current.keyCode == KeyCode.LeftArrow ? -1 : Event.current.keyCode == KeyCode.RightArrow ? 1 : 0;
+
                 if (directionY != 0 || directionX != 0)
                 {
-                    if (directionY < 0 || directionY < 0)
+                    if (directionY < 0 || directionX < 0)
                     {
                         SelectedNode = nodes[nodes.Count - 1];
                         selectionChanged = true;


Initial functionality to select file nodes

# Conflicts:
#	src/UnityExtension/Assets/Editor/GitHub.Unity/UI/TreeControl.cs

--- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/TreeControl.cs
+++ src/UnityExtension/Assets/Editor/GitHub.Unity/UI/TreeControl.cs
@@ -160,11 +160,15 @@
             if (DisplayRootNode)
             {
                 var titleNode = nodes[0];
-                var selectionChanged = titleNode.Render(rect, Styles.TreeIndentation, selectedNode == titleNode, FolderStyle, TreeNodeStyle, ActiveTreeNodeStyle);
-
-                if (selectionChanged)
+                var renderResult = titleNode.Render(rect, Styles.TreeIndentation, selectedNode == titleNode, FolderStyle, TreeNodeStyle, ActiveTreeNodeStyle);
+
+                if (renderResult == TreeNodeRenderResult.VisibilityChange)
                 {
                     ToggleNodeVisibility(0, titleNode);
+                }
+                else if (renderResult == TreeNodeRenderResult.SelectionChange)
+                {
+                    ToggleNodeSelection(0, titleNode);
                 }

                 RequiresRepaint = HandleInput(rect, titleNode, 0);
@@ -182,12 +186,15 @@
                 {
                     Indent();
                 }
-                var changed = node.Render(rect, Styles.TreeIndentation, selectedNode == node, FolderStyle, TreeNodeStyle, ActiveTreeNodeStyle);
-
-                if (node.IsFolder && changed)
-                {
-                    // toggle visibility for all the nodes under this one
+                var renderResult = node.Render(rect, Styles.TreeIndentation, selectedNode == node, FolderStyle, TreeNodeStyle, ActiveTreeNodeStyle);
+
+                if (renderResult == TreeNodeRenderResult.VisibilityChange)
+                {
                     ToggleNodeVisibility(i, node);
+                }
+                else if (renderResult == TreeNodeRenderResult.SelectionChange)
+                {
+                    ToggleNodeSelection(i, node);
                 }

                 if (node.Level < level)
@@ -241,7 +248,28 @@
             RequiresRepaint = true;
         }

-        private int ToggleNodeVisibility(int idx, TreeNode rootNode)
+        private void ToggleNodeSelection(int idx, TreeNode node)
+        {
+            if (node.IsFolder)
+            {
+
+            }
+            else
+            {
+                switch (node.SelectionState)
+                {
+                    case SelectionState.Unselected:
+                        node.SelectionState = SelectionState.Selected;
+                        break;
+
+                    case SelectionState.Selected:
+                        node.SelectionState = SelectionState.Unselected;
+                        break;
+                }
+            }
+        }
+
+        private void ToggleNodeVisibility(int idx, TreeNode node)
         {
             var nodeLevel = node.Level;
             node.IsCollapsed = !node.IsCollapsed;
@@ -260,7 +288,6 @@
             {
                 SelectedNode = node;
             }
-            return idx;
         }

         private bool HandleInput(Rect rect, TreeNode currentNode, int index, Action<TreeNode> singleClick = null, Action<TreeNode> doubleClick = null, Action<TreeNode> rightClick = null)
@@ -417,20 +444,23 @@
         public bool IsHidden;
         public bool IsActive;
         public GUIContent content;
+        public bool Selectable;
+        public SelectionState SelectionState;
+
         [NonSerialized] public Texture2D Icon;
-        public bool Selectable;

         public void Load()
         {
             content = new GUIContent(Label, Icon);
         }

-        public bool Render(Rect rect, float indentation, bool isSelected, GUIStyle toggleStyle, GUIStyle nodeStyle, GUIStyle activeNodeStyle)
-        {
+        public TreeNodeRenderResult Render(Rect rect, float indentation, bool isSelected, GUIStyle toggleStyle, GUIStyle nodeStyle, GUIStyle activeNodeStyle)
+        {
+            var renderResult = TreeNodeRenderResult.None;
+
             if (IsHidden)
-                return false;
-
-            var changed = false;
+                return renderResult;
+
             var fillRect = rect;
             var nodeStartX = Level * indentation * (Selectable ? 2 : 1);

@@ -468,7 +498,10 @@
                 {
                     GUI.Toggle(toggleRect, !IsCollapsed, GUIContent.none, GUIStyle.none);
                 }
-                changed = EditorGUI.EndChangeCheck();
+                if (EditorGUI.EndChangeCheck())
+                {
+                    renderResult = TreeNodeRenderResult.VisibilityChange;
+                }
             }

             if (Selectable)
@@ -479,11 +512,26 @@

                 nodeStartX += selectRect.width + 2;

+                var selectionStyle = GUI.skin.toggle;
+                var selectionValue = false;
+
+                if (SelectionState == SelectionState.Selected)
+                {
+                    selectionValue = true;
+                }
+                else if (SelectionState == SelectionState.Mixed)
+                {
+                    selectionStyle = Styles.ToggleMixedStyle;
+                }
+
                 EditorGUI.BeginChangeCheck();
                 {
-                    GUI.Toggle(selectRect, false, GUIContent.none, Styles.ToggleMixedStyle);
-                }
-                EditorGUI.EndChangeCheck();
+                    GUI.Toggle(selectRect, selectionValue, GUIContent.none, selectionStyle);
+                }
+                if (EditorGUI.EndChangeCheck())
+                {
+                    renderResult = TreeNodeRenderResult.SelectionChange;
+                }
             }

             data += string.Format("ContentStart: {0} ", nodeStartX);
@@ -497,7 +545,7 @@

             Debug.Log(data);

-            return changed;
+            return renderResult;
         }

         public override string ToString()
@@ -552,4 +600,18 @@
             }
         }
     }
+
+    public enum TreeNodeRenderResult
+    {
+        None,
+        VisibilityChange,
+        SelectionChange
+    }
+
+    public enum SelectionState
+    {
+        Unselected,
+        Selected,
+        Mixed
+    }
 }


Restore MultiAdd helper to fix build break

--- src/Workspaces/Core/Portable/Utilities/IDictionaryExtensions.cs
+++ src/Workspaces/Core/Portable/Utilities/IDictionaryExtensions.cs
@@ -29,5 +29,17 @@

             return default;
         }
+
+        public static void MultiAdd<TKey, TValue, TCollection>(this IDictionary<TKey, TCollection> dictionary, TKey key, TValue value)
+            where TCollection : ICollection<TValue>, new()
+        {
+            if (!dictionary.TryGetValue(key, out var collection))
+            {
+                collection = new TCollection();
+                dictionary.Add(key, collection);
+            }
+
+            collection.Add(value);
+        }
     }
 }


Added arff parsing

Added arff parsing

--- EmotionalGUI/Classifier/Classifier.cs
+++ EmotionalGUI/Classifier/Classifier.cs
@@ -10,14 +10,20 @@
 {
     public class Classifier
     {
+
         class SongData
         {
-            string filename;
-            List<Double> features;
+            string filename = "";
+            List<List<Double>> features =  new List<List<Double>>();

-            public SongData()
+            public void AddFeatureList(List<Double> feature_list)
             {
-                features = new List<Double>();
+                features.Add(feature_list);
+            }
+
+            public void SetFilename(string in_filename)
+            {
+                filename = in_filename;
             }
         }

@@ -38,7 +44,7 @@
             WINDOW_FS = (2 ^ 21).ToString();
         }

-        public void classifySongs(string[] in_songs, ref double[] out_pos, ref double[] out_energy)
+        public string classifySongs(string[] in_songs)
         {

             //Create temporary directory
@@ -61,12 +67,15 @@
             parseArff(TEMP_DIRECTORY + Path.PathSeparator + "MARSYAS_EMPTY");

-            return;
+            return "";
         }

         protected string[] ffmpegConversion(string[] files)
         {
-            string[] tempfiles = new string[files.Length];
+            //bextract requires .wav files, but user will give .mp3 files.
+            //ffmpeg will make temporary .wav files.
+            string[] tempfiles = new string[files.Length];
+
             int i = 0;
             foreach (string file in files)
             {
@@ -96,7 +105,7 @@

         protected void runBextract(string mkcollection)
         {
-            string bextractArgs = BEXTRACT_FILENAME + "-fe -n -ws" + WINDOW_FS + "-od" + TEMP_DIRECTORY + Path.PathSeparator + mkcollection;
+            string bextractArgs = BEXTRACT_FILENAME + "-fe -n -ws " + WINDOW_FS + " -hp " + WINDOW_FS + "-od " + TEMP_DIRECTORY + Path.PathSeparator + mkcollection;
             System.Diagnostics.Process bextract = new System.Diagnostics.Process();
             bextract.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
             bextract.StartInfo.UseShellExecute = false;
@@ -114,11 +123,37 @@
             //One array for each song
             List<SongData> songData = new List<SongData>();

+            string arff = File.ReadAllText(arffFile);
+            string[] tokens = arff.Split(new[] { "% filename " }, StringSplitOptions.None);

+            //Go through each of the songs (skip the first token, that has the bextract attribute comments)
+            foreach(string token in tokens)
+            {
+                SongData sdata = new SongData();

+                string[] lines = token.Split('\n');
+                string filename = lines[0].Trim('\n');
+                sdata.SetFilename(filename);
+
+                //Line two is the sampling rate, which we do not use

+                //Go through each of the lines of the bextract features
+                foreach(string feature_line in lines)
+                {
+                    string[] feature_strs = feature_line.Split(',');
+                    List<Double> features = new List<Double>();

+                    //Convert each feature into a double, add to the double array
+                    foreach(string feature_str in feature_strs)
+                    {
+                        Double feature = Double.Parse(feature_str);
+                        features.Add(feature);
+                    }

+                    sdata.AddFeatureList(features);
+
+                }
+            }

         }


Improve brokerage connection error message

--- Engine/Setup/BrokerageSetupHandler.cs
+++ Engine/Setup/BrokerageSetupHandler.cs
@@ -230,7 +230,8 @@
                 catch (Exception err)
                 {
                     Log.Error(err);
-                    AddInitializationError("Error connecting to brokerage: " + err.Message);
+                    AddInitializationError(string.Format("Error connecting to brokerage: {0}. " +
+                        "This may be caused by incorrect login credentials or an unsupported account type.", err.Message));
                     return false;
                 }


Fixed a bug, that caused the LocalSongFinder to end it's work prematurely.

This was caused by a race condition where the tag processor thought that the file searcher finished it's work.

--- Espera/Espera.Core/LocalSongFinder.cs
+++ Espera/Espera.Core/LocalSongFinder.cs
@@ -116,6 +116,9 @@
         public void Start()
         {
             var fileScanTask = Task.Factory.StartNew(this.StartFileScan);
+
+            this.isSearching = true;
+
             var tagScanTask = Task.Factory.StartNew(this.StartTagScan);

             Task.WaitAll(fileScanTask, tagScanTask);
@@ -125,7 +128,6 @@

         private void StartFileScan()
         {
-            this.isSearching = true;
             this.scanner.Start();
             this.isSearching = false;
         }


added method for xml element to get summary

--- src/bgTeam.Extensions/DocumenationExtensions.cs
+++ src/bgTeam.Extensions/DocumenationExtensions.cs
@@ -30,13 +30,7 @@
         public static string GetSummary(this Type type)
         {
             var element = type.GetDocumentation();
-            var summary = element?.SelectSingleNode("summary");
-            if (summary == null)
-            {
-                return string.Empty;
-            }
-
-            return summary.InnerText.Trim();
+            return element.GetSummary();
         }

         /// <summary>
@@ -47,13 +41,7 @@
         public static string GetSummary(this MethodInfo methodInfo)
         {
             var element = methodInfo.GetDocumentation();
-            var summary = element?.SelectSingleNode("summary");
-            if (summary == null)
-            {
-                return string.Empty;
-            }
-
-            return summary.InnerText.Trim();
+            return element.GetSummary();
         }

         /// <summary>
@@ -64,6 +52,16 @@
         public static string GetSummary(this MemberInfo memberInfo)
         {
             var element = memberInfo.GetDocumentation();
+            return element.GetSummary();
+        }
+
+        /// <summary>
+        /// Find summary node and return inner text from this XmlElement
+        /// </summary>
+        /// <param name="element"></param>
+        /// <returns></returns>
+        public static string GetSummary(this XmlElement element)
+        {
             var summary = element?.SelectSingleNode("summary");
             if (summary == null)
             {


rename controller to commit

rename controller to commit

--- RepoStats/Startup.cs
+++ RepoStats/Startup.cs
@@ -34,9 +34,9 @@
             });

             HttpConfiguration config = new HttpConfiguration();
-            config.Routes.MapHttpRoute("Default", "{controller}/{checkinID}", new { controller = "Checkin", checkinID = RouteParameter.Optional });
-            config.Routes.MapHttpRoute("Default3", "{controller}/route/{arg}", new { controller = "Checkin", checkinID = RouteParameter.Optional });
-            config.Routes.MapHttpRoute("Default2", "{controller}/{checkinID}", new { controller = "Razor", checkinID = RouteParameter.Optional });
+            //config.Routes.MapHttpRoute("Default", "{controller}/{checkinID}", new { controller = "Checkin", checkinID = RouteParameter.Optional });
+            //config.Routes.MapHttpRoute("Default3", "{controller}/route/{arg}", new { controller = "Checkin", checkinID = RouteParameter.Optional });
+            config.Routes.MapHttpRoute("Default", "{controller}/{commitID}", new { controller = "Commit", commitID = RouteParameter.Optional });

             //config.Formatters.XmlFormatter.UseXmlSerializer = true;
             //config.Formatters.Remove(config.Formatters.JsonFormatter);
@@ -92,13 +92,13 @@
         }
     }

-    public class RazorController : ApiController
+    public class CommitController : ApiController
     {
         [HttpGet]
-        public HttpResponseMessage Get(string checkinId)
+        public HttpResponseMessage Get(string commitID)
         {
             string template = File.ReadAllText("views\\commit.cshtml");
-            string result = Engine.Razor.RunCompile(template, "templateName", null, CheckinController.GetCheckinDetails(checkinId));
+            string result = Engine.Razor.RunCompile(template, "templateName", null, CheckinController.GetCheckinDetails(commitID));
             return new HttpResponseMessage()
             {
                 Content = new StringContent(result, System.Text.Encoding.UTF8, "text/html"),


using named arguments to get rid of all the Type.Missing

git-svn-id: 5efc153a00cf115a12203e6f97f1439710c086e6@10 6814d51f-e170-1194-e9fb-5f60540ed962

--- Resx2Xls/ResxData.cs
+++ Resx2Xls/ResxData.cs
@@ -203,7 +203,7 @@
             foreach (var filesource in filesourcesdict.OrderBy(kvp => kvp.Key))
             {
                 // add sheet
-                var sheet = sheets.Add(sheets[sheetIndex], Type.Missing, Type.Missing, Type.Missing) as Excel.Worksheet;
+                var sheet = sheets.Add(Before: sheets[sheetIndex]) as Excel.Worksheet;
                 sheet.Name = filesource.Key;
                 sheetIndex++;
                 Trace.WriteLine("Created sheet " + filesource.Key);
@@ -226,12 +226,12 @@
                 }

                 // make header bold and metadata italic
-                var metadatarow = sheet.Rows[ExcelMetadataRow, Type.Missing] as Excel.Range;
+                var metadatarow = sheet.Rows[RowIndex: ExcelMetadataRow] as Excel.Range;
                 metadatarow.Font.Italic = true;
                 metadatarow.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White);
                 metadatarow.Locked = true;
                 metadatarow.Hidden = true;
-                var headerrow = sheet.Rows[ExcelHeaderRow, Type.Missing] as Excel.Range;
+                var headerrow = sheet.Rows[RowIndex: ExcelHeaderRow] as Excel.Range;
                 headerrow.Font.Bold = true;
                 headerrow.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White);
                 headerrow.Locked = true;
@@ -308,13 +308,13 @@
                 }

                 // Set width of value column
-                var valuecolumn = sheet.Columns.get_Item(ExcelValueColumn, Type.Missing) as Excel.Range;
+                var valuecolumn = sheet.Columns.get_Item(ExcelValueColumn) as Excel.Range;
                 valuecolumn.ColumnWidth = 80;

                 // Set width of translated columns
                 for (int i = 0; i < cultures.Count; i++)
                 {
-                    var column = sheet.Columns.get_Item(i + ExcelCultureColumn, Type.Missing) as Excel.Range;
+                    var column = sheet.Columns.get_Item(i + ExcelCultureColumn) as Excel.Range;
                     column.ColumnWidth = 60;
                     Marshal.ReleaseComObject(column);
                 }
@@ -322,7 +322,7 @@
                 // hide key column
                 if (Properties.Settings.Default.HideKeys)
                 {
-                    var column = sheet.Columns.get_Item(ExcelKeyColumn, Type.Missing) as Excel.Range;
+                    var column = sheet.Columns.get_Item(ExcelKeyColumn) as Excel.Range;
                     column.Hidden = true;
                     Marshal.ReleaseComObject(column);
                 }
@@ -330,15 +330,13 @@
                 // hide comment column
                 if (Properties.Settings.Default.HideComments)
                 {
-                    var column = sheet.Columns.get_Item(ExcelCommentColumn, Type.Missing) as Excel.Range;
+                    var column = sheet.Columns.get_Item(ExcelCommentColumn) as Excel.Range;
                     //column.Hidden = true;
                     column.ColumnWidth = 0;
                     Marshal.ReleaseComObject(column);
                 }

-                sheet.Protect("", Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, true,
-                    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
-                    Type.Missing, Type.Missing);
+                sheet.Protect(Password: "", Contents: true, AllowFormattingColumns: true);

                 Marshal.ReleaseComObject(metadatarow);
                 Marshal.ReleaseComObject(headerrow);
@@ -353,19 +351,7 @@
             // Save the Workbook and force overwriting by rename trick
             string tmpFile = Path.GetTempFileName();
             File.Delete(tmpFile);
-            wb.SaveAs(
-                tmpFile,
-                Type.Missing,
-                Type.Missing,
-                Type.Missing,
-                Type.Missing,
-                Type.Missing,
-                Excel.XlSaveAsAccessMode.xlNoChange,
-                Type.Missing,
-                Type.Missing,
-                Type.Missing,
-                Type.Missing,
-                Type.Missing);
+            wb.SaveAs(Filename: tmpFile, AccessMode: Excel.XlSaveAsAccessMode.xlNoChange);
             File.Delete(outputPath);

             ExcelQuit(app, wb);
@@ -430,7 +416,7 @@
         /// <param name="wb">Excel workbook to close</param>
         private static void ExcelQuit(Excel.Application app, Excel.Workbook wb)
         {
-            wb.Close(false, Type.Missing, Type.Missing);
+            wb.Close(SaveChanges: false);
             app.Quit();
             while (Marshal.ReleaseComObject(app) != 0)
             {


PushTest

PushTest

--- Execute/Assets/Scripts/GameManager.cs
+++ Execute/Assets/Scripts/GameManager.cs
@@ -39,7 +39,7 @@
 	// Initialisation d'une partie de jeu
 	void InitGame(){
 		// Assignation des joueurs et manettes
-		for (int j = 0; j < 1; j++) {
+		for (int j = 0; j < 4; j++) {
 			joypads[j] = new Joypad();
 			players[j] = new Player(j, joypads[j]);
 		}


fix win+r issue.

fix win+r issue.

--- WinAlfred/MainWindow.xaml.cs
+++ WinAlfred/MainWindow.xaml.cs
@@ -231,6 +231,7 @@
         {
             if (Settings.Instance.ReplaceWinR)
             {
+                //todo:need refatoring. move those codes to CMD file or expose events
                 if (keyevent == KeyEvent.WM_KEYDOWN && vkcode == (int)Keys.R && state.WinPressed)
                 {
                     WinRStroked = true;
@@ -255,6 +256,7 @@
                 resultCtrl.Clear();
                 ChangeQuery(">");
             }
+            tbQuery.CaretIndex = tbQuery.Text.Length;
         }

         private void TbQuery_OnPreviewKeyDown(object sender, KeyEventArgs e)


Fix cache find by name throwing exception

--- Winston/Cache/SqliteCache.cs
+++ Winston/Cache/SqliteCache.cs
@@ -100,11 +100,11 @@
                             new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
                         var result = DB.Execute(
                             @"insert or replace into Packages (Name, Description, PackageData) values (@Name, @Desc, @Data)",
-                            new {Name = pkg.Name, Desc = pkg.Description, Data = json},
+                            new { Name = pkg.Name, Desc = pkg.Description, Data = json },
                             transaction: t);
                         result = DB.Execute(
                             @"insert or replace into PackageSearch (Name, Desc) values (@Name, @Desc)",
-                            new {Name = pkg.Name, Desc = pkg.Description},
+                            new { Name = pkg.Name, Desc = pkg.Description },
                             transaction: t);
                     }
                     t.Commit();
@@ -129,27 +129,44 @@
         public async Task<Package> ByName(string pkgName)
         {
             var result = await DB.QueryAsync<string>("select PackageData from Packages where Name = @Name", new { Name = pkgName });
-            var json = result.Single();
+            var json = result.SingleOrDefault();
+            if (json == null) return null;
             var pkg = JsonConvert.DeserializeObject<Package>(json);
             return pkg;
         }

         public async Task<IList<Package>> ByNames(IEnumerable<string> names)
         {
-            return await Task.WhenAll(names.Select(ByName));
+            // SQLite is going to end up executing these all in serial anyway,
+            // little point in making this code parallel.
+            var result = new List<Package>();
+            foreach (var name in names)
+            {
+                var match = await ByName(name);
+                if (match != null)
+                {
+                    result.Add(match);
+                }
+            }
+            return result;
         }

         public async Task<IList<Package>> Search(string query)
         {
-            var nameMatches = await DB.QueryAsync<string>("select distinct Name from PackageSearch where Name match @query", new {query});
-            var descMatches = await DB.QueryAsync<string>("select distinct Name from PackageSearch where Desc match @query", new {query});
+            var nameMatches = await DB.QueryAsync<string>("select distinct Name from PackageSearch where Name match @query", new { query });
+            var descMatches = await DB.QueryAsync<string>("select distinct Name from PackageSearch where Desc match @query", new { query });
             var names = nameMatches.Union(descMatches).Distinct();
             var result = new List<Package>();
             foreach (var name in names)
             {
-                var json = await DB.QueryAsync<string>("select PackageData from Packages where Name = @name", new {name});
-                var pkg = JsonConvert.DeserializeObject<Package>(json.Single());
-                result.Add(pkg);
+                var json =
+                    await DB.QueryAsync<string>("select PackageData from Packages where Name = @name", new { name });
+                var single = json.SingleOrDefault();
+                if (single != null)
+                {
+                    var pkg = JsonConvert.DeserializeObject<Package>(single);
+                    result.Add(pkg);
+                }
             }

             return result;


A small fix submited by W6MKU

A small fix submited by W6MKU

git-svn-id: 6b7e1e5d0861e268462ba7828ef63c1bcab52a9b@445 d3cde5d6-82b8-4669-8b62-43054d6781d8

--- SDRSharp/MainForm.cs
+++ SDRSharp/MainForm.cs
@@ -793,7 +793,7 @@

         private void filterTypeComboBox_SelectedIndexChanged(object sender, EventArgs e)
         {
-            _vfo.WindowType = (WindowType) (filterTypeComboBox.SelectedIndex - 1);
+            _vfo.WindowType = (WindowType) (filterTypeComboBox.SelectedIndex + 1);
         }

         private void autoCorrectIQCheckBox_CheckedChanged(object sender, EventArgs e)


Deadlock comes as an edge case from ContinueWith, await and TaskComplitionSource

--- src/core/Akka/Actor/Futures.cs
+++ src/core/Akka/Actor/Futures.cs
@@ -100,13 +100,13 @@
         /// This exception is thrown if the system can't resolve the target provider.
         /// </exception>
         /// <returns>TBD</returns>
-        public static Task<T> Ask<T>(this ICanTell self, object message, TimeSpan? timeout, CancellationToken cancellationToken)
+        public static async Task<T> Ask<T>(this ICanTell self, object message, TimeSpan? timeout, CancellationToken cancellationToken)
         {
             IActorRefProvider provider = ResolveProvider(self);
             if (provider == null)
                 throw new ArgumentException("Unable to resolve the target Provider", nameof(self));

-            return Ask(self, message, provider, timeout, cancellationToken).CastTask<object, T>();
+            return (T) await Ask(self, message, provider, timeout, cancellationToken).ConfigureAwait(false);
         }

         /// <summary>


Fix the cursor not resetting the cell effect when you type

--- SadConsole/Cursor.cs
+++ SadConsole/Cursor.cs
@@ -776,6 +776,9 @@
                 }
             }

+            if (didSomething)
+                ResetCursorEffect();
+
             return didSomething;
         }
     }


renaming monster spawn method for better readability

--- YoloCrawler/Entities/Room.cs
+++ YoloCrawler/Entities/Room.cs
@@ -123,26 +123,23 @@
                 do
                 {
                     randomPosition = _dice.RollPosition(Size.Width, Size.Height);
-                } while (!PositionFreeForMonster(randomPosition));
+                } while (!MonsterCanSpawnOn(randomPosition));

                 Monsters.Add(MonsterFactory.CreateRandomMonster(randomPosition));
             });
         }

-        private bool PositionFreeForMonster(Position position)
+        private bool MonsterCanSpawnOn(Position position)
         {
             var monstersOnPosition = Monsters.Any(monster => monster.Position.Equals(position));
             var nearDoor = false;

             foreach (var tile in Tiles)
             {
-                if (tile.HasDoor)
+                if (tile.HasDoor && tile.CloseTo(position))
                 {
-                    if (tile.CloseTo(position))
-                    {
-                        nearDoor = true;
-                        break;
-                    }
+                    nearDoor = true;
+                    break;
                 }
             }


UnitTesting mocking.

UnitTesting mocking.

--- UnitTesting/Lab/Skeleton.Test/HeroTests.cs
+++ UnitTesting/Lab/Skeleton.Test/HeroTests.cs
@@ -23,25 +23,27 @@

         }

-        //[Test]
-        //public void MockingTest()
-        //{
-        //    //Arange
-        //    var weapon = new Mock<IWeapon>();
-        //    weapon
-        //        .Setup(w => w.Attack(It.IsAny<ITarget>()))
-        //        .Callback(() => weapon.Object.DurabilityPoints -= 1);
-        //    //weapon.Setup(w => w.AttackPoints == 10);
-        //    //weapon.Setup(w => w.DurabilityPoints == 3);
+        [Test]
+        public void MockingTest()
+        {
+            //Arange
+            var weapon = new Mock<IWeapon>();
+            //weapon
+            //    .Setup(w => w.Attack(It.IsAny<ITarget>()))
+            //    .Callback(() => weapon.Object.DurabilityPoints -= 1);
+            //weapon.Setup(w => w.AttackPoints == 10);
+            //weapon.Setup(w => w.DurabilityPoints == 3);

-        //    var systemUnderTest = new Hero("John", weapon.Object);
-        //    var target = new Dummy(10, 5);
+            var systemUnderTest = new Hero("John", weapon.Object);
+            var target = new Mock<ITarget>();
+            target.Setup(t => t.IsDead()).Returns(true);
+            target.Setup(t => t.GiveExperience()).Returns(5);

-        //    //Act
-        //    systemUnderTest.Attack(target);
+            //Act
+            systemUnderTest.Attack(target.Object);

-        //    //Assert
-        //    Assert.AreEqual(5, systemUnderTest.Experience);
-        //}
+            //Assert
+            Assert.AreEqual(5, systemUnderTest.Experience);
+        }
     }
 }


STMReceiver code refactoring

STMReceiver code refactoring

--- UnityProject/Assets/Scripts/STMReceiver.cs
+++ UnityProject/Assets/Scripts/STMReceiver.cs
@@ -54,23 +54,14 @@

 	private void InternalStartListening()
-	{
-            int command;
-            Int16 axisX, axisY, axisZ, max;
-            byte crc;
-            byte[] buffer = new byte[2];
-
+	{
            // command = Port.ReadByte();
-
-
-
-
 		while (_keepListenieng)
 		{
 			Port.BaseStream.Flush();
 			//Data = Port.ReadByte();
-            command = Port.ReadByte();
-
+            int command = Port.ReadByte();
+            byte[] buffer = new byte[2];
             if (command == 0xAA)
             {

@@ -78,25 +69,25 @@

                 buffer[0] = (byte)Port.ReadByte();
                 buffer[1] = (byte)Port.ReadByte();
-                axisX = BitConverter.ToInt16(buffer, 0);
+                Int16 axisX = BitConverter.ToInt16(buffer, 0);
                 Debug.Log("X axis: " + axisX + "\n");

                 buffer[0] = (byte)Port.ReadByte();
                 buffer[1] = (byte)Port.ReadByte();
-                Data = BitConverter.ToInt16(buffer, 0);
+                Int16 Data = BitConverter.ToInt16(buffer, 0);
                 Debug.Log("Y axis: " + Data + "\n");

                 buffer[0] = (byte)Port.ReadByte();
                 buffer[1] = (byte)Port.ReadByte();
-                axisZ = BitConverter.ToInt16(buffer, 0);
+                Int16 axisZ = BitConverter.ToInt16(buffer, 0);
                 Debug.Log("Z axis: " + axisZ + "\n");

                 buffer[0] = (byte)Port.ReadByte();
                 buffer[1] = (byte)Port.ReadByte();
-                max = BitConverter.ToInt16(buffer, 0);
+                Int16 max = BitConverter.ToInt16(buffer, 0);
                 Debug.Log("Accelerometer max: " + max + "\n");

-                crc = (byte)Port.ReadByte();
+                byte crc = (byte)Port.ReadByte();
                 Debug.Log("CRC: " + crc + "\n\n");

 			}


EqualityComparer<T>.Default is not needed, since it just calls one of the Equals() implementations we're already testing.

--- ValueTypeAssertions/ValueTypeAssertions.cs
+++ ValueTypeAssertions/ValueTypeAssertions.cs
@@ -27,9 +27,6 @@
 			((Action)(() => item.Equals(new object()))).ShouldNotThrow<InvalidCastException>("compare to other type");
 			item.Equals(new object()).Should().BeFalse("compare to other type");

-
-			EqualityComparer<T>.Default.Equals(item, equalItem).Should().BeTrue("EqualityComparer<>");
-
 			((object) item).Equals(equalItem).Should().BeTrue("object.Equals()");

 			item.GetHashCode().Should().Be(equalItem.GetHashCode(), "GetHashCode()");
@@ -50,8 +47,6 @@

 			((object) item).Equals(differentItem).Should().BeFalse("object.Equals()");

-			EqualityComparer<T>.Default.Equals(item, differentItem).Should().BeFalse("EqualityComparer<>");
-
 			if (item.ToString() != item.GetType().FullName) { item.ToString().Should().NotBe(differentItem.ToString(), "ToString()"); }

 			// Two unequal objects do not necessarily need to have differnet hash codes, but in practice


Fix message on non existing include path when running with /diagnostics, it's a warning not an error.

--- Sharpmake/Project.cs
+++ Sharpmake/Project.cs
@@ -1519,7 +1519,7 @@
                         {
                             if (!folder.StartsWith("$") && !includePathsExcludeFromWarningRegex.Any(regex => regex.Match(folder).Success) && !Directory.Exists(folder))
                             {
-                                ReportError($@"{conf.Project.SharpmakeCsFileName}: Error: Folder contained in include paths doesn't exist: {folder}.", true);
+                                ReportError($@"{conf.Project.SharpmakeCsFileName}: Warning: Folder contained in include paths doesn't exist: {folder}.", true);
                             }
                         }
                     }


Clean up using directives

Clean up using directives

--- WCF/Shared/ClientIpTelemetryInitializer.cs
+++ WCF/Shared/ClientIpTelemetryInitializer.cs
@@ -1,6 +1,4 @@
 using System;
-using System.Collections.Generic;
-using System.Text;
 using Microsoft.ApplicationInsights.Channel;
 using Microsoft.ApplicationInsights.Extensibility.Implementation;
 using System.ServiceModel.Channels;


[Changed] Override behavior

[Changed] Override behavior

Now optional to override keys with same authority name. If `-o` flag is
not set and keys already exist then use those to sign. If `-o` is set
then the keys are always overridden.

--- SignForge/Program.cs
+++ SignForge/Program.cs
@@ -30,6 +30,7 @@
                                     "\r\n" +
                                     "help - (OPTIONAL) display the help information\r\n" +
                                     "-r - (OPTIONAL) remove all old .bisign files from source folder\r\n" +
+                                    "-o - (OPTIONAL) override .bikey and .biprivatekey if they exist in the destination folder\r\n" +
                                     "-v - (OPTIONAL) verify all files\r\n" +
                                     "-s *source* - folder where the pbos that need to be signed reside\r\n" +
                                     "-a *name* - (OPTIONAL) authority name. If argument not provided then prompt\r\n" +
@@ -56,6 +57,10 @@
                 var verify = args.Contains("-v");
                 Console.WriteLine("Verify flag set to: {0}", verify);

+                // -o - (OPTIONAL) override keys
+                var over = args.Contains("-o");
+                Console.WriteLine("Override flag set to: {0}", over);
+
                 // -s - folder where the pbos that need to be signed reside
                 string sourcePath;

@@ -82,7 +87,6 @@
                 Console.WriteLine("Authority set to: {0}", authorityName);

                 // -d - (OPTIONAL) folder to put private and public keys into
-
                 string destinationPath = !args.Contains("-d") ? sourcePath : args[args.ToList().FindIndex(x => x == "-d") + 1];

                 Console.WriteLine("Source path set to: {0}", destinationPath);
@@ -97,7 +101,7 @@
                 string privateKey;

                 // create the signatures
-                CreateSignatureFiles(authorityName, destinationPath, out privateKey);
+                CreateSignatureFiles(authorityName, destinationPath, over, out privateKey);

                 // clean up if the flag is set
                 RemoveOldSignatures(remove, sourcePath);
@@ -238,10 +242,46 @@
         /// </summary>
         /// <param name="authorityName">Name of the authority.</param>
         /// <param name="destinationPath">The destination path.</param>
+        /// <param name="over">Override the files if keys for same authority exist</param>
         /// <param name="destPrivateFileName">The private key file location</param>
         /// <exception cref="System.ApplicationException"></exception>
-        private static void CreateSignatureFiles(string authorityName, string destinationPath, out string destPrivateFileName)
-        {
+        private static void CreateSignatureFiles(string authorityName, string destinationPath, bool over,out string destPrivateFileName)
+        {
+            var pubKeyFilename = string.Format("{0}.bikey", authorityName);
+            var prvKeyFilename = string.Format("{0}.biprivatekey", authorityName);
+#if WINE
+            Thread.Sleep(2000); // give time for the files to appear
+            var publicKey = string.Format("{1}/{0}", pubKeyFilename, AssemblyDirectory);
+            var privateKey = string.Format("{1}/{0}", prvKeyFilename, AssemblyDirectory);
+            var destPublicFileName = string.Format("{0}/{1}", destinationPath, pubKeyFilename);
+            destPrivateFileName = privateKey;
+
+#else
+            var publicKey = string.Format("{0}.bikey", authorityName);
+            var privateKey = string.Format("{0}.biprivatekey", authorityName);
+            var destPublicFileName = string.Format("{0}\\{1}", destinationPath, publicKey);
+            destPrivateFileName = privateKey;
+#endif
+
+            // if override is not set and keys all exist
+            if (!over && File.Exists(privateKey) && File.Exists(destPublicFileName))
+            {
+                Console.WriteLine("Override not set and all files were found. Skipping creation of new keys...");
+                return;
+            }
+
+            // if no override flag set but keys dont exixt then make them
+            if (!over && (!File.Exists(privateKey) || !File.Exists(destPublicFileName)))
+            {
+                Console.WriteLine("Override was set but either one or all of the keys were not found. Proceeding to generate new ones...");
+            }
+
+            // if override set make keys anyway
+            if (over)
+            {
+                Console.WriteLine("Override enabled. Proceeding to geenrate new keys...");
+            }
+
             // create signature
             var startInfo = new ProcessStartInfo();
             startInfo.CreateNoWindow = true;
@@ -268,21 +308,7 @@
                 throw new ApplicationException(string.Format("Creation of key files aborted: {0}", ex.Message));
             }

-            var pubKeyFilename = string.Format("{0}.bikey", authorityName);
-            var prvKeyFilename = string.Format("{0}.biprivatekey", authorityName);
-#if WINE
-            Thread.Sleep(2000); // give time for the files to appear
-            var publicKey = string.Format("{1}/{0}", pubKeyFilename, AssemblyDirectory);
-            var privateKey = string.Format("{1}/{0}", prvKeyFilename, AssemblyDirectory);
-            var destPublicFileName = string.Format("{0}/{1}", destinationPath, pubKeyFilename);
-            destPrivateFileName = privateKey;
-
-#else
-            var publicKey = string.Format("{0}.bikey", authorityName);
-            var privateKey = string.Format("{0}.biprivatekey", authorityName);
-            var destPublicFileName = string.Format("{0}\\{1}", destinationPath, publicKey);
-            destPrivateFileName = privateKey;
-#endif
+

             if (File.Exists(publicKey))
@@ -296,8 +322,6 @@
             {
                 throw new ApplicationException("Cannot find the generated public key file: " + publicKey);
             }
-
-

             if (!File.Exists(privateKey))
             {


replace the string conversation

replace the string conversation

--- WalletWasabi.Gui/Validation/Validations.cs
+++ WalletWasabi.Gui/Validation/Validations.cs
@@ -88,6 +88,11 @@
 			// Severities of the obsoleted errors
 			categoriesToNotify.AddRange(previousErrors.Except(currentErrors).Select(x => x.Severity).Distinct().ToList());

+			OnErrorsChanged(propertyName, categoriesToNotify);
+		}
+
+		private void OnErrorsChanged(string propertyName, List<ErrorSeverity> categoriesToNotify)
+		{
 			var propertiesToNotify = categoriesToNotify.Select(x => x switch
 			{
 				ErrorSeverity.Info => nameof(AnyInfos),
@@ -95,11 +100,6 @@
 				ErrorSeverity.Error => nameof(AnyErrors),
 			}).ToList();

-			OnErrorsChanged(propertyName, propertiesToNotify);
-		}
-
-		private void OnErrorsChanged(string propertyName, List<string> propertiesToNotify)
-		{
 			if (propertiesToNotify.Any())
 			{
 				ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));


Log host & port to debug issues easier.

Log host & port to debug issues easier.

--- WalletWasabi/Tor/Socks5/TorSocks5Client.cs
+++ WalletWasabi/Tor/Socks5/TorSocks5Client.cs
@@ -62,8 +62,7 @@
 				}
 				catch (Exception ex) when (IsConnectionRefused(ex))
 				{
-					throw new ConnectionException(
-						$"Could not connect to Tor SOCKSPort at {host}:{port}. Is Tor running?", ex);
+					throw new ConnectionException($"Could not connect to Tor SOCKSPort at {host}:{port}. Is Tor running?", ex);
 				}

 				Stream = TcpClient.GetStream();
@@ -208,7 +207,7 @@
 					// the reply.This must be no more than 10 seconds after detecting the
 					// condition that caused a failure.
 					DisposeTcpClient();
-					Logger.LogWarning($"Connection response indicates a failure. Actual response is: '{connectionResponse.Rep}'.");
+					Logger.LogWarning($"Connection response indicates a failure. Actual response is: '{connectionResponse.Rep}'. Request: {host}:{port}.");
 					throw new TorSocks5FailureResponseException(connectionResponse.Rep);
 				}

@@ -226,7 +225,7 @@
 			}
 			catch (Exception e)
 			{
-				Logger.LogError("Exception was thrown when connecting to destination.", e);
+				Logger.LogError($"Exception was thrown when connecting to destination ({host}:{port})", e);
 				throw;
 			}
 			finally


Refactored method.

Refactored method.

--- WildData.Npgsql/Core/ReadOnlyRepository.cs
+++ WildData.Npgsql/Core/ReadOnlyRepository.cs
@@ -67,6 +67,13 @@
         {
             StringBuilder query = new StringBuilder();

+            AppendSelectFrom(query);
+
+            return GetQuery(query.ToString());
+        }
+
+        protected void AppendSelectFrom(StringBuilder query)
+        {
             query.Append(SyntaxHelper.SelectToken);
             query.Append(SyntaxHelper.Space);

@@ -77,8 +84,6 @@
             query.Append(SyntaxHelper.Space);

             AppendStorageName(query);
-
-            return GetQuery(query.ToString());
         }

         protected void AppendStorageName(StringBuilder query)
@@ -165,16 +170,7 @@
             {
                 StringBuilder query = new StringBuilder();

-                query.Append(SyntaxHelper.SelectToken);
-                query.Append(SyntaxHelper.Space);
-
-                AppendColumnList(query);
-
-                query.Append(SyntaxHelper.Space);
-                query.Append(SyntaxHelper.FromToken);
-                query.Append(SyntaxHelper.Space);
-
-                AppendStorageName(query);
+                AppendSelectFrom(query);

                 query.Append(SyntaxHelper.Space);
                 query.Append(SyntaxHelper.WhereToken);


[Gtk] TableViewBackend: custom HeaderView is not visible

setting an custom HeaderView results in an invisible Header

Solution:
Show() has to be called
(see: http://stackoverflow.com/questions/24698901/header-widget-in-gtk-treeviewcolumn)

--- Xwt.Gtk/Xwt.GtkBackend/TableViewBackend.cs
+++ Xwt.Gtk/Xwt.GtkBackend/TableViewBackend.cs
@@ -163,8 +163,10 @@
 		{
 			if (col.HeaderView == null)
 				tc.Title = col.Title;
-			else
+			else {
 				tc.Widget = CellUtil.CreateCellRenderer (ApplicationContext, col.HeaderView);
+				tc.Widget?.Show ();
+			}
 		}

 		void MapColumn (ListViewColumn col, Gtk.TreeViewColumn tc)


[WPF] Custom separator

[WPF] Custom separator

--- Xwt.WPF/Xwt.WPFBackend/SeparatorBackend.cs
+++ Xwt.WPF/Xwt.WPFBackend/SeparatorBackend.cs
@@ -25,8 +25,9 @@
 // THE SOFTWARE.

 using System.Windows;
+using System.Windows.Media;
 using Xwt.Backends;
-using WindowsSeparator = System.Windows.Controls.Separator;
+using WindowsRectangle = System.Windows.Shapes.Rectangle;

 namespace Xwt.WPFBackend
 {
@@ -35,16 +36,37 @@
 	{
 		public SeparatorBackend()
 		{
-			Widget = new WindowsSeparator ();
+			Separator = new WindowsRectangle ();
+			Separator.Stroke = Brushes.DarkGray;
 		}

 		public void Initialize (Orientation dir)
 		{
+			this.direction = dir;
 		}

-		protected WindowsSeparator Separator
+		private Orientation direction;
+
+		protected WindowsRectangle Separator
 		{
-			get { return (WindowsSeparator) Widget; }
+			get { return (WindowsRectangle) Widget; }
+			set { Widget = value; }
+		}
+
+		public override WidgetSize GetPreferredHeight()
+		{
+			if (this.direction == Orientation.Vertical)
+				return new WidgetSize (((FrameworkElement) Widget.Parent).ActualHeight / HeightPixelRatio);
+
+			return new WidgetSize (1);
+		}
+
+		public override WidgetSize GetPreferredWidth()
+		{
+			if (this.direction == Orientation.Horizontal)
+				return new WidgetSize (((FrameworkElement) Widget.Parent).ActualWidth / WidthPixelRatio);
+
+			return new WidgetSize (1);
 		}
 	}
 }