Fixed bug in StratumClient when dealing with multiple queued line segments

--- src/MiningCore/Stratum/StratumClient.cs
+++ src/MiningCore/Stratum/StratumClient.cs
@@ -234,7 +234,8 @@

                                     // build buffer
                                     var queuedLength = recvQueue.Sum(x => x.Size);
-                                    var lineLength = queuedLength + index;
+                                    var segmentLength = index - prevIndex;
+                                    var lineLength = queuedLength + segmentLength;
                                     var line = ByteArrayPool.Rent(lineLength);
                                     var offset = 0;

@@ -247,8 +248,11 @@
                                         }
                                     }

-                                    // append latest buffer
-                                    Array.Copy(buf, prevIndex, line, offset, index - prevIndex);
+                                    if (segmentLength > 0)
+                                    {
+                                        // append remaining segment
+                                        Array.Copy(buf, prevIndex, line, offset, segmentLength);
+                                    }

                                     // emit
                                     observer.OnNext(new PooledArraySegment<byte>(line, 0, lineLength));


flush all events before test

flush all events before test

--- tests/NLog.UnitTests/NLogTestBase.cs
+++ tests/NLog.UnitTests/NLogTestBase.cs
@@ -56,6 +56,11 @@
         protected NLogTestBase()
         {
             //reset before every test
+            if (LogManager.Configuration != null)
+            {
+                //flush all events if needed.
+                LogManager.Configuration.Close();
+            }
             LogManager.Configuration = null;
             InternalLogger.Reset();
             LogManager.ThrowExceptions = false;


ConsoleScrollUtility

ConsoleScrollUtility


Add special-case optimizations to generic factory to improve performance

--- WootzJs.Runtime/Runtime/WootzJs/SpecialFunctions.cs
+++ WootzJs.Runtime/Runtime/WootzJs/SpecialFunctions.cs
@@ -174,9 +174,10 @@
             var type = o.GetType();
             if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>))
             {
-                if (typeof(T).GetGenericArguments()[0].IsAssignableFrom(type))
+                var typeArgument = typeof(T).GetGenericTypeArgument(0);
+                if (typeArgument.IsAssignableFrom(type))
                     return o.As<T>();
-                if (typeof(T).GetGenericArguments()[0] == typeof(char) && type == typeof(string))
+                if (typeArgument == typeof(char) && type == typeof(string))
                     return o.As<T>();
             }
             if (typeof(T) == typeof(char) && type == typeof(string))
@@ -286,16 +287,29 @@
                 cache = new JsObject();
                 unconstructedType.memberset(SpecialNames.TypeCache, cache);
             }
-            var keyArray = Jsni.call<JsArray>(x => x.slice(0), typeArgs, 0.As<JsNumber>()).As<JsArray>();
-            var keyParts = new JsArray();
-            for (var i = 0; i < keyArray.length; i++)
-            {
-                keyParts[i] = keyArray[i].member(SpecialNames.TypeName);
-            }
-            var keyString = keyParts.join(", ");
+
+            JsObject keyString;
+
+            // First two if statements are optimizations for performance reasons to avoid heap allocation when possible.
+            if (typeArgs.length == 0)
+                keyString = "";
+            else if (typeArgs.length == 1)
+                keyString = typeArgs[0].member(SpecialNames.TypeName);
+            else
+            {
+                var keyArray = Jsni.call<JsArray>(x => x.slice(0), typeArgs, 0.As<JsNumber>()).As<JsArray>();
+                var keyParts = new JsArray();
+                for (var i = 0; i < keyArray.length; i++)
+                {
+                    keyParts[i] = keyArray[i].member(SpecialNames.TypeName);
+                }
+                keyString = keyParts.join(", ");
+            }
+
             var result = cache[keyString];
             if (result == null)
             {
+                var keyArray = Jsni.call<JsArray>(x => x.slice(0), typeArgs, 0.As<JsNumber>()).As<JsArray>();
                 var lastIndexOfDollar = unconstructedType.TypeName.LastIndexOf('`');
                 if (lastIndexOfDollar == -1)
                     lastIndexOfDollar = unconstructedType.TypeName.Length;


Fix a bug that caused else clauses in if statements to get ignored by the parser (oops)

--- YarnSpinner/Parser.cs
+++ YarnSpinner/Parser.cs
@@ -705,25 +705,25 @@

 				// Handle as many <<elseif clauses as we find
 				while (p.NextSymbolsAre(TokenType.BeginCommand, TokenType.ElseIf)) {
-					var newElseClause = new Clause();
+					var elseIfClause = new Clause();

 					// Parse the syntax for this clause's condition
 					p.ExpectSymbol(TokenType.BeginCommand);
 					p.ExpectSymbol(TokenType.ElseIf);
-					newElseClause.expression = Expression.Parse(this, p);
+					elseIfClause.expression = Expression.Parse(this, p);
 					p.ExpectSymbol(TokenType.EndCommand);

 					// Read statements until we hit an <<endif, <<else or another <<elseif
-					var elseStatements = new List<Statement>();
+					var clauseStatements = new List<Statement>();
 					while (p.NextSymbolsAre(TokenType.BeginCommand, TokenType.EndIf) == false &&
 						p.NextSymbolsAre(TokenType.BeginCommand, TokenType.Else) == false &&
 						p.NextSymbolsAre(TokenType.BeginCommand, TokenType.ElseIf) == false) {
-						elseStatements.Add(new Statement(this, p));
+						clauseStatements.Add(new Statement(this, p));
 					}

-					newElseClause.statements = elseStatements;
-
-					clauses.Add(newElseClause);
+					elseIfClause.statements = clauseStatements;
+
+					clauses.Add(elseIfClause);
 				}

 				// Handle <<else>> if we have it
@@ -736,11 +736,13 @@

 					// and parse statements until we hit "<<endif"
 					var elseClause = new Clause();
-					var elseStatements = new List<Statement>();
+					var clauseStatements = new List<Statement>();
 					while (p.NextSymbolsAre(TokenType.BeginCommand, TokenType.EndIf) == false) {
-						elseStatements.Add(new Statement(this, p));
+						clauseStatements.Add(new Statement(this, p));
 					}
-					elseClause.statements = elseStatements;
+					elseClause.statements = clauseStatements;
+
+					this.clauses.Add(elseClause);
 				}

 				// Finish up by reading the <<endif>>


Correct default extension for image summarizer

