little向けの最適化

little向けの最適化

--- Sources/BrownSugar/Endianness/LittleEndianAny.cs
+++ Sources/BrownSugar/Endianness/LittleEndianAny.cs
@@ -123,7 +123,7 @@

         /// リトルエンディアン順で値を読み込みます
         public static unsafe ulong ToUInt64(byte* b) {
-            if (BitConverter.IsLittleEndian && ((int)b & 7) == 0) {
+            if (((int)b & 7) == 0 && BitConverter.IsLittleEndian) {
                 return *(ulong*)b;
             }
             return
@@ -132,7 +132,7 @@
         }

         public static unsafe long ToInt64(byte* b) {
-            if (BitConverter.IsLittleEndian && ((int)b & 7) == 0) {
+            if (((int)b & 7) == 0 && BitConverter.IsLittleEndian) {
                 return *(long*)b;
             }
             return
@@ -146,7 +146,7 @@
             fixed (byte* fix = buffer)
             {
                 var b = fix + index;
-                if (BitConverter.IsLittleEndian && ((int)b & 7) == 0) {
+                if (((int)b & 7) == 0 && BitConverter.IsLittleEndian) {
                     return *(ulong*)b;
                 }
                 return
@@ -159,7 +159,7 @@
             fixed (byte* fix = buffer)
             {
                 var b = fix + index;
-                if (BitConverter.IsLittleEndian && (index & 7) == 0) {
+                if ((index & 7) == 0 && BitConverter.IsLittleEndian) {
                     return *(long*)b;
                 }
                 return
@@ -170,10 +170,10 @@

         /// リトルエンディアン順で値を読み込みます
         public static unsafe double ToDouble(byte* b) {
-            if (BitConverter.IsLittleEndian && ((int)b & 7) == 0) {
+            if (((int)b & 7) == 0 && BitConverter.IsLittleEndian) {
                 return *(double*)b;
             }
-            var tmp =
+            var tmp =
                 (ulong)(b[7] << 24 | b[6] << 16 | b[5] << 8 | b[4]) << 32 |
                  (uint)(b[3] << 24 | b[2] << 16 | b[1] << 8 | b[0]);
             return *(double*)&tmp;
@@ -184,7 +184,7 @@
             fixed (byte* fix = buffer)
             {
                 var b = fix + index;
-                if (BitConverter.IsLittleEndian && (index & 7) == 0) {
+                if ((index & 7) == 0 && BitConverter.IsLittleEndian) {
                     return *(double*)b;
                 }
                 var tmp =
@@ -293,7 +293,7 @@

         /// リトルエンディアン順でバッファに書き込みます
         public static unsafe void Assign(byte* buffer, ulong value) {
-            if (BitConverter.IsLittleEndian && ((int)buffer & 7) == 0) {
+            if (((int)buffer & 7) == 0 && BitConverter.IsLittleEndian) {
                 *(ulong*)(buffer) = value;
                 return;
             }
@@ -311,7 +311,7 @@

         /// リトルエンディアン順でバッファに書き込みます
         public static unsafe void Assign(byte* buffer, long value) {
-            if (BitConverter.IsLittleEndian && ((int)buffer & 7) == 0) {
+            if (((int)buffer & 7) == 0 && BitConverter.IsLittleEndian) {
                 *(long*)(buffer) = value;
                 return;
             }
@@ -332,7 +332,7 @@
             fixed (byte* fix = buffer)
             {
                 var pointer = fix + index;
-                if (BitConverter.IsLittleEndian && ((int)index & 7) == 0) {
+                if (((int)index & 7) == 0 && BitConverter.IsLittleEndian) {
                     *(long*)pointer = value;
                     return;
                 }
@@ -356,7 +356,7 @@
             fixed (byte* fix = buffer)
             {
                 var pointer = fix + index;
-                if (BitConverter.IsLittleEndian && ((int)index & 7) == 0) {
+                if (((int)index & 7) == 0 && BitConverter.IsLittleEndian) {
                     *(ulong*)pointer = value;
                     return;
                 }
@@ -377,7 +377,7 @@

         /// リトルエンディアン順でバッファに書き込みます
         public static unsafe void Assign(byte* buffer, double value) {
-            if (BitConverter.IsLittleEndian && ((int)buffer & 7) == 0) {
+            if (((int)buffer & 7) == 0 && BitConverter.IsLittleEndian) {
                 *(double*)(buffer) = value;
                 return;
             }
@@ -399,7 +399,7 @@
             fixed (byte* fix = buffer)
             {
                 var pointer = fix + index;
-                if (BitConverter.IsLittleEndian && ((int)index & 7) == 0) {
+                if (((int)index & 7) == 0 && BitConverter.IsLittleEndian) {
                     *(double*)pointer = value;
                     return;
                 }


Change position of buttons

Change position of buttons

--- SpaceBlog/SpaceBlog/Views/Article/Details.cshtml
+++ SpaceBlog/SpaceBlog/Views/Article/Details.cshtml
@@ -32,9 +32,19 @@

+

+

+            @Html.ActionLink("Back", "Index", new { area = "" }, new { @class = "btn-sm btn-primary" })
+
+            @if (User.IsInRole("Administrators") || User.IsInRole("Moderators") || User.Identity.Name == Model.Author.UserName)
+            {
+                @Html.ActionLink("Edit", "Edit", new { id = Model.Id }, new { @class = "btn-sm btn-primary" })
+                @Html.ActionLink("Delete", "Delete", new { id = Model.Id }, new { @class = "btn-sm btn-danger" })
+            }
+

+

+

-
-

Comments

@@ -55,17 +65,6 @@

-
-

-

-        @Html.ActionLink("Back", "Index", new { area = "" }, new { @class = "btn-sm btn-primary" })
-
-        @if (User.IsInRole("Administrators") || User.IsInRole("Moderators") || User.Identity.Name == Model.Author.UserName)
-        {
-        @Html.ActionLink("Edit", "Edit", new { id = Model.Id }, new { @class = "btn-sm btn-primary" })
-            @Html.ActionLink("Delete", "Delete", new { id = Model.Id }, new { @class = "btn-sm btn-danger" })
-        }
-

 @{


Made SpecimenBuilderNodeCollection a bit DRYer.

--- Src/AutoFixture/SpecimenBuilderNodeCollection.cs
+++ Src/AutoFixture/SpecimenBuilderNodeCollection.cs
@@ -30,20 +30,12 @@

         public void Insert(int index, ISpecimenBuilder item)
         {
-            var builders = this.adaptedNode.Insert(index, item);
-            this.graph = this.ReplaceAdaptedWith(this.graph, builders);
-            this.adaptedNode = this.SelectAdaptedNodes(this.graph).Single();
-
-            this.OnGraphChanged(new SpecimenBuilderNodeEventArgs(this.graph));
+            this.Mutate(this.adaptedNode.Insert(index, item));
         }

         public void RemoveAt(int index)
         {
-            var builders = this.adaptedNode.RemoveAt(index);
-            this.graph = this.ReplaceAdaptedWith(this.graph, builders);
-            this.adaptedNode = this.SelectAdaptedNodes(this.graph).Single();
-
-            this.OnGraphChanged(new SpecimenBuilderNodeEventArgs(this.graph));
+            this.Mutate(this.adaptedNode.RemoveAt(index));
         }

         public ISpecimenBuilder this[int index]
@@ -54,29 +46,18 @@
             }
             set
             {
-                var builders = this.adaptedNode.SetItem(index, value);
-                this.graph = this.ReplaceAdaptedWith(this.graph, builders);
-                this.adaptedNode = this.SelectAdaptedNodes(this.graph).Single();
-
-                this.OnGraphChanged(new SpecimenBuilderNodeEventArgs(this.graph));
+                this.Mutate(this.adaptedNode.SetItem(index, value));
             }
         }

         public void Add(ISpecimenBuilder item)
         {
-            var builders = this.adaptedNode.Concat(new[] { item });
-            this.graph = this.ReplaceAdaptedWith(this.graph, builders);
-            this.adaptedNode = this.SelectAdaptedNodes(this.graph).Single();
-
-            this.OnGraphChanged(new SpecimenBuilderNodeEventArgs(this.graph));
+            this.Mutate(this.adaptedNode.Concat(new[] { item }));
         }

         public void Clear()
         {
-            this.graph = this.ReplaceAdaptedWith(this.graph, Enumerable.Empty<ISpecimenBuilder>());
-            this.adaptedNode = this.SelectAdaptedNodes(this.graph).Single();
-
-            this.OnGraphChanged(new SpecimenBuilderNodeEventArgs(this.graph));
+            this.Mutate(Enumerable.Empty<ISpecimenBuilder>());
         }

         public bool Contains(ISpecimenBuilder item)
@@ -131,6 +112,14 @@
                 handler(this, e);
         }

+        private void Mutate(IEnumerable<ISpecimenBuilder> builders)
+        {
+            this.graph = this.ReplaceAdaptedWith(this.graph, builders);
+            this.adaptedNode = this.SelectAdaptedNodes(this.graph).Single();
+
+            this.OnGraphChanged(new SpecimenBuilderNodeEventArgs(this.graph));
+        }
+
         private IEnumerable<ISpecimenBuilderNode> SelectAdaptedNodes(ISpecimenBuilderNode graph)
         {
             if (this.isAdaptedBuilder(graph))


Improve code comment

Improve code comment

--- StackExchange.Profiling/MiniProfiler.Settings.cs
+++ StackExchange.Profiling/MiniProfiler.Settings.cs
@@ -316,9 +316,11 @@
             public static string Version { get; private set; }

             /// <summary>
-            /// The provider used to provider the current instance of a provider
-            /// This is also
-            /// </summary>
+            /// The <see cref="IProfilerProvider"/> class that is used to run MiniProfiler
+            /// </summary>
+            /// <remarks>
+            /// If not set explicitly, will default to <see cref="WebRequestProfilerProvider"/>
+            /// </remarks>
             public static IProfilerProvider ProfilerProvider { get; set; }

             /// <summary>


Began commenting

Began commenting

On my iPad so may be a little wierd

--- TSP/WindowsFormsApplication1/ProblemAndSolver.cs
+++ TSP/WindowsFormsApplication1/ProblemAndSolver.cs
@@ -836,7 +836,7 @@
             List<List<Link>> routes = new List<List<Link>>();

-
+          //create the initial population.  Population number of random routes and a greedy route for each city
             //Making a bad assumption that default won't return the best solution because that requires rewriting the defaul method
             for(int i = routes.Count; i< population; i++)
             {
@@ -850,6 +850,7 @@
                 TSPSolution tsp = GreedyImplementation(i);
                 if ((tsp.costOfRoute()) < bestDistance)
                 {
+                    //if the found path is awesome, save it as the current best
                     GlobalBest = Linkify(tsp);
                     bestDistance = tsp.costOfRoute();
                     totalUpdates++;
@@ -876,17 +877,19 @@
             int sortPosition;
             int tempIndex;

+            //we used a timer to determine when to stop searching.  We could also have used a number of created generations,
+            //a number of generations without change, or when a certain degree of improvement has been reached
             while (fancyTimer.Elapsed < timeLimit)
             {
-

                 GrabRandom = new List<int>();

                 distances = new List<double>();

+              //create a selected population of which we will choose our breeders.
                 for (int i = 0; i < randomnums; i++)
                 {
-                    GrabRandom.Add(rand.Next(population));
+                    GrabRandom.Add(rand.Next(routes.Count));
                     ls = routes[GrabRandom[i]];
                     distance = 0;
                     for (int j = 0; j < Cities.Length; j++)
@@ -897,7 +900,9 @@
                 }

                 //sorting here because copying the GrabRandom array and giant routes array was ridiculous
-
+                //routes is unsourced so we need to sort GrabRandom in order to discover the best two solutions
+                //we chose bubble sort because that is what our predessors used and it is fine for such a small sample, if
+                //our selection size was larger we would probably want to switch to a quick or merge sort
                 sortedRandom = new List<int>();
                 for (int i = 0; i < randomnums; i++)
                 {
@@ -932,13 +937,16 @@
                 GrabRandom = sortedRandom;

-                //make the first child
+                //make the first child by crossing the 2 parents (best tsp solutions in our selection)
                 child = crossOver(routes[GrabRandom[0]], routes[GrabRandom[1]], rand);
+
+                // mutation percent of the time we will mutate the child in hopes of getting something better.
                 if (rand.Next(100) < mutation)
                 {
                     Mutate(child, rand);
                 }

+                //determine how good the child was.  If it is better then the worst of the selection, then it replaces it
                 worst = routes[GrabRandom[GrabRandom.Count - 1]];
                 childDistance = 0.0;
                 worstDistance = 0.0;
@@ -968,7 +976,9 @@

                 }

+
                 //crossover again switching order of parents
+                //and if the last child was better then a parent it is used in the crossover instead
                 child = crossOver(routes[GrabRandom[1]], routes[GrabRandom[0]], rand);
                 if (rand.Next(100) < mutation)
                 {
@@ -1005,6 +1015,7 @@
             return results;
         }

+        //a method to take our list of links to calculate the route and determine fitness
         private double routeCost(List<Link> route)
         {
             double distance = 0;
@@ -1015,6 +1026,8 @@
             return distance;
         }

+        //sometime creating routes makes out of whack lists that make route calculation difficult, this method
+        //puts them in order where a,b is followed by b,c followed by c,d etc.
         private List<Link> createList(List<Link> route)
         {
             List<Link> ordered = new List<Link>();


Fix missin ctrl key modifier in new mission

--- TacticalAdvanceMissionBuilder/MainWindow.xaml.cs
+++ TacticalAdvanceMissionBuilder/MainWindow.xaml.cs
@@ -434,7 +434,10 @@
             }
             else if (e.Key == Key.N)
             {
-                this.NewButtonClick(sender, new RoutedEventArgs());
+                if (Keyboard.IsKeyDown(Key.LeftCtrl))
+                {
+                    this.NewButtonClick(sender, new RoutedEventArgs());
+                }
             }
         }


Fix type printing of typedef qualifiers in C++ type printer.

--- src/Generator/Generators/C/CppTypePrinter.cs
+++ src/Generator/Generators/C/CppTypePrinter.cs
@@ -204,9 +204,15 @@
             if (ResolveTypedefs && !typedef.Declaration.Type.IsPointerTo(out func))
             {
                 TypePrinterResult type = typedef.Declaration.QualifiedType.Visit(this);
-                return new TypePrinterResult { Type = $"{qual}{type.Type}", NamePrefix = type.NamePrefix, NameSuffix = type.NameSuffix };
-            }
-            return $"{qual}{typedef.Declaration.Visit(this)}";
+                return new TypePrinterResult { Type = $"{qual}{type.Type}",
+                    NamePrefix = type.NamePrefix, NameSuffix = type.NameSuffix };
+            }
+
+            var result = typedef.Declaration.Visit(this);
+            if (result.NamePrefix.Length > 0)
+                result.NamePrefix.Append($"{qual}");
+
+            return result;
         }

         public override TypePrinterResult VisitAttributedType(AttributedType attributed,


Use var instead.

Use var instead.


test coverage

test coverage

--- Frost/Rectangle.cs
+++ Frost/Rectangle.cs
@@ -439,6 +439,9 @@
 			Assert.True(FromCorners(0, 0, 1, 1).Contains(FromCorners(0.5f, 0, 0.5f, 1)));
 			Assert.False(FromCorners(0, 0, 1, 1).Contains(FromCorners(-1, -1, 1, 1)));

+			Assert.Equal(new Rectangle(2, 2, 05, 05), new Rectangle(0, 0, 5, 5).Translate(new Size(2)));
+			Assert.Equal(new Rectangle(0, 0, 10, 10), new Rectangle(0, 0, 5, 5).Scale(new Size(2)));
+
 			Assert.TestObject(MinValue, MaxValue);
 		}


improved performance of claim service

improved performance of claim service


Comments

Comments


Add NFluent-like versions

Add NFluent-like versions

--- src/Pickles/Pickles.Test/AssertExtensions.cs
+++ src/Pickles/Pickles.Test/AssertExtensions.cs
@@ -2,6 +2,7 @@
 using System.Linq;
 using System.Xml.Linq;
 using NFluent;
+using NFluent.Extensibility;
 using NUnit.Framework;
 using PicklesDoc.Pickles.Test.Extensions;

@@ -9,12 +10,26 @@
 {
     public static class AssertExtensions
     {
+        public static void HasAttribute(this ICheck<XElement> check, string name, string value)
+        {
+            var actual = ExtensibilityHelper.ExtractChecker(check).Value;
+
+            ShouldHaveAttribute(actual, name, value);
+        }
+
         public static void ShouldHaveAttribute(this XElement element, string name, string value)
         {
             XAttribute xAttribute = element.Attributes().FirstOrDefault(attribute => attribute.Name.LocalName == name);
             Check.That(xAttribute).IsNotNull();
             // ReSharper disable once PossibleNullReferenceException
             Check.That(xAttribute.Value).IsEqualTo(value);
+        }
+
+        public static void HasElement(this ICheck<XElement> check, string name)
+        {
+          var actual = ExtensibilityHelper.ExtractChecker(check).Value;
+
+          ShouldHaveElement(actual, name);
         }

         public static void ShouldHaveElement(this XElement element, string name)


TypeFields

TypeFields

- runtime fields not listed

--- src/Runtime/pchpcor/Reflection/TypeFields.cs
+++ src/Runtime/pchpcor/Reflection/TypeFields.cs
@@ -73,7 +73,7 @@
             return getter;
         }

-        static Func<FieldInfo, bool> _IsAllowedField = f => ReflectionUtils.IsAllowedPhpName(f.Name);
+        static Func<FieldInfo, bool> _IsAllowedField = f => ReflectionUtils.IsAllowedPhpName(f.Name) && !ReflectionUtils.IsRuntimeFields(f);
         static Func<FieldInfo, string> _FieldName = f => f.Name;
         static Func<PropertyInfo, string> _PropertyName = p => p.Name;

@@ -83,6 +83,7 @@
             Debug.Assert(_statics.IsNested);

             var getter = BinderHelpers.GetStatic_T_Method(_statics);    // ~ Context.GetStatics<_statics>, in closure
+            // TODO: getter.CreateDelegate
             return ctx => getter.Invoke(ctx, ArrayUtils.EmptyObjects);
         }


rephrased description of local context checking

--- osu.Game/Beatmaps/BeatmapStore.cs
+++ osu.Game/Beatmaps/BeatmapStore.cs
@@ -34,12 +34,14 @@

             foreach (var beatmap in beatmapSet.Beatmaps.Where(b => b.Metadata != null))
             {
-                // check local context for metadata so we can reuse duplicates from the same set
+                // If we detect a new metadata object it'll be attached to the current context so it can be reused
+                // to prevent duplicate entries when persisting. To accomplish this we look in the cache (.Local)
+                // of the corresponding table (.Set<BeatmapMetadata>()) for matching entries to our criteria.
                 var contextMetadata = context.Set<BeatmapMetadata>().Local.SingleOrDefault(e => e.Equals(beatmap.Metadata));
                 if (contextMetadata != null)
                     beatmap.Metadata = contextMetadata;
                 else
-                    context.BeatmapMetadata.Attach(beatmap.Metadata); // adding new to context
+                    context.BeatmapMetadata.Attach(beatmap.Metadata);
             }

             context.BeatmapSetInfo.Attach(beatmapSet);


Fix typo

Fix typo

--- osu.Game/Database/OsuDbContext.cs
+++ osu.Game/Database/OsuDbContext.cs
@@ -180,7 +180,7 @@
         {
             try
             {
-                // will fail if the database isn't in a sane EF-migradted state.
+                // will fail if the database isn't in a sane EF-migrated state.
                 Database.ExecuteSqlCommand("SELECT MetadataID FROM BeatmapSetInfo LIMIT 1");
             }
             catch


Typo.

Typo.

--- osu.Game/Overlays/MedalOverlay.cs
+++ osu.Game/Overlays/MedalOverlay.cs
@@ -37,7 +37,7 @@
         private readonly Container backgroundStrip, particleContainer;
         private readonly BackgroundStrip leftStrip, rightStrip;
         private readonly CircularContainer disc;
-        private readonly Sprite innerSpin, outterSpin;
+        private readonly Sprite innerSpin, outerSpin;
         private DrawableMedal drawableMedal;

         private SampleChannel getSample;
@@ -56,7 +56,7 @@
                     RelativeSizeAxes = Axes.Both,
                     Colour = Color4.Black.Opacity(60),
                 },
-                outterSpin = new Sprite
+                outerSpin = new Sprite
                 {
                     Anchor = Anchor.Centre,
                     Origin = Anchor.Centre,
@@ -149,7 +149,7 @@
         private void load(OsuColour colours, TextureStore textures, AudioManager audio)
         {
             getSample = audio.Sample.Get(@"MedalSplash/medal-get");
-            innerSpin.Texture = outterSpin.Texture = textures.Get(@"MedalSplash/disc-spin");
+            innerSpin.Texture = outerSpin.Texture = textures.Get(@"MedalSplash/disc-spin");

             disc.EdgeEffect = leftStrip.EdgeEffect = rightStrip.EdgeEffect = new EdgeEffectParameters
             {
@@ -216,11 +216,11 @@
             };

             outerRotate.Loop(0);
-            outterSpin.Transforms.Add(outerRotate);
+            outerSpin.Transforms.Add(outerRotate);

             disc.FadeIn(duration1);
             particleContainer.FadeIn(duration1);
-            outterSpin.FadeTo(0.1f, duration1 * 2);
+            outerSpin.FadeTo(0.1f, duration1 * 2);
             disc.ScaleTo(1f, duration1 * 2, EasingTypes.OutElastic);

             Delay(duration1 + 200, true);


Inline complete method as well

Inline complete method as well

For better guarantees that `finalAction` is actually called on the same
screen that `checkCanComplete()` was (uses result of one
`getCurrentScreen()` call throughout instead of calling multiple times).

--- osu.Game/PerformFromMenuRunner.cs
+++ osu.Game/PerformFromMenuRunner.cs
@@ -84,7 +84,8 @@
             // we may already be at the target screen type.
             if (validScreens.Contains(current.GetType()) && !beatmap.Disabled)
             {
-                complete();
+                finalAction(current);
+                Cancel();
                 return;
             }

@@ -138,11 +139,5 @@
             lastEncounteredDialogScreen = current;
             return true;
         }
-
-        private void complete()
-        {
-            finalAction(getCurrentScreen());
-            Cancel();
-        }
     }
 }


Minor style fixes.

Minor style fixes.

--- osu.Game/Screens/Menu/MainMenu.cs
+++ osu.Game/Screens/Menu/MainMenu.cs
@@ -105,14 +105,16 @@
             base.OnEntering(last);
             buttons.FadeInFromZero(500);
             if (last is Intro && song != null)
+            {
                 Task.Run(() =>
                 {
                     trackManager.SetExclusive(song.Track);
                     song.Track.Seek(song.Beatmap.Metadata.PreviewTime);
                     if (song.Beatmap.Metadata.PreviewTime == -1)
-                        song.Track.Seek(song.Track.Length * .4f);
+                        song.Track.Seek(song.Track.Length * 0.4f);
                     song.Track.Start();
                 });
+            }
         }

         protected override void OnSuspending(Screen next)


Use skia ArcTo method

Use skia ArcTo method

--- src/Skia/Avalonia.Skia/StreamGeometryImpl.cs
+++ src/Skia/Avalonia.Skia/StreamGeometryImpl.cs
@@ -104,7 +104,15 @@

             public void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection)
             {
-                ArcToHelper.ArcTo(this, _currentPoint, point, size, rotationAngle, isLargeArc, sweepDirection);
+                _path.ArcTo(
+                    (float)size.Width,
+                    (float)size.Height,
+                    (float)rotationAngle,
+                    isLargeArc ? SKPathArcSize.Large : SKPathArcSize.Small,
+                    sweepDirection == SweepDirection.Clockwise ? SKPathDirection.Clockwise : SKPathDirection.CounterClockwise,
+                    (float)point.X,
+                    (float)point.Y);
+                _currentPoint = point;
             }

             public void BeginFigure(Point startPoint, bool isFilled)


Fix things where resharper mistakenly mis-identifies

the !isWhisper parameter as redundant.

--- TwitchPlaysAssembly/Src/Helpers/IRCConnection.cs
+++ TwitchPlaysAssembly/Src/Helpers/IRCConnection.cs
@@ -610,122 +610,82 @@
 	}

 	[StringFormatMethod("message")]
-	public static void SendChatMessage(string message)
+	public static void SendChatMessage(string message, params object[] args)
+	{
+		SendMessage(message, args);
+	}
+
+	//NOTE: whisper mode is not fully supported, as bots need to be registered with twitch to take advantage of it.
+	[StringFormatMethod("message")]
+	public static void SendWhisper(string userNickName, string message, params object[] args)
+	{
+		SendMessage(message, userNickName, false, args);
+	}
+
+	[StringFormatMethod("message")]
+	public static void SendMessage(string message, params object[] args)
+	{
+		SendMessage(string.Format(message, args));
+	}
+
+	[StringFormatMethod("message")]
+	public static void SendMessage(string message, string userNickName, bool sendToChat, params object[] args)
+	{
+		SendMessage(string.Format(message, args), userNickName, sendToChat);
+	}
+
+	public static void ToggleSilenceMode()
 	{
 		if (Instance == null) return;
+		if (!Instance._silenceMode)
+		{
+			Instance.SendCommand(string.Format("PRIVMSG #{0} :Silence mode on.", Instance._settings.channelName));
+			lock (Instance._messageQueue)
+			{
+				Instance._messageQueue.Enqueue(new Message(Instance.UserNickName, Instance.CurrentColor, "Silence mode on.", false, true));
+			}
+		}
+		Instance._silenceMode = !Instance._silenceMode;
+		if (!Instance._silenceMode)
+		{
+			Instance.SendCommand($"PRIVMSG #{Instance._settings.channelName} :Silence mode off.");
+			lock (Instance._messageQueue)
+			{
+				Instance._messageQueue.Enqueue(new Message(Instance.UserNickName, Instance.CurrentColor, "Silence mode off.", false, true));
+			}
+		}
+	}
+
+	public static Color GetUserColor(string userNickName)
+	{
+		if (Instance == null) return Color.black;
+		lock (Instance._userColors)
+		{
+			return Instance._userColors.TryGetValue(userNickName, out Color color) ? color : Color.black;
+		}
+	}
+	#endregion
+
+	#region Private Methods
+	private static void SendMessage(string message, string userNickName = null, bool sendToChat = true)
+	{
+		if (Instance == null) return;
+
+		sendToChat |= !IsUsernameValid(userNickName) || !TwitchPlaySettings.data.EnableWhispers || userNickName == Instance.UserNickName;
 		foreach (string line in message.Wrap(MaxMessageLength).Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries))
 		{
 			if (!Instance._silenceMode && Instance._state != IRCConnectionState.Disconnected)
-				Instance.SendCommand(string.Format("PRIVMSG #{0} :{1}", Instance._settings.channelName, line));
+				Instance.SendCommand(sendToChat
+					? $"PRIVMSG #{Instance._settings.channelName} :{line}"
+					: $"PRIVMSG #{Instance._settings.channelName} :.w {userNickName} {line}");
 			if (line.StartsWith(".") || line.StartsWith("/")) continue;
 			lock (Instance._messageQueue)
 			{
-				Instance._messageQueue.Enqueue(new Message(Instance.UserNickName, Instance.CurrentColor, line, false, true));
-			}
-		}
-	}
-
-	[StringFormatMethod("message")]
-	public static void SendChatMessage(string message, params object[] args)
-	{
-		SendMessage(string.Format(message, args));
-	}
-
-	[StringFormatMethod("message")]
-	public static void SendMessage(string message, params object[] args)
-	{
-		SendMessage(string.Format(message, args));
-	}
-
-	[StringFormatMethod("message")]
-	public new static void SendMessage(string message, object arg)
-	{
-		SendMessage(string.Format(message, arg));
-	}
-
-	[StringFormatMethod("message")]
-	public new static void SendMessage(string message)
-	{
-		SendMessage(message, null, true);
-	}
-
-	[StringFormatMethod("message")]
-	public static void SendMessage(string message, string userNickName, bool sendToChat)
-	{
-		if (Instance == null) return;
-		if (sendToChat || string.IsNullOrEmpty(userNickName) || !TwitchPlaySettings.data.EnableWhispers || userNickName == Instance.UserNickName) //can't send whispers to yourself
-		{
-			SendChatMessage(message);
-		}
-		else
-		{
-			SendWhisper(userNickName, message);
-		}
-	}
-
-	[StringFormatMethod("message")]
-	public static void SendMessage(string message, string userNickName, bool sendToChat, params object[] args)
-	{
-		SendMessage(string.Format(message, args), userNickName, sendToChat);
-	}
-
-	//NOTE: whisper mode is not fully supported, as bots need to be registered with twitch to take advantage of it.
-	[StringFormatMethod("message")]
-	public static void SendWhisper(string userNickName, string message)
-	{
-		if (Instance == null) return;
-		foreach (string line in message.Wrap(MaxMessageLength).Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries))
-		{
-			if (!Instance._silenceMode && Instance._state != IRCConnectionState.Disconnected)
-				Instance.SendCommand(string.Format("PRIVMSG #{0} :.w {1} {2}", Instance._settings.channelName, userNickName, line));
-			if (line.StartsWith(".") || line.StartsWith("/")) continue;
-			lock (Instance._messageQueue)
-			{
-				Instance._messageQueue.Enqueue(new Message(Instance.UserNickName, Instance.CurrentColor, line, true, true));
-			}
-		}
-	}
-
-	[StringFormatMethod("message")]
-	public static void SendWhisper(string userNickName, string message, params object[] args)
-	{
-		SendWhisper(userNickName, string.Format(message, args));
-	}
-
-
-	public static void ToggleSilenceMode()
-	{
-		if (Instance == null) return;
-		if (!Instance._silenceMode)
-		{
-			Instance.SendCommand(string.Format("PRIVMSG #{0} :Silence mode on.", Instance._settings.channelName));
-			lock (Instance._messageQueue)
-			{
-				Instance._messageQueue.Enqueue(new Message(Instance.UserNickName, Instance.CurrentColor, "Silence mode on.", false, true));
-			}
-		}
-		Instance._silenceMode = !Instance._silenceMode;
-		if (!Instance._silenceMode)
-		{
-			Instance.SendCommand(string.Format("PRIVMSG #{0} :Silence mode off.", Instance._settings.channelName));
-			lock (Instance._messageQueue)
-			{
-				Instance._messageQueue.Enqueue(new Message(Instance.UserNickName, Instance.CurrentColor, "Silence mode off.", false, true));
-			}
-		}
-	}
-
-	public static Color GetUserColor(string userNickName)
-	{
-		if (Instance == null) return Color.black;
-		lock (Instance._userColors)
-		{
-			return Instance._userColors.TryGetValue(userNickName, out Color color) ? color : Color.black;
-		}
-	}
-	#endregion
-
-	#region Private Methods
+				Instance._messageQueue.Enqueue(new Message(Instance.UserNickName, Instance.CurrentColor, line, !sendToChat, true));
+			}
+		}
+	}
+
 	private void SetOwnColor()
 	{
 		if (!ColorUtility.TryParseHtmlString(CurrentColor, out Color color)) return;


Fix a crash when renaming a file in a folder with path length > ~255 characters Fixes canton7/SyncTrayzor#72


Prevent messages from getting stuck and not being executed until more messages came in

--- TwitchPlaysAssembly/Src/Helpers/IRCConnection.cs
+++ TwitchPlaysAssembly/Src/Helpers/IRCConnection.cs
@@ -471,6 +471,19 @@
 		Instance.StartCoroutine(Instance._keepConnectionAlive);
 	}

+	/// <summary>
+	/// A NetworkStream that doesn't block if there is no data to read from the network.
+	/// This means the "end of the stream" indicates there is no data to read from the network.
+	/// </summary>
+	class AsyncNetworkStream : NetworkStream
+	{
+		public AsyncNetworkStream(TcpClient tcpClient) : base(tcpClient.Client, true)
+		{
+		}
+
+		public override int Read(byte[] buffer, int offset, int count) => !base.DataAvailable ? 0 : base.Read(buffer, offset, count);
+	}
+
 	private void ConnectToIRC()
 	{
 		_state = IRCConnectionState.Connecting;
@@ -489,7 +502,7 @@

 			AddTextToHoldable("[IRC:Connect] Connection to chat IRC successful.");

-			NetworkStream networkStream = sock.GetStream();
+			AsyncNetworkStream networkStream = new AsyncNetworkStream(sock);
 			try
 			{
 				AddTextToHoldable("[IRC:Connect] Attempting to set up SSL connection.");
@@ -510,8 +523,7 @@
 					return;
 				}

-				NetworkStream stream = networkStream;
-				_inputThread = new Thread(() => InputThreadMethod(inputStream, stream));
+				_inputThread = new Thread(() => InputThreadMethod(inputStream));
 				_inputThread.Start();

 				_outputThread = new Thread(() => OutputThreadMethod(outputStream));
@@ -527,7 +539,7 @@
 				DebugHelper.LogException(ex, "An Exception has occurred when attempting to connect using SSL, using insecure stream instead:");
 				_settings.serverPort = 6667;
 				sock = new TcpClient(_settings.serverName, _settings.serverPort);
-				networkStream = sock.GetStream();
+				networkStream = new AsyncNetworkStream(sock);
 				StreamReader inputStream = new StreamReader(networkStream);
 				StreamWriter outputStream = new StreamWriter(networkStream);

@@ -539,7 +551,7 @@
 					return;
 				}

-				_inputThread = new Thread(() => InputThreadMethod(inputStream, networkStream));
+				_inputThread = new Thread(() => InputThreadMethod(inputStream));
 				_inputThread.Start();

 				_outputThread = new Thread(() => OutputThreadMethod(outputStream));
@@ -739,7 +751,7 @@
 	}

 	private int ConnectionTimeout => _state == IRCConnectionState.Connected ? 360000 : 30000;
-	private void InputThreadMethod(TextReader input, NetworkStream networkStream)
+	private void InputThreadMethod(StreamReader input)
 	{
 		bool pingTimeoutTest = false; // Keeps track of if we are currently in a ping timeout test.
 		Stopwatch stopwatch = new Stopwatch();
@@ -774,7 +786,7 @@
 					}
 				}

-				if (!networkStream.DataAvailable)
+				if (input.EndOfStream)
 				{
 					Thread.Sleep(25);
 					continue;


fixes.

fixes.

--- src/TWCore/Serialization/SerializedObject.cs
+++ src/TWCore/Serialization/SerializedObject.cs
@@ -314,9 +314,48 @@
         {
             if (sequence.IsEmpty) return null;
             var length = sequence.Length;
-            Span<byte> lengthSpan = stackalloc byte[4];
+            byte[] dataArray = null;
             string dataType = null;
             string mimeType = null;
+
+#if NETSTANDARD2_0
+            var lengthBytes = new byte[4];
+
+            sequence.Slice(0, 4).CopyTo(lengthBytes);
+            var dtLength = BitConverter.ToInt32(lengthBytes, 0);
+            if (dtLength < -1 || dtLength > length) return null;
+            if (dtLength != -1)
+            {
+                var buffer = new byte[dtLength];
+                sequence.Slice(4, dtLength).CopyTo(buffer);
+                dataType = Encoding.UTF8.GetString(buffer);
+                length -= dtLength;
+                sequence = sequence.Slice(4 + dtLength);
+            }
+
+            sequence.Slice(0, 4).CopyTo(lengthBytes);
+            var smtLength = BitConverter.ToInt32(lengthBytes, 0);
+            if (smtLength < -1 || smtLength > length) return null;
+            if (smtLength != -1)
+            {
+                var buffer = new byte[smtLength];
+                sequence.Slice(4, smtLength).CopyTo(buffer);
+                mimeType = Encoding.UTF8.GetString(buffer);
+                length -= smtLength;
+                sequence = sequence.Slice(4 + smtLength);
+            }
+
+            sequence.Slice(0, 4).CopyTo(lengthBytes);
+            var dataLength = BitConverter.ToInt32(lengthBytes, 0);
+            if (dataLength < -1 || dataLength > length) return null;
+            if (dataLength != -1)
+            {
+                dataArray = new byte[dataLength];
+                var dSpan = dataArray.AsSpan();
+                sequence.Slice(4, dataLength).CopyTo(dSpan);
+            }
+#else
+            Span<byte> lengthSpan = stackalloc byte[4];

             sequence.Slice(0, 4).CopyTo(lengthSpan);
             var dtLength = BitConverter.ToInt32(lengthSpan);
@@ -345,13 +384,13 @@
             sequence.Slice(0, 4).CopyTo(lengthSpan);
             var dataLength = BitConverter.ToInt32(lengthSpan);
             if (dataLength < -1 || dataLength > length) return null;
-            byte[] dataArray = null;
             if (dataLength != -1)
             {
                 dataArray = new byte[dataLength];
                 var dSpan = dataArray.AsSpan();
                 sequence.Slice(4, dataLength).CopyTo(dSpan);
             }
+#endif

             return new SerializedObject(dataArray, dataType, mimeType);
         }


(FormatCatalog): images are prioritized over archives in format lookups.

--- GameRes/GameRes.cs
+++ GameRes/GameRes.cs
@@ -305,8 +305,8 @@

             //Fill the imports of this object
             container.ComposeParts (this);
+            AddResourceImpl (m_image_formats);
             AddResourceImpl (m_arc_formats);
-            AddResourceImpl (m_image_formats);
             AddResourceImpl (m_audio_formats);
             AddResourceImpl (m_script_formats);
         }


- Modified exception handling on unknown errors when writing monolithic output

--- GenProc/Program.cs
+++ GenProc/Program.cs
@@ -410,7 +410,12 @@
 				}
 				catch (UnauthorizedAccessException ex)
 				{
-					Logger.Error("Could not access output file: ({0}) {1}", ex.GetType().Name, ex.Message);
+					Logger.Error("Could not access output file: {0}", ex.Message);
+					return Return.FileAccess;
+				}
+				catch (Exception ex)
+				{
+					Logger.Error("Unknown error: ({0}) {1}", ex.GetType().Name, ex.Message);
 					return Return.FileAccess;
 				}
 			}


fix for filtered requests

fix for filtered requests

--- Ve.Metrics.StatsDClient.WebForms/StatsDModule.cs
+++ Ve.Metrics.StatsDClient.WebForms/StatsDModule.cs
@@ -43,17 +43,20 @@
                 if (fileExtension != null && fileExtension.Equals(".aspx"))
                 {
                     var stopwatch = (Stopwatch)context.Items[StopwatchKey];
-                    stopwatch.Stop();
+                    if (stopwatch != null)
+                    {
+                        stopwatch.Stop();

-                    var hasException = false;
-                    if (context.Error != null)
-                    {
-                        hasException = true;
-                        Statsd.LogCount("exceptions", GetRouteData(context, hasException));
+                        var hasException = false;
+                        if (context.Error != null)
+                        {
+                            hasException = true;
+                            Statsd.LogCount("exceptions", GetRouteData(context, hasException));
+                        }
+
+                        Statsd.LogCount("request", GetRouteData(context, hasException));
+                        Statsd.LogTiming("responses", stopwatch.ElapsedMilliseconds, GetRouteData(context, hasException));
                     }
-
-                    Statsd.LogCount("request", GetRouteData(context, hasException));
-                    Statsd.LogTiming("responses", stopwatch.ElapsedMilliseconds, GetRouteData(context, hasException));
                 }
             }
         }


LocalizedString: Ignore empty translated values in Merge

Fixes a bug merging translated strings between a POT with 2 plurals
and a PO with 1 plural.  Merge was choosing the two empty translations
over the single real translation.

--- Vernacular.Catalog/Vernacular/LocalizedString.cs
+++ Vernacular.Catalog/Vernacular/LocalizedString.cs
@@ -27,6 +27,7 @@
 using System;
 using System.Text;
 using System.Collections.Generic;
+using System.Linq;

 namespace Vernacular
 {
@@ -132,8 +133,13 @@
                 TranslatorComments = Join (a.TranslatorComments, b.TranslatorComments)
             };

-            var a_translated = new List<string> (a.TranslatedValues ?? new string [0]);
-            var b_translated = new List<string> (b.TranslatedValues ?? new string [0]);
+            var a_translated = a.TranslatedValues != null ?
+                a.TranslatedValues.Where (tr => !String.IsNullOrEmpty (tr)).ToList<string> () :
+                new List<string> ();
+
+            var b_translated = b.TranslatedValues != null ?
+                b.TranslatedValues.Where (tr => !String.IsNullOrEmpty (tr)).ToList<string> () :
+                new List<string> ();

             if (b_translated.Count >= a_translated.Count) {
                 a_translated = b_translated;


add volume control

add volume control

--- ivrToolkit.DialogicPlugin/DialogicDef.cs
+++ ivrToolkit.DialogicPlugin/DialogicDef.cs
@@ -217,6 +217,22 @@
             SC_HALFDUP = 0x01
         }

+        private const ushort SV_SPEEDTBL = 0x01;    /* Modify Speed */
+        private const ushort SV_VOLUMETBL = 0x02;   /* Modify Volume */
+
+        private const ushort SV_ABSPOS = 0x00;      /* Absolute Position */
+        private const ushort SV_RELCURPOS = 0x10;   /* Relative to Current Position */
+        private const ushort SV_TOGGLE = 0x20;      /* Toggle */
+
+        private const ushort SV_WRAPMOD = 0x0010;
+        private const ushort SV_SETDEFAULT = 0x0020;
+        private const ushort SV_LEVEL = 0x0100;
+        private const ushort SV_BEGINPLAY = 0x0200;
+
+        private const ushort SV_TOGORIGIN = 0x00;    /* Toggle Between Origin and Last Modified Position */
+        private const ushort SV_CURORIGIN = 0x01;    /* Reset Current Position to Origin */
+        private const ushort SV_CURLASTMOD = 0x02;   /* Reset Current Position to Last Modified Position */
+        private const ushort SV_RESETORIG = 0x03;    /* Reset Current Position and Last Modified State to Origin */

         [StructLayoutAttribute(LayoutKind.Sequential)]
         public struct DX_CST
@@ -699,6 +715,10 @@
         private static extern int dx_distone(int chdev, int toneid, int evt_mask);

         [DllImport("LIBDXXMT.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
+        private static extern int dx_adjsv( int chdev, ushort tabletype, ushort action, ushort adjsize );
+
+
+        [DllImport("LIBDXXMT.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
         private static extern int dx_enbtone(int chdev, int toneid, int evt_mask);

         [DllImport("LIBDXXMT.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]


Remove unecessary string null check - the culture ext in mapping code will deal with this

--- src/Umbraco.Web/Editors/ContentController.cs
+++ src/Umbraco.Web/Editors/ContentController.cs
@@ -494,10 +494,7 @@
                 Mapper.Map<IContent, ContentItemBasic<ContentPropertyBasic>>(content,
                     opts =>
                     {
-                        if(string.IsNullOrEmpty(cultureName) == false)
-                        {
-                            opts.Items[ResolutionContextExtensions.CultureKey] = cultureName;
-                        }
+                        opts.Items[ResolutionContextExtensions.CultureKey] = cultureName;

                         // if there's a list of property aliases to map - we will make sure to store this in the mapping context.
                         if (string.IsNullOrWhiteSpace(includeProperties) == false)


Fixed #1

Fixed #1

--- src/Velyo.Web.Security/XmlProfileProvider.cs
+++ src/Velyo.Web.Security/XmlProfileProvider.cs
@@ -333,18 +333,19 @@
                 if (!string.IsNullOrEmpty(username)) {
                     XmlProfile profile = this.GetProfile(username);

+                    foreach (SettingsProperty prop in collection) {
+                        if (prop.SerializeAs == SettingsSerializeAs.ProviderSpecific) {
+                            if (prop.PropertyType.IsPrimitive || (prop.PropertyType == typeof(string))) {
+                                prop.SerializeAs = SettingsSerializeAs.String;
+                            }
+                            else {
+                                prop.SerializeAs = SettingsSerializeAs.Xml;
+                            }
+                        }
+                        coll.Add(new SettingsPropertyValue(prop));
+                    }
+
                     if (profile != null) {
-                        foreach (SettingsProperty prop in collection) {
-                            if (prop.SerializeAs == SettingsSerializeAs.ProviderSpecific) {
-                                if (prop.PropertyType.IsPrimitive || (prop.PropertyType == typeof(string))) {
-                                    prop.SerializeAs = SettingsSerializeAs.String;
-                                }
-                                else {
-                                    prop.SerializeAs = SettingsSerializeAs.Xml;
-                                }
-                            }
-                            coll.Add(new SettingsPropertyValue(prop));
-                        }
                         GetPropertyValues(profile.Names, profile.ValuesString, profile.ValuesBinary, coll);
                     }
                 }


Add another retry

Add another retry

--- tests/Foundatio.Tests/Jobs/JobTests.cs
+++ tests/Foundatio.Tests/Jobs/JobTests.cs
@@ -10,6 +10,7 @@
 using Foundatio.Metrics;
 using Foundatio.Utility;
 using Microsoft.Extensions.Logging;
+using xRetry;
 using Xunit;
 using Xunit.Abstractions;

@@ -105,7 +106,7 @@
             }
         }

-        [Fact]
+        [RetryFact]
         public async Task CanRunJobsWithLocks() {
             var job = new WithLockingJob(Log);
             Assert.Equal(0, job.RunCount);


Add #region

Add #region

coverd UnCompletedCount by region.

--- WhatNeedToBeDone/ViewModels/TodoListViewModel.cs
+++ WhatNeedToBeDone/ViewModels/TodoListViewModel.cs
@@ -21,8 +21,8 @@
 		}
 		#endregion

+		#region UnCompletedCount 変更通知プロパティ
 		private int _UnCompletedCount;
-
 		public int UnCompletedCount
 		{
 			get { return _UnCompletedCount; }
@@ -32,7 +32,7 @@
 				this.RaisePropertyChanged("UnCompletedCount");
 			}
 		}
-
+		#endregion

 		public ObservableCollection<Todo> Todos { get; set; }


Added Alpha, Vertex Identity

Added Alpha, Vertex Identity

--- Graphics/Vertex.cs
+++ Graphics/Vertex.cs
@@ -11,8 +11,8 @@
     {

         public float X, Y, Z;      // Position
-        public float R, G, B;      // Color
-        public float NX, NY, NZ;   // Normal
+        public float R, G, B, A;      // Color
+        public float Nx, Ny, Nz;   // Normal
         public float Tx, Ty;       // Texture

         #region Readonly
@@ -21,7 +21,15 @@
         public static readonly Vertex UnitX = new Vertex(1, 0);
         public static readonly Vertex UnitY = new Vertex(0, 1);
         public static readonly Vertex One   = new Vertex(1, 1);
-        public static readonly int    Stride  = 44;
+		public static readonly Vertex[] Identity =
+		{
+			Zero,
+			UnitX,
+			One,
+			UnitY
+		};
+
+		public static readonly int Stride = 48;

         #endregion Readonly

@@ -40,10 +48,11 @@
             R = 0f;
             G = 0f;
             B = 0f;
+			A = 1f;

-            NX = 0f;
-            NY = 0f;
-            NZ = 1f;
+            Nx = 0f;
+            Ny = 0f;
+            Nz = 1f;

             Tx = 0f;
             Ty = 0f;


Change assertion to Equals

Change assertion to Equals

Equals gives feedback on the changes, True won't, making it hard to figure
out was is wrong

--- tests/NLog.UnitTests/Common/InternalLoggerTests.cs
+++ tests/NLog.UnitTests/Common/InternalLoggerTests.cs
@@ -338,7 +338,7 @@
                     expectedDateTime + " Debug DDD\n" +
                     expectedDateTime + " Info III\n";

-            Assert.True(consoleOutWriter.ToString() == expected);
+            Assert.Equal(expected, consoleOutWriter.ToString());
         }
 #endif
     }


添加备份时间统计

添加备份时间统计

--- 2017-01-07/BakWin/Form1.cs
+++ 2017-01-07/BakWin/Form1.cs
@@ -2,6 +2,7 @@
 using System.IO;
 using System.Windows.Forms;
 using System.Collections.Generic;
+using System.Diagnostics;

 namespace BakWin
 {
@@ -44,38 +45,41 @@
         /// <param name="e"></param>
         private void btn1_Click(object sender, EventArgs e)
         {
+            BakDB($"backup database MyBlog to disk=N'{GetFilePath()}'");
+        }
+        /// <summary>
+        /// 完整备份-压缩
+        /// </summary>
+        /// <param name="sender"></param>
+        /// <param name="e"></param>
+        private void btn2_Click(object sender, EventArgs e)
+        {
+            BakDB($"backup database MyBlog to disk=N'{GetFilePath()}' with compression");
+        }
+        private void BakDB(string sql)
+        {
+            Stopwatch timer = new Stopwatch();
+            timer.Start();
+            int i = 0;
             try
             {
                 using (var conn = ConnectionFactory.GetConnection())
                 {
-                    int i = SQLHelper.ExecuteNoQuery(conn, $"backup database MyBlog to disk=N'{GetFilePath()}'");
-                    if (i != 0) { MessageBox.Show("备份成功！"); }
+                    i = SQLHelper.ExecuteNoQuery(conn, sql);
                 }
             }
             catch (Exception ex)
             {
                 MessageBox.Show(ex.Message);
             }
-        }
-
-        /// <summary>
-        /// 完整备份-压缩
-        /// </summary>
-        /// <param name="sender"></param>
-        /// <param name="e"></param>
-        private void btn2_Click(object sender, EventArgs e)
-        {
-            try
-            {
-                using (var conn = ConnectionFactory.GetConnection())
-                {
-                    int i = SQLHelper.ExecuteNoQuery(conn, $"backup database MyBlog to disk=N'{GetFilePath()}' with compression");
-                    if (i != 0) { MessageBox.Show("备份成功！"); }
-                }
-            }
-            catch (Exception ex)
-            {
-                MessageBox.Show(ex.Message);
+            timer.Stop();
+            if (i != 0)
+            {
+                MessageBox.Show($"备份成功！耗时：{timer.ElapsedMilliseconds}");
+            }
+            else
+            {
+                MessageBox.Show($"备份失败！耗时：{timer.ElapsedMilliseconds}");
             }
         }
         #endregion


Use request.responseHeaders to look for status code on success

--- Assets/Teak/Teak.cs
+++ Assets/Teak/Teak.cs
@@ -1051,10 +1051,15 @@
         }
         else
         {
+            Match match = Regex.Match(request.responseHeaders["STATUS"], "^([0-9]+)");
+            if(match.Success)
+            {
+                statusCode = int.Parse(match.Value);
+            }
+
             if(!string.IsNullOrEmpty(request.text))
             {
                 reply = Json.Deserialize(request.text) as Dictionary<string, object>;
-                if(reply != null && reply.ContainsKey("code")) statusCode = (int)((long)reply["code"]);
             }
         }


Handle non-200 codes for paged results

Handle non-200 codes for paged results

--- Auth0.Net/Client.cs
+++ Auth0.Net/Client.cs
@@ -776,6 +776,12 @@

         private Page<T> BuildPage<T>(IRestResponse response)
         {
+            if (response.StatusCode != HttpStatusCode.OK)
+            {
+                throw new InvalidOperationException(
+                    string.Format("A non-success status code of '{0}' was returned, with response '{1}'", response.StatusCode, response.Content));
+            }
+
             var results = JsonConvert.DeserializeObject<List<T>>(response.Content);
             var links = ParseLinks(response.Headers.FirstOrDefault(h => h.Name == "Link"));


Optimise tags for domain warp

Optimise tags for domain warp

--- CSharp/FastNoise.cs
+++ CSharp/FastNoise.cs
@@ -1372,6 +1372,7 @@

     // Domain Warp

+    [MethodImpl(OPTIMISE)]
     public void DomainWarp(ref FNfloat x, ref FNfloat y)
     {
         switch (mFractalType)
@@ -1388,6 +1389,7 @@
         }
     }

+    [MethodImpl(OPTIMISE)]
     public void DomainWarp(ref FNfloat x, ref FNfloat y, ref FNfloat z)
     {
         switch (mFractalType)


Guaranteed to return a configuration

Guaranteed to return a configuration

--- AngleSharp/DOM/Document.cs
+++ AngleSharp/DOM/Document.cs
@@ -590,8 +590,8 @@
         /// </summary>
         internal IConfiguration Options
         {
-            get { return _options; }
-            set { _options = value ?? Configuration.Default; }
+            get { return _options ?? Configuration.Default; }
+            set { _options = value; }
         }

         /// <summary>


Detect accidental “(not A) ? B”

Detect accidental “(not A) ? B”

--- inklecate/ParsedHierarchy/Expression.cs
+++ inklecate/ParsedHierarchy/Expression.cs
@@ -74,6 +74,29 @@
             container.AddContent(Runtime.NativeFunctionCall.CallWithName(opName));
 		}

+        public override void ResolveReferences (Story context)
+        {
+            base.ResolveReferences (context);
+
+            // Check for the following case:
+            //
+            //    (not A) ? B
+            //
+            // Since this easy to accidentally do:
+            //
+            //    not A ? B
+            //
+            // when you intend:
+            //
+            //    not (A ? B)
+            if (NativeNameForOp (opName) == "?") {
+                var leftUnary = leftExpression as UnaryExpression;
+                if( leftUnary != null && (leftUnary.op == "not" || leftUnary.op == "!") ) {
+                    Error ("Using 'not' or '!' here negates '"+leftUnary.innerExpression+"' rather than the result of the '?' or 'has' operator. You need to add parentheses around the (A ? B) expression.");
+                }
+            }
+        }
+
         string NativeNameForOp(string opName)
         {
             if (opName == "and")


Fixed a bug with the code to retrieve the provider cancellation policy id #205

--- App_Code/LcData.Booking.cs
+++ App_Code/LcData.Booking.cs
@@ -1035,15 +1035,15 @@
             if (db == null)
                 db = Database.Open("sqlloco");

-            var rtn = (int)(db.QueryValue(@"
+            int rtn = N.D(db.QueryValue(@"
                 SELECT  U.CancellationPolicyID
                 FROM    UserProfilePositions As U
                 WHERE   U.UserID = @0
                          AND U.PositionID = @1
                          AND U.LanguageID = @2
                          AND U.CountryID = @3
-            ", providerUserID, positionID, LcData.GetCurrentLanguageID(), LcData.GetCurrentCountryID())
-            ?? DefaultCancellationPolicyID);
+            ", providerUserID, positionID, LcData.GetCurrentLanguageID(), LcData.GetCurrentCountryID()))
+            ?? DefaultCancellationPolicyID;

             if (disposeDb)
                 db.Dispose();


(PSB): support "icon" entries and RL compression.

--- ArcFormats/Emote/ArcPSB.cs
+++ ArcFormats/Emote/ArcPSB.cs
@@ -246,26 +246,64 @@
                 var item_value = item.Value as IDictionary;
                 if (null == item_value)
                     continue;
-                var texture = item_value["texture"] as IDictionary;
-                if (null == texture)
-                    continue;
-                var pixel = texture["pixel"] as EmChunk;
+                if (item_value.Contains ("texture"))
+                {
+                    AddTextureEntry (dir, item.Key, item_value["texture"] as IDictionary);
+                }
+                else if (item_value.Contains ("icon"))
+                {
+                    AddIconEntry (dir, item.Key, item_value["icon"] as IDictionary);
+                }
+            }
+            return dir;
+        }
+
+        void AddTextureEntry (List<Entry> dir, object name, IDictionary texture)
+        {
+            if (null == texture)
+                return;
+            var pixel = texture["pixel"] as EmChunk;
+            if (null == pixel)
+                return;
+            var entry = new TexEntry {
+                Name            = name.ToString(),
+                Type            = "image",
+                Offset          = DataOffset + pixel.Offset,
+                Size            = (uint)pixel.Length,
+                TexType         = texture["type"].ToString(),
+                Width           = Convert.ToInt32 (texture["width"]),
+                Height          = Convert.ToInt32 (texture["height"]),
+                TruncatedWidth  = Convert.ToInt32 (texture["truncated_width"]),
+                TruncatedHeight = Convert.ToInt32 (texture["truncated_height"]),
+            };
+            dir.Add (entry);
+        }
+
+        void AddIconEntry (List<Entry> dir, object name, IDictionary icon_list)
+        {
+            if (null == icon_list)
+                return;
+            foreach (DictionaryEntry icon in icon_list)
+            {
+                var layer = icon.Value as IDictionary;
+                var pixel = layer["pixel"] as EmChunk;
                 if (null == pixel)
                     continue;
                 var entry = new TexEntry {
-                    Name            = item.Key.ToString(),
-                    Type            = "image",
-                    Offset          = DataOffset + pixel.Offset,
-                    Size            = (uint)pixel.Length,
-                    TexType         = texture["type"].ToString(),
-                    Width           = Convert.ToInt32 (texture["width"]),
-                    Height          = Convert.ToInt32 (texture["height"]),
-                    TruncatedWidth  = Convert.ToInt32 (texture["truncated_width"]),
-                    TruncatedHeight = Convert.ToInt32 (texture["truncated_height"]),
+                    Name        = name.ToString()+'#'+icon.Key.ToString(),
+                    Type        = "image",
+                    Offset      = DataOffset + pixel.Offset,
+                    Size        = (uint)pixel.Length,
+                    Width       = Convert.ToInt32 (layer["width"]),
+                    Height      = Convert.ToInt32 (layer["height"]),
+                    OffsetX     = Convert.ToInt32 (layer["originX"]),
+                    OffsetY     = Convert.ToInt32 (layer["originY"]),
+                    TexType     = layer.Contains ("compress") ? layer["compress"].ToString() : "RGBA8",
                 };
+                entry.TruncatedWidth = entry.Width;
+                entry.TruncatedHeight = entry.Height;
                 dir.Add (entry);
             }
-            return dir;
         }

         int m_names;
@@ -651,6 +689,8 @@
                 ReadA8L8 (pixels, stride);
             else if ("RGBA4444" == m_info.TexType)
                 ReadRgba4444 (pixels, stride);
+            else if ("RL" == m_info.TexType)
+                ReadRle (pixels, stride);
             else
                 throw new NotImplementedException (string.Format ("PSB texture format '{0}' not implemented", m_info.TexType));
             return ImageData.Create (m_info, PixelFormats.Bgra32, null, pixels, stride);
@@ -734,5 +774,28 @@
                 }
             }
         }
+
+        void ReadRle (byte[] output, int dst_stride)
+        {
+            const int pixel_size = 4;
+            m_input.Position = 0;
+            int dst = 0;
+            while (dst < output.Length)
+            {
+                int count = m_input.ReadUInt8();
+                if (0 == (count & 0x80))
+                {
+                    count = pixel_size * (count + 1);
+                    dst += m_input.Read (output, dst, count);
+                }
+                else
+                {
+                    count = pixel_size * ((count & 0x7F) + 3);
+                    m_input.Read (output, dst, pixel_size);
+                    Binary.CopyOverlapped (output, dst, dst+pixel_size, count-pixel_size);
+                    dst += count;
+                }
+            }
+        }
     }
 }


(QLIE): set ContainedFormats property.

(QLIE): set ContainedFormats property.

--- ArcFormats/Qlie/ArcQLIE.cs
+++ ArcFormats/Qlie/ArcQLIE.cs
@@ -84,6 +84,7 @@
         public PackOpener ()
         {
             Extensions = new string [] { "pack" };
+            ContainedFormats = new[] { "ABMP/QLIE", "DPNG", "PNG", "JPEG", "OGG", "WAV" };
         }

         /// <summary>
@@ -147,7 +148,7 @@
                     if (name_length != index.Read (name_buffer, 0, name_length))
                         return null;
                     var name = enc.DecryptName (name_buffer, name_length);
-                    var entry = FormatCatalog.Instance.Create<QlieEntry> (name);
+                    var entry = Create<QlieEntry> (name);
                     if (use_pack_keyfile)
                         entry.RawName = name_buffer.Take (name_length).ToArray();


select right sections with condition

select right sections with condition

--- kinect/BodyBasics-WPF/MainWindow.xaml.cs
+++ kinect/BodyBasics-WPF/MainWindow.xaml.cs
@@ -274,12 +274,15 @@

         public static void right_part(float angle)
         {
-            if(angle<=180&&angle>=120)
-                        Console.Out.WriteLine(" section 1" +1);
-                else if(angle<120&&angle>=60)
-                        Console.Out.WriteLine(" section 1" +2);
-            else if (angle<60&&angle>=0)
-                        Console.Out.WriteLine(" section 1" +3);
+
+            if(angle<=180&&angle>=130)
+                Console.Out.WriteLine(" section " + 1 + " angle " + angle);
+                else if(angle<130&&angle>=80)
+                Console.Out.WriteLine(" section " + 2 + " angle " + angle);
+            else if (angle<80&&angle>=30)
+                Console.Out.WriteLine(" section " + 3 + " angle " + angle);
+
+
         }

         public static float AngleBetweenJoints(Body body, JointType centerJoint, JointType topJoint, JointType bottomJoint)
@@ -288,8 +291,8 @@
             Vector3 topJointCoord = new Vector3(body.Joints[topJoint].Position.X, body.Joints[topJoint].Position.Y, body.Joints[topJoint].Position.Z);
             Vector3 bottomJointCoord = new Vector3(body.Joints[bottomJoint].Position.X, body.Joints[bottomJoint].Position.Y, body.Joints[bottomJoint].Position.Z);

-            Vector3 firstVector = bottomJointCoord - centerJointCoord;
-            Vector3 secondVector = topJointCoord - centerJointCoord;
+            Vector3 firstVector = (bottomJointCoord - centerJointCoord);
+            Vector3 secondVector = (topJointCoord - centerJointCoord);

             return AngleBetweenTwoVectors(firstVector, secondVector);
         }
@@ -311,7 +314,15 @@
         public static float depth_from_chest(Body body, JointType ShoulderRight, JointType HandRight)
         {

-            return (body.Joints[ShoulderRight].Position.Z-body.Joints[HandRight].Position.Z)*100;
+            Joint neck = body.Joints[JointType.Neck];
+            Joint spinebase = body.Joints[JointType.SpineBase];
+
+            float length = Math.Abs(neck.Position.Y - spinebase.Position.Y);
+
+
+                float depth =Math.Abs(body.Joints[ShoulderRight].Position.Z - body.Joints[HandRight].Position.Z) * 100;
+                depth = depth / length;
+                return depth;
         }

         //code for jump from right leg
@@ -399,16 +410,32 @@
                         Pen drawPen = this.bodyColors[penIndex++];

                         if (body.IsTracked)
+
                         {
+              //=================================================================================================================//
                             //angle between three point
                    //     float angle=   AngleBetweenJoints(body, JointType.ElbowRight, JointType.HandRight, JointType.ShoulderRight);

+              //============================================================================================//
                             //select section from right side
-                    float right_section = AngleBetweenJoints(body, JointType.ShoulderRight, JointType.ElbowRight, JointType.HipRight);
-                    right_part(right_section);
-
-                            //find distance from z axis
-                       float depth_z = depth_from_chest(body,JointType.ShoulderRight,JointType.HandRight);
+
+                            Boolean select = false;
+                            Joint head = body.Joints[JointType.Head];
+                            Joint Wristleft = body.Joints[JointType.WristLeft];
+
+                            float right_section = AngleBetweenJoints(body,  JointType.ShoulderRight, JointType.ElbowRight, JointType.HipRight);
+
+                            if (head.Position.Y < Wristleft.Position.Y) { select = true; }
+
+                            if (select) { right_part(right_section); select = false; }
+
+               //=======================================================================================//
+                    //find distance from z axis
+                    if (body.HandLeftState == HandState.Closed)
+                    {
+                        float depth_z = depth_from_chest(body, JointType.ShoulderRight, JointType.HandRight);
+                        Console.Out.WriteLine("depth_z" + depth_z);
+                    }

                             // detect jump
                        Boolean jump= jump_right_leg(body,JointType.FootRight,JointType.FootLeft);
@@ -416,7 +443,7 @@
                        if (jump)
                        {
                            Console.Out.WriteLine("jump");
-                           EigenRequest.startLoop("0");
+                          // EigenRequest.startLoop("0");
                        }

                             //play rip
@@ -424,7 +451,7 @@

                        // Console.Out.WriteLine(angle);
                        // Console.Out.WriteLine(right_section);
-                            Console.Out.WriteLine("depth_z" + depth_z);
+

                             this.DrawClippedEdges(body, dc);


don't persist display_patched_conics_

don't persist display_patched_conics_

--- ksp_plugin_adapter/ksp_plugin_adapter.cs
+++ ksp_plugin_adapter/ksp_plugin_adapter.cs
@@ -38,7 +38,6 @@

   private IntPtr plugin_ = IntPtr.Zero;

-  [KSPField(isPersistant = true)]
   private bool display_patched_conics_ = false;
   [KSPField(isPersistant = true)]
   private bool fix_navball_in_plotting_frame_ = true;


let's not get ahead of ourselves

let's not get ahead of ourselves

--- ksp_plugin_adapter/ksp_plugin_adapter.cs
+++ ksp_plugin_adapter/ksp_plugin_adapter.cs
@@ -37,8 +37,6 @@

   private bool time_is_advancing_;

-  private bool should_initialize_ = false;
-  private int fixed_updates_until_initialization_;
   private DateTime last_plugin_reset_;

   private static bool an_instance_is_loaded;
@@ -251,14 +249,6 @@
   }

   private void FixedUpdate() {
-    if (should_initialize_) {
-      if (fixed_updates_until_initialization_ > 0) {
-        --fixed_updates_until_initialization_;
-      } else {
-        ResetPlugin();
-        should_initialize_ = false;
-      }
-    }
     if (PluginRunning()) {
       double universal_time = Planetarium.GetUniversalTime();
       double plugin_time = current_time(plugin_);
@@ -381,8 +371,9 @@
   }

   private void InitializeOnGameStateLoad(ConfigNode node) {
-    should_initialize_ = true;
-    fixed_updates_until_initialization_ = 1;
+    // TODO(egg): Here loading of the persisted game state should occur, or
+    // initialization should be scheduled.  Without persistence, we get plugin
+    // resets at every scene change or vessel switch, so we do nothing.
   }

   private void DrawMainWindow(int window_id) {


scusé

scusé

--- Assets/Scripts/Movement.cs
+++ Assets/Scripts/Movement.cs
@@ -14,8 +14,7 @@

 	}
-
-
+/*
 	/// <summary>
 	/// Termine le mouvement entamé
 	/// </summary>
@@ -25,12 +24,12 @@
 		{
 			case('h')
 			{
-
+				break;
 			}

 		}

 	}

-	*/
+*/
 }


Fix bug with ListDatasetDefinition that popped up in unit tests

--- Keen/KeenClient.cs
+++ Keen/KeenClient.cs
@@ -1064,7 +1064,7 @@
         {
             try
             {
-                return ListDatasetDefinitionsAsync().Result;
+                return ListDatasetDefinitionsAsync(limit, afterName).Result;
             }
             catch(AggregateException ex)
             {


Rope uses Nodes struct instead of Nodes class

--- Assets/Scripts/Tentacle.cs
+++ Assets/Scripts/Tentacle.cs
@@ -32,9 +32,9 @@
         if (Application.isPlaying)
         {
             Gizmos.color = Color.cyan;
-            for (int i = 0; i < _tentacleData.nodes.Count - 1; i++)
+            for (int i = 0; i < _tentacleData.nodes.Length - 1; i++)
             {
-                Gizmos.DrawLine(_tentacleData.nodes[i].GetVec(), _tentacleData.nodes[i + 1].GetVec());
+                Gizmos.DrawLine(_tentacleData.nodes[i].position(), _tentacleData.nodes[i + 1].position());
             }
         }
     }
@@ -47,19 +47,21 @@
         public float spacing;
         public float friction;

-        public List<Node> nodes;
-
+        //public List<Node> nodes;
+        public Node[] nodes;

         public TentacleData(float _length, float _spacing, float _friction)
         {
             length = _length;
             spacing = _spacing;
             friction = _friction;
-            nodes = new List<Node>();
-            for (var i = 0; i < _length; i++)
-            {
-                nodes.Add(new Node());
-            }
+            //nodes = new List<Node>();
+            nodes = new Node[(int)_length];
+
+            //for (var i = 0; i < _length; i++)
+            //{
+            //    nodes.Add(new Node());
+            //}
         }
         public void Move(Vector2 _position)
         {
@@ -72,67 +74,79 @@
             var i = 0;
             var px = 0f;
             var py = 0f;
-            var node = new Node();
-            var prev = nodes[0];
+            //var node = new Node();
+            int prev = 0;

             for (i = 1; i < length; i++)
             {
-                node = nodes[i];
+                //node = nodes[i];

-                node.x += node.vx;
-                node.y += node.vy;
+                nodes[i].x += nodes[i].vx;
+                nodes[i].y += nodes[i].vy;

                 //much more understandable, but when using a vector the rope doesn't unfold when origin is at (0,0,0)
-                Vector2 dir = new Vector2(prev.x, prev.y) - new Vector2(node.x, node.y);
+                Vector2 dir = new Vector2(nodes[prev].x, nodes[prev].y) - new Vector2(nodes[i].x, nodes[i].y);
                 dir.Normalize();
-                px = node.x + dir.x * spacing * _length;
-                py = node.y + dir.y * spacing * _length;
+                px = nodes[i].x + dir.x * spacing * _length;
+                py = nodes[i].y + dir.y * spacing * _length;

-                node.x = prev.x - (px - node.x);
-                node.y = prev.y - (py - node.y);
+                nodes[i].x = nodes[prev].x - (px - nodes[i].x);
+                nodes[i].y = nodes[prev].y - (py - nodes[i].y);

-                node.vx = node.x - node.ox;
-                node.vy = node.y - node.oy;
+                nodes[i].vx = nodes[i].x - nodes[i].ox;
+                nodes[i].vy = nodes[i].y - nodes[i].oy;

-                node.vx *= friction * (1 - _friction);
-                node.vy *= friction * (1 - _friction);
+                nodes[i].vx *= friction * (1 - _friction);
+                nodes[i].vy *= friction * (1 - _friction);

-                node.vx += _wind;
-                node.vy += _gravity;
+                nodes[i].vx += _wind;
+                nodes[i].vy += _gravity;

-                node.ox = node.x;
-                node.oy = node.y;
+                nodes[i].ox = nodes[i].x;
+                nodes[i].oy = nodes[i].y;

-                prev = node;
+                prev = i;
             }
         }
     }
     #endregion

     #region Node
-    //[System.SerializableAttribute]
-    public class Node
+    //public class Node
+    //{
+    //    public float x;
+    //    public float y;
+
+    //    public float ox;
+    //    public float oy;
+
+    //    public float vx;
+    //    public float vy;
+
+    //    public Node() { }
+
+    //    public Vector2 position()
+    //    {
+    //        return new Vector2(x, y);
+    //    }
+    //}
+
+    public struct Node
     {
         public float x;
         public float y;
+
         public float ox;
         public float oy;
+
         public float vx;
         public float vy;
-        public Node(float _x, float _y)
-        {
-            x = _x;
-            y = _y;
-            ox = _x;
-            oy = _y;
-        }
-        public Node() { }
-        public Vector2 GetVec()
+
+        public Vector2 position()
         {
             return new Vector2(x, y);
         }
     }
     #endregion
-
-
+
 }


_Referee transformed in a singleton

_Referee transformed in a singleton

--- Assets/Scripts/_Referee.cs
+++ Assets/Scripts/_Referee.cs
@@ -2,6 +2,7 @@
 using System.Collections;

 public class _Referee : MonoBehaviour {
+	public static _Referee instance;
 	public bool p1 = false;
 	public bool changed = false;

@@ -10,6 +11,12 @@

 	void Awake() {
 		DontDestroyOnLoad(transform.gameObject);
+	}
+
+	private void Start() {
+		if (instance == null) {
+			instance = this.gameObject.GetComponent<_Referee>();
+		}
 	}

 	void FixedUpdate() {


Added ability to start at an angle and go in order.

--- LegoGif/Program.cs
+++ LegoGif/Program.cs
@@ -34,7 +34,7 @@

             Environment.SetEnvironmentVariable("LDRAWDIR", LDPath.Value, EnvironmentVariableTarget.Process);

-            foreach (var angle in CameraAngles())
+            foreach (var angle in CameraAngles(start: 45))
             {
                 var frameName = "frame_" + angle;
                 var povFile = frameName + ".pov";
@@ -87,18 +87,18 @@
             }
         }

-        public static IEnumerable<int> CameraAngles()
+        public static IEnumerable<int> CameraAngles(bool forceOrder = false, int start = 0)
         {
             var done = new bool[360];

-            for (var step = 360; step >= 1; step /= 2)
+            for (var step = forceOrder ? 1 : 360; step >= 1; step /= 2)
             {
                 for (int i = 0; i < 360; i += step)
                 {
                     if (!done[i])
                     {
                         done[i] = true;
-                        yield return i;
+                        yield return (i + start) % 360;
                     }
                 }
             }


register Default XPMMarkupService

register Default XPMMarkupService

--- source/DD4T.DI.Unity/MVCTypes.cs
+++ source/DD4T.DI.Unity/MVCTypes.cs
@@ -28,12 +28,21 @@
             var iComponentPresentationRenderer = providerTypes.Where(a => a.FullName.Equals("DD4T.Mvc.Html.IComponentPresentationRenderer")).FirstOrDefault();
             var defaultComponentPresentationRenderer = providerTypes.Where(a => a.FullName.Equals("DD4T.Mvc.Html.DefaultComponentPresentationRenderer")).FirstOrDefault();

-            if (iComponentPresentationRenderer == null || defaultComponentPresentationRenderer == null)
-                return;
+            var iXpmMarkupService = providerTypes.Where(a => a.FullName.Equals("DD4T.MVC.ViewModels.XPM.IXpmMarkupService")).FirstOrDefault();
+            var defaultXpmMarkupService = providerTypes.Where(a => a.FullName.Equals("DD4T.Mvc.ViewModels.XPM.XpmMarkupService")).FirstOrDefault();

-            if (!container.IsRegistered(iComponentPresentationRenderer))
-                container.RegisterType(iComponentPresentationRenderer, defaultComponentPresentationRenderer);
+            if (iComponentPresentationRenderer != null || defaultComponentPresentationRenderer != null)
+            {
+                if (!container.IsRegistered(iComponentPresentationRenderer))
+                    container.RegisterType(iComponentPresentationRenderer, defaultComponentPresentationRenderer);
+            }
+
+            if (iXpmMarkupService != null || defaultXpmMarkupService != null)
+            {
+                if (!container.IsRegistered(iXpmMarkupService))
+                    container.RegisterType(iXpmMarkupService, defaultXpmMarkupService);
+            }
         }
     }
 }


no change

no change

git-svn-id: 16f658619b342a39b0afd2472f072a689916e5a2@190 6f2d7086-9719-0410-ba06-0b8292a297aa

--- psycho/Psycho/Core/MindView.cs
+++ psycho/Psycho/Core/MindView.cs
@@ -123,7 +123,7 @@
                         DrawTopics (mapContext);
                         this.mapArea.SetSizeRequest ((int) Model.CentralTopic.GlobalWidth + 2 * margin, (int) Model.CentralTopic.GlobalHeight + 2 * margin);

-                        //// Temporary code used to draw to png file. That has to be a separate method called by the user.
+                        ////// Temporary code used to draw to png file. That has to be a separate method called by the user.
                         //Cairo.ImageSurface image = new ImageSurface (Format.Rgb24, (int) Model.CentralTopic.GlobalWidth + 20, (int) Model.CentralTopic.GlobalHeight + 20);
                         //Cairo.Context pictureContext = new Cairo.Context (image);
                         //DrawBackground (pictureContext);
@@ -133,7 +133,7 @@
                         //image.WriteToPng ("psycho.png");
                         //((IDisposable) pictureContext.Target).Dispose ();
                         //((IDisposable) pictureContext).Dispose ();
-                        // End of that hack...
+                        //// End of that hack...

                         ((IDisposable) mapContext.Target).Dispose ();
                         ((IDisposable) mapContext).Dispose ();


[Modify] Polish it

[Modify] Polish it

--- websocket-sharp/WebSocket.cs
+++ websocket-sharp/WebSocket.cs
@@ -1372,11 +1372,17 @@
     }

     // As server
-    private bool customCheckHandshakeRequest (WebSocketContext context, out string message)
+    private bool customCheckHandshakeRequest (
+      WebSocketContext context, out string message
+    )
     {
       message = null;
-      return _handshakeRequestChecker == null
-             || (message = _handshakeRequestChecker (context)) == null;
+
+      if (_handshakeRequestChecker == null)
+        return true;
+
+      message = _handshakeRequestChecker (context);
+      return message == null;
     }

     private MessageEventArgs dequeueFromMessageEventQueue ()


[Modify] Polish it

[Modify] Polish it

--- websocket-sharp/WebSocket.cs
+++ websocket-sharp/WebSocket.cs
@@ -834,21 +834,22 @@
           return false;
         }

+        var accepted = false;
+
         try {
-          var accepted = acceptHandshake ();
-
-          if (!accepted)
-            return false;
+          accepted = acceptHandshake ();
         }
         catch (Exception ex) {
           _logger.Fatal (ex.Message);
           _logger.Debug (ex.ToString ());

           var msg = "An exception has occurred while attempting to accept.";
+
           fatal (msg, ex);
-
+        }
+
+        if (!accepted)
           return false;
-        }

         _readyState = WebSocketState.Open;


Bug fix - incorrect number of exceptions being displayed

--- MinidumpExplorer/MinidumpExplorer/MainForm.cs
+++ MinidumpExplorer/MinidumpExplorer/MainForm.cs
@@ -84,7 +84,12 @@
                     break;
                 case "Exception":
                     MiniDumpExceptionStream exceptionStream = this._miniDumpFile.ReadExceptionStream();
-                    numberOfItems = 1;
+
+                    if (exceptionStream == null)
+                        numberOfItems = 0;
+                    else
+                        numberOfItems = 1;
+
                     viewToDisplay = new ExceptionStreamView(exceptionStream);
                     break;
                 case "UnloadedModules":


[Modify] Polish it

[Modify] Polish it

--- websocket-sharp/WebSocket.cs
+++ websocket-sharp/WebSocket.cs
@@ -829,12 +829,12 @@
       message = null;

       if (!client && _client) {
-        message = "This operation isn't available in: client";
+        message = "This operation is not available in: client";
         return false;
       }

       if (!server && !_client) {
-        message = "This operation isn't available in: server";
+        message = "This operation is not available in: server";
         return false;
       }


[Modify] Replace it

[Modify] Replace it

--- websocket-sharp/WebSocket.cs
+++ websocket-sharp/WebSocket.cs
@@ -1442,7 +1442,7 @@
     private bool processCloseFrame (WebSocketFrame frame)
     {
       var payload = frame.PayloadData;
-      close (new CloseEventArgs (payload), !payload.HasReservedCode, false, true);
+      close (payload, !payload.HasReservedCode, false, true);

       return false;
     }


Adding missing ServerName property

Adding missing ServerName property

--- SSLLabsApiWrapper/Models/Response/Endpoint.cs
+++ SSLLabsApiWrapper/Models/Response/Endpoint.cs
@@ -5,6 +5,7 @@
 	public class Endpoint : BaseModel
 	{
 		public string ipAddress { get; set; }
+		public string serverName { get; set; }
 		public string statusMessage { get; set; }
 		public string statusDetails { get; set; }
 		public string statusDetailsMessage { get; set; }


[Modify] Throw exceptions

[Modify] Throw exceptions

--- websocket-sharp/WebSocket.cs
+++ websocket-sharp/WebSocket.cs
@@ -2664,14 +2664,12 @@
     /// </param>
     public void Send (byte[] data)
     {
-      var msg = _readyState.CheckIfAvailable (false, true, false, false) ??
-                CheckSendParameter (data);
-
-      if (msg != null) {
-        _logger.Error (msg);
-        error ("An error has occurred in sending data.", null);
-
-        return;
+      if (data == null)
+        throw new ArgumentNullException ("data");
+
+      if (_readyState != WebSocketState.Open) {
+        var msg = "The current state of the connection is not Open.";
+        throw new InvalidOperationException (msg);
       }

       send (Opcode.Binary, new MemoryStream (data));


Removed unnecessary namespace qualifier (it was necessary before a class rename)

--- examples/modular_input/Program.cs
+++ examples/modular_input/Program.cs
@@ -136,7 +136,7 @@
                 if (varValue != lastVarValue)
                 {
                     writer.Write(
-                        new Splunk.ModularInputs.EventElement
+                        new EventElement
                             {
                                 Source = varName,
                                 Data = varValue,


Updated the cake scripts since they didn't run before.

--- cake-scripts/nunit.csx
+++ cake-scripts/nunit.csx
@@ -1,4 +1,4 @@
-#tool "nuget:?package=NUnit.ConsoleRunner&version=3.6.1"
+#tool "nuget:?package=NUnit.ConsoleRunner&version=3.7.0"

 Task("NUnit")
     .Description("Runs the NUnit tests.")
@@ -10,7 +10,6 @@
         NUnit3(testAssemblies, new NUnit3Settings
         {
             Workers = 30,
-            Verbose = true,
             Work = "./Build"
         });
     });


whitespace

whitespace

--- ModCore/ModCore.cs
+++ ModCore/ModCore.cs
@@ -116,7 +116,7 @@
 				    {
 					    Command = name
 				    });
-			    }
+			    }
 			    await db.SaveChangesAsync();
 		    }


Added events for added/removed.

Added events for added/removed.

--- Model/Component.cs
+++ Model/Component.cs
@@ -51,10 +51,13 @@
                         _previousRecord = _record;
                         _record = value;

+                        ComponentStateEventArgs stateChange =
+                            new ComponentStateEventArgs(_record, _previousRecord);
+
                         if (_record != null) {
-                            OnAdded(new ComponentStateEventArgs(_record, _previousRecord));
+                            OnAdded(stateChange);
                         } else {
-                            OnRemoved(new ComponentStateEventArgs(_record, _previousRecord));
+                            OnRemoved(stateChange);
                         }
                     }
                 }
@@ -78,16 +81,27 @@
                     !Record.HasComponent(this);
             }
         }
