Added logic for calculation of insulation contamination fault cause metric.

--- Source/Libraries/FaultData/DataResources/FaultDataResource.cs
+++ Source/Libraries/FaultData/DataResources/FaultDataResource.cs
@@ -1568,6 +1568,30 @@
                 .Min();
         }

+        // Insulation contamination
+        private double GetInceptionDistanceFromPeak(Fault fault, VICycleDataGroup viCycleDataGroup, int samplesPerCycle)
+        {
+            DataSeries angleSeries = new Func<DataSeries>(() =>
+            {
+                switch (fault.Type)
+                {
+                    case FaultType.AN: return viCycleDataGroup.VA?.Phase;
+                    case FaultType.BN: return viCycleDataGroup.VB?.Phase;
+                    case FaultType.CN: return viCycleDataGroup.VC?.Phase;
+                    default: return null;
+                }
+            })();
+
+            if (angleSeries == null)
+                return double.NaN;
+
+            int inceptionIndex = fault.StartSample;
+            double angle = angleSeries[inceptionIndex].Value * 180.0D / Math.PI;
+            double positiveDistance = Math.Abs(angle - 90.0D);
+            double negativeDistance = Math.Abs(angle + 90.0D);
+            return Math.Min(positiveDistance, negativeDistance);
+        }
+
         private ComplexNumber ToComplexNumber(CycleDataGroup cycleDataGroup, int cycle)
         {
             Angle angle = cycleDataGroup.Phase[cycle].Value;


Added default constructor #348

Added default constructor #348

--- Source/OxyPlot.Xamarin.Forms.Platform.iOS/PlotViewRenderer.cs
+++ Source/OxyPlot.Xamarin.Forms.Platform.iOS/PlotViewRenderer.cs
@@ -1,16 +1,13 @@
 using OxyPlot.Xamarin.Forms;
 using OxyPlot.Xamarin.Forms.Platform.iOS;
-
 using global::Xamarin.Forms;
 using global::Xamarin.Forms.Platform.iOS;

 // Exports the renderer.
 [assembly: ExportRenderer(typeof(PlotView), typeof(PlotViewRenderer))]
-
 namespace OxyPlot.Xamarin.Forms.Platform.iOS
 {
     using System.ComponentModel;
-
     using OxyPlot.Xamarin.iOS;

     /// <summary>
@@ -18,6 +15,13 @@
     /// </summary>
     public class PlotViewRenderer : ViewRenderer<Xamarin.Forms.PlotView, PlotView>
     {
+        /// <summary>
+        /// Default constructor.
+        /// </summary>
+        public PlotViewRenderer()
+        {
+        }
+
         /// <summary>
         /// Raises the element changed event.
         /// </summary>


Fix RegEx bug

Fix RegEx bug

--- Test/AdventureWorksFunctionalModel/Person/Person_Functions.cs
+++ Test/AdventureWorksFunctionalModel/Person/Person_Functions.cs
@@ -186,7 +186,7 @@

         public static (Person, IContext) CreateNewPhoneNumber(this Person p, PhoneNumberType type,
-    [RegEx(@"^[0-9][0-9\s-]+$")] string phoneNumber, IContext context)
+    [RegEx(Validation=@"^[0-9][0-9\s-]+$")] string phoneNumber, IContext context)
             => (p, context.WithPendingSave(new PersonPhone()
             {
                 BusinessEntityID = p.BusinessEntityID,


continue experiment with name updates

continue experiment with name updates

--- Test/AdventureWorksFunctionalModel/Person/Person_Functions.cs
+++ Test/AdventureWorksFunctionalModel/Person/Person_Functions.cs
@@ -17,22 +17,12 @@
             Person original, Person updated, IContext context) =>
             context.WithUpdated(original, new Person(original) { ModifiedDate = context.Now() });

-        public static IContext EditNameFields(this Person p,
-                                       [Optionally] string title,
-                                       string firstName,
+        public static IContext EditMiddleName(this Person p,
                                        [Optionally] string middleName,
-                                       string lastName,
-                                       [Optionally] string suffix,
-                                       [Named("Reverse name order")] bool nameStyle,
                                        IContext context) =>
            UpdatePerson(p, new Person(p)
            {
-               Title = title,
-               FirstName = firstName,
-               MiddleName = middleName,
-               LastName = lastName,
-               Suffix = suffix,
-               NameStyle = nameStyle
+               MiddleName = middleName
            }, context);

         [Edit]


avoid compilation warnings

avoid compilation warnings

svn path=/trunk/; revision=4070

--- extensions/FolderExport/FolderExport.cs
+++ extensions/FolderExport/FolderExport.cs
@@ -1175,8 +1175,8 @@
 				writer.RenderBeginTag ("a");
 				if (exportTagIcons) {
 					writer.AddAttribute ("alt", tag.Name);
-					writer.AddAttribute ("longdesc", Mono.Posix.Catalog.GetString ("Tags: ")+tag.Name);
-					writer.AddAttribute ("title", Mono.Posix.Catalog.GetString ("Tags: ")+tag.Name);
+					writer.AddAttribute ("longdesc", Catalog.GetString ("Tags: ")+tag.Name);
+					writer.AddAttribute ("title", Catalog.GetString ("Tags: ")+tag.Name);
 					writer.AddAttribute ("src", TagPath (tag));
 					writer.RenderBeginTag ("img");
 					writer.RenderEndTag ();


optimize certificate maker for alternative subject names

cleanup win cert maker

--- Titanium.Web.Proxy/Network/Certificate/WinCertificateMaker.cs
+++ Titanium.Web.Proxy/Network/Certificate/WinCertificateMaker.cs
@@ -33,6 +33,12 @@
         private readonly Type typeSignerCertificate;

         private readonly Type typeX509Enrollment;
+
+        private readonly Type typeAltNamesCollection;
+
+        private readonly Type typeExtNames;
+
+        private readonly Type typeCAlternativeName;

         private readonly string sProviderName = "Microsoft Enhanced Cryptographic Provider v1.0";

@@ -55,7 +61,12 @@
             typeSignerCertificate = Type.GetTypeFromProgID("X509Enrollment.CSignerCertificate");
             typeX509Enrollment = Type.GetTypeFromProgID("X509Enrollment.CX509Enrollment");

+            //for alternative names
+            typeAltNamesCollection = Type.GetTypeFromProgID("X509Enrollment.CAlternativeNames");
+            typeExtNames = Type.GetTypeFromProgID("X509Enrollment.CX509ExtensionAlternativeNames");
+            typeCAlternativeName = Type.GetTypeFromProgID("X509Enrollment.CAlternativeName");
         }
+

         /// <summary>
         /// Make certificate.
@@ -172,13 +183,8 @@
                 //add alternative names
                 // https://forums.iis.net/t/1180823.aspx

-                var typeAltNamesCollection = Type.GetTypeFromProgID("X509Enrollment.CAlternativeNames");
                 var altNameCollection = Activator.CreateInstance(typeAltNamesCollection);
-
-                var typeExtNames = Type.GetTypeFromProgID("X509Enrollment.CX509ExtensionAlternativeNames");
                 var extNames = Activator.CreateInstance(typeExtNames);
-
-                var typeCAlternativeName = Type.GetTypeFromProgID("X509Enrollment.CAlternativeName");
                 var altDnsNames = Activator.CreateInstance(typeCAlternativeName);

                 typeValue = new object[] { 3,  subject };


Fixed bug in NMF Transformations

Fixed bug in NMF Transformations

--- Transformations/Transformations/NTL/TransformationRuleBase.cs
+++ Transformations/Transformations/NTL/TransformationRuleBase.cs
@@ -814,7 +814,7 @@
             if (persistor == null) persistor = (o1, o2) => { };
             if (filter == null) filter = i => true;
             if (selector == null) throw new ArgumentNullException("selector");
-            CallForInternal(new Type[] { typeof(TRequiredInput) }, typeof(TRequiredOutput), o => o.Output is TRequiredOutput && filter((TRequiredInput)o.GetInput(0)), o => new object[] { selector((TRequiredInput)o.GetInput(0)) }, (t, v) => persistor((TOut)t, (TRequiredOutput)v), false);
+            CallForInternal(new Type[] { typeof(TRequiredInput) }, typeof(TRequiredOutput), o => o.Output is TRequiredOutput && filter((TRequiredInput)o.GetInput(0)), o => new object[] { selector((TRequiredInput)o.GetInput(0)) }, (t, v) => persistor((TOut)v, (TRequiredOutput)t), false);
         }

         /// <summary>
@@ -837,7 +837,7 @@
             if (filter == null) filter = o => true;
             if (selector == null) throw new ArgumentNullException("selector");
             if (rule == null) throw new ArgumentNullException("rule");
-            CallForInternal(rule, o => filter((TRequiredInput)o.GetInput(0)), o => new object[] { selector((TRequiredInput)o.GetInput(0)) }, (t, v) => persistor((TOut)t, (TRequiredOutput)v), false);
+            CallForInternal(rule, o => filter((TRequiredInput)o.GetInput(0)), o => new object[] { selector((TRequiredInput)o.GetInput(0)) }, (t, v) => persistor((TOut)v, (TRequiredOutput)t), false);
         }

         /// <summary>
@@ -855,7 +855,7 @@
             if (persistor == null) persistor = (o1, o2) => { };
             if (filter == null) filter = (s1, s2) => true;
             if (selector == null) throw new ArgumentNullException("selector");
-            CallForInternal(new Type[] { typeof(TRequiredInput1), typeof(TRequiredInput2) }, typeof(TRequiredOutput), o => filter((TRequiredInput1)o.GetInput(0), (TRequiredInput2)o.GetInput(1)), o => new object[] { selector((TRequiredInput1)o.GetInput(0), (TRequiredInput2)o.GetInput(1)) }, (t, v) => persistor((TOut)t, (TRequiredOutput)v), false);
+            CallForInternal(new Type[] { typeof(TRequiredInput1), typeof(TRequiredInput2) }, typeof(TRequiredOutput), o => filter((TRequiredInput1)o.GetInput(0), (TRequiredInput2)o.GetInput(1)), o => new object[] { selector((TRequiredInput1)o.GetInput(0), (TRequiredInput2)o.GetInput(1)) }, (t, v) => persistor((TOut)v, (TRequiredOutput)t), false);
         }

         /// <summary>
@@ -880,7 +880,7 @@
             if (filter == null) filter = (o1, o2) => true;
             if (selector == null) throw new ArgumentNullException("selector");
             if (rule == null) throw new ArgumentNullException("rule");
-            CallForInternal(rule, o => filter((TRequiredInput1)o.GetInput(0), (TRequiredInput2)o.GetInput(1)), o => new object[] { selector((TRequiredInput1)o.GetInput(0), (TRequiredInput2)o.GetInput(1)) }, (t, v) => persistor((TOut)t, (TRequiredOutput)v), false);
+            CallForInternal(rule, o => filter((TRequiredInput1)o.GetInput(0), (TRequiredInput2)o.GetInput(1)), o => new object[] { selector((TRequiredInput1)o.GetInput(0), (TRequiredInput2)o.GetInput(1)) }, (t, v) => persistor((TOut)v, (TRequiredOutput)t), false);
         }

         /// <summary>


fix: Injection error. Fixes #15

fix: Injection error. Fixes #15

- Fixed injection for multiple registration in HangfireConfiguration using lists instead of IEnumerable

--- VaraniumSharp.Monolith/Configuration/HangfireConfiguration.cs
+++ VaraniumSharp.Monolith/Configuration/HangfireConfiguration.cs
@@ -1,6 +1,7 @@
 using Hangfire;
 using Owin;
 using System.Collections.Generic;
+using System.Linq;
 using VaraniumSharp.Attributes;
 using VaraniumSharp.Enumerations;
 using VaraniumSharp.Extensions;
@@ -24,11 +25,11 @@
         /// <param name="hangfireStorageConfigurations">Collection of all Hangfire Storage Provider configurations</param>
         /// <param name="hangfireContainerJobActivator">Hangfire JobActivator using DryIoC</param>
         /// <param name="jobs">Jobs to execute</param>
-        public HangfireConfiguration(List<HangfireStorageConfigurationBase> hangfireStorageConfigurations, JobActivator hangfireContainerJobActivator, List<HangfireJobBase> jobs)
+        public HangfireConfiguration(IEnumerable<HangfireStorageConfigurationBase> hangfireStorageConfigurations, JobActivator hangfireContainerJobActivator, IEnumerable<HangfireJobBase> jobs)
         {
-            _hangfireStorageConfigurations = hangfireStorageConfigurations;
+            _hangfireStorageConfigurations = hangfireStorageConfigurations.ToList();
             _hangfireContainerJobActivator = hangfireContainerJobActivator;
-            _jobs = jobs;
+            _jobs = jobs.ToList();
         }

         #endregion


[Skip CI] Improve fee estimation feedback

--- WalletWasabi.Gui/Converters/FeeConfirmationTargetConverter.cs
+++ WalletWasabi.Gui/Converters/FeeConfirmationTargetConverter.cs
@@ -12,15 +12,17 @@
 			{
 				if (integer >= 2 && integer <= 6) // minutes
 				{
-					return $"Minutes";
+					return $"{integer}0 minutes";
 				}
 				if (integer >= 7 && integer <= 144) // hours
 				{
-					return "Hours";
+					var h = integer / 6;
+					return $"{h} hours";
 				}
 				if (integer >= 145 && integer <= 1008) // days
 				{
-					return "Days";
+					var d = integer / 144;
+					return $"{d} days";
 				}
 			}


CP-36392: remuve redundant iteration in `ResumeVMOnHostToolStripMenuItem.cs`

Signed-off-by: Danilo Del Busso <766dc0f994b57f2d2e98930ecfa5ee8fb1091a62@citrix.com>

--- XenAdmin/Commands/Controls/ResumeVMOnHostToolStripMenuItem.cs
+++ XenAdmin/Commands/Controls/ResumeVMOnHostToolStripMenuItem.cs
@@ -92,18 +92,14 @@

             protected override bool CanRunCore(SelectedItemCollection selection)
             {
-                if (!selection.AllItemsAre<VM>())
-                {
-                    return false;
-                }
-
                 IXenConnection connection = null;

                 var atLeastOneCanRun = false;
                 foreach (var item in selection)
                 {
-                    var vm = (VM)item.XenObject;
-
+                    if (!(item.XenObject is VM vm))
+                        return false;
+
                     // all VMs must be on the same connection
                     if (connection != null && vm.Connection != connection)
                     {


Fixed duration field border (win)

Fixed duration field border (win)

--- src/ui/windows/TogglDesktop/TogglDesktop/TimeEntryEditViewController.Designer.cs
+++ src/ui/windows/TogglDesktop/TogglDesktop/TimeEntryEditViewController.Designer.cs
@@ -337,7 +337,7 @@
             this.panelStartEndTime.Controls.Add(this.textBoxEndTime);
             this.panelStartEndTime.Controls.Add(this.label5);
             this.panelStartEndTime.Controls.Add(this.textBoxStartTime);
-            this.panelStartEndTime.Location = new System.Drawing.Point(0, 26);
+            this.panelStartEndTime.Location = new System.Drawing.Point(0, 30);
             this.panelStartEndTime.Name = "panelStartEndTime";
             this.panelStartEndTime.Size = new System.Drawing.Size(317, 30);
             this.panelStartEndTime.TabIndex = 5;
@@ -450,7 +450,7 @@
             this.panelDateTag.Controls.Add(this.dateTimePickerStartDate);
             this.panelDateTag.Controls.Add(this.label7);
             this.panelDateTag.Controls.Add(this.checkBoxBillable);
-            this.panelDateTag.Location = new System.Drawing.Point(0, 56);
+            this.panelDateTag.Location = new System.Drawing.Point(0, 60);
             this.panelDateTag.Name = "panelDateTag";
             this.panelDateTag.Size = new System.Drawing.Size(317, 100);
             this.panelDateTag.TabIndex = 8;


volunteer added to database

volunteer added to database


Improved appearance of the verse list

Improved appearance of the verse list


Update Filter Demo

Update Filter Demo

--- SqlServerTest/Demos/Filter.cs
+++ SqlServerTest/Demos/Filter.cs
@@ -18,15 +18,22 @@
             var db = GetInstance1();

             var sql = db.Queryable<Student>().ToSql();
+            //SELECT [ID],[SchoolId],[Name],[CreateTime] FROM [STudent]  WHERE  isDelete=0

             var sql2 = db.Queryable<Student, School>((f, s) => new object[] { JoinType.Left, f.SchoolId == s.Id }).ToSql();
+            //SELECT[f].[ID],[f].[SchoolId],[f].[Name],[f].[CreateTime]
+            //FROM[STudent] f Left JOIN School s ON([f].[SchoolId] = [s].[Id])   WHERE f.isDelete=0
+

             //Specify name filter
             var sql3 = db.Queryable<Student>().Filter("query1").ToSql();
+            //SELECT [ID],[SchoolId],[Name],[CreateTime] FROM [STudent]  WHERE  WHERE  id>@id  AND  isDelete=0
+

             //Specify key filter  and disabled global filter
             string key = "query1";
             var sql4 = db.Queryable<Student>().Filter(key,true).ToSql();
+            //SELECT [ID],[SchoolId],[Name],[CreateTime] FROM [STudent]  WHERE  WHERE  id>@id

         }


Error.cs: Introduce TimeoutError().

Error.cs: Introduce TimeoutError().

--- AIWolfLib/Error.cs
+++ AIWolfLib/Error.cs
@@ -18,7 +18,7 @@
     public static class Error
     {
         /// <summary>
-        /// Writes an error message, then throws exception on debug.
+        /// Writes an error message, then throws AIWolfRuntimeException on debug.
         /// </summary>
         /// <param name="message">Error message.</param>
         public static void RuntimeError(params string[] messages)
@@ -28,7 +28,7 @@
             {
                 message = messages[0];
             }
-            ThrowException(message);
+            ThrowRuntimeException(message);
             foreach (var m in messages)
             {
                 Console.Error.WriteLine(m);
@@ -36,9 +36,33 @@
         }

         [Conditional("DEBUG")]
-        static void ThrowException(string message)
+        static void ThrowRuntimeException(string message)
         {
             throw new AIWolfRuntimeException(message);
         }
+
+        /// <summary>
+        /// Writes an error message, then throws TimeoutException on debug.
+        /// </summary>
+        /// <param name="message">Error message.</param>
+        public static void TimeoutError(params string[] messages)
+        {
+            string message = "";
+            if (messages.Length > 0)
+            {
+                message = messages[0];
+            }
+            ThrowTimeoutException(message);
+            foreach (var m in messages)
+            {
+                Console.Error.WriteLine(m);
+            }
+        }
+
+        [Conditional("DEBUG")]
+        static void ThrowTimeoutException(string message)
+        {
+            throw new TimeoutException(message);
+        }
     }
 }


comment chnages

comment chnages

--- facebook-filter/Views/Home/Index.cshtml
+++ facebook-filter/Views/Home/Index.cshtml
@@ -80,7 +80,7 @@
             cookie: true,  // enable cookies to allow the server to access
             // the session
             xfbml: true,  // parse social plugins on this page
-            version: 'v2.3' // use graph api version 2.5
+            version: 'v2.3' // use graph api version 2.3!!! till July 2017.  then /me/home goes away.
         });

         // Now that we've initialized the JavaScript SDK, we call


