fixing ToExpressionString

fixing ToExpressionString

--- src/FastExpressionCompiler.LightExpression/Expression.cs
+++ src/FastExpressionCompiler.LightExpression/Expression.cs
@@ -43,6 +43,7 @@
 using System.Runtime.CompilerServices;
 using System.Text;
 using SysExpr = System.Linq.Expressions.Expression;
+using static System.Environment;

 namespace FastExpressionCompiler.LightExpression
 {
@@ -105,15 +106,18 @@
             return CreateExpressionString(sb, uniqueExprs, lineIdent, stripNamespace, printType, identSpaces);
         }

-        /// Prints the expression in its constructing syntax - helpful to get it from debug and put into the code for test,
-        /// e.g. <![CDATA[ var expr = Lambda(New(typeof(X).GetTypeInfo().DeclaredConstructors.ToArray()[1]), Parameter(typeof(X), "x")) ]]>.
-        public string ToExpressionString()
+        /// Prints the expression in its constructing syntax - helpful to get it from the debug session and put into the code for the test
+        public string ToExpressionString() => ToExpressionString(out _);
+
+        /// Prints the expression in its constructing syntax - helpful to get it from the debug session and put into the code for the test
+        public string ToExpressionString(out List<Expression> uniqueExprs,
+            bool stripNamespace = false, Func<Type, string, string> printType = null)
         {
             var sb = new StringBuilder(1024);
             sb.Append("var expr = ");
-            var e = new List<Expression>();
-            sb = CreateExpressionString(sb, e, 2).Append(';');
-            sb.Insert(0, $"var e = new Expression[{e.Count}]; // unique expressions{System.Environment.NewLine}");
+            uniqueExprs = new List<Expression>();
+            sb = CreateExpressionString(sb, uniqueExprs, 2, stripNamespace, printType).Append(';');
+            sb.Insert(0, $"var e = new Expression[{uniqueExprs.Count}]; // unique expressions{NewLine}");
             return sb.ToString();
         }

@@ -1361,11 +1365,8 @@
             int lineIdent, bool stripNamespace = false, Func<Type, string, string> printType = null, int identSpaces = 2)
         {
             sb.NewLineIdent(lineIdent);
-            if (expr == null)
-                sb.Append("null");
-            else
-                expr.ToExpressionString(sb, uniqueExprs, lineIdent + identSpaces, stripNamespace, printType, identSpaces);
-            return sb;
+            return expr?.ToExpressionString(sb, uniqueExprs, lineIdent + identSpaces, stripNamespace, printType, identSpaces)
+                ?? sb.Append("null");
         }

         internal static StringBuilder NewLineIdentCs(this StringBuilder sb, Expression expr,
@@ -1384,15 +1385,10 @@
             where T : Expression
         {
             if (exprs.Count == 0)
-                return sb.Append(" new ").Append(typeof(T).Name).Append("[0]");
+                return sb.Append("new ").Append(typeof(T).ToCode(true, null)).Append("[0]");

             for (var i = 0; i < exprs.Count; i++)
-            {
-                if (i > 0)
-                    sb.Append(',');
-                sb.NewLineIdentExpr(exprs[i], uniqueExprs, lineIdent, stripNamespace, printType, identSpaces);
-            }
-
+                (i > 0 ? sb.Append(',') : sb).NewLineIdentExpr(exprs[i], uniqueExprs, lineIdent, stripNamespace, printType, identSpaces);
             return sb;
         }

@@ -1400,13 +1396,8 @@
             int lineIdent, bool stripNamespace = false, Func<Type, string, string> printType = null, int identSpaces = 4)
             where T : Expression
         {
-            if (exprs.Count != 0)
-                for (var i = 0; i < exprs.Count; i++)
-                {
-                    if (i > 0)
-                        sb.Append(',');
-                    sb.NewLineIdentCs(exprs[i], lineIdent, stripNamespace, printType, identSpaces);
-                }
+            for (var i = 0; i < exprs.Count; i++)
+                (i > 0 ? sb.Append(',') : sb).NewLineIdentCs(exprs[i], lineIdent, stripNamespace, printType, identSpaces);
             return sb;
         }
     }
@@ -1437,23 +1428,27 @@
         internal static StringBuilder AppendField(this StringBuilder sb, FieldInfo field,
             bool stripNamespace = false, Func<Type, string, string> printType = null) =>
             sb.AppendTypeof(field.DeclaringType, stripNamespace, printType)
-              .Append(".GetTypeInfo().GetDeclaredField(\"").Append(field.Name).Append("\"),");
+              .Append(".GetTypeInfo().GetDeclaredField(\"").Append(field.Name).Append("\")");

         internal static StringBuilder AppendProperty(this StringBuilder sb, PropertyInfo property,
             bool stripNamespace = false, Func<Type, string, string> printType = null) =>
             sb.AppendTypeof(property.DeclaringType, stripNamespace, printType)
-              .Append(".GetTypeInfo().GetDeclaredProperty(\"").Append(property.Name).Append("\"),");
+              .Append(".GetTypeInfo().GetDeclaredProperty(\"").Append(property.Name).Append("\")");