--- Yeena/UI/StashForm.cs
+++ Yeena/UI/StashForm.cs
@@ -254,7 +254,7 @@
         private void imageToolStripMenuItem_Click(object sender, EventArgs e) {
             FileDialog dialog = new SaveFileDialog();
             dialog.Filter = "PNG Images (*.png)|*.png|All Files (*.*)|*.*";
-            dialog.DefaultExt = "txt";
+            dialog.DefaultExt = "png";
             if (dialog.ShowDialog() == DialogResult.Cancel) return;

             DoSummarize(new StashImageSummarizer(_imageCache), dialog.FileName);


TrueTypeMarker and RasterMarkerSymbol: Allow Multipoint

--- gView.Symbology/Framework/Symbology/Symbologies.cs
+++ gView.Symbology/Framework/Symbology/Symbologies.cs
@@ -1104,7 +1104,7 @@
             }
             else if (geometry is IMultiPoint)
             {
-                for (int i = 0; i < ((IMultiPoint)geometry).PointCount; i++)
+                for (int i = 0, to = ((IMultiPoint)geometry).PointCount; i < to; i++)
                 {
                     IPoint p = ((IMultiPoint)geometry)[i];
                     Draw(display, p);
@@ -1536,6 +1536,14 @@
                 display.World2Image(ref x, ref y);
                 IPoint p = new gView.Framework.Geometry.Point(x, y);
                 DrawPoint(display, p);
+            }
+            else if (geometry is IMultiPoint)
+            {
+                for (int i = 0, to=((IMultiPoint)geometry).PointCount; i < to; i++)
+                {
+                    IPoint p = ((IMultiPoint)geometry)[i];
+                    Draw(display, p);
+                }
             }
         }

@@ -1855,6 +1863,14 @@
                 display.World2Image(ref x, ref y);
                 IPoint p = new gView.Framework.Geometry.Point(x, y);
                 DrawPoint(display, p);
+            }
+            else if (geometry is IMultiPoint)
+            {
+                for (int i = 0, to = ((IMultiPoint)geometry).PointCount; i < to; i++)
+                {
+                    IPoint p = ((IMultiPoint)geometry)[i];
+                    Draw(display, p);
+                }
             }
         }


LoggingConfiguration - Initialize should warn when LogManager.ThrowExceptions=true (#3773)

* LoggingConfiguration - InitializeAll should warn when LogManager.ThrowExceptions = true

* Changed warning to can cause application crashes

--- src/NLog/Config/LoggingConfiguration.cs
+++ src/NLog/Config/LoggingConfiguration.cs
@@ -81,7 +81,7 @@
         /// </summary>
         public LoggingConfiguration(LogFactory logFactory)
         {
-            LogFactory = logFactory;
+            LogFactory = logFactory ?? LogManager.LogFactory;
             LoggingRules = new List<LoggingRule>();
         }

@@ -495,10 +495,9 @@
                     return null;
                 }

-                var logFactory = LogFactory ?? LogManager.LogFactory;
-                if (logFactory.KeepVariablesOnReload)
-                {
-                    var currentConfig = logFactory._config ?? this;
+                if (LogFactory.KeepVariablesOnReload)
+                {
+                    var currentConfig = LogFactory._config ?? this;
                     if (!ReferenceEquals(newConfig, currentConfig))
                     {
                         newConfig.CopyVariables(currentConfig.Variables);
@@ -533,14 +532,7 @@

                 // Refresh active logger-objects, so they stop using the removed target
                 //  - Can be called even if no LoggingConfiguration is loaded (will not trigger a config load)
-                if (LogFactory != null)
-                {
-                    LogFactory.ReconfigExistingLoggers();
-                }
-                else
-                {
-                    LogManager.ReconfigExistingLoggers();
-                }
+                LogFactory.ReconfigExistingLoggers();

                 // Perform flush and close after having stopped logger-objects from using the target
                 ManualResetEvent flushCompleted = new ManualResetEvent(false);
@@ -761,6 +753,11 @@
         {
             bool firstInitializeAll = _configItems.Count == 0;

+            if (firstInitializeAll && (LogFactory.ThrowExceptions==true || LogManager.ThrowExceptions))
+            {
+                InternalLogger.Info("LogManager.ThrowExceptions = true can crash the application! Use only for unit-testing and last resort troubleshooting.");
+            }
+
             ValidateConfig();

             if (firstInitializeAll && _targets.Count > 0)


add datatables to root

add datatables to root

--- src/Namster/Views/Shared/_Layout.cshtml
+++ src/Namster/Views/Shared/_Layout.cshtml
@@ -7,7 +7,7 @@

         <link href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en" rel="stylesheet">
         <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
-
+
         <environment names="Development">
             <link rel="stylesheet" href="~/css/dist/site.css" />
         </environment>
@@ -28,6 +28,7 @@
             asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
             asp-fallback-test="window.jQuery">
     </script>
+    <script src="//cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>

     @RenderSection("scripts", required: false)
 </body>


Code formatted

Code formatted

--- src/Nuterra.Installer/Hooking/Hooker.cs
+++ src/Nuterra.Installer/Hooking/Hooker.cs
@@ -38,7 +38,7 @@
 			Redirect(module, "ManStats+IntStatList", typeof(Hooks.Managers.Stats.IntStatList), new RedirectSettings(nameof(Hooks.Managers.Stats.IntStatList.OnSerializing)) { ReplaceBody = true });
 			Hook_StringLookup_GetString(module);
 			Hook_SpriteFetcher_GetSprite(module);
-
+
 			//Custom camera support
 			Hook_TankControl_PlayerInput(module);
 		}


implementation imageopenpolygon

implementation imageopenpolygon

--- src/Peachpie.Library.Graphics/PhpGd2.cs
+++ src/Peachpie.Library.Graphics/PhpGd2.cs
@@ -1891,6 +1891,44 @@
         public static bool imagefilledpolygon(PhpResource im, PhpArray point, int num_points, long col)
             => Polygon(im, point, num_points, col, filled: true);

+        /// <summary>
+        /// Draws an open polygon on the given image. Contrary to imagepolygon(), no line is drawn between the last and the first point.
+        /// </summary>
+        /// <param name="image">An image resource, returned by one of the image creation functions.</param>
+        /// <param name="point">An array containing the polygon's vertices.</param>
+        /// <param name="num_points">Total number of points (vertices), which must be at least 3.</param>
+        /// <param name="color">A color identifier created with imagecolorallocate().</param>
+        /// <returns>Returns TRUE on success or FALSE on failure.</returns>
+        public static bool imageopenpolygon(PhpResource image, PhpArray point, int num_points, long color)
+        {
+            var img = PhpGdImageResource.ValidImage(image);
+            if (img == null)
+                return false;
+
+            if (point == null)
+            {
+                PhpException.Throw(PhpError.Warning, Pchp.Library.Resources.Resources.unexpected_arg_given, nameof(point), PhpArray.PhpTypeName, PhpVariable.TypeNameNull);
+                return false;
+            }
+
+            if (point.Count < num_points * 2)
+            {
+                return false;
+            }
+
+            if (num_points <= 0)
+            {
+                PhpException.Throw(PhpError.Warning, Resources.must_be_positive_number_of_points);
+                return false;
+            }
+
+            var points = GetPointFsFromArray(point, num_points);
+
+            img.Image.Mutate(o => o.DrawLines(new Pen(FromRGBA(color), 1.0f),points));
+
+            return true;
+        }
+
         static bool Polygon(PhpResource im, PhpArray point, int num_points, long col, bool filled)
         {
             var img = PhpGdImageResource.ValidImage(im);
@@ -1916,17 +1954,7 @@
                 return false;
             }

-            var enumerator = point.GetFastEnumerator();
-            var points = new PointF[num_points];
-            for (int i = 0; i < points.Length; i++)
-            {
-                enumerator.MoveNext();
-                var x = (float)enumerator.CurrentValue.ToDouble();
-                enumerator.MoveNext();
-                var y = (float)enumerator.CurrentValue.ToDouble();
-
-                points[i] = new PointF(x, y);
-            }
+            var points = GetPointFsFromArray(point, num_points);

             if (filled)
             {
@@ -1958,9 +1986,30 @@
             return true;
         }

-        #endregion
-
-        #endregion
+        /// <summary>
+        /// Gets a SixLabors representation of point from PhpArray
+        /// </summary>
+        private static PointF[] GetPointFsFromArray(PhpArray point, int num_points)
+        {
+            var enumerator = point.GetFastEnumerator();
+            var points = new PointF[num_points];
+            for (int i = 0; i < points.Length; i++)
+            {
+                enumerator.MoveNext();
+                var x = (float)enumerator.CurrentValue.ToDouble();
+                enumerator.MoveNext();
+                var y = (float)enumerator.CurrentValue.ToDouble();
+
+                points[i] = new PointF(x, y);
+            }
+            return points;
+        }
+
+        #endregion
+
+        #endregion
+
+        //imagegrabscreen is only available on Windows.

         #region imageflip, imagecrop, imagescale, imageaffine, imageaffinematrixget, imageaffinematrixconcat, imageresolution

@@ -2366,6 +2415,7 @@

             return true;
         }
+
         #endregion
     }
 }