CodeOwnersParser.GetContactsForPath returns empty list instead of null

--- tools/notification-configuration/github-codeowner-subscriber/CodeOwnersParser.cs
+++ tools/notification-configuration/github-codeowner-subscriber/CodeOwnersParser.cs
@@ -32,13 +32,16 @@
         /// <summary>
         /// Returns GitHub contacts for a given file path
         /// </summary>
-        /// <param name="path"></param>
-        /// <returns></returns>
+        /// <param name="path">Path to search in CODEOWNERS</param>
+        /// <returns>A list of contacts at the associated path or an empty list if no contacts are found</returns>
         public List<string> GetContactsForPath(string path)
         {
-            return expressionContacts
-                .LastOrDefault(expr => path.StartsWith(expr.GlobExpression))
-                ?.Contacts;
+            var result = expressionContacts
+                .LastOrDefault(expr => path.StartsWith(expr.GlobExpression));
+
+            return result == default
+                ? new List<string>()
+                : result.Contacts;
         }

         /// <summary>


Add docs to PropertyChangedBase, and create OnPropertyChanged method to integrate with Fody.PropertyChanged

--- Stylet/PropertyChangedBase.cs
+++ Stylet/PropertyChangedBase.cs
@@ -12,7 +12,10 @@
     public class PropertyChangedBase : INotifyPropertyChanged, INotifyPropertyChangedDispatcher
     {
         private Action<Action> _propertyChangedDispatcher = Execute.DefaultPropertyChangedDispatcher;
-        public Action<Action> PropertyChangedDispatcher
+        /// <summary>
+        /// Dispatcher to use to dispatch PropertyChanged events. Defaults to Execute.DefaultPropertyChangedDispatcher
+        /// </summary>
+        public virtual Action<Action> PropertyChangedDispatcher
         {
             get { return this._propertyChangedDispatcher; }
             set { this._propertyChangedDispatcher = value; }
@@ -20,17 +23,39 @@

         public event PropertyChangedEventHandler PropertyChanged;

+        /// <summary>
+        /// Refresh all properties
+        /// </summary>
         public void Refresh()
         {
             this.NotifyOfPropertyChange(String.Empty);
         }

+        /// <summary>
+        /// Raise a PropertyChanged notification from the property in the given expression, e.g. NotifyOfPropertyChange(() => this.Property)
+        /// </summary
+        /// <param name="property">Expression describing the property to raise a PropertyChanged notification for</param>
         protected void NotifyOfPropertyChange<TProperty>(Expression<Func<TProperty>> property)
         {
-            this.NotifyOfPropertyChange(property.NameForProperty());
+            this.OnPropertyChanged(property.NameForProperty());
         }

+        /// <summary>
+        /// Raise a PropertyChanged notification from the property with the given name
+        /// </summary>
+        /// <param name="propertyName">Name of the property to raise a PropertyChanged notification for. Defaults to the calling property</param>
         protected virtual void NotifyOfPropertyChange([CallerMemberName] string propertyName = "")
+        {
+            this.OnPropertyChanged(propertyName);
+        }
+
+        /// <summary>
+        /// Fires the PropertyChanged notification.
+        /// </summary>
+        /// <remarks>Specially named so that Fody.PropertyChanged calls it</remarks>
+        /// <param name="propertyName">Name of the property to raise the notification for</param>
+        [EditorBrowsable(EditorBrowsableState.Never)]
+        protected virtual void OnPropertyChanged(string propertyName)
         {
             var handler = this.PropertyChanged;
             if (handler != null)
@@ -39,9 +64,15 @@
             }
         }

+        /// <summary>
+        /// Takes, by reference, a field, and its new value. If field != value, will set field = value and raise a PropertyChanged notification
+        /// </summary>
+        /// <param name="field">Field to assign</param>
+        /// <param name="value">Value to assign to the field, if it differs</param>
+        /// <param name="propertyName">Name of the property to notify for. Defaults to the calling property</param>
         protected virtual void SetAndNotify<T>(ref T field, T value, [CallerMemberName] string propertyName = "")
         {
-            if (Comparer<T>.Default.Compare(field, value) != 0)
+            if (!EqualityComparer<T>.Default.Equals(field, value))
             {
                 field = value;
                 this.NotifyOfPropertyChange(propertyName);


Fix tooltips on the session tree when using just a PuTTY profile

--- SuperPutty/SessionTreeview.cs
+++ SuperPutty/SessionTreeview.cs
@@ -544,7 +544,7 @@
                 addedNode = parentNode.Nodes.Add(session.SessionName, session.SessionName, ImageKeySession, ImageKeySession);
                 addedNode.Tag = session;
                 addedNode.ContextMenuStrip = this.contextMenuStripAddTreeItem;
-                addedNode.ToolTipText = session.ToString();
+                addedNode.ToolTipText = GetSessionToolTip(session);

                 // Override with custom icon if valid
                 if (IsValidImage(session.ImageKey))
@@ -714,6 +714,35 @@
                     }
                 }
             }