+        internal static StringBuilder AppendEnum<TEnum>(this StringBuilder sb, TEnum value,
+            bool stripNamespace = false, Func<Type, string, string> printType = null) =>
+            sb.Append(typeof(TEnum).ToCode(stripNamespace, printType)).Append('.')
+              .Append(Enum.GetName(typeof(TEnum), value));
+
         private const string _nonPubStatMethods = ".GetMethods(BindingFlags.NonPublic|BindingFlags.Static)[";
         private const string _nonPubInstMethods = ".GetMethods(BindingFlags.NonPublic|BindingFlags.Instance)[";

         internal static StringBuilder AppendMethod(this StringBuilder sb, MethodInfo method,
             bool stripNamespace = false, Func<Type, string, string> printType = null)
         {
-            sb.Append("/*").Append(method.Name).Append("*/");
-
             var type = method.DeclaringType;
             sb.AppendTypeof(type, stripNamespace, printType);
+            sb.Append("/*.").Append(method.Name).Append("*/"); // print the method name in comments

             if (method.IsPublic)
             {
@@ -1496,6 +1491,28 @@
         /// Converts the <paramref name="type"/> into the proper C# representation.
         public static string ToCode(this Type type, bool stripNamespace = false, Func<Type, string, string> printType = null)
         {
+            // the default handling of the built-in types
+            if (type == typeof(void))
+                return "void";
+            if (type == typeof(object))
+                return "object";
+            if (type == typeof(bool))
+                return "bool";
+            if (type == typeof(int))
+                return "int";
+            if (type == typeof(short))
+                return "short";
+            if (type == typeof(byte))
+                return "byte";
+            if (type == typeof(double))
+                return "double";
+            if (type == typeof(float))
+                return "float";
+            if (type == typeof(char))
+                return "char";
+            if (type == typeof(string))
+                return "string";
+
             var isArray = type.IsArray;
             if (isArray)
                 type = type.GetElementType();
@@ -2540,8 +2557,9 @@
         {
             sb.Append("Call(");
             sb.NewLineIdentExpr(Object, uniqueExprs, lineIdent, stripNamespace, printType, identSpaces).Append(", ");
-            sb.NewLineIdent(lineIdent).AppendMethod(Method, stripNamespace, printType).Append(", ");
-            sb.NewLineIdentExprs(Arguments, uniqueExprs, lineIdent, stripNamespace, printType, identSpaces);
+            sb.NewLineIdent(lineIdent).AppendMethod(Method, stripNamespace, printType);
+            if (Arguments.Count > 0)
+                sb.Append(',').NewLineIdentExprs(Arguments, uniqueExprs, lineIdent, stripNamespace, printType, identSpaces);
             return sb.Append(')');
         }

@@ -2855,7 +2873,7 @@
             int lineIdent = 0, bool stripNamespace = false, Func<Type, string, string> printType = null, int identSpaces = 2)
         {
             sb.Append("Bind(");
-            sb.NewLineIdent(lineIdent).AppendFieldOrProperty(Member, stripNamespace, printType);
+            sb.NewLineIdent(lineIdent).AppendFieldOrProperty(Member, stripNamespace, printType).Append(", ");
             sb.NewLineIdentExpr(Expression, uniqueExprs, lineIdent, stripNamespace, printType, identSpaces);
             return sb.Append(")");
         }
@@ -2894,10 +2912,8 @@

             for (int i = 0; i < Bindings.Count; i++)
             {
-                var b = Bindings[i];
-                if (i > 0) sb.Append(",");
-                sb.NewLineIdent(lineIdent);
-                b.CreateExpressionString(sb, uniqueExprs, lineIdent, stripNamespace, printType, identSpaces);
+                sb.Append(", ").NewLineIdent(lineIdent);
+                Bindings[i].CreateExpressionString(sb, uniqueExprs, lineIdent, stripNamespace, printType, identSpaces);
             }

             return sb.Append(")");
@@ -2923,10 +2939,8 @@

             for (int i = 0; i < Initializers.Count; i++)
             {
-                var x = Initializers[i];
-                if (i > 0) sb.Append(",");
-                sb.NewLineIdent(lineIdent);
-                x.CreateExpressionString(sb, uniqueExprs, lineIdent, stripNamespace, printType, identSpaces);
+                sb.Append(", ").NewLineIdent(lineIdent);
+                Initializers[i].CreateExpressionString(sb, uniqueExprs, lineIdent, stripNamespace, printType, identSpaces);
             }

             return sb.Append(")");
@@ -3125,7 +3139,6 @@
     {
         public override ExpressionType NodeType => ExpressionType.Index;
         public override Type Type => Indexer != null ? Indexer.PropertyType : Object.Type.GetElementType();
-
         public readonly Expression Object;
         public readonly PropertyInfo Indexer;

@@ -3134,7 +3147,7 @@
         internal IndexExpression(Expression @object, PropertyInfo indexer, IReadOnlyList<Expression> arguments)
             : base(arguments)
         {
-            Object = @object;
+            Object  = @object;
             Indexer = indexer;
         }

@@ -3144,13 +3157,15 @@
         public override StringBuilder CreateExpressionString(StringBuilder sb, List<Expression> uniqueExprs,
             int lineIdent = 0, bool stripNamespace = false, Func<Type, string, string> printType = null, int identSpaces = 2)
         {
-            sb.Append("MakeIndex(");
-            sb.NewLineIdentExpr(Object, uniqueExprs, lineIdent, stripNamespace, printType, identSpaces);
-
-            if (Indexer == null)
-                sb.Append("null,");
-            else
-                sb.NewLineIdent(lineIdent).AppendProperty(Indexer, stripNamespace, printType);
+            if (Indexer != null)
+                sb.Append("MakeIndex(");
+            else
+                sb.Append("ArrayAccess(");
+
+            sb.NewLineIdentExpr(Object, uniqueExprs, lineIdent, stripNamespace, printType, identSpaces).Append(", ");
+
+            if (Indexer != null)
+                sb.NewLineIdent(lineIdent).AppendProperty(Indexer, stripNamespace, printType).Append(", ");

             sb.NewLineIdentExprs(Arguments, uniqueExprs, lineIdent, stripNamespace, printType, identSpaces);
             return sb.Append(')');
@@ -3515,7 +3530,6 @@
     {
         public override ExpressionType NodeType => ExpressionType.Label;
         public override Type Type => Target.Type;
-
         public readonly LabelTarget Target;
         public virtual Expression DefaultValue => null;

@@ -3531,14 +3545,10 @@
         public override StringBuilder CreateExpressionString(StringBuilder sb, List<Expression> uniqueExprs,
             int lineIdent = 0, bool stripNamespace = false, Func<Type, string, string> printType = null, int identSpaces = 2)
         {
-            sb.Append("Label(\"").Append(Target).Append('"');
-
+            sb.Append("Label(");
+            Target.CreateExpressionString(sb, stripNamespace, printType);
             if (DefaultValue != null)
-            {
-                sb.Append(',');
-                sb.NewLineIdentExpr(DefaultValue, uniqueExprs, lineIdent, stripNamespace, printType, identSpaces);
-            }
-
+                sb.Append(',').NewLineIdentExpr(DefaultValue, uniqueExprs, lineIdent, stripNamespace, printType, identSpaces);
             return sb.Append(')');
         }

@@ -3593,12 +3603,8 @@
         public StringBuilder CreateExpressionString(StringBuilder sb,
             bool stripNamespace = false, Func<Type, string, string> printType = null)
         {
-            sb.Append("Label(");
-            sb.Append(Type.ToCode(stripNamespace, printType));
-            if (Name != null)
-                sb.Append(", ").Append(Name);
-            sb.Append(")");
-            return sb;
+            sb.Append("Label(").AppendTypeof(Type, stripNamespace, printType);
+            return (Name != null ? sb.Append(", \"").Append(Name).Append("\"") : sb).Append(")");
         }

         public StringBuilder ToCSharpString(StringBuilder sb) =>
@@ -3648,17 +3654,13 @@
         public override StringBuilder CreateExpressionString(StringBuilder sb, List<Expression> uniqueExprs,
             int lineIdent = 0, bool stripNamespace = false, Func<Type, string, string> printType = null, int identSpaces = 2)
         {
-            sb.Append("MakeGoto(");
-
-            sb.Append(nameof(GotoExpressionKind)).Append('.').Append(Enum.GetName(typeof(GotoExpressionKind), Kind)).Append(',');
-
+            sb.Append("MakeGoto(").AppendEnum(Kind, stripNamespace, printType).Append(',');
+
             sb.NewLineIdent(lineIdent);
             Target.CreateExpressionString(sb, stripNamespace, printType).Append(',');

             sb.NewLineIdentExpr(Value, uniqueExprs, lineIdent, stripNamespace, printType, identSpaces).Append(',');
-
             sb.NewLineIdent(lineIdent).AppendTypeof(Type, stripNamespace, printType);
-
             return sb.Append(')');
         }


Revert "Merge pull request #175 from AndyBareWeb/master"

This reverts commit cf086908887ce13afb405524cc860f19b3f02cae, reversing
changes made to d002d20dbe3751505623c7d4706ff1e59eda9e97.

--- src/FluentMigrator.Runner/Versioning/VersionMigration.cs
+++ src/FluentMigrator.Runner/Versioning/VersionMigration.cs
@@ -34,8 +34,7 @@
 		{
 			Create.Table(_versionTableMetaData.TableName)
                 .InSchema(_versionTableMetaData.SchemaName)
-				.WithColumn(_versionTableMetaData.ColumnName).AsInt64().NotNullable()
-                .PrimaryKey();
+				.WithColumn(_versionTableMetaData.ColumnName).AsInt64().NotNullable();
 		}

 		public override void Down()


Fix scrolling algorithm

Fix scrolling algorithm

--- src/Avalonia.Controls/Presenters/ThingamybobPresenter.cs
+++ src/Avalonia.Controls/Presenters/ThingamybobPresenter.cs
@@ -31,20 +31,26 @@
         {
             get
             {
-                return new Vector(0, _firstIndex * AverageItemSize);
+                return new Vector(0, (_firstIndex * AverageItemSize) + (_panel?.PixelOffset ?? 0));
             }

             set
             {
                 var count = _lastIndex - _firstIndex;
-                _firstIndex = (int)(value.Y / AverageItemSize);
+                var firstIndex = (int)(value.Y / AverageItemSize);
+                var firstIndexChanged = _firstIndex != firstIndex;
+                _firstIndex = firstIndex;
                 _lastIndex = _firstIndex + count;
                 _panel.PixelOffset = value.Y % AverageItemSize;
-                Renumber();
+
+                if (firstIndexChanged)
+                {
+                    Renumber();
+                }
             }
         }

-        Size IScrollable.Viewport => new Size(1, (_lastIndex - _firstIndex) * AverageItemSize);
+        Size IScrollable.Viewport => new Size(1, _panel?.Bounds.Height ?? 0);
         Size IScrollable.ScrollSize => new Size(0, 1);
         Size IScrollable.PageScrollSize => new Size(0, 1);


* Corrected the context check

 * Corrected the context check

git-svn-id: e2945e6dc2723cb01f425b5a7c3c201ce5019a89@691 080cfd25-d5d9-4c59-82ea-70d02a200d8b

--- src/Gablarski.OpenAL/Providers/OpenALPlaybackProvider.cs
+++ src/Gablarski.OpenAL/Providers/OpenALPlaybackProvider.cs
@@ -79,7 +79,7 @@
 			if (!this.device.IsOpen)
 				this.device.Open();

-			if (Context.CurrentContext != null)
+			if (Context.CurrentContext == null)
 				Context.CreateAndActivate (this.device);
 		}

@@ -158,6 +158,9 @@

 		public void Dispose ()
 		{
+			if (OpenAL.Log.IsDebugEnabled)
+				OpenAL.Log.Debug ("Freeing OpenALPlaybackProvider");
+
 			if (this.device != null)
 			{
 				this.device.Dispose ();
@@ -167,13 +170,12 @@

 		#endregion

-		private Context context;
 		private PlaybackDevice device;
 		private readonly SourcePool<AudioSource> pool = new SourcePool<AudioSource>();
 		private readonly object bufferLock = new object ();
 		private readonly Dictionary<AudioSource, Stack<SourceBuffer>> buffers = new Dictionary<AudioSource, Stack<SourceBuffer>> ();

-		private void RequireBuffers (Stack<SourceBuffer> bufferStack, Source source, int num)
+		private static void RequireBuffers (Stack<SourceBuffer> bufferStack, Source source, int num)
 		{
 			if (source.ProcessedBuffers > 0)
 			{


Fix last link bug

Fix last link bug

--- src/BeautifulRestApi/Models/PagedCollectionFactory{T}.cs
+++ src/BeautifulRestApi/Models/PagedCollectionFactory{T}.cs
@@ -41,7 +41,7 @@
         private Link GetLastLink(int size, int limit)
         {
             return size > limit
-                ? new CollectionLink(_endpoint, new RouteValueDictionary(new { offset = Math.Floor((size - (double)limit) / limit) * limit }))
+                ? new CollectionLink(_endpoint, new RouteValueDictionary(new { offset = Math.Ceiling((size - (double)limit) / limit) * limit }))
                 : new CollectionLink(_endpoint);
         }


Added missing ColorUtils ColorToRGB

Added missing ColorUtils ColorToRGB

--- src/Client/Rs317.Client.Unity/Rendering/3D/ColorUtils.cs
+++ src/Client/Rs317.Client.Unity/Rendering/3D/ColorUtils.cs
@@ -169,6 +169,12 @@
 			return new Color(r, g, b, (byte)a);
 		}

+
+		public static int ColorToRGB(Color32 rgbColor)
+		{
+			return ((int)rgbColor.r << 16) + ((int)rgbColor.g << 8) + ((int)rgbColor.b);
+		}
+
 		/// <summary>
 		/// Converts a RGB color code to a color object.
 		/// </summary>


One less enumerator allocation in ToGroovy for object arrays.

--- src/ExRam.Gremlinq.Core/Extensions/BytecodeExtensions.cs
+++ src/ExRam.Gremlinq.Core/Extensions/BytecodeExtensions.cs
@@ -109,6 +109,21 @@

                         break;
                     }
+                    case object[] objectArray when allowEnumerableExpansion:
+                    {
+                        var comma = false;
+                        foreach (var argument in objectArray)
+                        {
+                            if (comma)
+                                builder.Append(", ");
+                            else
+                                comma = true;
+
+                            Append(argument);
+                        }
+
+                        break;
+                    }
                     case IEnumerable enumerable when allowEnumerableExpansion:
                     {
                         var comma = false;


optimizing the index expression

optimizing the index expression

--- src/FastExpressionCompiler.LightExpression/Expression.cs
+++ src/FastExpressionCompiler.LightExpression/Expression.cs
@@ -373,10 +373,10 @@
                 ?? throw new ArgumentException($"Declared property with the name '{propertyName}' is not found in '{expression.Type}'", nameof(propertyName)));

         public static IndexExpression Property(Expression instance, PropertyInfo indexer, params Expression[] arguments) =>
-            new IndexExpression(instance, indexer, arguments);
+            new IndexWithIndexerExpression(instance, indexer, arguments);

         public static IndexExpression Property(Expression instance, PropertyInfo indexer, IEnumerable<Expression> arguments) =>
-            new IndexExpression(instance, indexer, arguments.AsReadOnlyList());
+            new IndexWithIndexerExpression(instance, indexer, arguments.AsReadOnlyList());

         public static MemberExpression PropertyOrField(Expression expression, string memberName) =>
             expression.Type.FindProperty(memberName) != null
@@ -396,14 +396,14 @@

         public static IndexExpression MakeIndex(Expression instance, PropertyInfo indexer, IEnumerable<Expression> arguments) =>
             indexer != null
-            ? Property(instance, indexer, arguments)
-            : ArrayAccess(instance, arguments);
+                ? Property(instance, indexer, arguments)
+                : ArrayAccess(instance, arguments);

         public static IndexExpression ArrayAccess(Expression array, params Expression[] indexes) =>
-            new IndexExpression(array, null, indexes);
+            new IndexExpression(array, indexes);

         public static IndexExpression ArrayAccess(Expression array, IEnumerable<Expression> indexes) =>
-            new IndexExpression(array, null, indexes.AsReadOnlyList());
+            new IndexExpression(array, indexes.AsReadOnlyList());

         public static MemberExpression Field(FieldInfo field) =>
             new FieldExpression(field);
@@ -1944,7 +1944,6 @@
     {
         public override ExpressionType NodeType => ExpressionType.ArrayIndex;
         public override Type Type { get; }
-
         internal ArrayIndexExpression(Expression left, Expression right, Type type) : base(left, right) =>
             Type = type;
     }
@@ -1992,7 +1991,6 @@
     {
         public readonly MethodInfo AddMethod;
         public readonly IReadOnlyList<Expression> Arguments;
-
         public int ArgumentCount => Arguments.Count;
         public Expression GetArgument(int index) => Arguments[index];

@@ -2021,9 +2019,7 @@
     public sealed class ListInitExpression : Expression
     {
         public override ExpressionType NodeType => ExpressionType.ListInit;
-
         public override Type Type => NewExpression.Type;
-
         public readonly NewExpression NewExpression;
         public readonly IReadOnlyList<ElementInit> Initializers;

@@ -3138,23 +3134,25 @@
             Type = type;
     }

-    // todo: @perf optimize for the absence of the Indexer
     /// For indexer property or array access.
-    public sealed class IndexExpression : ArgumentsExpression
+    public class IndexExpression : Expression, IArgumentProvider
     {
         public override ExpressionType NodeType => ExpressionType.Index;
-        public override Type Type => Indexer != null ? Indexer.PropertyType : Object.Type.GetElementType();
+        public override Type Type => Indexer?.PropertyType ?? Object.Type.GetElementType();
+        public readonly IReadOnlyList<Expression> Arguments;
         public readonly Expression Object;
-        public readonly PropertyInfo Indexer;
+        public virtual PropertyInfo Indexer => null;
+        public int ArgumentCount => Arguments.Count;
+
+        internal IndexExpression(Expression @object, IReadOnlyList<Expression> arguments)
+        {
+            Object  = @object;
+            Arguments = arguments;
+        }

         protected internal override Expression Accept(ExpressionVisitor visitor) => visitor.VisitIndex(this);

-        internal IndexExpression(Expression @object, PropertyInfo indexer, IReadOnlyList<Expression> arguments)
-            : base(arguments)
-        {
-            Object  = @object;
-            Indexer = indexer;
-        }
+        public Expression GetArgument(int index) => Arguments[index];

         internal override SysExpr CreateSysExpression(ref LiveCountArray<LightAndSysExpr> exprsConverted) =>
             SysExpr.MakeIndex(Object.ToExpression(ref exprsConverted), Indexer, ToExpressions(Arguments, ref exprsConverted));
@@ -3175,6 +3173,14 @@
             sb.NewLineIdentExprs(Arguments, uniqueExprs, lineIdent, stripNamespace, printType, identSpaces);
             return sb.Append(')');
         }
+    }
+
+    public sealed class IndexWithIndexerExpression : IndexExpression
+    {
+        public override PropertyInfo Indexer { get; }
+
+        internal IndexWithIndexerExpression(Expression @object, PropertyInfo indexer, IReadOnlyList<Expression> arguments)
+            : base(@object, arguments) => Indexer = indexer;
     }

     /// Base Block expression with no variables and with Type of its last (Result) exporession


more #314

more #314

--- src/FastExpressionCompiler.LightExpression/Expression.cs
+++ src/FastExpressionCompiler.LightExpression/Expression.cs
@@ -1456,14 +1456,17 @@
         {
             switch (binaryType)
             {
-                case ExpressionType.Add: return Add(left, right);
-                case ExpressionType.AddChecked: return AddChecked(left, right);
-                case ExpressionType.Subtract: return Subtract(left, right);
-                case ExpressionType.SubtractChecked: return SubtractChecked(left, right);
-                case ExpressionType.Multiply: return Multiply(left, right);
-                case ExpressionType.MultiplyChecked: return MultiplyChecked(left, right);
-                case ExpressionType.Divide: return Divide(left, right);
-                case ExpressionType.Modulo: return Modulo(left, right);
+                case ExpressionType.Add:
+                case ExpressionType.AddChecked:
+                case ExpressionType.Subtract:
+                case ExpressionType.SubtractChecked:
+                case ExpressionType.Multiply:
+                case ExpressionType.MultiplyChecked:
+                case ExpressionType.Divide:
+                case ExpressionType.Modulo:
+                    return GetArithmeticBinary(binaryType, left, right);
+
+                // todo: @wip incomplete - use similar to GetArithmeticBinary
                 case ExpressionType.Power: return Power(left, right);
                 case ExpressionType.And: return And(left, right);
                 case ExpressionType.AndAlso: return AndAlso(left, right);
@@ -1501,7 +1504,8 @@
             }
         }

-        public static BinaryExpression MakeBinary(ExpressionType binaryType, Expression left, Expression right, bool liftToNull, MethodInfo method, LambdaExpression conversion = null)
+        public static BinaryExpression MakeBinary(ExpressionType binaryType, Expression left, Expression right, bool liftToNull, MethodInfo method,
+            LambdaExpression conversion = null)
         {
             switch (binaryType)
             {
@@ -1518,7 +1522,7 @@
                 case ExpressionType.AndAlso:
                 case ExpressionType.Or:
                 case ExpressionType.OrElse:
-                    return GetLeftTypedBinary(binaryType, left, right, method);
+                    return GetLeftTypedBinary(binaryType, left, right, method); // todo: @wip incomplete

                 case ExpressionType.LessThan: return LessThan(left, right, liftToNull, method);
                 case ExpressionType.LessThanOrEqual: return LessThanOrEqual(left, right, liftToNull, method);


Remove extra messagebox that would appear when the log/audio path was invalid

--- vmPing/Views/OptionsWindow.xaml.cs
+++ vmPing/Views/OptionsWindow.xaml.cs
@@ -364,7 +364,6 @@
                         !Directory.Exists(Path.GetDirectoryName(AudioFilePath.Text)) ||
                         Path.GetFileName(AudioFilePath.Text).Length < 1)
                     {
-                        MessageBox.Show(Path.GetFileName(AudioFilePath.Text));
                         throw new Exception();
                     }
                 }
@@ -410,7 +409,6 @@
                         !Directory.Exists(Path.GetDirectoryName(LogStatusChangesPath.Text)) ||
                         Path.GetFileName(LogStatusChangesPath.Text).Length < 1)
                     {
-                        MessageBox.Show(Path.GetFileName(LogStatusChangesPath.Text));
                         throw new Exception();
                     }
                 }


crawled date dependent on HttpStatusCode

--- src/FilterLists.Services/FilterList/FilterListService.cs
+++ src/FilterLists.Services/FilterList/FilterListService.cs
@@ -24,12 +24,13 @@
             return summaries.GroupJoin(latestSnapshots, summary => summary.Id, snap => snap.FilterListId,
                 (summary, snap) =>
                 {
-                    var snaps = snap as Data.Entities.Snapshot[] ?? snap.ToArray();
+                    snap = snap as Data.Entities.Snapshot[] ?? snap.ToArray();
+                    var crawledDate = snap.Any() ? snap.Single().CreatedDateUtc : (DateTime?) null;
                     return new ListSummaryDto
                     {
                         Id = summary.Id,
                         AddedDate = summary.AddedDate,
-                        CrawledDate = snaps.Any() ? snaps.Single().CreatedDateUtc : (DateTime?) null,
+                        CrawledDate = crawledDate,
                         Languages = summary.Languages,
                         Name = summary.Name,
                         ViewUrl = summary.ViewUrl
@@ -40,7 +41,7 @@
         private async Task<List<ListSummaryDto>> GetSummaryDtos()
         {
             return await DbContext.FilterLists.AsNoTracking()
-                                  .OrderBy(list => list.Name)
+                                  .OrderBy(l => l.Name)
                                   .ProjectTo<ListSummaryDto>()
                                   .ToListAsync();
         }
@@ -48,10 +49,10 @@
         private async Task<List<Data.Entities.Snapshot>> GetLatestSnapshots()
         {
             return await DbContext.Snapshots.AsNoTracking()
-                                  .Where(snap =>
-                                      snap.IsCompleted &&
-                                      (snap.AddedSnapshotRules.Count > 0 || snap.RemovedSnapshotRules.Count > 0))
-                                  .GroupBy(snap => snap.FilterListId,
+                                  .Where(s => s.IsCompleted &&
+                                              s.HttpStatusCode == "200" &&
+                                              (s.AddedSnapshotRules.Count > 0 || s.RemovedSnapshotRules.Count > 0))
+                                  .GroupBy(s => s.FilterListId,
                                       (key, x) => x.OrderByDescending(y => y.CreatedDateUtc).First())
                                   .ToListAsync();
         }
@@ -78,7 +79,9 @@
         private async Task<DateTime?> GetCrawledDate(ListDetailsDto details)
         {
             var snapshotDates = DbContext.Snapshots.AsNoTracking()
-                                         .Where(s => s.FilterListId == details.Id && s.IsCompleted &&
+                                         .Where(s => s.FilterListId == details.Id &&
+                                                     s.IsCompleted &&
+                                                     s.HttpStatusCode == "200" &&
                                                      (s.AddedSnapshotRules.Count > 0 ||
                                                       s.RemovedSnapshotRules.Count > 0))
                                          .Select(s => s.CreatedDateUtc)


Update HtmlSanitizerOptions.cs

Update HtmlSanitizerOptions.cs


fix TocMap parallelism issue (#2219)

fix TocMap parallelism issue (#2219)

--- src/Microsoft.DocAsCode.Build.Engine/LinkPhaseHandler.cs
+++ src/Microsoft.DocAsCode.Build.Engine/LinkPhaseHandler.cs
@@ -199,11 +199,9 @@
                         toc.Value,
                         (k, v) =>
                         {
-                            foreach (var item in toc.Value)
-                            {
-                                v.Add(item);
-                            }
-                            return v;
+                            var union = new HashSet<string>(v, FilePathComparer.OSPlatformSensitiveComparer);
+                            union.UnionWith(toc.Value);
+                            return union;
                         });
                 }
             }


Better behavior for FileSizeCondition when local file doesn't exist

--- src/NAppUpdate.Framework/Conditions/FileSizeCondition.cs
+++ src/NAppUpdate.Framework/Conditions/FileSizeCondition.cs
@@ -23,21 +23,29 @@
             if (FileSize <= 0)
                 return true;

-            string localPath = !string.IsNullOrEmpty(LocalPath)
-                                   ? LocalPath
-                                   : Utils.Reflection.GetNauAttribute(task, "LocalPath") as string;
-            if (string.IsNullOrEmpty(localPath) || !File.Exists(localPath))
+            var localPath = !string.IsNullOrEmpty(LocalPath)
+                ? LocalPath
+                : Utils.Reflection.GetNauAttribute(task, "LocalPath") as string;
+
+            // local path is invalid, we can't check for anything so we will return as if the condition was met
+            if (string.IsNullOrEmpty(localPath))
                 return true;

-            FileInfo fi = new FileInfo(localPath);
+            long localFileSize = 0;
+            if (File.Exists(localPath))
+            {
+                var fi = new FileInfo(localPath);
+                localFileSize = fi.Length;
+            }
+
             switch (ComparisonType)
             {
                 case "above":
-                    return FileSize < fi.Length;
+                    return FileSize < localFileSize;
                 case "is":
-                    return FileSize == fi.Length;
+                    return FileSize == localFileSize;
             }
-            return FileSize > fi.Length;
+            return FileSize > localFileSize;
         }
     }
 }


Placeholder for auto-property

Placeholder for auto-property

--- src/NRoles.Engine.Test/Support/Placeholder_Properties.cs
+++ src/NRoles.Engine.Test/Support/Placeholder_Properties.cs
@@ -17,12 +17,17 @@
       get { return answer + 2; }
       set { answer = value - 2; }
     }
+    public int AutoAnswer { get; set; }
   }

   public class DeepThought : Does<RDeepThought> {
     [Placeholder] public int Answer {
       get { return 4 + 2; }
       set { }
+    }
+    [Placeholder] public int AutoAnswer {
+      get { return 4 * 2; }
+      set { throw new Exception(); }
     }
   }

@@ -31,13 +36,13 @@
       var thinker = new DeepThought();
       thinker.Answer = 42;
       Assert.AreEqual(42, thinker.Answer);
+      thinker.AutoAnswer = 42;
+      Assert.AreEqual(42, thinker.AutoAnswer);
     }
   }

   // TODO: possible bug: test superceded property

-  // TODO: auto-property
-
   // TODO: placeholder in individual getter or setter

 }


Update AssemblyDomain.cs

Update AssemblyDomain.cs

--- src/Natasha/Core/Engine/AssemblyModule/AssemblyDomain.cs
+++ src/Natasha/Core/Engine/AssemblyModule/AssemblyDomain.cs
@@ -1,7 +1,6 @@
 using Microsoft.CodeAnalysis;
 using Microsoft.Extensions.DependencyModel;
 using Natasha.AssemblyModule.Model;
-using Natasha.Template;
 using System;
 using System.Collections.Concurrent;
 using System.Collections.Generic;


Update RarVolume.cs

Update RarVolume.cs


Fixed incorrect logic on length in reader

--- src/LightningQueues/Net/Protocol/V1/ReceivingProtocol.cs
+++ src/LightningQueues/Net/Protocol/V1/ReceivingProtocol.cs
@@ -50,7 +50,7 @@
                 .Select(x => BitConverter.ToInt32(x, 0))
                 .Catch((Exception ex) => sendSerializationError<int>(stream, ex))
                 .Do(x => _logger.DebugFormat("Read in length value of {0}", x))
-                .Where(x => x >= 0);
+                .Where(x => x > 0);
         }

         public IObservable<Message[]> MessagesChunk(Stream stream, int length)