Only add customer and product features when required

--- src/Portable.Licensing/Model/License.cs
+++ src/Portable.Licensing/Model/License.cs
@@ -41,8 +41,6 @@
         public License()
             : base("License")
         {
-            ProductFeatures = new ProductFeatures();
-            Customer = new Customer();
         }

         /// <summary>
@@ -83,7 +81,13 @@
         /// </summary>
         public IProductFeatures ProductFeatures
         {
-            get { return Element("ProductFeatures") as ProductFeatures; }
+            get
+            {
+                if (Element("ProductFeatures") == null)
+                    ProductFeatures = new ProductFeatures();
+
+                return Element("ProductFeatures") as ProductFeatures;
+            }
             private set { Add(value); }
         }

@@ -92,7 +96,13 @@
         /// </summary>
         public ICustomer Customer
         {
-            get { return Element("Customer") as Customer; }
+            get
+            {
+                if(Element("Customer") == null)
+                    Customer = new Customer();
+
+                return Element("Customer") as Customer;
+            }
             private set { Add(value); }
         }


Fix logic used when comparing whether a covered statement overlaps a statement in the object being evaluated. Resolves issue when final statement in a batch is a multi-line statement prepended with a semicolon (e.g. a CTE)

--- src/SQLCover/SQLCover/CoverageResult.cs
+++ src/SQLCover/SQLCover/CoverageResult.cs
@@ -52,27 +52,18 @@

         private bool Overlaps(Statement statement, CoveredStatement coveredStatement)
         {
+            var coveredOffset = coveredStatement.Offset / 2;
+
+            if (coveredStatement.OffsetEnd == -1)
+            {
+                // Last statement in the batch, so only covered if the 'start' is equal to or less than the statement start
+                return (statement.Offset >= coveredOffset);
+            }
+
             var statementEnd = statement.Offset + statement.Length;
-
-            var coveredOffset = coveredStatement.Offset/2;
-            var coveredEnd = (coveredStatement.OffsetEnd == -1 ? statementEnd + coveredOffset : coveredStatement.OffsetEnd)/2;
-
-
-
-            if (statement.Offset >= coveredOffset && statementEnd <= coveredEnd)
-                return true;
-
-            if (statement.Offset <= coveredOffset && statementEnd >= coveredEnd)
-                return true;
-
-            if (statement.Offset >= coveredOffset && statementEnd <= coveredEnd)
-                return true;
-
-            if (coveredOffset >= statement.Offset && coveredEnd <= statementEnd)
-                return true;
-
-
-            return false;
+            var coveredEnd = coveredStatement.OffsetEnd / 2;
+
+            return (statement.Offset >= coveredOffset && statementEnd <= coveredEnd);
         }

         public string RawXml()


fixing documentation

fixing documentation