-
+
+        public event EventHandler<ComponentStateEventArgs> Added;
+        public event EventHandler<ComponentStateEventArgs> Removed;
+
         /// <summary>
         /// Occurs when the component is attached to an entity.
         /// </summary>
-        protected virtual void OnAdded(ComponentStateEventArgs registrationArgs) { }
+        protected virtual void OnAdded(ComponentStateEventArgs registrationArgs) {
+            if (Added != null) {
+                Added(this, registrationArgs);
+            }
+        }

         /// <summary>
         /// Occurs when the component is dettached from an entity.
         /// </summary>
-        protected virtual void OnRemoved(ComponentStateEventArgs registrationArgs) { }
+        protected virtual void OnRemoved(ComponentStateEventArgs registrationArgs) {
+            if (Removed != null) {
+                Removed(this, registrationArgs);
+            }
+        }

         /// <summary>
         /// Receives a message from a containing arbitrary data.


added support for different HTTP Methods

--- OpenAPI/OpenAPI.cs
+++ OpenAPI/OpenAPI.cs
@@ -43,7 +43,7 @@
             string accessToken = null;
             string apiurl = null;
             List<string> headers = new List<string>();
-            bool isGetMethod = true;
+            string httpMethod = "GET";
             string contentType = "application/json";

@@ -73,11 +73,11 @@
                             outputfile = arg;
                             break;
                         case "-f":