Fix case sensitive comparison in TemplateMatcher

--- src/Microsoft.AspNet.Routing/Template/TemplateMatcher.cs
+++ src/Microsoft.AspNet.Routing/Template/TemplateMatcher.cs
@@ -204,7 +204,9 @@
                 }
                 else
                 {
-                    if (requestSegment.EndsWith(routeSegment.Parts[indexOfLastSegment - 1].Text))
+                    if (requestSegment.EndsWith(
+                        routeSegment.Parts[indexOfLastSegment - 1].Text,
+                        StringComparison.OrdinalIgnoreCase))
                     {
                         return false;
                     }


Unify namespace placement with the .Overloads partial class

--- src/Moq/Moq/contentFiles/cs/netstandard2.0/Mocks/Mock.cs
+++ src/Moq/Moq/contentFiles/cs/netstandard2.0/Mocks/Mock.cs
@@ -1,11 +1,11 @@
+using System;
+using System.CodeDom.Compiler;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using Moq.Sdk;
+
 namespace Moq
 {
-    using System;
-    using System.CodeDom.Compiler;
-    using System.Reflection;
-    using System.Runtime.CompilerServices;
-    using Moq.Sdk;
-
     /// <summary>
     /// Instantiates mocks for the specified types.
     /// </summary>


Bring ServerUtilities.cs in line with coding standard

--- src/NUnitEngine/nunit.engine/Internal/ServerUtilities.cs
+++ src/NUnitEngine/nunit.engine/Internal/ServerUtilities.cs
@@ -8,10 +8,10 @@
 // distribute, sublicense, and/or sell copies of the Software, and to
 // permit persons to whom the Software is furnished to do so, subject to
 // the following conditions:
-//
+//
 // The above copyright notice and this permission notice shall be
 // included in all copies or substantial portions of the Software.
-//
+//
 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
@@ -22,11 +22,12 @@
 // ***********************************************************************

 using System;
-using System.Collections;
+using System.Collections.Generic;
 using System.Runtime.Remoting;
 using System.Runtime.Remoting.Channels;
 using System.Runtime.Remoting.Channels.Tcp;
-using System.Reflection;
+using System.Runtime.Serialization.Formatters;
+using System.Threading;

 namespace NUnit.Engine.Internal
 {
@@ -36,49 +37,55 @@
     /// </summary>
     public static class ServerUtilities
     {
-        static Logger log = InternalTrace.GetLogger(typeof(ServerUtilities));
+        private static readonly Logger Log = InternalTrace.GetLogger(typeof(ServerUtilities));

         /// <summary>
-        ///  Create a <see cref="TcpChannel"/> with a given name on a given port.
+        /// Create a <see cref="TcpChannel"/> with a given name on a given port.
         /// </summary>
         /// <param name="name">The name of the channel to create.</param>
         /// <param name="port">The port number of the channel to create.</param>
         /// <param name="limit">The rate limit of the channel to create.</param>
         /// <returns>A <see cref="TcpChannel"/> configured with the given name and port.</returns>
-        private static TcpChannel CreateTcpChannel( string name, int port, int limit )
+        private static TcpChannel CreateTcpChannel(string name, int port, int limit)
         {
-            Hashtable props = new Hashtable();
-            props.Add( "port", port );
-            props.Add( "name", name );
-            props.Add( "bindTo", "127.0.0.1" );
+            var props = new Dictionary<string, object>
+            {
+                { "port", port },
+                { "name", name },
+                { "bindTo", "127.0.0.1" },
+                //{ "clientConnectionLimit", limit }
+            };

-            BinaryServerFormatterSinkProvider serverProvider =
-                new BinaryServerFormatterSinkProvider();
+            var serverProvider = new BinaryServerFormatterSinkProvider
+            {
+                TypeFilterLevel = TypeFilterLevel.Full
+            };

-            // NOTE: TypeFilterLevel and "clientConnectionLimit" property don't exist in .NET 1.0.
-            Type typeFilterLevelType = typeof(object).Assembly.GetType("System.Runtime.Serialization.Formatters.TypeFilterLevel");
-            if (typeFilterLevelType != null)
-            {
-                PropertyInfo typeFilterLevelProperty = serverProvider.GetType().GetProperty("TypeFilterLevel");
-                object typeFilterLevel = Enum.Parse(typeFilterLevelType, "Full");
-                typeFilterLevelProperty.SetValue(serverProvider, typeFilterLevel, null);
+            var clientProvider = new BinaryClientFormatterSinkProvider();

-//                props.Add("clientConnectionLimit", limit);
-            }
-
-            BinaryClientFormatterSinkProvider clientProvider =
-                new BinaryClientFormatterSinkProvider();
-
-            return new TcpChannel( props, clientProvider, serverProvider );
+            return new TcpChannel(props, clientProvider, serverProvider);
         }

         /// <summary>
         /// Get a default channel. If one does not exist, then one is created and registered.
         /// </summary>
-        /// <returns>The specified <see cref="TcpChannel"/> or null if it cannot be found and created</returns>
+        /// <returns>The specified <see cref="TcpChannel"/> or <see langword="null"/> if it cannot be found and created.</returns>
         public static TcpChannel GetTcpChannel()
         {
-            return GetTcpChannel( "", 0, 2 );
+            return GetTcpChannel("", 0, 2);
+        }
+
+        /// <summary>
+        /// Get a channel by name, casting it to a <see cref="TcpChannel"/>.
+        /// Otherwise, create, register and return a <see cref="TcpChannel"/> with
+        /// that name, on the port provided as the second argument.
+        /// </summary>
+        /// <param name="name">The name of the channel.</param>
+        /// <param name="port">The port to use if the channel must be created.</param>
+        /// <returns>The specified <see cref="TcpChannel"/> or <see langword="null"/> if it cannot be found and created.</returns>
+        public static TcpChannel GetTcpChannel(string name, int port)
+        {
+            return GetTcpChannel(name, port, 2);
         }

         /// <summary>
@@ -87,63 +94,47 @@
         /// that name, on the port provided as the second argument.
         /// </summary>
         /// <param name="name">The name of the channel</param>
-        /// <param name="port">The port to use if the channel must be created</param>
-        /// <returns>The specified <see cref="TcpChannel"/> or null if it cannot be found and created</returns>
-        public static TcpChannel GetTcpChannel( string name, int port )
-        {
-            return GetTcpChannel( name, port, 2 );
-        }
-
-        /// <summary>
-        /// Get a channel by name, casting it to a <see cref="TcpChannel"/>.
-        /// Otherwise, create, register and return a <see cref="TcpChannel"/> with
-        /// that name, on the port provided as the second argument.
-        /// </summary>
-        /// <param name="name">The name of the channel</param>
-        /// <param name="port">The port to use if the channel must be created</param>
-        /// <param name="limit">The client connection limit or negative for the default</param>
-        /// <returns>The specified <see cref="TcpChannel"/> or null if it cannot be found and created</returns>
+        /// <param name="port">The port to use if the channel must be created.</param>
+        /// <param name="limit">The client connection limit or negative for the default.</param>
+        /// <returns>The specified <see cref="TcpChannel"/> or <see langword="null"/> if it cannot be found and created.</returns>
         public static TcpChannel GetTcpChannel(string name, int port, int limit)
         {
-            TcpChannel channel = ChannelServices.GetChannel( name ) as TcpChannel;
+            var existingChannel = ChannelServices.GetChannel(name) as TcpChannel;
+            if (existingChannel != null) return existingChannel;

-            if ( channel == null )
-            {
-                // NOTE: Retries are normally only needed when rapidly creating
-                // and destroying channels, as in running the NUnit tests.
-                int retries = 10;
-                while( --retries > 0 )
-                    try
-                    {
-                        channel = CreateTcpChannel( name, port, limit );
-                        ChannelServices.RegisterChannel( channel, false );
-                        break;
-                    }
-                    catch( Exception e )
-                    {
-                        log.Error("Failed to create/register channel", e);
-                        System.Threading.Thread.Sleep(300);
-                    }
-            }
+            // NOTE: Retries are normally only needed when rapidly creating
+            // and destroying channels, as in running the NUnit tests.
+            for (var retries = 0; retries < 10; retries++)
+                try
+                {
+                    var newChannel = CreateTcpChannel(name, port, limit);
+                    ChannelServices.RegisterChannel(newChannel, false);
+                    return newChannel;
+                }
+                catch (Exception ex)
+                {
+                    Log.Error("Failed to create/register channel", ex);
+                    Thread.Sleep(300);
+                }

-            return channel;
+            return null;
         }

         /// <summary>
         /// Unregisters the <see cref="IChannel"/> from the <see cref="ChannelServices"/> registry.
         /// </summary>
         /// <param name="channel">The channel to unregister.</param>
-        public static void SafeReleaseChannel( IChannel channel )
+        public static void SafeReleaseChannel(IChannel channel)
         {
-            if( channel != null )
-                try
-                {
-                    ChannelServices.UnregisterChannel( channel );
-                }
-                catch( RemotingException )
-                {
-                    // Channel was not registered - ignore
-                }
+            if (channel == null) return;
+            try
+            {
+                ChannelServices.UnregisterChannel(channel);
+            }
+            catch (RemotingException)
+            {
+                // Channel was not registered - ignore
+            }
         }
     }
 }


Deal with obsolete key if we get one

Deal with obsolete key if we get one

--- src/NUnitEngine/nunit.engine/Runners/MasterTestRunner.cs
+++ src/NUnitEngine/nunit.engine/Runners/MasterTestRunner.cs
@@ -342,6 +342,17 @@
                 && _projectService.CanLoadFrom(package.FullName);
         }

+        private struct ObsoletePackageSetting
+        {
+            public string OldKey;
+            public string NewKey;
+        }
+
+        private static ObsoletePackageSetting[] ObsoleteSettings = new ObsoletePackageSetting[]
+        {
+            new ObsoletePackageSetting() { OldKey = "RuntimeFramework", NewKey = "RequestedRuntimeFramework"}
+        };
+
         // Any Errors thrown from this method indicate that the client
         // runner is putting invalid values into the package.
         private void ValidatePackageSettings()
@@ -376,6 +387,14 @@

             if (runningInProcess && runAsX86 && IntPtr.Size == 8)
                 throw new NUnitEngineException("Cannot run tests in process - a 32 bit process is required.");
+
+            foreach (var entry in ObsoleteSettings)
+            {
+                var oldKey = entry.OldKey;
+                var newKey = entry.NewKey;
+                if (TestPackage.Settings.ContainsKey(oldKey) && !TestPackage.Settings.ContainsKey(newKey))
+                    TestPackage.Settings[newKey] = TestPackage.Settings[oldKey];
+            }
 #endif
         }