--- TruffleCache/CacheBase.cs
+++ TruffleCache/CacheBase.cs
@@ -14,7 +14,14 @@
     /// <remarks>Default Expiry of cache items is 24 hours. If you wish to extend this set an AppSetting for "TruffleCache.ExpiryInHours".</remarks>
     public abstract class CacheBase<T>
     {
+        /// <summary>
+        /// The <see cref="ICacheStore"/> this cache is using.
+        /// </summary>
         protected readonly ICacheStore cache;
+
+        /// <summary>
+        /// The default expiry that this cache is using.
+        /// </summary>
         protected readonly TimeSpan defaultExpiry;

         /// <summary>


refactored settings

refactored settings

--- TweetPublisher/Program.cs
+++ TweetPublisher/Program.cs
@@ -21,7 +21,7 @@
             Auth.SetUserCredentials(ConfigurationManager.AppSettings["Access_Token"], ConfigurationManager.AppSettings["Access_Token_Secret"], ConfigurationManager.AppSettings["Consumer_Key"], ConfigurationManager.AppSettings["Consumer_Secret"]);

             var filteredStream = Stream.CreateFilteredStream();
-            filteredStream.AddTrack("hashtagfilter");
+            filteredStream.AddTrack(ConfigurationManager.AppSettings["hashtag_filter"]);

             filteredStream.MatchingTweetReceived += (sender, tweetArgs) => {
                 Console.WriteLine(string.Format("{0} tweeted: {1}", tweetArgs.Tweet.CreatedBy.ScreenName, tweetArgs.Tweet.Text));


fixed application crash when invalid url enterd

--- src/SampleClient.Gui/MainWindow.xaml.cs
+++ src/SampleClient.Gui/MainWindow.xaml.cs
@@ -74,8 +74,12 @@
         {
             ClearOutput();
             Output("Getting timelines...");
-            SendAsync((client, cancellationToken) => client.GetTimelinesAsync(cancellationToken))
-                .ContinueWith(t =>
+            Task<TimelinesResource> task = SendAsync((client, cancellationToken) => client.GetTimelinesAsync(cancellationToken));
+
+            if (task == null)
+                return;
+
+            task.ContinueWith(t =>
                 {
                     TimelinesResource timelines = t.Result;
                     if (timelines == null)
@@ -133,8 +137,11 @@
         {
             ClearOutput();
             Output("Getting tag combination list...");
-            SendAsync((client, cancellationToken) => client.GetTagCombinationsAsync(cancellationToken))
-                .ContinueWith(t =>
+            Task<TagCombinationListResource> task = SendAsync((client, cancellationToken) => client.GetTagCombinationsAsync(cancellationToken));
+
+            if (task == null)
+                return;
+            task.ContinueWith(t =>
                 {
                     TagCombinationListResource combinations = t.Result;
                     if (combinations == null)


Forgot to save before commit

Forgot to save before commit

--- SemDiff.Core/GitHub.cs
+++ SemDiff.Core/GitHub.cs
@@ -78,17 +78,11 @@
         private async Task<string> HttpGetAsync(string url, Ref<string> etag = null)
         {
             //Request, but retry once waiting 5 minutes
-<<<<<<< HEAD
             Client.DefaultRequestHeaders.IfNoneMatch.Clear();
             if (etag?.Value != null)
             {
                 Client.DefaultRequestHeaders.IfNoneMatch.Add(EntityTagHeaderValue.Parse(etag.Value));
             }
-=======
-            paginationURL = null;
-            if (EtagNoChanges != null)
-                Client.DefaultRequestHeaders.Add("If-None-Match", EtagNoChanges);
->>>>>>> master
             var response = await Extensions.RetryOnceAsync(() => Client.GetAsync(url), TimeSpan.FromMinutes(5));
             IEnumerable<string> headerVal;
             if (response.Headers.TryGetValues("X-RateLimit-Limit", out headerVal))
@@ -105,7 +99,7 @@
             }
             if (response.Headers.TryGetValues("Link", out headerVal))
             {
-                var parsedLink = headerVal.First().Split('<', '>','"');
+                var parsedLink = headerVal.First().Split('<', '>', '"');
                 var count = 0;
                 foreach (var p in parsedLink)
                 {
@@ -116,6 +110,10 @@
                     }
                     count++;
                 }
+            }
+            else
+            {
+                paginationURL = null;
             }
             if (!response.IsSuccessStatusCode)
             {
@@ -153,31 +151,26 @@
         {
             //TODO: Investigate using the If-Modified-Since and If-None-Match headers https://developer.github.com/v3/#conditional-requests
             var url = $"/repos/{RepoOwner}/{RepoName}/pulls";
-<<<<<<< HEAD
             var etag = Ref.Create(EtagNoChanges);
-            var pullRequests = await HttpGetAsync<IList<PullRequest>>(url);
-            if (pullRequests == null)
-=======
-            var paginationPRs = await HttpGetAsync<IList<PullRequest>>(url);
+            var paginationPRs = await HttpGetAsync<IList<PullRequest>>(url, etag);
+            EtagNoChanges = etag.Value;
             var pullRequests = paginationPRs;
-            while(paginationPRs != null)
+            while (paginationPRs != null)
             {
                 paginationPRs = null;
-                if(paginationURL != null)
+                if (paginationURL != null)
                 {
                     paginationPRs = await HttpGetAsync<IList<PullRequest>>(paginationURL);
-                    foreach(var cur in paginationPRs)
+                    foreach (var cur in paginationPRs)
                     {
                         pullRequests.Add(cur);
                     }
                 }
             }
-            if(pullRequests == null)
->>>>>>> master
+            if (pullRequests == null)
             {
                 return null;
             }
-            EtagNoChanges = etag.Value;
             return await Task.WhenAll(pullRequests.Select(async pr =>
             {
                 var files = await HttpGetAsync<IList<Files>>($"/repos/{RepoOwner}/{RepoName}/pulls/{pr.Number}/files");


Cast byte to char to show ASCII output

Cast byte to char to show ASCII output

--- SerialTool/MainForm.cs
+++ SerialTool/MainForm.cs
@@ -136,7 +136,7 @@
                             if (data[i] < ' ' || data[i] > '~')
                                 output.Append('.');
                             else
-                                output.Append(data[i]);
+                                output.Append((char)data[i]);
                             break;
                     }
                 }


remove unused ACL class

remove unused ACL class

--- OpenSim/Framework/ACL.cs
+++ OpenSim/Framework/ACL.cs
@@ -1,252 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of the OpenSimulator Project nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using System;
-using System.Collections.Generic;
-
-namespace OpenSim.Framework
-{
-    // ACL Class
-    // Modelled after the structure of the Zend ACL Framework Library
-    // with one key difference - the tree will search for all matching
-    // permissions rather than just the first. Deny permissions will
-    // override all others.
-
-    #region ACL Core Class
-
-    /// <summary>
-    /// Access Control List Engine
-    /// </summary>
-    public class ACL
-    {
-        private Dictionary<string, Resource> Resources = new Dictionary<string, Resource>();
-        private Dictionary<string, Role> Roles = new Dictionary<string, Role>();
-
-        /// <summary>
-        /// Adds a new role
-        /// </summary>
-        /// <param name="role"></param>
-        /// <returns></returns>
-        public ACL AddRole(Role role)
-        {
-            if (Roles.ContainsKey(role.Name))
-                throw new AlreadyContainsRoleException(role);
-
-            Roles.Add(role.Name, role);
-
-            return this;
-        }
-
-        /// <summary>
-        /// Adds a new resource
-        /// </summary>
-        /// <param name="resource"></param>
-        /// <returns></returns>
-        public ACL AddResource(Resource resource)
-        {
-            Resources.Add(resource.Name, resource);
-
-            return this;
-        }
-
-        /// <summary>
-        /// Permision for user/roll on a resource
-        /// </summary>
-        /// <param name="role"></param>
-        /// <param name="resource"></param>
-        /// <returns></returns>
-        public Permission HasPermission(string role, string resource)
-        {
-            if (!Roles.ContainsKey(role))
-                throw new KeyNotFoundException();
-
-            if (!Resources.ContainsKey(resource))
-                throw new KeyNotFoundException();
-
-            return Roles[role].RequestPermission(resource);
-        }
-
-        public ACL GrantPermission(string role, string resource)
-        {
-            if (!Roles.ContainsKey(role))
-                throw new KeyNotFoundException();
-
-            if (!Resources.ContainsKey(resource))
-                throw new KeyNotFoundException();
-
-            Roles[role].GivePermission(resource, Permission.Allow);
-
-            return this;
-        }
-
-        public ACL DenyPermission(string role, string resource)
-        {
-            if (!Roles.ContainsKey(role))
-                throw new KeyNotFoundException();
-
-            if (!Resources.ContainsKey(resource))
-                throw new KeyNotFoundException();
-
-            Roles[role].GivePermission(resource, Permission.Deny);
-
-            return this;
-        }
-
-        public ACL ResetPermission(string role, string resource)
-        {
-            if (!Roles.ContainsKey(role))
-                throw new KeyNotFoundException();
-
-            if (!Resources.ContainsKey(resource))
-                throw new KeyNotFoundException();
-
-            Roles[role].GivePermission(resource, Permission.None);
-
-            return this;
-        }
-    }
-
-    #endregion
-
-    #region Exceptions
-
-    /// <summary>
-    /// Thrown when an ACL attempts to add a duplicate role.
-    /// </summary>
-    public class AlreadyContainsRoleException : Exception
-    {
-        protected Role m_role;
-
-        public AlreadyContainsRoleException(Role role)
-        {
-            m_role = role;
-        }
-
-        public Role ErrorRole
-        {
-            get { return m_role; }
-        }
-
-        public override string ToString()
-        {
-            return "This ACL already contains a role called '" + m_role.Name + "'.";
-        }
-    }
-
-    #endregion
-
-    #region Roles and Resources
-
-    /// <summary>
-    /// Does this Role have permission to access a specified Resource?
-    /// </summary>
-    public enum Permission
-    {
-        Deny,
-        None,
-        Allow
-    } ;
-
-    /// <summary>
-    /// A role class, for use with Users or Groups
-    /// </summary>
-    public class Role
-    {
-        private string m_name;
-        private Role[] m_parents;
-        private Dictionary<string, Permission> m_resources = new Dictionary<string, Permission>();
-
-        public Role(string name)
-        {
-            m_name = name;
-            m_parents = null;
-        }
-
-        public Role(string name, Role[] parents)
-        {
-            m_name = name;
-            m_parents = parents;
-        }
-
-        public string Name
-        {
-            get { return m_name; }
-        }
-
-        public Permission RequestPermission(string resource)
-        {
-            return RequestPermission(resource, Permission.None);
-        }
-
-        public Permission RequestPermission(string resource, Permission current)
-        {
-            // Deny permissions always override any others
-            if (current == Permission.Deny)
-                return current;
-
-            Permission temp = Permission.None;
-
-            // Pickup non-None permissions
-            if (m_resources.ContainsKey(resource) && m_resources[resource] != Permission.None)
-                temp = m_resources[resource];
-
-            if (m_parents != null)
-            {
-                foreach (Role parent in m_parents)
-                {
-                    temp = parent.RequestPermission(resource, temp);
-                }
-            }
-
-            return temp;
-        }
-
-        public void GivePermission(string resource, Permission perm)
-        {
-            m_resources[resource] = perm;
-        }
-    }
-
-    public class Resource
-    {
-        private string m_name;
-
-        public Resource(string name)
-        {
-            m_name = name;
-        }
-
-        public string Name
-        {
-            get { return m_name; }
-        }
-    }
-
-    #endregion
-
-
-}


Add basic blocking migration, move not copy

--- osu.Game/IO/OsuStorage.cs
+++ osu.Game/IO/OsuStorage.cs
@@ -1,6 +1,8 @@
 // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
 // See the LICENCE file in the repository root for full licence text.

+using System;
+using System.IO;
 using osu.Framework.Logging;
 using osu.Framework.Platform;
 using osu.Game.Configuration;
@@ -9,10 +11,15 @@
 {
     public class OsuStorage : WrappedStorage
     {
+        private readonly GameHost host;
+        private readonly StorageConfigManager storageConfig;
+
         public OsuStorage(GameHost host)
             : base(host.Storage, string.Empty)
         {
-            var storageConfig = new StorageConfigManager(host.Storage);
+            this.host = host;
+
+            storageConfig = new StorageConfigManager(host.Storage);

             var customStoragePath = storageConfig.Get<string>(StorageConfig.FullPath);

@@ -22,5 +29,34 @@
                 Logger.Storage = UnderlyingStorage.GetStorageForDirectory("logs");
             }
         }
+
+        public void Migrate(string newLocation)
+        {
+            string oldLocation = GetFullPath(".");
+
+            // ensure the new location has no files present, else hard abort
+            if (Directory.Exists(newLocation))
+            {
+                if (Directory.GetFiles(newLocation).Length > 0)
+                    throw new InvalidOperationException("Migration destination already has files present");
+
+                Directory.Delete(newLocation, true);
+            }
+
+            Directory.Move(oldLocation, newLocation);
+
+            Directory.CreateDirectory(newLocation);
+            // temporary
+            Directory.CreateDirectory(oldLocation);
+
+            // move back exceptions for now
+            Directory.Move(Path.Combine(newLocation, "cache"), Path.Combine(oldLocation, "cache"));
+            File.Move(Path.Combine(newLocation, "framework.ini"), Path.Combine(oldLocation, "framework.ini"));
+
+            ChangeTargetStorage(host.GetStorage(newLocation));
+
+            storageConfig.Set(StorageConfig.FullPath, newLocation);
+            storageConfig.Save();
+        }
     }
 }


Fixed ToxId.IsValid

Fixed ToxId.IsValid

--- SharpTox/Core/ToxId.cs
+++ SharpTox/Core/ToxId.cs
@@ -115,7 +115,7 @@
                 Array.Copy(id, 36, checksum, 0, 2);
                 check = BitConverter.ToUInt16(checksum, 0);

-                return CalcChecksum(id, 36) != check;
+                return CalcChecksum(id, 36) == check;
             }
             catch
             {


1.5.0

--- Views/Shared/Error.cshtml
+++ Views/Shared/Error.cshtml
@@ -1,7 +1,10 @@
-@model ErrorViewModel
+@using Microsoft.AspNetCore.Hosting
+@model ErrorViewModel
+@inject IHostingEnvironment host

 @{
     var error = Model?.Error?.Error;
+    var errorDescription = host.IsDevelopment() ? Model?.Error?.ErrorDescription : null;
     var request_id = Model?.Error?.RequestId;
 }

@@ -22,6 +25,11 @@
                             : @error
                         </em>
                     </strong>
+
+                    if (errorDescription != null)
+                    {
+                        <div>@errorDescription</div>
+                    }
                 }
             </div>


more rescan menu

more rescan menu

--- SimpleDLNA/FormMain.cs
+++ SimpleDLNA/FormMain.cs
@@ -418,9 +418,12 @@
           continue;
         }
         var innerItem = item;
-        var sm = new ToolStripMenuItem(item.Text) { Tag = innerItem };
-        var rescan = sm.DropDownItems.Add("Rescan");
-        rescan.Click += (s, a) =>
+        var menuItem =
+          new ToolStripMenuItem(String.Format("Rescan {0}", item.Text)) {
+            Tag = innerItem,
+            Image = Properties.Resources.refreshing
+          };
+        menuItem.Click += (s, a) =>
         {
           try {
             innerItem.Rescan();
@@ -429,7 +432,7 @@
             // no op
           }
         };
-        items.Add(sm);
+        items.Add(menuItem);
       }
       items.Reverse();
       var idx = notifyContext.Items.IndexOf(ContextSeperatorPre) + 1;


Remove debug logs

Remove debug logs

--- Source/DMExtensions.cs
+++ Source/DMExtensions.cs
@@ -43,7 +43,7 @@
 		{
 			if (node.HasValue(name))
 			{
-				DMUtils.DebugLog("Parsing value [{0}] = {1}", name, node.GetValue(name));
+				//DMUtils.DebugLog("Parsing value [{0}] = {1}", name, node.GetValue(name));
 				return node.GetValue(name);
 			}

@@ -59,7 +59,7 @@

 			if (int.TryParse(node.GetValue(name), out i))
 			{
-				DMUtils.DebugLog("Parsing value [{0}] = {1}", name, i);
+				//DMUtils.DebugLog("Parsing value [{0}] = {1}", name, i);
 				return i;
 			}

@@ -88,7 +88,7 @@

 			if (float.TryParse(node.GetValue(name), out f))
 			{
-				DMUtils.DebugLog("Parsing value [{0}] = {1}", name, f);
+				//DMUtils.DebugLog("Parsing value [{0}] = {1}", name, f);
 				return f;
 			}

@@ -117,7 +117,7 @@

 			if (double.TryParse(node.GetValue(name), out d))
 			{
-				DMUtils.DebugLog("Parsing value [{0}] = {1}", name, d);
+				//DMUtils.DebugLog("Parsing value [{0}] = {1}", name, d);
 				return d;
 			}

@@ -133,7 +133,7 @@

 			if (bool.TryParse(node.GetValue(name), out b))
 			{
-				DMUtils.DebugLog("Parsing value [{0}] = {1}", name, b);
+				//DMUtils.DebugLog("Parsing value [{0}] = {1}", name, b);
 				return b;
 			}

@@ -145,7 +145,7 @@
 			if (!node.HasValue(name))
 				return original;

-			DMUtils.DebugLog("Parsing value [{0}] = {1}", name, node.GetValue(name));
+			//DMUtils.DebugLog("Parsing value [{0}] = {1}", name, node.GetValue(name));

 			return node.GetValue(name).Split(separator).ToList();
 		}
@@ -283,7 +283,7 @@
 				c = FlightGlobals.Bodies[body];
 			else
 			{
-				DMUtils.DebugLog("Parsing value [{0}] = {1}", name, c.theName);
+				//DMUtils.DebugLog("Parsing value [{0}] = {1}", name, c.theName);
 				return original;
 			}


Don't log empty metadata updates

Don't log empty metadata updates

--- SpotifyClient/Track.cs
+++ SpotifyClient/Track.cs
@@ -134,6 +134,9 @@
                         remove.Add(track);
                 }

+                if(remove.Count == 0)
+                    return;
+
                 LogTo.Debug("Tracks loaded: {0}", remove.Count);
                 foreach (var removal in remove)
                     ToInitialize.Remove(removal);


used var by convention

used var by convention

--- Storks/StorkHelpers.cs
+++ Storks/StorkHelpers.cs
@@ -25,7 +25,7 @@
         {
             if (parameterExpression.Compile()() == null)
             {
-                string name = GetParameterName(parameterExpression);
+                var name = GetParameterName(parameterExpression);
                 throw new ArgumentNullException(name);
             }
         }


Fix for multiline whitespace before and after multiline condition lines

--- inklecate2Sharp/Parser/InkParser_Conditional.cs
+++ inklecate2Sharp/Parser/InkParser_Conditional.cs
@@ -127,12 +127,15 @@

         protected List<ConditionalSingleBranch> MultilineConditionalBranches()
         {
+            MultilineWhitespace ();
+
             List<object> multipleConditions = OneOrMore (SingleMultilineCondition);
-            if (multipleConditions == null) {
+            if (multipleConditions == null)
                 return null;
-            } else {
-                return multipleConditions.Cast<ConditionalSingleBranch>().ToList();
-            }
+
+            MultilineWhitespace ();
+
+            return multipleConditions.Cast<ConditionalSingleBranch>().ToList();
         }

         protected ConditionalSingleBranch SingleMultilineCondition()


Committing this file so tkimball can start documenting

git-svn-id: c32cf1ecefca26b8770d7b0740bc0c5c174087e4@334 c754d5e9-d413-0410-bcdf-9574c9dba6b7

--- libsecondlife-cs/Avatar.cs
+++ libsecondlife-cs/Avatar.cs
@@ -673,9 +673,6 @@

                 if ( sim != null)
                 {
-                    // Sync the current region and current simulator
-                    Client.CurrentRegion = Client.Network.CurrentSim.Region;
-
                     // Move the avatar in to this sim
                     CompleteAgentMovementPacket move = new CompleteAgentMovementPacket();
                     move.AgentData.AgentID = this.ID;


フォローが見れない不具合を修正

フォローが見れない不具合を修正

--- SRNicoNico/Models/NicoNicoWrapper/NicoNicoFollow.cs
+++ SRNicoNico/Models/NicoNicoWrapper/NicoNicoFollow.cs
@@ -75,7 +75,7 @@

                     //説明文がないユーザーはなしにする
                     var p = outer.SelectSingleNode("div/p");
-                    user.Description = p.Attributes["class"] == null ? p.InnerText.Trim(): "";
+                    user.Description = p == null ? "" : p.InnerText.Trim();

                     ret.Add(user);
                 }


fix asserts

fix asserts

--- osu.Framework.Tests/Clocks/StopwatchClockTest.cs
+++ osu.Framework.Tests/Clocks/StopwatchClockTest.cs
@@ -75,7 +75,10 @@
         public void TestSeekNegativeAdjustRate()
         {
             var stopwatchClock = new StopwatchClock();
+
             stopwatchClock.Seek(-5000);
+            Assert.AreEqual(-5000, stopwatchClock.CurrentTime);
+
             stopwatchClock.Rate = 2.0f;
             stopwatchClock.Start();

@@ -83,7 +86,7 @@

             stopwatchClock.Stop();
             var stoppedTime = stopwatchClock.CurrentTime;
-            Assert.Greater(stoppedTime, 0);
+            Assert.Less(stoppedTime, 0);

             stopwatchClock.Seek(stopwatchClock.CurrentTime);


Fixed nullreference exception within SimpleTasks/FilterTask

--- SabberStoneCore/src/Tasks/SimpleTasks/FilterTask.cs
+++ SabberStoneCore/src/Tasks/SimpleTasks/FilterTask.cs
@@ -46,8 +46,9 @@

 			if (SelfConditions != null)
 			{
+				var selfConditionList = SelfConditions.Where(x => x != null).ToList();
 				Playables = Playables
-					.Where(p1 => SelfConditions.ToList().TrueForAll(p2 => p2.Eval(p1)))
+					.Where(p1 => selfConditionList.TrueForAll(p2 => p2.Eval(p1)))
 					.ToList();
 			}


add a sprite text to show current display in test case

--- osu.Framework.Tests/Visual/TestCaseFullscreen.cs
+++ osu.Framework.Tests/Visual/TestCaseFullscreen.cs
@@ -14,6 +14,7 @@
     public class TestCaseFullscreen : TestCase
     {
         private readonly SpriteText currentActualSize = new SpriteText();
+        private readonly SpriteText currentDisplay = new SpriteText();

         private GameWindow window;
         private readonly BindableSize sizeFullscreen = new BindableSize();
@@ -29,6 +30,7 @@
                 {
                     currentBindableSize,
                     currentActualSize,
+                    currentDisplay
                 },
             };

@@ -64,6 +66,7 @@
             base.Update();

             currentActualSize.Text = $"Window size: {window?.Bounds.Size}";
+            currentDisplay.Text = $"Current display device: {window?.GetCurrentDisplay()}";
         }
     }
 }


Fix incorrect test assumption (affected by random select above)

--- osu.Game.Tests/Visual/TestCaseBeatmapCarousel.cs
+++ osu.Game.Tests/Visual/TestCaseBeatmapCarousel.cs
@@ -240,7 +240,7 @@

             checkVisibleItemCount(false, set_count);

-            checkSelected(set_count, 2);
+            checkSelected(set_count);
         }

         /// <summary>


[packages,WindowsSDK,10] Issue #259. Added missing include path for the WindowsSDK 10 headers

--- packages/WindowsSDK-10/bam/Scripts/WindowsSDK.cs
+++ packages/WindowsSDK-10/bam/Scripts/WindowsSDK.cs
@@ -54,6 +54,7 @@
                 var rcCompilation = settings as C.ICommonWinResourceCompilerSettings;
                 if (null != rcCompilation)
                 {
+                    rcCompilation.IncludePaths.AddUnique(this.CreateTokenizedString(@"$(0)Include\$(1)\ucrt", installDir10, v10));
                     rcCompilation.IncludePaths.AddUnique(this.CreateTokenizedString(@"$(0)Include\um", installDir81));
                     rcCompilation.IncludePaths.AddUnique(this.CreateTokenizedString(@"$(0)Include\shared", installDir81));
                 }


Ignoring ReSharper warnings about meaningful method names in Extensions

--- src/Specific/SpecificationExtensions.cs
+++ src/Specific/SpecificationExtensions.cs
@@ -1,5 +1,7 @@
 namespace Specific
 {
+    // ReSharper disable MethodNamesNotMeaningful
+
     /// <summary>
     /// Extensions for combining specifications using logical operations.
     /// </summary>


added finish statement to let users know when done

--- iRobotSongSimulator/iRobotSongSimulator/Program.cs
+++ iRobotSongSimulator/iRobotSongSimulator/Program.cs
@@ -32,7 +32,7 @@
                 {
                     case "song":
                         if (cmd.Length % 2 == 1)
-                            consoleNotes(cmd, dictionary);
+                            fromConsole(cmd, dictionary);
                         else
                             Console.WriteLine("Incorrect number of arguments (need even number).");
                         break;
@@ -64,9 +64,10 @@
                 int length = Int32.Parse(splitLines[1]);
                 playNote(freq, length);
             }
+            Console.Write("Finished.");
         }

-        private static void consoleNotes(string[] args, Dictionary<int, double> dic)
+        private static void fromConsole(string[] args, Dictionary<int, double> dic)
         {
             for (int i = 1; i < args.Length - 1; i += 2)
             {
@@ -78,6 +79,7 @@
                     playNote(freq, duration);
                 }
             }
+            Console.Write("Finished.");
         }

         /* string outerTag = "<DeviceSettings>\n{0}</DeviceSettings>";


Add serilog sink dependencies to build script.

--- packages.cake
+++ packages.cake
@@ -243,6 +243,8 @@
                 Dependencies = new DependencyBuilder(this)
                 {
                     new NuSpecDependency() { Id = "Serilog", Version = SerilogVersion },
+                    new NuSpecDependency() { Id = "Serilog.Sinks.Debug", Version = "1.0.0" },
+                    new NuSpecDependency() { Id = "Serilog.Sinks.Trace", Version = "2.1.0" },
                     new NuSpecDependency() { Id = "Sprache", Version = SpracheVersion },
                     new NuSpecDependency() { Id = "System.Reactive", Version = SystemReactiveVersion },
                     new NuSpecDependency() { Id = "Avalonia.Remote.Protocol", Version = parameters.Version },
@@ -251,6 +253,8 @@
                     new NuSpecDependency() { Id = "Microsoft.Extensions.DependencyModel", TargetFramework = "netcoreapp2.0", Version = "1.1.0" },
                     new NuSpecDependency() { Id = "NETStandard.Library", TargetFramework = "netcoreapp2.0", Version = "1.6.0" },
                     new NuSpecDependency() { Id = "Serilog", TargetFramework = "netcoreapp2.0", Version = SerilogVersion },
+                    new NuSpecDependency() { Id = "Serilog.Sinks.Debug", TargetFramework = "netcoreapp2.0", VersionVersion = "1.0.0" },
+                    new NuSpecDependency() { Id = "Serilog.Sinks.Trace", TargetFramework = "netcoreapp2.0", VersionVersion = "2.1.0" },
                     new NuSpecDependency() { Id = "Sprache", TargetFramework = "netcoreapp2.0", Version = SpracheVersion },
                     new NuSpecDependency() { Id = "System.Reactive", TargetFramework = "netcoreapp2.0", Version = SystemReactiveVersion },
                     new NuSpecDependency() { Id = "Avalonia.Remote.Protocol", TargetFramework = "netcoreapp2.0", Version = parameters.Version },


Fixed bug in the RSS-handler with PrefixlessPermalinks. See issue #140.

--- Piranha/Web/RssHelper.cs
+++ Piranha/Web/RssHelper.cs
@@ -73,7 +73,7 @@
 		/// <returns>The public link</returns>
 		private static string PublicLink(HttpRequest request, string permalink) {
 			return WebPages.WebPiranha.GetSiteUrl() + "/" +
-				Application.Current.Handlers.GetUrlPrefix("PERMALINK") + "/" + permalink ;
+				(!WebPages.WebPiranha.PrefixlessPermalinks ? Application.Current.Handlers.GetUrlPrefix("PERMALINK") + "/" : "") + permalink ;
 		}

 		/// <summary>


Get an Encoding as parameter in several methods, instead of instantiating a new local one. Don't XMLize macro text anymore (i.e. no <autotrans> tags, but they're still supported when reading the XML file). In WriteEncodedString(), handle being passed null.

--- PlayOnline.FFXI/Macro.cs
+++ PlayOnline.FFXI/Macro.cs
@@ -63,10 +63,9 @@

     #region MacroBar Access

-    internal static Macro ReadFromMacroBar(BinaryReader BR) {
+    internal static Macro ReadFromMacroBar(BinaryReader BR, Encoding E) {
     Macro M = new Macro();
       if (BR != null) {
-      Encoding E = new FFXIEncoding();
 	BR.ReadInt32(); // Unknown
 	for (int i = 0; i < 6; ++i) { // 6 Lines of text, 61 bytes each, null-terminated shift-jis
 	string Command = "";
@@ -78,8 +77,7 @@
       return M;
     }

-    internal void WriteToMacroBar(BinaryWriter BW) {
-    Encoding E = new FFXIEncoding();
+    internal void WriteToMacroBar(BinaryWriter BW, Encoding E) {
       BW.Write((uint) 0);
       for (int i = 0; i < 6; ++i) // 6 Lines of text, 61 bytes each, nul-terminated shift-jis
 	this.WriteEncodedString(BW, this.Commands_[i], E, 61);
@@ -88,6 +86,8 @@

     private void WriteEncodedString(BinaryWriter BW, string Text, Encoding E, int Bytes) {
     ArrayList OutBytes = new ArrayList(Bytes);
+      if (Text == null)
+	Text = String.Empty;
       OutBytes.AddRange(E.GetBytes(Text));
       while (OutBytes.Count > Bytes)
 	OutBytes.RemoveAt(Bytes);
@@ -104,6 +104,7 @@
     Macro M = new Macro();
       if (MacroNode.Attributes["name"] != null)
 	M.Name_ = MacroNode.Attributes["name"].InnerText;
+    Encoding E = new FFXIEncoding();
       for (int i = 0; i < 6; ++i) {
       XmlNode CommandNode = MacroNode.SelectSingleNode(String.Format("command[@line = {0}]", i + 1));
 	if (CommandNode != null && CommandNode is XmlElement) {
@@ -111,11 +112,13 @@
 	  foreach (XmlNode XN in CommandNode.ChildNodes) {
 	    if (XN is XmlText)
 	      CommandText += XN.InnerText;
+	    // Backwards compatibility - to be removed
 	    else if (XN is XmlElement && XN.Name == "autotrans") {
 	    ushort Category = 0; try { XmlAttribute XCat   = XN.Attributes["category"]; Category = ushort.Parse(XCat.InnerText);   } catch {}
 	    byte   Group    = 0; try { XmlAttribute XGroup = XN.Attributes["group"];    Group    =   byte.Parse(XGroup.InnerText); } catch {}
 	    byte   ID       = 0; try { XmlAttribute XID    = XN.Attributes["id"];       ID       =   byte.Parse(XID.InnerText);    } catch {}
-	      CommandText += String.Format("\x00AB{0}/{1}/{2}: {3}\x00BB", Category, Group, ID, AutoTranslator.GetMessage(Group, ID, Category));
+	    byte[] ResourceMarker = new byte[] { 0xFD, (byte) (Category & 0xff), (byte) (Category >> 8), Group, ID, 0xFD };
+	      CommandText += E.GetString(ResourceMarker);
 	    }
 	  }
 	  M.Commands_[i] = CommandText;
@@ -139,53 +142,7 @@
 	    XLine.InnerText = String.Format("{0}", i + 1);
 	    XCommand.Attributes.Append(XLine);
 	  }
-	string CommandText = this.Commands_[i];
-	int MarkerPos = CommandText.IndexOf('\x00AB', 0);
-	  while (MarkerPos >= 0) {
-	  int EndMarkerPos = CommandText.IndexOf('\x00BB', MarkerPos);
-	  int NextMarkerPos = CommandText.IndexOf('\x00AB', MarkerPos + 1);
-	    if (EndMarkerPos > 0 && (NextMarkerPos < 0 || NextMarkerPos > EndMarkerPos)) { // Parse Contents
-	      if (MarkerPos > 0) // Save preceding text (if any)
-		XCommand.AppendChild(XDoc.CreateTextNode(CommandText.Substring(0, MarkerPos)));
-	    string Marker = CommandText.Substring(MarkerPos + 1, (EndMarkerPos - MarkerPos - 1));
-	      CommandText = CommandText.Substring(EndMarkerPos + 1);
-	    XmlElement XAutoTrans = null;
-	    string[] MarkerAndText = Marker.Split(new char[] { ':' }, 2);
-	      if (MarkerAndText.Length == 2) {
-	      string[] MarkerValues = MarkerAndText[0].Split('/');
-		if (MarkerValues.Length == 3) {
-		XAutoTrans = XDoc.CreateElement("autotrans");
-		  XAutoTrans.InnerText = MarkerAndText[1].Substring(1); // skip space after the ':'
-		  { // add 'category' attribute
-		  XmlAttribute XATCategory = XDoc.CreateAttribute("category");
-		    XATCategory.InnerText = MarkerValues[0];
-		    XAutoTrans.Attributes.Append(XATCategory);
-		  }
-		  { // add 'group' attribute
-		  XmlAttribute XATLang = XDoc.CreateAttribute("group");
-		    XATLang.InnerText = MarkerValues[1];
-		    XAutoTrans.Attributes.Append(XATLang);
-		  }
-		  { // add 'id' attribute
-		  XmlAttribute XATLang = XDoc.CreateAttribute("id");
-		    XATLang.InnerText = MarkerValues[2];
-		    XAutoTrans.Attributes.Append(XATLang);
-		  }
-		}
-	      }
-	      if (XAutoTrans == null) // invalid marker
-		XCommand.AppendChild(XDoc.CreateTextNode(Marker));
-	      else
-		XCommand.AppendChild(XAutoTrans);
-	    }
-	    else { // Not a valid autotrans marker
-	      XCommand.AppendChild(XDoc.CreateTextNode(CommandText.Substring(0, MarkerPos + 1)));
-	      CommandText = CommandText.Substring(MarkerPos + 1);
-	    }
-	    MarkerPos = CommandText.IndexOf('\x00AB', 0);
-	  }
-	  if (CommandText != String.Empty)
-	    XCommand.AppendChild(XDoc.CreateTextNode(CommandText));
+	  XCommand.AppendChild(XDoc.CreateTextNode(this.Commands_[i]));
 	  XMacro.AppendChild(XCommand);
 	}
       }