+        }
+
+        private static string GetSessionToolTip(SessionData session)
+        {
+            if (string.IsNullOrEmpty(session.PuttySession))
+            {
+                return session.ToString();
+            }
+
+            if (session.Proto != ConnectionProtocol.Auto && !string.IsNullOrEmpty(session.Host) && session.Port > 0)
+            {
+                return session.ToString();
+            }
+
+            var puttyProfile = PuttyDataHelper.GetSessionData(session.SessionName);
+
+            var protocol = (session.Proto == ConnectionProtocol.Auto)
+                ? puttyProfile.Proto
+                : session.Proto;
+
+            var host = string.IsNullOrEmpty(session.Host)
+                ? puttyProfile.Host
+                : session.Host;
+
+            var port = (session.Port == 0)
+                ? puttyProfile.Port
+                : session.Port;
+
+            return string.Format("{0}://{1}:{2}", protocol.ToString().ToLower(), host, port);
         }
         #endregion


Added reverted Item Serializer with one log in

--- Assets/Plugins/OpenUnityTools/unityserializer-ng/Serialization/UnitySerializer.cs
+++ Assets/Plugins/OpenUnityTools/unityserializer-ng/Serialization/UnitySerializer.cs
@@ -1,4 +1,4 @@
-#region
+#region

 using System;
 using System.Collections;