Fix KeyNotFoundException and return null as expected by callers

--- src/OmniSharp.DotNetTest/TestFrameworks/TestFramework.cs
+++ src/OmniSharp.DotNetTest/TestFrameworks/TestFramework.cs
@@ -24,7 +24,9 @@

         public static TestFramework GetFramework(string name)
         {
-            return s_frameworks[name];
+            return s_frameworks.TryGetValue(name, out var result)
+                ? result
+                : null;
         }

         public static IEnumerable<TestFramework> GetFrameworks()


Fix load order of PSSA modules (#705)

Fix load order of PSSA modules (#705)

--- src/PowerShellEditorServices/Analysis/AnalysisService.cs
+++ src/PowerShellEditorServices/Analysis/AnalysisService.cs
@@ -533,7 +533,7 @@
                     pssaModuleInfo = ps.Invoke()?
                         .Select(psObj => psObj.BaseObject)
                         .OfType<PSModuleInfo>()
-                        .OrderBy(moduleInfo => moduleInfo.Version)
+                        .OrderByDescending(moduleInfo => moduleInfo.Version)
                         .FirstOrDefault();
                 }
                 catch (Exception e)


Use raw console bgcolor by default in IHostOutput.WriteOutput

This change resolves PowerShell/vscode-powershell#637 which reports that
on Linux and macOS the input prompt is printed out with a black
background, overriding the console's default background color.  The
fix is to use a System.ConsoleColor of -1 as the default rather than
System.ConsoleColor.Black so that .NET's console library will not
override the console's background color.

--- src/PowerShellEditorServices/Session/Host/IHostOutput.cs
+++ src/PowerShellEditorServices/Session/Host/IHostOutput.cs
@@ -135,7 +135,7 @@
                 includeNewLine,
                 outputType,
                 ConsoleColor.Gray,
-                ConsoleColor.Black);
+                (ConsoleColor)(-1)); // -1 indicates the console's raw background color
         }

         /// <summary>