-                            isGetMethod = false;
+                            if (httpMethod == "GET") httpMethod = "PUT";
                             uploadfile = arg;
                             break;
                         case "-d":
-                            isGetMethod = false;
+                            if (httpMethod == "GET") httpMethod = "POST";
                             data = arg;
                             break;
                         case "-T":
@@ -85,6 +85,9 @@
                             break;
                         case "-H":
                             headers.Add(arg);
+                            break;
+                        case "-X":
+                            httpMethod = arg;
                             break;

                     }
@@ -96,9 +99,7 @@
                     return;
                 }
                 else if (arg == "-v" || arg == "-vv")
-                    verbose = true;
-                else if (arg == "-P")
-                    isGetMethod = false;
+                    verbose = true;
                 else if (!arg.StartsWith("-"))
                     apiurl = arg;
                 else
@@ -107,7 +108,7 @@

             if (verbose)
             {
-                Console.WriteLine("{0} {1}", isGetMethod ? "GET" : "POST", apiurl);
+                Console.WriteLine("{0} {1}", httpMethod, apiurl);
                 Console.WriteLine("ClientToken: {0}", clientToken);
                 Console.WriteLine("AccessToken: {0}", accessToken);
                 Console.WriteLine("Secret: {0}", secret);
@@ -119,10 +120,10 @@
                 Console.WriteLine("Content-Type: {0}", contentType);
             }