@@ -938,15 +938,16 @@
         public static object Deserialize(Stream inputStream, object instance) {
             // this version always uses the BinarySerializer
             using (new SerializationScope()) {
-                var v = Verbose;
+	            var v = Verbose;
+
                 CreateStacks();
                 try {
                     PushKnownTypes();
-                    PushPropertyNames();
+	                PushPropertyNames();

                     var rw = new BinaryReader(inputStream);
-                    var version = rw.ReadString();
-                    currentVersion = Int32.Parse(version.Substring(4));
+	                var version = rw.ReadString();
+	                currentVersion = Int32.Parse(version.Substring(4));
                     if (currentVersion >= 5) {
                         inputStream.Position = 0;
                         var serializer = new BinarySerializer(rw.ReadBytes((int)inputStream.Length));
@@ -965,10 +966,10 @@
                     Radical.LogError("Serialization error: " + e.ToString());
                     return null;
                 }
-                finally {
+	                finally {
                     PopKnownTypes();
                     PopPropertyNames();
-                    Verbose = v;
+		                Verbose = v;
                 }
             }
         }
@@ -1022,8 +1023,9 @@
         /// <returns> The rehydrated object represented by the data supplied </returns>
         public static void DeserializeInto(byte[] bytes, object instance) {
             using (new SerializationScope()) {
-                using (var inputStream = new MemoryStream(bytes)) {
-                    Deserialize(inputStream, instance);
+	            using (var inputStream = new MemoryStream(bytes))
+	            {
+		            Deserialize(inputStream, instance);
                 }
             }
         }
@@ -1791,8 +1793,7 @@
                 //this is normally only tr
                 if (entry.Value == null) {
                     //Check for custom serialization
-                    if (Serializers.ContainsKey(itemType))
-					{
+                    if (Serializers.ContainsKey(itemType)) {
                         //Read the serializer and its data
                         var serializer = Serializers[itemType];
                         var nentry = new Entry {
@@ -1801,9 +1802,7 @@
                         };
                         storage.BeginReadProperty(nentry);
                         object[] data = null;
-
-                        using (new SerializationSplitScope())
-						{
+                        using (new SerializationSplitScope()) {
                             data =
                                 (object[])
                                 DeserializeObject(nentry, storage);
@@ -1903,11 +1902,6 @@
                 }
                 return result2;
             }
-			catch (System.Exception e)
-			{
-				Debug.Log(e);
-				return null;
-			}
             finally {
 #if US_LOGGING
                 if (Radical.IsLogging()) {
@@ -1949,7 +1943,6 @@
                     };
                     var value = storage.BeginReadObjectArrayItem(l, entry);
                     value = value ?? DeserializeObject(entry, storage);
-					Debug.Log(string.Format("Item Type is {0}", itemType.FullName));
                     if (value != null && value.GetType().IsDefined(typeof(DeferredAttribute), true)) {
                         var toSet = value;
                         value = new DeferredSetter(d => toSet);
@@ -2059,7 +2052,6 @@
                 var entry = new Entry() {
                     StoredType = keyType
                 };
-				Debug.Log(string.Format("2061 Item Type is {0}", itemType));
                 var value = storage.BeginReadDictionaryKeyItem(i, entry) ??
                     DeserializeObject(entry, storage);
                 if (value.GetType().IsDefined(typeof(DeferredAttribute), true)) {
@@ -2090,7 +2082,6 @@
                 var entry = new Entry() {
                     StoredType = valueType
                 };
-				Debug.Log(string.Format("Item Type is {0}", itemType));
                 var value = storage.BeginReadDictionaryValueItem(i, entry) ??
                     DeserializeObject(entry, storage);
                 if (value != null && value.GetType().IsDefined(typeof(DeferredAttribute), true) || list[i] == null) {
@@ -2143,7 +2134,6 @@
                 var entry = new Entry() {
                     StoredType = valueType,
                 };
-				Debug.Log(string.Format("Item Type is {0}", itemType));
                 var value = storage.BeginReadListItem(i, entry) ??
                      DeserializeObject(entry, storage);
                 if (value != null && value.GetType().IsDefined(typeof(DeferredAttribute), true)) {
@@ -2222,8 +2212,6 @@
                     OwningType = itemType,
                     MustHaveName = true
                 });
-
-				Debug.Log(string.Format("ItemType is {0}", itemType));
                 var value = DeserializeObject(entry, storage);
 #if US_LOGGING
                 if (Radical.IsLogging()) {
@@ -2296,9 +2284,9 @@
                     OwningType = itemType,
                     MustHaveName = true
                 });
-				Debug.Log(string.Format("ItemType is {0}", itemType));
+				Debug.Log(string.Format("Item Type is {0}", itemType));
                 var value = DeserializeObject(entry, storage);
-				Debug.Log("2031");
+				Debug.Log(string.Format("Item Type after is {0}", itemType));
 #if US_LOGGING
                 if (Radical.IsLogging()) {
                     Radical.Log(string.Format("Field {0} : {1}", entry.Name, value == null ? "null" : value.GetType().FullName));


Fixed OrderBy

Fixed OrderBy

--- SyMath/Expression/Constant.cs
+++ SyMath/Expression/Constant.cs
@@ -64,11 +64,12 @@
         public override string ToString() { return x.ToString("G6"); }
         public string ToString(string format, IFormatProvider formatProvider) { return x.ToString(format, formatProvider); }

+        // Note that this is *not* an arithmetic comparison, it is a canonicalization ordering.
         public override int CompareTo(Expression R)
         {
             Constant RC = R as Constant;
             if (!ReferenceEquals(RC, null))
-                return RC.Value.CompareTo(Value);
+                return Real.Abs(RC.Value).CompareTo(Real.Abs(Value));

             return base.CompareTo(R);
         }


feat: add FileWriter Test

feat: add FileWriter Test

--- CopyDllsAfterBuildLocalTool/CopyDllsAfterBuildLocalToolUnitTest/FileWriterTest.cs
+++ CopyDllsAfterBuildLocalTool/CopyDllsAfterBuildLocalToolUnitTest/FileWriterTest.cs
@@ -2,17 +2,86 @@
 using System;
 using System.IO;
 using System.Linq;
-using System.Threading.Tasks;
 using Xunit;

 namespace CopyDllsAfterBuildLocalToolUnitTest
 {
-    public class FileWriterTest
+    public class FileWriterTest : IDisposable
     {
-        // todo: add Binary Compare test
-        // todo: add Write test. Binary match file should skipped.
-        // todo: add Write test. Binary mismatch file should write.
-        // todo: add Write test. None CheckOption should write even if binary equals.
-        // todo: add Write test. None CheckOption should write if binary mismatch..
+        private readonly string _path;
+
+        // setup
+        public FileWriterTest()
+        {
+            _path = Path.Combine(Path.GetTempPath(), "FileWriterTest", Guid.NewGuid().ToString());
+
+            if (!Directory.Exists(_path))
+                Directory.CreateDirectory(_path);
+        }
+
+        // teardown
+        public void Dispose()
+        {
+            if (Directory.Exists(_path))
+                Directory.Delete(_path, true);
+        }
+
+        [Fact]
+        public void BinaryCompareTest()
+        {
+            var random = new Random();
+            var content = Enumerable.Range(0, 10).Select(x => (byte)random.Next(0, 254)).ToArray();
+            var mismatchContent = content.Append((byte)random.Next(0, 254)).ToArray();
+
+            // binary match item should be true
+            var a = Path.Combine(_path, "a");
+            File.WriteAllBytes(a, content);
+            using var fa = File.OpenRead(a);
+            Assert.True(FileWriter.Compare(content, fa));
+
+            // binary miss-match item should be false
+            var b = Path.Combine(_path, "b");
+            File.WriteAllBytes(b, mismatchContent);
+            using var fb = File.OpenRead(b);
+            Assert.False(FileWriter.Compare(content, fb));
+        }
+
+        [Fact]
+        public void Write_WriteCheckOption_BinaryEquality_Test()
+        {
+            var option = WriteCheckOption.BinaryEquality;
+
+            // Destination not exists should write.
+            var random = new Random();
+            var content = Enumerable.Range(0, 10).Select(x => (byte)random.Next(0, 254)).ToArray();
+            var a = Path.Combine(_path, "a");
+            Assert.True(FileWriter.Write(content, a, option));
+
+            // Binary match file should skipped.
+            Assert.False(FileWriter.Write(content, a, option));
+
+            // Binary mismatch file should write.
+            var mismatchContent = content.Append((byte)random.Next(0, 254)).ToArray();
+            Assert.True(FileWriter.Write(mismatchContent, a, option));
+        }
+
+        [Fact]
+        public void Write_WriteCheckOption_None_Test()
+        {
+            var option = WriteCheckOption.None;
+
+            // Destination not exists should write.
+            var random = new Random();
+            var content = Enumerable.Range(0, 10).Select(x => (byte)random.Next(0, 254)).ToArray();
+            var a = Path.Combine(_path, "a");
+            Assert.True(FileWriter.Write(content, a, option));
+
+            // Binary match file should write.
+            Assert.True(FileWriter.Write(content, a, option));
+
+            // Binary mismatch file should write.
+            var mismatchContent = content.Append((byte)random.Next(0, 254)).ToArray();
+            Assert.True(FileWriter.Write(mismatchContent, a, option));
+        }
     }
 }


Fix NonSpecific Search Conflicts (Continued)

--- EngineLayer/NonSpecificEnzymeSearch/NonSpecificEnzymeSequencesToActualPeptides.cs
+++ EngineLayer/NonSpecificEnzymeSearch/NonSpecificEnzymeSequencesToActualPeptides.cs
@@ -291,10 +291,29 @@
                     foreach (var psm in psmListForASpecificSearchMode)
                         if (psm != null)
                         {
+                            List<Tuple<CompactPeptideBase, int>> cps = new List<Tuple<CompactPeptideBase, int>>();
                             foreach (KeyValuePair<CompactPeptideBase, Tuple<int, HashSet<PeptideWithSetModifications>>> kvp in psm.CompactPeptides)
                             {
                                 (kvp.Key as CompactPeptideWithModifiedMass).SwapMonoisotopicMassWithModifiedMass();
-                            }
+                                //Change CPWM to reflect actual CP
+                                if(CPWMtoPWSM.TryGetValue(kvp.Key, out HashSet<PeptideWithSetModifications> misplacedPWSMs))
+                                {
+                                    kvp.Key.CropTerminalMasses(terminusType);
+                                    Tuple<CompactPeptideBase, int> tempTuple = new Tuple<CompactPeptideBase, int>(kvp.Key, kvp.Value.Item1);
+                                    if (!cps.Contains(tempTuple))
+                                        cps.Add(tempTuple);
+                                    if(CPWMtoPWSM.TryGetValue(kvp.Key, out HashSet<PeptideWithSetModifications> wellPlacedPWSMs))
+                                    {
+                                        foreach (PeptideWithSetModifications PWSM in misplacedPWSMs)
+                                            wellPlacedPWSMs.Add(PWSM);
+                                    }
+                                    else
+                                    {
+                                        CPWMtoPWSM.Add(kvp.Key, misplacedPWSMs);
+                                    }
+                                }
+                            }
+                            psm.ReplaceAndAdd(cps);
                         }
             return new SequencesToActualProteinPeptidesEngineResults(this, CPWMtoPWSM);
         }


add TargetType != null in EntityScripUtil

--- Framework/Source/Tralus.Framework.Module/Utility/EntityScript/EntityScriptUtil.cs
+++ Framework/Source/Tralus.Framework.Module/Utility/EntityScript/EntityScriptUtil.cs
@@ -25,6 +25,7 @@
                     {
                         var esGroups =
                             from es in db.Set<EntityRuleScript>().ToList()
+                            where es.TargetType != null
                             group es by es.TargetType
                             into esGroup
                             select esGroup;
@@ -41,13 +42,14 @@
                {
                    using (var db = new FrameworkDbContext())
                    {
-                       var esGroups =
-                           from es in db.Set<EntityNumbering>().ToList()
-                           group es by es.TargetType
-                           into esGroup
-                           select esGroup;
+                       var enGroups =
+                           from en in db.Set<EntityNumbering>().ToList()
+                           where en.TargetType != null
+                           group en by en.TargetType
+                           into enGroup
+                           select enGroup;

-                       var dictionary = esGroups.ToDictionary(esg => esg.Key, esg => esg.ToList());
+                       var dictionary = enGroups.ToDictionary(eng => eng.Key, eng => eng.ToList());
                        var cach = new ConcurrentDictionary<Type, List<EntityNumbering>>(dictionary);
                        return cach;
                    }


Removed unused using

Removed unused using

--- Mindscape.Raygun4Net.AspNetCore/Builders/RaygunAspNetCoreRequestMessageBuilder.cs
+++ Mindscape.Raygun4Net.AspNetCore/Builders/RaygunAspNetCoreRequestMessageBuilder.cs
@@ -4,7 +4,6 @@
 using System.Globalization;
 using System.IO;
 using System.Linq;
-using System.Text;
 using System.Threading.Tasks;
 using Mindscape.Raygun4Net.Messages;
 using Microsoft.AspNetCore.Http;


Allow the map tile module to be enabled without also eabling refresh

--- OpenSim/Region/CoreModules/ServiceConnectorsOut/MapImage/MapImageServiceModule.cs
+++ OpenSim/Region/CoreModules/ServiceConnectorsOut/MapImage/MapImageServiceModule.cs
@@ -93,8 +93,8 @@
             if (config == null)
                 return;

-            int refreshminutes = Convert.ToInt32(config.GetString("RefreshTime"));
-            if (refreshminutes <= 0)
+            int refreshminutes = Convert.ToInt32(config.GetString("RefreshTime", "-1"));
+            if (refreshminutes < 0)
             {
                 m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: No refresh time given in config. Module disabled.");
                 return;
@@ -117,12 +117,15 @@
                 return;
             }

-            m_refreshTimer.Enabled = true;
-            m_refreshTimer.AutoReset = true;
-            m_refreshTimer.Interval = m_refreshtime;
-            m_refreshTimer.Elapsed += new ElapsedEventHandler(HandleMaptileRefresh);
-
-            m_log.InfoFormat("[MAP IMAGE SERVICE MODULE]: enabled with refresh time {0}min and service object {1}",
+            if (m_refreshtime > 0)
+            {
+                m_refreshTimer.Enabled = true;
+                m_refreshTimer.AutoReset = true;
+                m_refreshTimer.Interval = m_refreshtime;
+                m_refreshTimer.Elapsed += new ElapsedEventHandler(HandleMaptileRefresh);
+            }
+
+            m_log.InfoFormat("[MAP IMAGE SERVICE MODULE]: enabled with refresh time {0} min and service object {1}",
                              refreshminutes, service);

             m_enabled = true;
@@ -238,4 +241,4 @@
             }
         }
     }
-}+}


Updated OfferSalesChannelDto

Updated OfferSalesChannelDto

--- PS.Mothership.Core/PS.Mothership.Core.Common/Dto/Merchant/OfferSalesChannelDto.cs
+++ PS.Mothership.Core/PS.Mothership.Core.Common/Dto/Merchant/OfferSalesChannelDto.cs
@@ -10,6 +10,9 @@
     public class OfferSalesChannelDto
     {
         [DataMember]
+        public Guid SalesChannelGuid { get; set; }
+
+        [DataMember]
         public long DepartmentKey { get; set; }

         [DataMember]


优化 Demo

优化 Demo

--- Samples/net45-mvc/Senparc.Weixin.MP.Sample.CommonService/Download/ConfigHelper.cs
+++ Samples/net45-mvc/Senparc.Weixin.MP.Sample.CommonService/Download/ConfigHelper.cs
@@ -54,8 +54,8 @@
                 var root = new XElement("Config");
                 root.Add(new XElement("QrCodeId", config.QrCodeId));
                 root.Add(new XElement("DownloadCount", config.DownloadCount));
-                root.Add(new XElement("Versions", config.Versions.First()));
-                root.Add(new XElement("WebVersions", config.WebVersions.First()));
+                root.Add(new XElement("Versions", new XElement("Version", config.Versions.First())));
+                root.Add(new XElement("WebVersions", new XElement("Version", config.Versions.First())));
                 newDoc.Add(root);
                 using (FileStream fs = new FileStream(databaseFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                 {


[Toolkit.Game] Fix issue #408 and issue #413. Simplify code and recreate render targets and depth stencil at every frame

--- Source/Toolkit/SharpDX.Toolkit.Game/WindowsPhone/GameWindowPhoneBackgroundXaml.cs
+++ Source/Toolkit/SharpDX.Toolkit.Game/WindowsPhone/GameWindowPhoneBackgroundXaml.cs
@@ -38,8 +38,6 @@
     {
         #region Fields

-        private readonly RenderTargetLocal[] renderTargets = new RenderTargetLocal[3];
-
         private readonly IntPtr thisComObjectPtr;

         private RenderTarget2D backBuffer;
@@ -57,8 +55,6 @@
         private GraphicsDevice graphicsDevice;

         private IGraphicsDeviceManager graphicsDeviceManager;
-
-        private RenderTargetGraphicsPresenter graphicsPresenter;

         private DrawingSurfaceRuntimeHost host;

@@ -284,37 +280,18 @@
         /// <param name="resetPresenter">if set to <c>true</c> [reset presenter].</param>
         internal void EnsurePresenter(bool resetPresenter)
         {
-            // Find any previous render target that was already allocated.
-            if (!resetPresenter)
-            {
-                foreach (RenderTargetLocal renderTargetLocal in renderTargets)
-                {
-                    if (renderTargetLocal.NativePointer == currentRenderTargetView.NativePointer)
-                    {
-                        backBuffer = renderTargetLocal.RenderTarget;
-                        graphicsPresenter.SetBackBuffer(backBuffer);
-                        return;
-                    }
-                }
-            }
-
             // Creates the backbuffer
+            Utilities.Dispose(ref backBuffer);
             backBuffer = RenderTarget2D.New(graphicsDevice, currentRenderTargetView, true);
             currentRenderTargetView.Tag = backBuffer;
-
-            // Dispose any previous render target.
-            renderTargets[nextRenderTarget].Dispose();
-            renderTargets[nextRenderTarget].NativePointer = currentRenderTargetView.NativePointer;
-            renderTargets[nextRenderTarget].RenderTarget = backBuffer;
-            nextRenderTarget = (nextRenderTarget + 1) % renderTargets.Length;
-
-            if (resetPresenter)
-            {
-                graphicsPresenter = new RenderTargetGraphicsPresenter(graphicsDevice, backBuffer, RequestDepthFormat);
-                graphicsDevice.Presenter = graphicsPresenter;
-            }
-
-            graphicsPresenter.SetBackBuffer(backBuffer);
+
+            if(graphicsDevice.Presenter != null)
+            {
+                graphicsDevice.Presenter.Dispose();
+                graphicsDevice.Presenter = null;
+            }
+
+            graphicsDevice.Presenter = new RenderTargetGraphicsPresenter(graphicsDevice, backBuffer, RequestDepthFormat);
         }

         internal override void Initialize(GameContext gameContext)
@@ -375,12 +352,6 @@
         {
             // Dispose the graphics device
             Utilities.Dispose(ref graphicsDevice);
-
-            // Dispose all allocated render targets
-            for (int i = 0; i < renderTargets.Length; i++)
-            {
-                renderTargets[i].Dispose();
-            }

             // Dispose the backbuffer
             Utilities.Dispose(ref backBuffer);


updated test to match new calculation of total tests run

--- src/nunit.v2.driver.tests/TestEventAdapterTests.cs
+++ src/nunit.v2.driver.tests/TestEventAdapterTests.cs
@@ -102,7 +102,7 @@
             result.Time = 12.5;
             _eventAdapter.SuiteFinished(result);
             string expected = string.Format(
-                "<test-suite type=\"TestSuite\" id=\"{0}-{1}\" name=\"{2}\" fullname=\"{3}\" runstate=\"Runnable\" testcasecount=\"1234\" result=\"Failed\" duration=\"12.500000\" total=\"1234\" passed=\"0\" failed=\"0\" inconclusive=\"0\" skipped=\"0\" asserts=\"9999\"><failure><message><![CDATA[Something failed!]]></message></failure></test-suite>",
+                "<test-suite type=\"TestSuite\" id=\"{0}-{1}\" name=\"{2}\" fullname=\"{3}\" runstate=\"Runnable\" testcasecount=\"1234\" result=\"Failed\" duration=\"12.500000\" total=\"0\" passed=\"0\" failed=\"0\" inconclusive=\"0\" skipped=\"0\" asserts=\"9999\"><failure><message><![CDATA[Something failed!]]></message></failure></test-suite>",
                 RUNNER_ID, TEST_ID, TEST_NAME, FULL_NAME);
             Assert.That(_report, Is.EqualTo(expected));
         }


Test to show that comments are wrongly included in the check for the left side of expressions in ConvertIfStatementToConditionalTernaryExpressionAnalyzer

--- Tests/CSharp/Diagnostics/ConvertIfStatementToConditionalTernaryExpressionTests.cs
+++ Tests/CSharp/Diagnostics/ConvertIfStatementToConditionalTernaryExpressionTests.cs
@@ -132,6 +132,33 @@
         }

+
+
+        [Test]
+        public void TestCommentsIgnoredWhenFindingLeftOfExpression()
+        {
+            Analyze<ConvertIfStatementToConditionalTernaryExpressionAnalyzer>(@"
+    public class Class1
+    {
+        string DoIt(bool a)
+        {
+            string status;
+
+            $if$ (a)
+            {
+                    // Comment
+                    status = ""A"";
+            }
+            else
+            {
+                    // Different comment
+                    status = ""B"";
+            }
+
+            return status;
+        }
+    }", issueToFix: 1);
+        }
     }
 }


Duplicate

Duplicate

--- Assets/Platform.cs
+++ Assets/Platform.cs
@@ -14,10 +14,10 @@

 	public bool manualRebuild = false;

-	private List<GameObject> tileObjects = new List<GameObject>();
+	[SerializeField]private List<GameObject> tileObjects = new List<GameObject>();

-	private GameObject leftEdgeFix;
-	private GameObject rightEdgeFix;
+	[SerializeField]private GameObject leftEdgeFix;
+	[SerializeField]private GameObject rightEdgeFix;

 	void CreateEdgeFixes() {


Don't use sum for latency (#1798)

Don't use sum for latency (#1798)

--- perf/benchmarkapps/GrpcClient/Program.cs
+++ perf/benchmarkapps/GrpcClient/Program.cs
@@ -309,12 +309,12 @@

         private static void CalculateLatency()
         {
-            BenchmarksEventSource.Register("grpc/latency/mean;http/latency/mean", Operations.Max, Operations.Sum, "Mean latency (ms)", "Mean latency (ms)", "n2");
-            BenchmarksEventSource.Register("grpc/latency/50;http/latency/50", Operations.Max, Operations.Sum, "50th percentile latency (ms)", "50th percentile latency (ms)", "n2");
-            BenchmarksEventSource.Register("grpc/latency/75;http/latency/75", Operations.Max, Operations.Sum, "75th percentile latency (ms)", "75th percentile latency (ms)", "n2");
-            BenchmarksEventSource.Register("grpc/latency/90;http/latency/90", Operations.Max, Operations.Sum, "90th percentile latency (ms)", "90th percentile latency (ms)", "n2");
-            BenchmarksEventSource.Register("grpc/latency/99;http/latency/99", Operations.Max, Operations.Sum, "99th percentile latency (ms)", "99th percentile latency (ms)", "n2");
-            BenchmarksEventSource.Register("grpc/latency/max;http/latency/max", Operations.Max, Operations.Sum, "Max latency (ms)", "Max latency (ms)", "n2");
+            BenchmarksEventSource.Register("grpc/latency/mean;http/latency/mean", Operations.Max, Operations.Max, "Mean latency (ms)", "Mean latency (ms)", "n2");
+            BenchmarksEventSource.Register("grpc/latency/50;http/latency/50", Operations.Max, Operations.Max, "50th percentile latency (ms)", "50th percentile latency (ms)", "n2");
+            BenchmarksEventSource.Register("grpc/latency/75;http/latency/75", Operations.Max, Operations.Max, "75th percentile latency (ms)", "75th percentile latency (ms)", "n2");
+            BenchmarksEventSource.Register("grpc/latency/90;http/latency/90", Operations.Max, Operations.Max, "90th percentile latency (ms)", "90th percentile latency (ms)", "n2");
+            BenchmarksEventSource.Register("grpc/latency/99;http/latency/99", Operations.Max, Operations.Max, "99th percentile latency (ms)", "99th percentile latency (ms)", "n2");
+            BenchmarksEventSource.Register("grpc/latency/max;http/latency/max", Operations.Max, Operations.Max, "Max latency (ms)", "Max latency (ms)", "n2");
             if (_options.Latency)
             {
                 var totalCount = 0;
@@ -744,4 +744,4 @@
             }
         }
     }
-}+}


littlebit of nothing

littlebit of nothing

--- TVS-Player/Classes/Checker.cs
+++ TVS-Player/Classes/Checker.cs
@@ -2,10 +2,13 @@
 using System;
 using System.Collections.Generic;
 using System.Globalization;
+using System.IO;
 using System.Linq;
 using System.Text;
+using System.Text.RegularExpressions;
 using System.Threading;
 using System.Threading.Tasks;
+using System.Windows;
 using System.Windows.Threading;

 namespace TVS_Player {
@@ -25,6 +28,75 @@
             threadCheck.Start();
         }

+        private static void RescanEP(int id, List<string> locations) {
+            List<string> showFiles = new List<string>();
+            List<string> aliases = Api.GetAliases(id);
+            List<string> files = new List<string>();
+            foreach (string location in locations) {
+                files.AddRange(Directory.GetFiles(location, "*.*", System.IO.SearchOption.AllDirectories));
+            }
+            foreach (string file in files) {
+                foreach (string alias in aliases) {
+                    if (Path.GetFileName(file).IndexOf(alias, StringComparison.OrdinalIgnoreCase) >= 0 && !showFiles.Contains(file)) {
+                        showFiles.Add(file);
+                    }
+                }
+            }
+            showFiles = FilterExtensions(showFiles);
+           //Database
+            //RenameFiles(files, lib + "\\" + showName, id, showName);
+
+        }
+
+        public static void RenameFiles(List<string> files, string path, int id, string showName) {
+            List<Episode> EPNames = new List<Episode>(); //DownloadInfo(id);
+            foreach (string file in files) {
+                Tuple<int, int> t = GetInfo(file);
+                int season = t.Item1;
+                int episode = t.Item2;
+                var selectedEP = EPNames.FirstOrDefault(o => o.season == season && o.episode == episode);
+                int index = EPNames.FindIndex(o => o.season == season && o.episode == episode);
+                if (selectedEP == null) {
+                    MessageBox.Show("This TV Show doesnt have episode " + episode + " in season " + season + ".\nFile " + file + " won't be renamed", "Error");
+                } else {
+                    string output = Renamer.GetValidName(path, Renamer.GetName(showName, selectedEP.season, selectedEP.episode, selectedEP.name), Path.GetExtension(file), file);
+                    if (file != output) {
+                        File.Move(file, output);
+                    }
+                    EPNames[index].downloaded = true;
+                    EPNames[index].locations.Add(output);
+                }
+            }
+            DatabaseEpisodes.createDB(id, EPNames);
+        }
+
+
+
+        public static Tuple<int, int> GetInfo(string file) {
+            Match season = new Regex("[s][0-5][0-9]", RegexOptions.IgnoreCase).Match(file);
+            Match episode = new Regex("[e][0-5][0-9]", RegexOptions.IgnoreCase).Match(file);
+            Match special = new Regex("[0-5][0-9][x][0-5][0-9]", RegexOptions.IgnoreCase).Match(file);
+            if (season.Success && episode.Success) {
+                int s = Int32.Parse(season.Value.Remove(0, 1));
+                int e = Int32.Parse(episode.Value.Remove(0, 1));
+                return new Tuple<int, int>(s, e);
+            } else if (special.Success) {
+                int s = Int32.Parse(special.Value.Substring(0, 2));
+                int e = Int32.Parse(special.Value.Substring(3, 2));
+                return new Tuple<int, int>(s, e);
+            }
+            return null;
+        }
+        public static List<string> FilterExtensions(List<string> files) {
+            string[] fileExtension = new string[10] { ".mkv", ".srt", ".m4v", ".avi", ".mp4", ".mov", ".sub", ".wmv", ".flv", ".idx" };
+            List<string> filtered = new List<string>();
+            foreach (string file in files) {
+                if (fileExtension.Any(file.Contains)) {
+                    filtered.Add(file);
+                }
+            }
+            return filtered;
+        }
         private static void Update(int id) {
             List<Episode> EPList = DatabaseEpisodes.readDb(id);
             int season = EPList.Max(y => y.season);


Improved support for file names with long numbers

If you were in a folder with a file that had a really long number in
it's name (20 digits or more); vimage would crash when you tried to
navigate to another image. I fixed that by making the code that compares
names trim down numbers to 19 characters if they are too long.

--- vimage/Source/ImageViewer.cs
+++ vimage/Source/ImageViewer.cs
@@ -832,8 +832,13 @@
                     // Natural Sorting
                     Func<string, object> convert = str =>
                     {
-                        try { return ulong.Parse(str); }
-                        catch { return str; }
+                        ulong number;
+                        bool success = ulong.TryParse(str.Substring(0, Math.Min(str.Length, 19)), out number);
+                        // max ulong is 18446744073709551615 (20 chars)
+                        if (success)
+                            return number;
+                        else
+                            return str;
                     };
                     if (SortImagesByDir == SortDirection.Ascending)
                     {


EditorUtils.FindDerivedTypes now finds within ALL assembles -Uses TypeCache if available

--- Assets/Fungus/Scripts/Editor/EditorExtensions.cs
+++ Assets/Fungus/Scripts/Editor/EditorExtensions.cs
@@ -4,6 +4,7 @@
 using UnityEngine;
 using System.Collections.Generic;
 using System.Linq;
+using UnityEditor;

 namespace Fungus.EditorUtils
 {
@@ -52,7 +53,7 @@
         }

         /// <summary>
-        /// A convenient method for calling the above.
+        /// A convenient method for calling the above, but for ALL assemblies.
         /// Example usage:
         ///     List<System.Type> subTypes = EditorUtility.FindDerivedTypes(typeof(BaseTimelineEvent)).ToList();
         /// </summary>
@@ -61,7 +62,21 @@
         /// <returns></returns>
         public static System.Type[] FindDerivedTypes(System.Type baseType, bool classOnly = true)
         {
-            return FindDerivedTypesFromAssembly(System.Reflection.Assembly.GetAssembly(baseType), baseType, classOnly);
+#if UNITY_2019_2_OR_NEWER
+            var results = TypeCache.GetTypesDerivedFrom(baseType).ToArray();
+            if (classOnly)
+                return results.Where(x => x.IsClass).ToArray();
+            else
+                return results.ToArray();
+#else
+            System.Type[] typeArray = new System.Type[0];
+            var retval = typeArray.Concat(typeArray);
+            foreach (var assem in System.AppDomain.CurrentDomain.GetAssemblies())
+            {
+                retval = retval.Concat(FindDerivedTypesFromAssembly(assem, baseType, classOnly));
+            }
+            return retval.ToArray();
+#endif
         }
     }
 }


change Sample Operator

change Sample Operator

--- Assets/Plugins/UniRx/Scripts/Operators/Sample.cs
+++ Assets/Plugins/UniRx/Scripts/Operators/Sample.cs
@@ -201,6 +201,18 @@

                 public void OnCompleted()
                 {
+                    lock (parent.gate)
+                    {
+                        if (parent.isUpdated)
+                        {
+                            parent.isUpdated = false;
+                            parent.observer.OnNext(parent.latestValue);
+                        }
+                        if (parent.isCompleted)
+                        {
+                            try { parent.observer.OnCompleted(); } finally { parent.Dispose(); }
+                        }
+                    }
                 }

                 public void OnError(Exception error)


Moved tests around.

Moved tests around.

The test cases that verify that the AtomEventStream correctly yields its
events is a new group of tests, so there's no reason they should remove
the AppendAsync tests from their private helper classes. This follows
Uncle Bob/Clean Code's concept of code being readable as a newspaper
article: from the top containing general overview, to increasin levels of
detail.

--- AtomEventStore.UnitTests/AtomEventStreamTests.cs
+++ AtomEventStore.UnitTests/AtomEventStreamTests.cs
@@ -139,38 +139,6 @@
             // Teardown
         }

-        [Theory, AutoAtomData]
-        public void SutIsEnumerable(AtomEventStream<TestEventY> sut)
-        {
-            Assert.IsAssignableFrom<IEnumerable<TestEventY>>(sut);
-        }
-
-        [Theory, AutoAtomData]
-        public void SutIsInitiallyEmpty(
-            [Frozen(As = typeof(IAtomEventStorage))]AtomEventsInMemory dummyInjectedIntoSut,
-            AtomEventStream<TestEventX> sut)
-        {
-            Assert.False(sut.Any(), "Intial event stream should be empty.");
-            Assert.Empty(sut);
-        }
-
-        [Theory, AutoAtomData]
-        public void SutYieldsCorrectEvents(
-            [Frozen(As = typeof(IAtomEventStorage))]AtomEventsInMemory dummyInjectedIntoSut,
-            AtomEventStream<TestEventX> sut,
-            List<TestEventX> events)
-        {
-            events.ForEach(e => sut.AppendAsync(e).Wait());
-
-            var expected = events.AsEnumerable().Reverse();
-            Assert.True(
-                expected.SequenceEqual(sut),
-                "Events should be yielded in a FILO order");
-            Assert.True(
-                expected.Cast<object>().SequenceEqual(sut.OfType<object>()),
-                "Events should be yielded in a FILO order");
-        }
-
         private class AtomFeedLikeness
         {
             private readonly DateTimeOffset minimumTime;
@@ -267,5 +235,36 @@
             }
         }

+        [Theory, AutoAtomData]
+        public void SutIsEnumerable(AtomEventStream<TestEventY> sut)
+        {
+            Assert.IsAssignableFrom<IEnumerable<TestEventY>>(sut);
+        }
+
+        [Theory, AutoAtomData]
+        public void SutIsInitiallyEmpty(
+            [Frozen(As = typeof(IAtomEventStorage))]AtomEventsInMemory dummyInjectedIntoSut,
+            AtomEventStream<TestEventX> sut)
+        {
+            Assert.False(sut.Any(), "Intial event stream should be empty.");
+            Assert.Empty(sut);
+        }
+
+        [Theory, AutoAtomData]
+        public void SutYieldsCorrectEvents(
+            [Frozen(As = typeof(IAtomEventStorage))]AtomEventsInMemory dummyInjectedIntoSut,
+            AtomEventStream<TestEventX> sut,
+            List<TestEventX> events)
+        {
+            events.ForEach(e => sut.AppendAsync(e).Wait());
+
+            var expected = events.AsEnumerable().Reverse();
+            Assert.True(
+                expected.SequenceEqual(sut),
+                "Events should be yielded in a FILO order");
+            Assert.True(
+                expected.Cast<object>().SequenceEqual(sut.OfType<object>()),
+                "Events should be yielded in a FILO order");
+        }
     }
 }


Refactored test to use a Likeness for AtomFeed too.

--- AtomEventStore.UnitTests/AtomEventStreamTests.cs
+++ AtomEventStore.UnitTests/AtomEventStreamTests.cs
@@ -57,7 +57,10 @@

             // Verify outcome
             var writtenFeed = storage.Feeds.Select(AtomFeed.Parse).Single();
-            AssertFeed(before, sut.Id, expectedEvent, writtenFeed);
+            var expectedFeed = new AtomFeedLikeness(before, sut.Id, expectedEvent);
+            Assert.True(
+                expectedFeed.Equals(writtenFeed),
+                "Expected feed must match actual feed.");

             var writtenEntry = storage.Entries.Select(AtomEntry.Parse).Single();
             var expectedEntry = new AtomEntryLikeness(
@@ -74,33 +77,57 @@
             // Teardown
         }

-        private static void AssertFeed(
-            DateTimeOffset before,
-            UuidIri expectedId,
-            object expectedEvent,
-            AtomFeed actual)
+        private class AtomFeedLikeness
         {
-            var expectedEntry = new AtomEntryLikeness(
-                before,
-                expectedEvent,
-                new[]
-                {
-                    AtomEventStream
-                        .CreateSelfLinkFrom(
-                            actual.Entries.Single().Id)
-                        .ToViaLink()
-                });
+            private readonly DateTimeOffset minimumTime;
+            private readonly UuidIri expectedId;
+            private readonly object expectedEvent;

-            Assert.Equal(expectedId, actual.Id);
-            Assert.Equal("Head of event stream " + (Guid)expectedId, actual.Title);
-            Assert.True(before <= actual.Updated, "Updated should be very recent.");
-            Assert.True(actual.Updated <= DateTimeOffset.Now, "Updated should not be in the future.");
-            Assert.True(
-                expectedEntry.Equals(actual.Entries.Single()),
-                "Expected entry must match actual entry.");
-            Assert.Contains(
-                AtomEventStream.CreateSelfLinkFrom(expectedId),
-                actual.Links);
+            public AtomFeedLikeness(
+                DateTimeOffset minimumTime,
+                UuidIri expectedId,
+                object expectedEvent)
+            {
+                this.minimumTime = minimumTime;
+                this.expectedId = expectedId;
+                this.expectedEvent = expectedEvent;
+            }
+
+            public override bool Equals(object obj)
+            {
+                var actual = obj as AtomFeed;
+                if (actual == null)
+                    return base.Equals(obj);
+
+                var expectedEntry = new AtomEntryLikeness(
+                    this.minimumTime,
+                    this.expectedEvent,
+                    new[]
+                    {
+                        AtomEventStream
+                            .CreateSelfLinkFrom(
+                                actual.Entries.Single().Id)
+                            .ToViaLink()
+                    });
+
+                Assert.Equal(this.expectedId, actual.Id);
+                Assert.Equal("Head of event stream " + (Guid)this.expectedId, actual.Title);
+                Assert.True(this.minimumTime <= actual.Updated, "Updated should be very recent.");
+                Assert.True(actual.Updated <= DateTimeOffset.Now, "Updated should not be in the future.");
+                Assert.True(
+                    expectedEntry.Equals(actual.Entries.Single()),
+                    "Expected entry must match actual entry.");
+                Assert.Contains(
+                    AtomEventStream.CreateSelfLinkFrom(this.expectedId),
+                    actual.Links);
+
+                return true;
+            }
+
+            public override int GetHashCode()
+            {
+                return 0;
+            }
         }

         private class AtomEntryLikeness


Tiny bits of documentation

Tiny bits of documentation

--- AutomagicDownloader/MediaAPIs/IMDB/IMDBClient.cs
+++ AutomagicDownloader/MediaAPIs/IMDB/IMDBClient.cs
@@ -50,6 +50,7 @@
             var totalRatings = int.Parse(totalRatingsMatch.Groups["num"].Value.Replace(",", ""));

             var start = 0;
+            // Set up all the requests needed to get the list as individual tasks.
             do
             {
                 var headers = new NameValueCollection()
@@ -68,6 +69,7 @@
                 start += view.GetInterval();
             } while (totalRatings > start);

+            // Now wait for each task to complete
             while (tasks.Count > 0)
             {
                 var finishedTask = await Task.WhenAny(tasks);


fix typo

fix typo

--- BTCPayServer/Views/Apps/UpdatePointOfSale.cshtml
+++ BTCPayServer/Views/Apps/UpdatePointOfSale.cshtml
@@ -48,7 +48,7 @@
                         }
                         @if(Model.Example2 != null)
                         {
-                            For a specific item or your template
+                            For a specific item of your template

@Model.Example2

                         }

A POST callback will be sent to notification with the following form will be sent to notificationUrl:


Eaager-load events

Eaager-load events

--- Battery-Commander.Web/Queries/GetSUTARequests.cs
+++ Battery-Commander.Web/Queries/GetSUTARequests.cs
@@ -42,7 +42,8 @@
                  .Include(suta => suta.Soldier)
                  .ThenInclude(soldier => soldier.Unit)
                  .Include(suta => suta.Soldier)
-                 .ThenInclude(soldier => soldier.Supervisor);
+                 .ThenInclude(soldier => soldier.Supervisor)
+                 .Include(suta => suta.Events);
         }
     }
 }