@@ -169,7 +169,7 @@
                 includeNewLine,
                 outputType,
                 foregroundColor,
-                ConsoleColor.Black);
+                (ConsoleColor)(-1)); // -1 indicates the console's raw background color
         }
     }
 }


add failing test case to reproduce #289

add failing test case to reproduce #289

--- src/common/tests_xunit.cs
+++ src/common/tests_xunit.cs
@@ -1018,6 +1018,74 @@
                 Assert.True(fail);

                 Assert.True(raw.sqlite3_errstr(raw.SQLITE_CONSTRAINT).utf8_to_string() != null);
+            }
+        }
+
+        [Fact]
+        public void test_value_blob_issue_289()
+        {
+            var ka = new byte[]
+            {
+                37,
+                42,
+                22,
+                198,
+                0,
+                222,
+                16,
+                4
+            };
+
+            int compare_and_return_sum(byte[] ba)
+            {
+                Assert.Equal(ka.Length, ba.Length);
+                //System.Console.WriteLine($"got ba: {string.Join(",", ba.Select(x => x.ToString()))}");
+                int sum = 0;
+                for (int i=0; i<ka.Length; i++)
+                {
+                    Assert.Equal(ka[i], ba[i]);
+                    sum += ba[i];
+                }
+                return sum;
+            }
+
+            delegate_function_scalar func289 =
+                (ctx, user_data, args) =>
+                {
+                    var ba = raw.sqlite3_value_blob(args[0]).ToArray();
+                    var sum = compare_and_return_sum(ba);
+                    raw.sqlite3_result_int(ctx, sum);
+                };
+
+            using (sqlite3 db = ugly.open(":memory:"))
+            {
+                db.exec("CREATE TABLE foo (x blob);");
+                db.create_function("func289", 1, null, func289);
+                db.exec("INSERT INTO foo (x) VALUES(?);", ka);
+                var rowid = db.last_insert_rowid();
+
+                int sum_expected;
+                {
+                    var tot = 0;
+                    foreach (var b in ka)
+                    {
+                        tot += b;
+                    }
+                    sum_expected = tot;
+                }
+
+                // make sure the blob went into the table correctly
+                {
+                    var ba = db.query_scalar<byte[]>("SELECT x FROM foo WHERE rowid=" + rowid);
+                    var sum_result = compare_and_return_sum(ba);
+                    Assert.Equal(sum_expected, sum_result);
+                }
+
+                // now call the function to see if the blob arrives properly
+                {
+                    var sum_result = db.query_scalar<int>("SELECT func289(x) FROM foo;");
+                    Assert.Equal(sum_expected, sum_result);
+                }
             }
         }