-            execute(isGetMethod, apiurl, headers, clientToken, accessToken, secret, data, uploadfile, outputfile, contentType, verbose);
+            execute(httpMethod, apiurl, headers, clientToken, accessToken, secret, data, uploadfile, outputfile, contentType, verbose);
         }

-        static void execute(bool isGetMethod, string apiurl, List<string> headers, string clientToken, string accessToken, string secret, string data, string uploadfile, string outputfile, string contentType, bool verbose = false)
+        static void execute(string httpMethod, string apiurl, List<string> headers, string clientToken, string accessToken, string secret, string data, string uploadfile, string outputfile, string contentType, bool verbose = false)
         {
             if (apiurl == null || clientToken == null || accessToken == null || secret == null)
             {
@@ -141,15 +142,9 @@

             var uri = new Uri(apiurl);
             var request = WebRequest.Create(uri);
-
-            if (uploadStream != null)
-            {
-                isGetMethod = false;
-                request.ContentType = contentType;
-            }
-
+
             foreach (string header in headers) request.Headers.Add(header);
-            request.Method = isGetMethod ? "GET" : "POST";
+            request.Method = httpMethod;

             Stream output = Console.OpenStandardOutput();
             if (outputfile != null)
@@ -187,7 +182,8 @@
             Console.Error.WriteLine(@"
 Usage: openapi <-c client-token> <-a access-token> <-s secret>
            [-d data] [-f srcfile]
-           [-o outfile] [-P]
+           [-o outfile]
+           [-X method]
            [-H header-line]
            [-T content-type]
            <url>
@@ -197,7 +193,7 @@
     -d data         string of data to PUT to the API
     -f srcfile      local file used as source when action=upload
     -H header-line  Http Header 'Name: value'
-    -P              force HTTP PUT
+    -X method       force HTTP PUT,POST,DELETE
     -T content-type the HTTP content type (default = application/json)
     url             fully qualified api url such as https://akab-1234.luna.akamaiapis.net/diagnostic-tools/v1/locations


bug fix: need to reparse the program after each phase of cfiverifier

--- CfiVerifier/source/main.cs
+++ CfiVerifier/source/main.cs
@@ -17,6 +17,19 @@
 {
     class CfiVerifierMain
     {
+        static void ExtractProgAndImpl(string fname, out Program prog, out Implementation impl)
+        {
+            if (!Utils.ParseProgram(fname, out prog)) {
+                Utils.Assert(false, "Unable to parse file " + fname);
+            }
+
+            impl = prog.TopLevelDeclarations.Where(x => x is Implementation &&
+                ((Implementation)x).Name.Contains("dll_func")).ElementAt(0) as Implementation;
+
+            Utils.Assert(impl != null, "Unable to find Boogie implementation named \"dll_func\"");
+
+        }
+
         static void Main(string[] args)
         {
             /* Command line parsing */
@@ -30,25 +43,27 @@

                 try
                 {
-                    if (!Utils.ParseProgram(f, out prog)) return;
-                    impl = prog.TopLevelDeclarations.Where(x => x is Implementation &&
-                        ((Implementation)x).Name.Contains("dll_func")).ElementAt(0) as Implementation;
-                    Utils.Assert(impl != null, "Unable to find Boogie implementation named \"dll_func\"");
-
+                    // NOTE: Below, we have to reextract prog and impl because we want to purge the instrumentation from the previous phase
                     //Phase 0
+                    ExtractProgAndImpl(f, out prog, out impl);
                     (new Validator()).Visit(prog);

                     //Phase 1
                     Dictionary<Tuple<string, Cmd, AssertCmd>, bool> storeDB = null, loadDB = null;
-                    if (Options.optimizeStoreITE) {
+                    if (Options.optimizeStoreITE)
+                    {
+                        ExtractProgAndImpl(f, out prog, out impl);
                         storeDB = DecideAddressRegions(prog, impl, true);
                     }

-                    if (Options.optimizeLoadITE) {
+                    if (Options.optimizeLoadITE)
+                    {
+                        ExtractProgAndImpl(f, out prog, out impl);
                         loadDB = DecideAddressRegions(prog, impl, false);
                     }

                     //Phase 2
+                    ExtractProgAndImpl(f, out prog, out impl);
                     InstrumentEnclave(prog, impl, storeDB, loadDB);
                 }
                 catch (Exception e)


Added support for cvMerge.

Added support for cvMerge.

--- OpenCV.Net/Core.cs
+++ OpenCV.Net/Core.cs
@@ -77,6 +77,9 @@

         [DllImport(libName)]
         public static extern void cvFlip(CvArr src, CvArr dst, FlipMode flipMode);
+
+        [DllImport(libName)]
+        public static extern void cvMerge(CvArr src0, CvArr src1, CvArr src2, CvArr src3, CvArr dst);

         [DllImport(libName)]
         public static extern void cvMul(CvArr src1, CvArr src2, CvArr dst, double scale);


[Modify] Edit it

[Modify] Edit it

--- websocket-sharp/Net/HttpListenerRequest.cs
+++ websocket-sharp/Net/HttpListenerRequest.cs
@@ -399,10 +399,17 @@
     }

     /// <summary>
-    /// Gets the raw URL (without the scheme, host, and port) requested by the client.
-    /// </summary>
-    /// <value>
-    /// A <see cref="string"/> that represents the raw URL requested by the client.
+    /// Gets the raw URL (without the scheme, host, and port) requested by
+    /// the client.
+    /// </summary>
+    /// <value>
+    ///   <para>
+    ///   A <see cref="string"/> that represents the raw URL specified in
+    ///   the request.
+    ///   </para>
+    ///   <para>
+    ///   It includes the query string if present.
+    ///   </para>
     /// </value>
     public string RawUrl {
       get {


[Modify] Remove it

[Modify] Remove it

--- websocket-sharp/Net/WebHeaderCollection.cs
+++ websocket-sharp/Net/WebHeaderCollection.cs
@@ -1056,11 +1056,6 @@
       _state = headerType;
     }

-    private void setWithoutCheckingName (string name, string value)
-    {
-      doWithoutCheckingName (base.Set, name, value);
-    }
-
     #endregion

     #region Internal Methods


[Modify] Polish it

[Modify] Polish it

--- websocket-sharp/Net/WebHeaderCollection.cs
+++ websocket-sharp/Net/WebHeaderCollection.cs
@@ -881,8 +881,11 @@

     private static string convert (string key)
     {
-      HttpHeaderInfo info;
-      return _headers.TryGetValue (key, out info) ? info.Name : String.Empty;
+      HttpHeaderInfo headerInfo;
+
+      return _headers.TryGetValue (key, out headerInfo)
+             ? headerInfo.Name
+             : String.Empty;
     }

     private void doWithCheckingState (


ApplicationClaimsTransformation update

ApplicationClaimsTransformation update

--- src/ASPNETCoreIdentitySample.Services/Identity/ApplicationClaimsTransformation.cs
+++ src/ASPNETCoreIdentitySample.Services/Identity/ApplicationClaimsTransformation.cs
@@ -23,25 +23,26 @@
             _userManager.CheckArgumentIsNull(nameof(_userManager));
         }

-        public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
+        public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
         {
             var identity = principal.Identity as ClaimsIdentity;
             if (identity == null)
             {
-                return Task.FromResult(principal);
+                return principal;
             }

-            var claims = addExistingUserClaims(identity);
+            var claims = await addExistingUserClaims(identity).ConfigureAwait(false);
             identity.AddClaims(claims);

-            return Task.FromResult(principal);
+            return principal;
         }

-        private IEnumerable<Claim> addExistingUserClaims(IIdentity identity)
+        private async Task<IEnumerable<Claim>> addExistingUserClaims(IIdentity identity)
         {
             var claims = new List<Claim>();
-            var existingUserClaims = _userManager.Users.Include(u => u.Claims)
-                                                 .SingleOrDefault(u => u.UserName == identity.Name);
+            var existingUserClaims = await _userManager.Users.Include(u => u.Claims)
+                                                 .FirstOrDefaultAsync(u => u.UserName == identity.Name)
+                                                 .ConfigureAwait(false);
             if (existingUserClaims == null)
             {
                 return claims;


Tests

Tests

--- src/EditorFeatures/CSharpTest/ConvertProgram/ConvertToProgramMainAnalyzerTests.cs
+++ src/EditorFeatures/CSharpTest/ConvertProgram/ConvertToProgramMainAnalyzerTests.cs
@@ -631,65 +631,39 @@
             }.RunAsync();
         }

-        [Fact]
+        [Theory]
         [WorkItem(62943, "https://github.com/dotnet/roslyn/issues/62943")]
-        public async Task TestHasExistingPublicPart()
-        {
-            await new VerifyCS.Test
-            {
-                TestCode = @"
-using System;
-
-{|IDE0211:Console|}.WriteLine(0);
-
-public partial class Program
-{
+        [InlineData("public")]
+        [InlineData("internal")]
+        [InlineData("static")]
+        [InlineData("abstract")]
+        [InlineData("file")]
+        public async Task TestHasExistingPart_KeepsModifiers(string modifier)
+        {
+            await new VerifyCS.Test
+            {
+                TestCode = $@"
+using System;
+
+{{|IDE0211:Console|}}.WriteLine(0);
+
+{modifier} partial class Program
+{{
     int x;
-}
-",
-                FixedCode = @"
-using System;
-
-public partial class Program
-{
+}}
+",
+                FixedCode = $@"
+using System;
+
+{modifier} partial class Program
+{{
     int x;

     private static void Main(string[] args)
-    {
-        Console.WriteLine(0);
-    }
-}",
-                LanguageVersion = LanguageVersion.CSharp9,
-                TestState = { OutputKind = OutputKind.ConsoleApplication },
-                Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion } },
-            }.RunAsync();
-        }
-
-        [Fact]
-        [WorkItem(62943, "https://github.com/dotnet/roslyn/issues/62943")]
-        public async Task TestHasExistingPart_KeepsModifiers()
-        {
-            await new VerifyCS.Test
-            {
-                TestCode = @"
-using System;
-
-{|IDE0211:Console|}.WriteLine(0);
-
-static partial class Program
-{
-}
-",
-                FixedCode = @"
-using System;
-
-static partial class Program
-{
-    private static void Main(string[] args)
-    {
-        Console.WriteLine(0);
-    }
-}",
+    {{
+        Console.WriteLine(0);
+    }}
+}}",
                 LanguageVersion = LanguageVersion.CSharp9,
                 TestState = { OutputKind = OutputKind.ConsoleApplication },
                 Options = { { CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion } },


#943 fixed xss (#944)

#943 fixed xss (#944)

--- src/Modules/SimplCommerce.Module.Catalog/Areas/Catalog/ViewModels/SearchOption.cs
+++ src/Modules/SimplCommerce.Module.Catalog/Areas/Catalog/ViewModels/SearchOption.cs
@@ -73,6 +73,7 @@
         public string ToJson()
         {
             var jsonSetting = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
+            jsonSetting.StringEscapeHandling = StringEscapeHandling.EscapeHtml;
             return JsonConvert.SerializeObject(this, jsonSetting);
         }
     }