Rework fxcm history provider logic to be more robust

--- Brokerages/Fxcm/FxcmBrokerage.HistoryProvider.cs
+++ Brokerages/Fxcm/FxcmBrokerage.HistoryProvider.cs
@@ -84,6 +84,7 @@

                 // download data
                 var history = new List<BaseData>();
+                var lastEndTime = DateTime.MinValue;

                 var end = request.EndTimeUtc;

@@ -113,27 +114,40 @@
                         _mapRequestsToAutoResetEvents[_currentRequest] = autoResetEvent;
                         _pendingHistoryRequests.Add(_currentRequest);
                     }
+
                     if (!autoResetEvent.WaitOne(HistoryResponseTimeout))
                     {
-                        // no response
-                        if (EnableOnlyHistoryRequests)
+                        // No response can mean genuine timeout or the history data has ended.
+
+                        // 90% of the time no response because no data; widen the search net to 5m if we don't get a response:
+                        if (request.StartTimeUtc.AddSeconds(300) >= end)
                         {
-                            // Potentially no response because no data; widen the search net to 5m if we don't get a response.
-                            if (request.StartTimeUtc.AddSeconds(300) >= end)
-                            {
-                                break;
-                            }
-
-                            throw new TimeoutException(string.Format("FxcmBrokerage.GetHistory(): Operation took longer than {0} seconds.", (decimal) HistoryResponseTimeout/1000));
+                            break;
                         }

+                        // 5% of the time its because the data ends at a specific, repeatible time not close to our desired endtime:
+                        if (end == lastEndTime)
+                        {
+                            Log.Trace("FxcmBrokerage.GetHistory(): Request for {0} ended at {1:O}", request.Symbol.Value, end);
+                            break;
+                        }
+
+                        // 5% of the time its because of an internet / time of day / api settings / timeout: throw if this is the *second* attempt.
+                        if (EnableOnlyHistoryRequests && lastEndTime != DateTime.MinValue)
+                        {
+                            throw new TimeoutException(string.Format("FxcmBrokerage.GetHistory(): History operation ending in {0:O} took longer than {1} seconds. This may be because there is no data, retrying...", end, (decimal)HistoryResponseTimeout / 1000));
+                        }
+
+                        // Assuming Timeout: If we've already retried quite a few times, lets bail.
                         if (++attempt > MaximumHistoryRetryAttempts)
                         {
                             Log.Trace("FxcmBrokerage.GetHistory(): Maximum attempts reached for: " + request.Symbol.Value);
                             break;
                         }

-                        Log.Trace("FxcmBrokerage.GetHistory(): Attempt " + attempt + " for: " + request.Symbol.Value);
+                        // Assuming Timeout: Save end time and if have the same endtime next time, break since its likely there's no data after that time.
+                        lastEndTime = end;
+                        Log.Trace("FxcmBrokerage.GetHistory(): Attempt " + attempt + " for: " + request.Symbol.Value + " ended at " + lastEndTime.ToString("O"));
                         continue;
                     }