Fix #2162: SwitchFromInstalledToAvailableWhileLoadingInstalled is hanging

Fix R expression in SetCranRepoAsync to parse correctly.

--- src/R/Components/Test/PackageManager/TestRepositories.cs
+++ src/R/Components/Test/PackageManager/TestRepositories.cs
@@ -20,7 +20,7 @@
             return eval.ExecuteAsync(code);
         }
         public static Task SetCranRepoAsync(IRExpressionEvaluator eval) {
-            var code = @"options(repos=list(CRAN='[http://cran.r-project.org\](http://cran.r-project.org\)'";
+            var code = @"options(repos=list(CRAN='http://cran.r-project.org'))";
             return eval.ExecuteAsync(code);
         }
     }


Select word tests

Select word tests

--- src/R/Editor/Application.Test/Selection/SelectionTest.cs
+++ src/R/Editor/Application.Test/Selection/SelectionTest.cs
@@ -12,8 +12,9 @@
         [Test]
         [Category.Interactive]
         public void R_SelectWord01() {
-            using (var script = new TestScript("abc$def", RContentTypeDefinition.ContentType)) {
+            using (var script = new TestScript("\r\nabc$def['test test']", RContentTypeDefinition.ContentType)) {

+                script.MoveDown();
                 script.Execute(Languages.Editor.Controller.Constants.VSConstants.VSStd2KCmdID.SELECTCURRENTWORD);
                 var span = EditorWindow.CoreEditor.View.Selection.StreamSelectionSpan;
                 var selectedWord = span.GetText();
@@ -25,6 +26,11 @@
                 selectedWord = span.GetText();
                 selectedWord.Should().Be("def");

+                script.MoveRight(3);
+                script.Execute(Languages.Editor.Controller.Constants.VSConstants.VSStd2KCmdID.SELECTCURRENTWORD);
+                span = EditorWindow.CoreEditor.View.Selection.StreamSelectionSpan;
+                selectedWord = span.GetText();
+                selectedWord.Should().Be("test");
             }
         }

@@ -43,7 +49,6 @@
                 span = EditorWindow.CoreEditor.View.Selection.StreamSelectionSpan;
                 selectedWord = span.GetText();
                 selectedWord.Should().Be("def");
-
             }
         }
     }


Uses a lock object around file accesses

Uses a lock object around file accesses