@@ -149,7 +163,7 @@
                         // new end date = first datapoint date.
                         end = request.Resolution == Resolution.Tick ? firstDateUtc.AddMilliseconds(-1) : firstDateUtc.AddSeconds(-1);

-                        if (request.StartTimeUtc.AddSeconds(1) >= end)
+                        if (request.StartTimeUtc.AddSeconds(10) >= end)
                             break;
                     }
                     else


* Fix test failure

* Fix test failure

--- test/WebSites/SimpleWebSite/Startup.cs
+++ test/WebSites/SimpleWebSite/Startup.cs
@@ -1,8 +1,10 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

+using System.Text.Encodings.Web;
 using Microsoft.AspNet.Builder;
 using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.WebEncoders.Testing;
 using Microsoft.Net.Http.Headers;
 using Newtonsoft.Json;

@@ -18,6 +20,7 @@
                 .AddAuthorization()
                 .AddFormatterMappings(m => m.SetMediaTypeMappingForFormat("js", new MediaTypeHeaderValue("application/json")))
                 .AddJsonFormatters(j => j.Formatting = Formatting.Indented);
+            services.AddSingleton<UrlEncoder, UrlTestEncoder>();
         }

         public void Configure(IApplicationBuilder app)


Amount, not max-amount, for subscriptions

--- source/docs/07_resources/subscription/02_create_a_new_subscription/code/example.cs
+++ source/docs/07_resources/subscription/02_create_a_new_subscription/code/example.cs
@@ -1,3 +1,3 @@
-var request = new SubscriptionRequest(MerchantID, MaxAmount, IntervalLength, IntervalUnit);
+var request = new SubscriptionRequest(MerchantID, Amount, IntervalLength, IntervalUnit);

 new ConnectClient().NewSubscriptionUrl(request);