--- src/SourceBrowser.Site/Repositories/BrowserRepository.cs
+++ src/SourceBrowser.Site/Repositories/BrowserRepository.cs
@@ -17,6 +17,10 @@
     internal static class BrowserRepository
     {
         private static readonly string StaticHtmlAbsolutePath = System.Web.Hosting.HostingEnvironment.MapPath("~/SB_Files/");
+        /// <summary>
+        /// Lock used for querying repo's status (n/a, processing or ready)
+        /// </summary>
+        private static object fileOperationLock = new object();

         // TODO: DO NOT LOAD THIS INTO MEMORY.
         // This string could be really big. We should probably be distributing this
@@ -37,43 +41,55 @@
         {
 	        string lockFileDirectory = Path.Combine(StaticHtmlAbsolutePath, userName, repoName);
             string lockFilePath = Path.Combine(lockFileDirectory, Constants.REPO_LOCK_FILENAME);
-	        if (File.Exists(lockFilePath))
-	        {
-		        return false;
-	        }
-	        else
-	        {
-		        // Create a file that indicates that the upload will begin
-		        Directory.CreateDirectory(lockFileDirectory);
-                File.WriteAllText(lockFilePath, Constants.REPO_STATUS_PROCESSING);
-		        return true;
-	        }
+            lock (fileOperationLock)
+            {
+                if (File.Exists(lockFilePath))
+                {
+                    return false;
+                }
+                else
+                {
+                    // Create a file that indicates that the upload will begin
+                    Directory.CreateDirectory(lockFileDirectory);
+                    File.WriteAllText(lockFilePath, Constants.REPO_STATUS_PROCESSING);
+                    return true;
+                }
+            }
         }

         internal static void UnlockRepository(string userName, string repoName)
         {
 	        string lockFilePath = Path.Combine(StaticHtmlAbsolutePath, userName, repoName, Constants.REPO_LOCK_FILENAME);
-	        if (File.Exists(lockFilePath))
-	        {
-		        File.Delete(lockFilePath);
-	        }
+            lock (fileOperationLock)
+            {
+                if (File.Exists(lockFilePath))
+                {
+                    File.Delete(lockFilePath);
+                }
+            }
         }

         internal static void MarkRepositoryReady(string userName, string repoName)
         {
             string lockFilePath = Path.Combine(StaticHtmlAbsolutePath, userName, repoName, Constants.REPO_LOCK_FILENAME);
-            File.WriteAllText(lockFilePath, Constants.REPO_STATUS_READY);
+            lock (fileOperationLock)
+            {
+                File.WriteAllText(lockFilePath, Constants.REPO_STATUS_READY);
+            }
         }

         internal static bool RepositoryIsReady(string userName, string repoName)
         {
             string lockFilePath = Path.Combine(StaticHtmlAbsolutePath, userName, repoName, Constants.REPO_LOCK_FILENAME);
-            if (File.Exists(lockFilePath))
-            {
-                var contents = File.ReadAllText(lockFilePath);
-                if (contents.Trim().Equals(Constants.REPO_STATUS_READY))
-                {
-                    return true;
+            lock (fileOperationLock)
+            {
+                if (File.Exists(lockFilePath))
+                {
+                    var contents = File.ReadAllText(lockFilePath);
+                    if (contents.Trim().Equals(Constants.REPO_STATUS_READY))
+                    {
+                        return true;
+                    }
                 }
             }
             return false;


Fix compat issue with Type.IsAssignableFrom

--- src/System.Private.CoreLib/shared/System/Type.Helpers.cs
+++ src/System.Private.CoreLib/shared/System/Type.Helpers.cs
@@ -342,7 +342,7 @@
             // For backward-compatibility, we need to special case for the types
             // whose UnderlyingSystemType are runtime implemented.
             Type toType = this.UnderlyingSystemType;
-            if (toType.IsRuntimeImplemented())
+            if (toType?.IsRuntimeImplemented() == true)
                 return toType.IsAssignableFrom(c);

             // If c is a subclass of this class, then c can be cast to this type.


Support System.Reflection.Emit tests on the full .NET Framework

--- src/System.Reflection.Emit/tests/AssemblyBuilderTests.cs
+++ src/System.Reflection.Emit/tests/AssemblyBuilderTests.cs
@@ -4,6 +4,7 @@

 using System.Collections.Generic;
 using System.Linq;
+using System.Runtime.InteropServices;
 using Xunit;

 namespace System.Reflection.Emit.Tests
@@ -71,11 +72,20 @@
         }

         [Theory]
-        [InlineData((AssemblyBuilderAccess)0)] // No such case
-        [InlineData((AssemblyBuilderAccess)10)] // No such case
+        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "The coreclr doesn't support Save or ReflectionOnly AssemblyBuilders.")]
         [InlineData((AssemblyBuilderAccess)2)] // Save (not supported)
         [InlineData((AssemblyBuilderAccess)2 | AssemblyBuilderAccess.Run)] // RunAndSave (not supported)
         [InlineData((AssemblyBuilderAccess)6)] // ReflectionOnly (not supported)
+        public void DefineDynamicAssembly_CoreclrNotSupportedAccess_ThrowsArgumentException(AssemblyBuilderAccess access)
+        {
+            DefineDynamicAssembly_InvalidAccess_ThrowsArgumentException(access);
+        }
+
+        [Theory]
+        [InlineData((AssemblyBuilderAccess)(-1))]
+        [InlineData((AssemblyBuilderAccess)0)]
+        [InlineData((AssemblyBuilderAccess)10)]
+        [InlineData((AssemblyBuilderAccess)int.MaxValue)]
         public void DefineDynamicAssembly_InvalidAccess_ThrowsArgumentException(AssemblyBuilderAccess access)
         {
             Assert.Throws<ArgumentException>("access", () => AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), access));
@@ -87,10 +97,10 @@
         {
             AssemblyName name = new AssemblyName("Name") { Version = new Version(0, 0, 0, 0) };
             AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
-            Assert.Equal(name.ToString(), assembly.FullName);
+            Assert.StartsWith(name.ToString(), assembly.FullName);

             name.Name = "NewName";
-            Assert.NotEqual(name.ToString(), assembly.FullName);
+            Assert.False(assembly.FullName.StartsWith(name.ToString()));
         }

         public static IEnumerable<object[]> DefineDynamicModule_TestData()
@@ -113,26 +123,53 @@
             Assert.Empty(module.CustomAttributes);

             Assert.Equal("<In Memory Module>", module.Name);
-            Assert.Equal("RefEmit_InMemoryManifestModule", module.FullyQualifiedName);
+
+            // The coreclr ignores the name passed to AssemblyBuilder.DefineDynamicModule
+            if (RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework"))
+            {
+                Assert.Equal(name, module.FullyQualifiedName);
+            }
+            else
+            {
+                Assert.Equal("RefEmit_InMemoryManifestModule", module.FullyQualifiedName);
+            }

             Assert.Equal(module, assembly.GetDynamicModule(module.FullyQualifiedName));
         }

-        [Theory]
-        [InlineData(null, typeof(ArgumentNullException))]
-        [InlineData("", typeof(ArgumentException))]
-        [InlineData("\0test", typeof(ArgumentException))]
-        public void DefineDyamicModule_InvalidName_ThrowsArgumentException(string name, Type exceptionType)
-        {
-            AssemblyBuilder assembly = Helpers.DynamicAssembly();
-            Assert.Throws(exceptionType, () => assembly.DefineDynamicModule(name));
-        }
-
-        [Fact]
-        public void DefineDyamicModule_ModuleAlreadyDefined_ThrowsInvalidOperationException()
-        {
-            AssemblyBuilder assembly = Helpers.DynamicAssembly();
-            ModuleBuilder mb = assembly.DefineDynamicModule("module1");
+        [Fact]
+        public void DefineDynamicModule_NullName_ThrowsArgumentNullException()
+        {
+            AssemblyBuilder assembly = Helpers.DynamicAssembly();
+            Assert.Throws<ArgumentNullException>("name", () => assembly.DefineDynamicModule(null));
+        }
+
+        [Theory]
+        [InlineData("")]
+        [InlineData("\0test")]
+        public void DefineDynamicModule_InvalidName_ThrowsArgumentException(string name)
+        {
+            AssemblyBuilder assembly = Helpers.DynamicAssembly();
+            Assert.Throws<ArgumentException>("name", () => assembly.DefineDynamicModule(name));
+        }
+
+        [Fact]
+        [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "The coreclr only supports AssemblyBuilders with one module.")]
+        public void DefineDynamicModule_NetFxModuleAlreadyDefined_ThrowsInvalidOperationException()
+        {
+            AssemblyBuilder assembly = Helpers.DynamicAssembly();
+            assembly.DefineDynamicModule("module1");
+            assembly.DefineDynamicModule("module2");
+            Assert.Throws<ArgumentException>(null, () => assembly.DefineDynamicModule("module1"));
+        }
+
+        [Fact]
+        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "The coreclr only supports AssemblyBuilders with one module.")]
+        public void DefineDynamicModule_CoreFxModuleAlreadyDefined_ThrowsInvalidOperationException()
+        {
+            AssemblyBuilder assembly = Helpers.DynamicAssembly();
+            assembly.DefineDynamicModule("module1");
+            Assert.Throws<InvalidOperationException>(() => assembly.DefineDynamicModule("module1"));
             Assert.Throws<InvalidOperationException>(() => assembly.DefineDynamicModule("module2"));
         }

@@ -258,9 +295,9 @@

         public static void VerifyAssemblyBuilder(AssemblyBuilder assembly, AssemblyName name, IEnumerable<CustomAttributeBuilder> attributes)
         {
-            Assert.Equal(name.ToString(), assembly.FullName);
-            Assert.Equal(name.ToString(), assembly.GetName().ToString());
-
+            Assert.StartsWith(name.ToString(), assembly.FullName);
+            Assert.StartsWith(name.ToString(), assembly.GetName().ToString());
+
             Assert.True(assembly.IsDynamic);

             Assert.Equal(attributes?.Count() ?? 0, assembly.CustomAttributes.Count());


Fix logging for option value change

Fix logging for option value change

--- src/VisualStudio/Core/Impl/Options/AbstractOptionPage.cs
+++ src/VisualStudio/Core/Impl/Options/AbstractOptionPage.cs
@@ -109,8 +109,11 @@
             // Save the changes that were accumulated in the option store.
             var oldOptions = s_optionService.GetOptions();
             var newOptions = s_optionStore.GetOptions();
+
+            // Must log the option change before setting the new option values via s_optionService,
+            // otherwise oldOptions and newOptions would be identical and nothing will be logged.
+            OptionLogger.Log(oldOptions, newOptions);
             s_optionService.SetOptions(newOptions);
-            OptionLogger.Log(oldOptions, newOptions);

             // Make sure we load the next time a page is activated, in case that options changed
             // programmatically between now and the next time the page is activated


Tweak

Tweak

--- src/Workspaces/Core/Portable/FindSymbols/SymbolFinder.cs
+++ src/Workspaces/Core/Portable/FindSymbols/SymbolFinder.cs
@@ -236,11 +236,11 @@
         }

         /// <summary>
-        /// If <paramref name="symbol"/> is declared in a linked file, then this function returns all the symbols that
+        /// If <paramref name="symbolAndProjectId"/> is declared in a linked file, then this function returns all the symbols that
         /// are defined by the same symbol's syntax in the all projects that the linked file is referenced from.
         /// <para/>
         /// In order to be returned the other symbols must have the same <see cref="ISymbol.Name"/> and <see
-        /// cref="ISymbol.Kind"/> as <paramref name="symbol"/>.  This matches general user intuition that these are all
+        /// cref="ISymbol.Kind"/> as <paramref name="symbolAndProjectId"/>.  This matches general user intuition that these are all
         /// the 'same' symbol, and should be examined, regardless of the project context and <see cref="ISymbol"/> they
         /// originally started with.
         /// </summary>
@@ -271,8 +271,9 @@
                     var semanticModel = await linkedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
                     var linkedSymbol = semanticModel.GetDeclaredSymbol(linkedNode, cancellationToken);

-                    if (linkedSymbol?.Kind == symbol.Kind &&
-                        linkedSymbol?.Name == symbol.Name)
+                    if (linkedSymbol != null &&
+                        linkedSymbol.Kind == symbol.Kind &&
+                        linkedSymbol.Name == symbol.Name)
                     {
                         linkedSymbols.Add(SymbolAndProjectId.Create(linkedSymbol, linkedDocument.Project.Id));
                     }


Adjust logic

Adjust logic

--- src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspace.cs
+++ src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspace.cs
@@ -193,11 +193,12 @@
             // Ensure we release the ref count on this solution once we're done.
             await using var _ = anyBranchRefCountedSolution.ConfigureAwait(false);

+            var anyBranchSolution = await anyBranchRefCountedSolution.Target.Task.WithCancellation(cancellationToken).ConfigureAwait(false);
+
             return await _primaryBranchSolutionCache.SlowGetOrCreateSolutionAsync(
                 solutionChecksum,
                 async cancellationToken =>
                 {
-                    var anyBranchSolution = await anyBranchRefCountedSolution.Target.Task.WithCancellation(cancellationToken).ConfigureAwait(false);
                     var (primaryBranchSolution, _) = await this.TryUpdateWorkspaceCurrentSolutionAsync(workspaceVersion, anyBranchSolution, cancellationToken).ConfigureAwait(false);
                     return primaryBranchSolution;
                 },


The "SortDate" property should just return the created time as they now use the same type

--- src/Skybrud.Social.Facebook/Models/Posts/FacebookPost.cs
+++ src/Skybrud.Social.Facebook/Models/Posts/FacebookPost.cs
@@ -368,7 +368,7 @@
         /// the response - otherwise <see cref="DateTime.MinValue"/> will be returned instead.
         /// </summary>
         public EssentialsDateTime SortDate {
-            get { return HasCreatedTime ? CreatedTime.DateTime : DateTime.MinValue; }
+            get { return CreatedTime; }
         }

         #endregion


typo: Double word "old" (#36289)

typo: Double word "old" (#36289)

--- src/System.Data.Common/src/System/Xml/XmlDataDocument.cs
+++ src/System.Data.Common/src/System/Xml/XmlDataDocument.cs
@@ -1937,7 +1937,7 @@
             {
                 // Sync the old region if it is not deleted
                 DataRow row = oldRowElem.Row;
-                // Since the old old region was disconnected, then the row can be only Deleted or Detached
+                // Since the old region was disconnected, then the row can be only Deleted or Detached
                 Debug.Assert(!IsRowLive(row));
                 if (oldRowElem.Row.RowState == DataRowState.Detached)
                     SynchronizeRowFromRowElement(oldRowElem);


Fix extra 'temp-' in printing

Fix extra 'temp-' in printing

--- src/Tools/GenerateDocumentationAndConfigFiles/Program.cs
+++ src/Tools/GenerateDocumentationAndConfigFiles/Program.cs
@@ -486,7 +486,7 @@
                     // Note: Although a using statement exists for the textWriter, its scope is the whole method.
                     // So Dispose isn't called before the whole method returns.
                     textWriter.Close();
-                    Validate(fileWithPath, File.ReadAllText(Path.Combine(directory.FullName, analyzerSarifFileName)), fileNamesWithValidationFailures);
+                    Validate(Path.Combine(directory.FullName, analyzerSarifFileName), File.ReadAllText(fileWithPath), fileNamesWithValidationFailures);
                 }

                 return;


Average percents.

Average percents.

Signed-off-by: fxmozart fxmozart <26d5702fc4845169d0388eda58c4a3dc47bd8c0d@gmail.com>

--- encog-core-cs/Util/NetworkUtil/NetworkUtility.cs
+++ encog-core-cs/Util/NetworkUtil/NetworkUtility.cs
@@ -918,6 +918,23 @@
             return norm;
         }

+
+        /// <summary>
+        /// Returns the difference between two doubles in percents.
+        ///  </summary>
+        /// <param name="first">The first double.</param>
+        /// <param name="second">The second double.</param>
+        /// <returns>return the absolute percentage difference between two numbers.</returns>
+        public static double AveragePercents (double first,double second)
+        {
+            double diffs = Math.Abs(first - second);
+            double result = (first + second)/2;
+            return (diffs/result)*0.01;
+
+        }
+
+
+
         /// <summary>
         /// Saves a normalization to the specified folder with the specified name.
         /// </summary>


Fazendo queue durable e ckonoledgement não automatico

--- tests/Integration/NewProductQueueTests.cs
+++ tests/Integration/NewProductQueueTests.cs
@@ -22,26 +22,25 @@
         {
             var factory = new ConnectionFactory() { HostName = "localhost" };
             using (var connection = factory.CreateConnection())
+            using (var channel = connection.CreateModel())
             {
-                using (var channel = connection.CreateModel())
-                {
-                    channel.QueueDeclare(queue: "hello",
-                                 durable: false,
-                                 exclusive: false,
-                                 autoDelete: false,
-                                 arguments: null);
+                channel.QueueDeclare(queue: "hello",
+                                durable: true,
+                                exclusive: false,
+                                autoDelete: false,
+                                arguments: null);

-                    string message = "Hello World!";
-                    var body = Encoding.UTF8.GetBytes(message);
+                string message = "Hello World!";
+                var body = Encoding.UTF8.GetBytes(message);

-                    channel.BasicPublish(exchange: "",
-                                        routingKey: "hello",
-                                        basicProperties: null,
-                                        body: body);
-                    Console.WriteLine(" [x] Sent {0}", message);
-                }
+                channel.BasicPublish(exchange: "",
+                                    routingKey: "hello",
+                                    basicProperties: null,
+                                    body: body);
+                Console.WriteLine(" [x] Sent {0}", message);
             }
         }
+

         [TestMethod]
         public void Smoke_Read_From_Queue()
@@ -51,7 +50,7 @@
             using (var channel = connection.CreateModel())
             {
                 channel.QueueDeclare(queue: "hello",
-                                     durable: false,
+                                     durable: true,
                                      exclusive: false,
                                      autoDelete: false,
                                      arguments: null);
@@ -62,9 +61,11 @@
                     var body = ea.Body;
                     var message = Encoding.UTF8.GetString(body);
                     Console.WriteLine(" [x] Received {0}", message);
+
+                    channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                 };
                 channel.BasicConsume(queue: "hello",
-                                     autoAck: true,
+                                     autoAck: false,
                                      consumer: consumer);

                 Console.WriteLine(" Press [enter] to exit.");