Update Rider plugin

Update Rider plugin

--- Assets/Plugins/Editor/JetBrains/Unity3DRider.cs
+++ Assets/Plugins/Editor/JetBrains/Unity3DRider.cs
@@ -1,7 +1,7 @@
 //------------------------------------------------------------------------------
 // <auto-generated>
 //     This code was generated by a tool.
-//     Version: 2.0.2.2395
+//     Version: 2.1.2.1402
 //
 //     Changes to this file may cause incorrect behavior and will be lost if
 //     the code is regenerated.
@@ -83,7 +83,14 @@
       XNamespace xmlns = projectContentElement.Name.NamespaceName; // do not use var

       FixTargetFrameworkVersion(projectContentElement, xmlns);
+      FixSystemXml(projectContentElement, xmlns);
       SetLangVersion(projectContentElement, xmlns);
+      // Unity_5_6_OR_NEWER switched to nunit 3.5
+      // Fix helps only for Windows, on mac and linux I get https://youtrack.jetbrains.com/issue/RSRP-459932
+#if UNITY_5_6_OR_NEWER && UNITY_STANDALONE_WIN
+      ChangeNunitReference(new FileInfo(projectFile).DirectoryName, projectContentElement, xmlns);
+#endif
+
 #if !UNITY_2017_1_OR_NEWER // Unity 2017.1 and later has this features by itself
       SetManuallyDefinedComilingSettings(projectFile, projectContentElement, xmlns);
       SetXCodeDllReference("UnityEditor.iOS.Extensions.Xcode.dll", xmlns, projectContentElement);
@@ -91,27 +98,66 @@
 #endif
       doc.Save(projectFile);
     }
+
+    private static void FixSystemXml(XElement projectContentElement, XNamespace xmlns)
+    {
+      var el = projectContentElement
+        .Elements(xmlns+"ItemGroup")
+        .Elements(xmlns+"Reference")
+        .FirstOrDefault(a => a.Attribute("Include").Value=="System.XML");
+      if (el != null)
+      {
+        el.Attribute("Include").Value = "System.Xml";
+      }
+    }
+
+    private static void ChangeNunitReference(string baseDir, XElement projectContentElement, XNamespace xmlns)
+    {
+      var el = projectContentElement
+        .Elements(xmlns+"ItemGroup")
+        .Elements(xmlns+"Reference")
+        .FirstOrDefault(a => a.Attribute("Include").Value=="nunit.framework");
+      if (el != null)
+      {
+        var hintPath = el.Elements(xmlns + "HintPath").FirstOrDefault();
+        if (hintPath != null)
+        {
+          string unityAppBaseFolder = Path.GetDirectoryName(EditorApplication.applicationPath);
+          var path = Path.Combine(unityAppBaseFolder, "Data/Managed/nunit.framework.dll");
+          if (new FileInfo(path).Exists)
+            hintPath.Value = path;
+        }
+      }
+    }

 #if !UNITY_2017_1_OR_NEWER  // Unity 2017.1 and later has this features by itself
     private const string UNITY_PLAYER_PROJECT_NAME = "Assembly-CSharp.csproj";
     private const string UNITY_EDITOR_PROJECT_NAME = "Assembly-CSharp-Editor.csproj";
     private const string UNITY_UNSAFE_KEYWORD = "-unsafe";
     private const string UNITY_DEFINE_KEYWORD = "-define:";
-    private const string PLAYER_PROJECT_MANUAL_CONFIG_RELATIVE_FILE_PATH = "smcs.rsp";
-    private static readonly string  PLAYER_PROJECT_MANUAL_CONFIG_ABSOLUTE_FILE_PATH = Path.Combine(UnityEngine.Application.dataPath, PLAYER_PROJECT_MANUAL_CONFIG_RELATIVE_FILE_PATH);
-    private const string EDITOR_PROJECT_MANUAL_CONFIG_RELATIVE_FILE_PATH = "gmcs.rsp";
-    private static readonly string  EDITOR_PROJECT_MANUAL_CONFIG_ABSOLUTE_FILE_PATH = Path.Combine(UnityEngine.Application.dataPath, EDITOR_PROJECT_MANUAL_CONFIG_RELATIVE_FILE_PATH);
+    private static readonly string  PROJECT_MANUAL_CONFIG_ABSOLUTE_FILE_PATH = Path.Combine(UnityEngine.Application.dataPath, "mcs.rsp");
+    private static readonly string  PLAYER_PROJECT_MANUAL_CONFIG_ABSOLUTE_FILE_PATH = Path.Combine(UnityEngine.Application.dataPath, "smcs.rsp");
+    private static readonly string  EDITOR_PROJECT_MANUAL_CONFIG_ABSOLUTE_FILE_PATH = Path.Combine(UnityEngine.Application.dataPath, "gmcs.rsp");

     private static void SetManuallyDefinedComilingSettings(string projectFile, XElement projectContentElement, XNamespace xmlns)
     {
-      string configPath;
-
-      if (IsPlayerProjectFile(projectFile))
-        configPath = PLAYER_PROJECT_MANUAL_CONFIG_ABSOLUTE_FILE_PATH;
-      else if (IsEditorProjectFile(projectFile))
-        configPath = EDITOR_PROJECT_MANUAL_CONFIG_ABSOLUTE_FILE_PATH;
-      else
-        configPath = null;
+      string configPath = null;
+
+      if (IsPlayerProjectFile(projectFile) || IsEditorProjectFile(projectFile))
+      {
+        //Prefer mcs.rsp if it exists
+        if (File.Exists(PROJECT_MANUAL_CONFIG_ABSOLUTE_FILE_PATH))
+        {
+          configPath = PROJECT_MANUAL_CONFIG_ABSOLUTE_FILE_PATH;
+        }
+        else
+        {
+          if (IsPlayerProjectFile(projectFile))
+            configPath = PLAYER_PROJECT_MANUAL_CONFIG_ABSOLUTE_FILE_PATH;
+          else if (IsEditorProjectFile(projectFile))
+            configPath = EDITOR_PROJECT_MANUAL_CONFIG_ABSOLUTE_FILE_PATH;
+        }
+      }

       if(!string.IsNullOrEmpty(configPath))
         ApplyManualCompilingSettings(configPath
@@ -217,16 +263,7 @@
         .FirstOrDefault(); // Processing csproj files, which are not Unity-generated #56
       if (targetFrameworkVersion != null)
       {
-        var version = new Version(targetFrameworkVersion.Value.Substring(1));
-        if (RiderPlugin.TargetFrameworkVersion45)
-        {
-          if (version < new Version(4, 5))
-            targetFrameworkVersion.SetValue("v4.5");
-        }
-        else
-        {
-          targetFrameworkVersion.SetValue("v3.5");
-        }
+        targetFrameworkVersion.SetValue("v"+RiderPlugin.TargetFrameworkVersion);
       }
     }

@@ -273,7 +310,7 @@
 {
   [InitializeOnLoad]
   public static class RiderPlugin
-  {
+  {
     private static bool Initialized;
     private static string SlnFile;

@@ -281,8 +318,8 @@
     {
       if (level < SelectedLoggingLevel) return;

-      var text = "[Rider] [" + level + "] " +  initialText;
-
+      var text = "[Rider] [" + level + "] " + initialText;
+
       switch (level)
       {
         case LoggingLevel.Warning:
@@ -293,72 +330,117 @@
           break;
       }
     }
-
+
     private static string GetDefaultApp()
     {
-        var alreadySetPath = GetExternalScriptEditor();
-        if (!string.IsNullOrEmpty(alreadySetPath) && RiderPathExist(alreadySetPath))
-          return alreadySetPath;
-
-        switch (SystemInfoRiderPlugin.operatingSystemFamily)
-        {
-          case OperatingSystemFamily.Windows:
-            //"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\JetBrains\*Rider*.lnk"
-            //%appdata%\Microsoft\Windows\Start Menu\Programs\JetBrains Toolbox\*Rider*.lnk
-            string[] folders = {@"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\JetBrains", Path.Combine(
+      var alreadySetPath = GetExternalScriptEditor();
+      if (!string.IsNullOrEmpty(alreadySetPath) && RiderPathExist(alreadySetPath))
+        return alreadySetPath;
+
+      return RiderPath;
+    }
+
+    private static string[] GetAllRiderPaths()
+    {
+      switch (SystemInfoRiderPlugin.operatingSystemFamily)
+      {
+        case OperatingSystemFamily.Windows:
+          string[] folders =
+          {
+            @"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\JetBrains", Path.Combine(
               Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
-              @"Microsoft\Windows\Start Menu\Programs\JetBrains Toolbox")};
-
-            var newPathLnks = folders.Select(b=>new DirectoryInfo(b)).Where(a => a.Exists).SelectMany(c=>c.GetFiles("*Rider*.lnk"));
-            if (newPathLnks.Any())
+              @"Microsoft\Windows\Start Menu\Programs\JetBrains Toolbox")
+          };
+
+          var newPathLnks = folders.Select(b => new DirectoryInfo(b)).Where(a => a.Exists)
+            .SelectMany(c => c.GetFiles("*Rider*.lnk")).ToArray();
+          if (newPathLnks.Any())
+          {
+            var newPaths = newPathLnks
+              .Select(newPathLnk => new FileInfo(ShortcutResolver.Resolve(newPathLnk.FullName)))
+              .Where(fi => File.Exists(fi.FullName))
+              .ToArray()
+              .OrderByDescending(fi => FileVersionInfo.GetVersionInfo(fi.FullName).ProductVersion)
+              .Select(a => a.FullName).ToArray();
+
+            return newPaths;
+          }
+          break;
+
+        case OperatingSystemFamily.MacOSX:
+          // "/Applications/*Rider*.app"
+          //"~/Applications/JetBrains Toolbox/*Rider*.app"
+          string[] foldersMac =
+          {
+            "/Applications", Path.Combine(Environment.GetEnvironmentVariable("HOME"), "Applications/JetBrains Toolbox")
+          };
+          var newPathsMac = foldersMac.Select(b => new DirectoryInfo(b)).Where(a => a.Exists)
+            .SelectMany(c => c.GetDirectories("*Rider*.app"))
+            .Select(a => a.FullName).ToArray();
+          return newPathsMac;
+      }
+      return new string[0];
+    }
+
+    private static string TargetFrameworkVersionDefault
+    {
+      get
+      {
+        var defaultValue = "4.5";
+        if (SystemInfoRiderPlugin.operatingSystemFamily == OperatingSystemFamily.Windows)
+        {
+          var dir = new DirectoryInfo(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework");
+          if (dir.Exists)
+          {
+            var availableVersions = dir.GetDirectories("v*").Select(a => a.Name.Substring(1))
+              .Where(v => TryCatch(v, s => { })).ToArray();
+            if (availableVersions.Any() && !availableVersions.Contains(defaultValue))
             {
-              var newPath = newPathLnks
-                .Select(newPathLnk => new FileInfo(ShortcutResolver.Resolve(newPathLnk.FullName)))
-                .Where(fi => File.Exists(fi.FullName))
-                .OrderBy(fi => FileVersionInfo.GetVersionInfo(fi.FullName).ProductVersion)
-                .LastOrDefault();
-
-              if (!string.IsNullOrEmpty(newPath.FullName))
-              {
-                /*RiderPlugin.Log(LoggingLevel.Verbose, "Update {0} to {1} product version: {2}", alreadySetPath, newPath, FileVersionInfo.GetVersionInfo(newPath.FullName).ProductVersion);
-                SetExternalScriptEditor(newPath.FullName);*/
-                return newPath.FullName;
-              }
+              defaultValue = availableVersions.OrderBy(a => new Version(a)).Last();
             }
-            break;
-
-          case OperatingSystemFamily.MacOSX:
-            // "/Applications/*Rider*.app"
-            //"~/Applications/JetBrains Toolbox/*Rider*.app"
-            string[] foldersMac = {"/Applications",Path.Combine(Environment.GetEnvironmentVariable("HOME"), "Applications")};
-            var newPathMac = foldersMac.Select(b=>new DirectoryInfo(b)).Where(a => a.Exists)
-              .SelectMany(c=>c.GetDirectories("*Rider*.app")).OrderBy(a => FileVersionInfo.GetVersionInfo(a.FullName).ProductVersion).LastOrDefault();
-            if (newPathMac != null)
-            {
-              if (!string.IsNullOrEmpty(newPathMac.FullName))
-              {
-                /*Log(LoggingLevel.Verbose, "Update {0} to {1}", alreadySetPath, newPathMac);
-                SetExternalScriptEditor(newPathMac.FullName);*/
-                return newPathMac.FullName;
-              }
-            }
-            break;
-        }
-
-        var riderPath = GetExternalScriptEditor();
-        if (!RiderPathExist(riderPath))
-        {
-          Log(LoggingLevel.Warning, "Rider plugin for Unity is present, but Rider executable was not found. Please update 'External Script Editor'.");
-          return null;
-        }
-
-        return riderPath;
-    }
-
-    public static bool TargetFrameworkVersion45
-    {
-      get { return EditorPrefs.GetBool("Rider_TargetFrameworkVersion45", true); }
-      set { EditorPrefs.SetBool("Rider_TargetFrameworkVersion45", value); }
+          }
+        }
+        return defaultValue;
+      }
+    }
+
+    public static string TargetFrameworkVersion
+    {
+      get
+      {
+        return EditorPrefs.GetString("Rider_TargetFrameworkVersion",
+          EditorPrefs.GetBool("Rider_TargetFrameworkVersion45", true) ? TargetFrameworkVersionDefault : "3.5");
+      }
+      set
+      {
+        TryCatch(value, val =>
+        {
+          EditorPrefs.SetString("Rider_TargetFrameworkVersion", val);
+        });
+      }
+    }
+
+    private static bool TryCatch(string value, Action<string> action)
+    {
+      try
+      {
+        new Version(value); // mono 2.6 doesn't support Version.TryParse
+        action(value);
+        return true;
+      }
+      catch (ArgumentException)
+      {
+      } // can't put loggin here because ot fire on every symbol
+      catch (FormatException)
+      {
+      }
+      return false;
+    }
+
+    public static string RiderPath
+    {
+      get { return EditorPrefs.GetString("Rider_RiderPath", GetAllRiderPaths().FirstOrDefault()); }
+      set { EditorPrefs.SetString("Rider_RiderPath", value); }
     }

     public enum LoggingLevel
@@ -367,13 +449,13 @@
       Info = 1,
       Warning = 2
     }
-
+
     public static LoggingLevel SelectedLoggingLevel
     {
       get { return (LoggingLevel) EditorPrefs.GetInt("Rider_SelectedLoggingLevel", 1); }
       set { EditorPrefs.SetInt("Rider_SelectedLoggingLevel", (int) value); }
     }
-
+
     public static bool RiderInitializedOnce
     {
       get { return EditorPrefs.GetBool("RiderInitializedOnce", false); }
@@ -392,9 +474,9 @@
     static RiderPlugin()
     {
       var riderPath = GetDefaultApp();
-      if (!RiderPathExist(riderPath))
+      if (!RiderPathExist(riderPath))
         return;
-
+
       AddRiderToRecentlyUsedScriptApp(riderPath, "RecentlyUsedScriptApp");
       if (!RiderInitializedOnce)
       {
@@ -419,7 +501,7 @@
       Log(LoggingLevel.Info, "Rider plugin initialized. You may change the amount of Rider Debug output via Edit -> Preferences -> Rider -> Logging Level");
       Initialized = true;
     }
-
+
     private static void AddRiderToRecentlyUsedScriptApp(string userAppPath, string recentAppsKey)
     {
       for (int index = 0; index < 10; ++index)
@@ -430,7 +512,7 @@
       }
       EditorPrefs.SetString(recentAppsKey + 9, userAppPath);
     }
-
+
     private static string GetExternalScriptEditor()
     {
       return EditorPrefs.GetString("kScriptsDefaultApp");
@@ -450,7 +532,8 @@
       if (!fileInfo.Name.ToLower().Contains("rider"))
         return false;
       var directoryInfo = new DirectoryInfo(path);
-      return fileInfo.Exists || (SystemInfoRiderPlugin.operatingSystemFamily==OperatingSystemFamily.MacOSX && directoryInfo.Exists);
+      return fileInfo.Exists || (SystemInfoRiderPlugin.operatingSystemFamily == OperatingSystemFamily.MacOSX &&
+                                 directoryInfo.Exists);
     }

     /// <summary>
@@ -502,21 +585,22 @@

         // determine asset that has been double clicked in the project view
         var selected = EditorUtility.InstanceIDToObject(instanceID);
-
+
         var assetFilePath = Path.Combine(appPath, AssetDatabase.GetAssetPath(selected));
         if (!(selected.GetType().ToString() == "UnityEditor.MonoScript" ||
-            selected.GetType().ToString() == "UnityEngine.Shader" ||
-            (selected.GetType().ToString() == "UnityEngine.TextAsset" &&
+              selected.GetType().ToString() == "UnityEngine.Shader" ||
+              (selected.GetType().ToString() == "UnityEngine.TextAsset" &&
 #if UNITY_5 || UNITY_5_5_OR_NEWER
-            EditorSettings.projectGenerationUserExtensions.Contains(Path.GetExtension(assetFilePath).Substring(1))
+               EditorSettings.projectGenerationUserExtensions.Contains(Path.GetExtension(assetFilePath).Substring(1))
 #else
             EditorSettings.externalVersionControl.Contains(Path.GetExtension(assetFilePath).Substring(1))
-#endif
-            )))
+#endif
+              )))
           return false;
-
+
         SyncSolution(); // added to handle opening file, which was just recently created.
-        if (!DetectPortAndOpenFile(line, assetFilePath, SystemInfoRiderPlugin.operatingSystemFamily == OperatingSystemFamily.Windows))
+        if (!DetectPortAndOpenFile(line, assetFilePath,
+          SystemInfoRiderPlugin.operatingSystemFamily == OperatingSystemFamily.Windows))
         {
           var args = string.Format("{0}{1}{0} --line {2} {0}{3}{0}", "\"", SlnFile, line, assetFilePath);
           return CallRider(args);
@@ -533,12 +617,12 @@
       if (SystemInfoRiderPlugin.operatingSystemFamily == OperatingSystemFamily.Windows)
       {
         var process = GetRiderProcess();
-        if (process == null)
-          return false;
-      }
-
+        if (process == null)
+          return false;
+      }
+
       int[] ports = Enumerable.Range(63342, 20).ToArray();
-      var res = ports.Any(port =>
+      var res = ports.Any(port =>
       {
         var aboutUrl = string.Format("http://localhost:{0}/api/about/", port);
         var aboutUri = new Uri(aboutUrl);
@@ -657,7 +741,8 @@
         string processName;
         try
         {
-          processName = p.ProcessName; // some processes like kaspersky antivirus throw exception on attempt to get ProcessName
+          processName =
+            p.ProcessName; // some processes like kaspersky antivirus throw exception on attempt to get ProcessName
         }
         catch (Exception)
         {
@@ -669,7 +754,6 @@
       return process;
     }

-#if !UNITY_2017_1_OR_NEWER
     // The default "Open C# Project" menu item will use the external script editor to load the .sln
     // file, but unless Unity knows the external script editor can properly load solutions, it will
     // also launch MonoDevelop (or the OS registered app for .sln files). This menu item side steps
@@ -691,7 +775,6 @@
     {
       return Enabled;
     }
-#endif

     /// <summary>
     /// Force Unity To Write Project File
@@ -714,25 +797,38 @@
     static void RiderPreferencesItem()
     {
       EditorGUILayout.BeginVertical();
-
-      var url = "https://github.com/JetBrains/resharper-unity";
-      if (GUILayout.Button(url))
-      {
-        Application.OpenURL(url);
-      }
-
       EditorGUI.BeginChangeCheck();

-      var help = @"For now target 4.5 is strongly recommended.
+      var alternatives = GetAllRiderPaths();
+      if (alternatives.Any())
+      {
+        int index = Array.IndexOf(alternatives, RiderPath);
+        var alts = alternatives.Select(s => s.Replace("/", ":"))
+          .ToArray(); // hack around https://fogbugz.unity3d.com/default.asp?940857_tirhinhe3144t4vn
+        RiderPath = alternatives[EditorGUILayout.Popup("Rider executable:", index == -1 ? 0 : index, alts)];
+        if (EditorGUILayout.Toggle(new GUIContent("Rider is default editor"), Enabled))
+        {
+          SetExternalScriptEditor(RiderPath);
+          EditorGUILayout.HelpBox("Unckecking will restore default external editor.", MessageType.None);
+        }
+        else
+        {
+          SetExternalScriptEditor(string.Empty);
+          EditorGUILayout.HelpBox("Checking will set Rider as default external editor", MessageType.None);
+        }
+
+      }
+      var help = @"TargetFramework >= 4.5 is strongly recommended.
  - Without 4.5:
     - Rider will fail to resolve System.Linq on Mac/Linux
     - Rider will fail to resolve Firebase Analytics.
- - With 4.5 Rider will show ambiguous references in UniRx.
+ - With 4.5 Rider may show ambiguous references in UniRx.
 All those problems will go away after Unity upgrades to mono4.";
-      TargetFrameworkVersion45 =
-        EditorGUILayout.Toggle(
-          new GUIContent("TargetFrameworkVersion 4.5",
-            help), TargetFrameworkVersion45);
+
+      TargetFrameworkVersion =
+        EditorGUILayout.TextField(
+          new GUIContent("TargetFrameworkVersion",
+            help), TargetFrameworkVersion);
       EditorGUILayout.HelpBox(help, MessageType.None);

       EditorGUI.EndChangeCheck();
@@ -745,13 +841,32 @@
       EditorGUILayout.HelpBox(loggingMsg, MessageType.None);

       EditorGUI.EndChangeCheck();
-
+
+      var url = "https://github.com/JetBrains/resharper-unity";
+      LinkButton(url, url);
+
 /*      if (GUILayout.Button("reset RiderInitializedOnce = false"))
       {
         RiderInitializedOnce = false;
       }*/
-
+
       EditorGUILayout.EndVertical();
+    }
+
+    private static void LinkButton(string caption, string url)
+    {
+      var style = GUI.skin.label;
+      style.richText = true;
+      caption = string.Format("<color=#0000FF>{0}</color>", caption);
+
+      bool bClicked = GUILayout.Button(caption, style);
+
+      var rect = GUILayoutUtility.GetLastRect();
+      rect.width = style.CalcSize(new GUIContent(caption)).x;
+      EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);
+
+      if (bClicked)
+        Application.OpenURL(url);
     }

     #region SystemInfoRiderPlugin


Refactor ElementsCount function

Refactor ElementsCount function

--- Asterix/Framework/WebUi/Elements/ElementBase.cs
+++ Asterix/Framework/WebUi/Elements/ElementBase.cs
@@ -69,14 +69,12 @@
         public T FindElement<T>(FindBy by) where T : IElementBase, new()
         {
             var element = FindElement(by);
-
             return (T)Activator.CreateInstance(typeof(T), element);
         }

         private int ElementsCount(FindBy by)
         {
-            int elementsCount = WebElement.FindElements(by.SeleniumBy).Count;
-            return elementsCount;
+            return WebElement.FindElements(by.SeleniumBy).Count;
         }

         private Element CreateElementByIndex(FindBy @by, int index)


Add extension method allowing both FileSystemScriptOptions and SqlScriptOptions to be passed in

Fixes #513

--- src/dbup-core/Builder/StandardExtensions.cs
+++ src/dbup-core/Builder/StandardExtensions.cs
@@ -412,6 +412,21 @@
     }

     /// <summary>
+    /// Adds all scripts from a folder on the file system, with custom options (Encoding, filter, etc.).
+    /// </summary>
+    /// <param name="builder">The builder.</param>
+    /// <param name="path">The directory path.</param>
+    /// <param name="options">Options for the file System Provider</param>
+    /// <param name="sqlScriptOptions">The sql script options</param>
+    /// <returns>
+    /// The same builder
+    /// </returns>
+    public static UpgradeEngineBuilder WithScriptsFromFileSystem(this UpgradeEngineBuilder builder, string path, FileSystemScriptOptions options, SqlScriptOptions sqlScriptOptions)
+    {
+        return WithScripts(builder, new FileSystemScriptProvider(path, options, sqlScriptOptions));
+    }
+
+    /// <summary>
     /// Adds all scripts found as embedded resources in the given assembly.
     /// </summary>
     /// <param name="builder">The builder.</param>


fixed a bug about pending handshake queue checking

git-svn-id: 264d93eb9283b6a3bfed80dd266caeb8f93e7ca3@73066 81fbe566-5dc4-48c1-bdea-7421811ca204

--- mainline/SuperWebSocket/WebSocketSession.cs
+++ mainline/SuperWebSocket/WebSocketSession.cs
@@ -251,7 +251,7 @@

         public override void Close(CloseReason reason)
         {
-            if (reason == CloseReason.TimeOut)
+            if (reason == CloseReason.TimeOut && ProtocolProcessor != null)
             {
                 CloseWithHandshake(ProtocolProcessor.CloseStatusClode.NormalClosure, "Session timeOut");
                 return;


Update Payments/Terms

Update Payments/Terms

--- Gamedalf/Views/Payments/Terms.cshtml
+++ Gamedalf/Views/Payments/Terms.cshtml
@@ -2,26 +2,35 @@

 @model AcceptTermsViewModel
 @{
-    ViewBag.Title = "Gibe moni plox";
+    ViewBag.Title = "Subscribe to Gamedalf!";
 }
-
-@section scripts {
-    @Scripts.Render("~/Scripts/app/ajax/terms.js")
+
+@section scripts {
+    @Scripts.Render("~/Scripts/app/elements/BtnSubmitter.js")
 }
-
-

-    @Html.Partial("_Error", new HandleErrorInfo(new RequestFailedException("api/terms seems to be unavaiable."), "Payment", "Terms"))
-

Terms and Conditions

-

-
Loading…

-

-

-

-    <samp id="terms-content" style="white-space: pre-line"></samp>
+

+        @Model.Terms.Title
+

+

+        @Model.Terms.DateCreated
+

+    <samp id="terms-content" style="white-space: pre-line">
+        @Model.Terms.Content
+    </samp>

-@Html.ValidationMessageFor(m => m.AcceptTerms, "", new { @class = "text-danger" })
-
+@using (Html.BeginForm("Make", "Payments", FormMethod.Post, new { id = "terms-form" }))
+{
+    @Html.AntiForgeryToken()
+

+
+            @Html.CheckBoxFor(m => m.AcceptTerms, new { @class = "btn btn-default" })
+            @Html.DisplayNameFor(m => m.AcceptTerms)
+
+

+    @Html.ValidationMessageFor(m => m.AcceptTerms, "", new { @class = "text-danger" })
+    @Html.Partial("_Confirm", "Accept")
+}


Switching casting to new CastAs<T> function

--- GenerateUserTypesFromPdb/UserType.cs
+++ GenerateUserTypesFromPdb/UserType.cs
@@ -142,7 +142,7 @@
             }
             else
             {
-                constructorText = string.Format("({0}){1}", castingTypeString, simpleFieldValue);
+                constructorText = string.Format("{1}.CastAs<{0}>()", castingTypeString, simpleFieldValue);
             }

             var transformation = typeTransformations.Where(t => t.Matches(originalFieldTypeString)).FirstOrDefault();


Version bump

Version bump

--- HelloSign/Properties/AssemblyInfo.cs
+++ HelloSign/Properties/AssemblyInfo.cs
@@ -30,6 +30,6 @@
 //      Revision
 //
 // NOTE: This gets reported in the user-agent string for HTTP requests made.
-[assembly: AssemblyVersion("0.5.5.0")]
+[assembly: AssemblyVersion("0.5.6.0")]
 // [assembly: AssemblyVersion("0.0.0.0")]
 // [assembly: AssemblyFileVersion("0.0.0.0")]


Allow coin flip to be heads.

Allow coin flip to be heads.

--- JefBot/Commands/CoinPluginCommand.cs
+++ JefBot/Commands/CoinPluginCommand.cs
@@ -21,7 +21,7 @@
         {
             if (rng.Next(1000) > 1)
             {
-                var result = rng.Next(0, 1) == 1 ? "heads" : "tails";
+                var result = rng.Next(0, 2) == 1 ? "heads" : "tails";

                 client.SendMessage(command.ChatMessage.Channel,
                     $"{command.ChatMessage.Username} flipped a coin, it was {result}");


Updating Camera initialization code to support cameras that don't have resolutions at or below 720p

--- Kiosk/Controls/CameraControl.xaml.cs
+++ Kiosk/Controls/CameraControl.xaml.cs
@@ -197,14 +197,25 @@
         private async Task SetVideoEncodingToHighestResolution(bool isForRealTimeProcessing = false)
         {
             VideoEncodingProperties highestVideoEncodingSetting;
+
+            // Sort the available resolutions from highest to lowest
+            var availableResolutions = this.captureManager.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview).Cast<VideoEncodingProperties>().OrderByDescending(v => v.Width * v.Height * (v.FrameRate.Numerator / v.FrameRate.Denominator));
+
             if (isForRealTimeProcessing)
             {
                 uint maxHeightForRealTime = 720;
-                highestVideoEncodingSetting = this.captureManager.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview).Cast<VideoEncodingProperties>().Where(v => v.Height <= maxHeightForRealTime).OrderByDescending(v => v.Width * v.Height * (v.FrameRate.Numerator / v.FrameRate.Denominator)).First();
+                // Find the highest resolution that is 720p or lower
+                highestVideoEncodingSetting = availableResolutions.FirstOrDefault(v => v.Height <= maxHeightForRealTime);
+                if (highestVideoEncodingSetting == null)
+                {
+                    // Since we didn't find 720p or lower, look for the first up from there
+                    highestVideoEncodingSetting = availableResolutions.LastOrDefault();
+                }
             }
             else
             {
-                highestVideoEncodingSetting = this.captureManager.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview).Cast<VideoEncodingProperties>().OrderByDescending(v => v.Width * v.Height * (v.FrameRate.Numerator / v.FrameRate.Denominator)).First();
+                // Use the highest resolution
+                highestVideoEncodingSetting = availableResolutions.FirstOrDefault();
             }

             if (highestVideoEncodingSetting != null)
@@ -496,43 +507,43 @@

         private async Task<ImageAnalyzer> CapturePhotoAsync()
         {
-			try
-			{
-				if (!(await this.frameProcessingSemaphore.WaitAsync(250)))
-				{
-					return null;
-				}
-
-				// Capture a frame from the preview stream
-				var videoFrame = new VideoFrame(BitmapPixelFormat.Bgra8, CameraResolutionWidth, CameraResolutionHeight);
-				using (var currentFrame = await captureManager.GetPreviewFrameAsync(videoFrame))
-				{
-					using (SoftwareBitmap previewFrame = currentFrame.SoftwareBitmap)
-					{
-						ImageAnalyzer imageWithFace = new ImageAnalyzer(await Util.GetPixelBytesFromSoftwareBitmapAsync(previewFrame));
-
-						imageWithFace.ShowDialogOnFaceApiErrors = this.ShowDialogOnApiErrors;
-						imageWithFace.FilterOutSmallFaces = this.FilterOutSmallFaces;
-						imageWithFace.UpdateDecodedImageSize(this.CameraResolutionHeight, this.CameraResolutionWidth);
-
-						return imageWithFace;
-					}
-				}
-			}
-			catch (Exception ex)
-			{
-				if (this.ShowDialogOnApiErrors)
-				{
-					await Util.GenericApiCallExceptionHandler(ex, "Error capturing photo.");
-				}
-			}
-			finally
-			{
-				this.frameProcessingSemaphore.Release();
-			}
-
-			return null;
-		}
+            try
+            {
+                if (!(await this.frameProcessingSemaphore.WaitAsync(250)))
+                {
+                    return null;
+                }
+
+                // Capture a frame from the preview stream
+                var videoFrame = new VideoFrame(BitmapPixelFormat.Bgra8, CameraResolutionWidth, CameraResolutionHeight);
+                using (var currentFrame = await captureManager.GetPreviewFrameAsync(videoFrame))
+                {
+                    using (SoftwareBitmap previewFrame = currentFrame.SoftwareBitmap)
+                    {
+                        ImageAnalyzer imageWithFace = new ImageAnalyzer(await Util.GetPixelBytesFromSoftwareBitmapAsync(previewFrame));
+
+                        imageWithFace.ShowDialogOnFaceApiErrors = this.ShowDialogOnApiErrors;
+                        imageWithFace.FilterOutSmallFaces = this.FilterOutSmallFaces;
+                        imageWithFace.UpdateDecodedImageSize(this.CameraResolutionHeight, this.CameraResolutionWidth);
+
+                        return imageWithFace;
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                if (this.ShowDialogOnApiErrors)
+                {
+                    await Util.GenericApiCallExceptionHandler(ex, "Error capturing photo.");
+                }
+            }
+            finally
+            {
+                this.frameProcessingSemaphore.Release();
+            }
+
+            return null;
+        }

         private void OnImageCaptured(ImageAnalyzer imageWithFace)
         {
@@ -566,13 +577,13 @@
         {
             if (this.cameraControlSymbol.Symbol == Symbol.Camera)
             {
-				var img = await CapturePhotoAsync();
-				if (img != null)
-				{
-					this.cameraControlSymbol.Symbol = Symbol.Refresh;
-					this.OnImageCaptured(img);
-				}
-			}
+                var img = await CapturePhotoAsync();
+                if (img != null)
+                {
+                    this.cameraControlSymbol.Symbol = Symbol.Refresh;
+                    this.OnImageCaptured(img);
+                }
+            }
             else
             {
                 this.cameraControlSymbol.Symbol = Symbol.Camera;


Thumbstick speed of run and animation frames.

--- MM3K/MM3K/MM3K/Screens/GameScreen.cs
+++ MM3K/MM3K/MM3K/Screens/GameScreen.cs
@@ -28,8 +28,8 @@
             new Rectangle(59 + 5 * 64, 64, 64, 64),
         };
         int currentRunFrame = 0;
-        const double RUN_FRAME_DURATION = 0.125;
-        double elapsedRunFrameDuration = RUN_FRAME_DURATION;
+        const double MAX_RUN_FRAME_DURATION = 0.1;
+        double elapsedRunFrameDuration = MAX_RUN_FRAME_DURATION;

         Rectangle rectStill = new Rectangle(59 + 5 * 64, 0, 64, 64);

@@ -62,25 +62,29 @@
             }
             var elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

+            isRunning = false;
+            float speed = padState.ThumbSticks.Left.X;
+            if (padState.DPad.Left == ButtonState.Pressed)
+            {
+                speed = -1.0f;
+            }
+            else if (padState.DPad.Right == ButtonState.Pressed)
+            {
+                speed = 1.0f;
+            }
+
+            locMonkey.X += speed * 150.0f * elapsed;
+            isRunning = speed != 0.0f;
+            if (speed != 0.0f)
+            {
+                isFacingLeft = speed < 0.0f;
+            }
+
             elapsedRunFrameDuration -= elapsed;
             if (elapsedRunFrameDuration <= 0.0)
             {
                 currentRunFrame = (currentRunFrame + 1) % rectRunFrames.Length;
-                elapsedRunFrameDuration = RUN_FRAME_DURATION;
-            }
-
-            isRunning = false;
-            if (padState.DPad.Left == ButtonState.Pressed)
-            {
-                locMonkey.X -= 100.0f * elapsed;
-                isRunning = true;
-                isFacingLeft = true;
-            }
-            else if (padState.DPad.Right == ButtonState.Pressed)
-            {
-                locMonkey.X += 100.0f * elapsed;
-                isRunning = true;
-                isFacingLeft = false;
+                elapsedRunFrameDuration = (2.0f - Math.Abs(speed)) * MAX_RUN_FRAME_DURATION;
             }

             var isAPressed =
@@ -131,15 +135,15 @@
             if (isRunning && accelerationY == 0)
             {
                 batch.Draw(
-                    texMonkey,
-                    locMonkey,
-                    rectRunFrames[currentRunFrame],
-                    Color.White,
-                    0.0f,
-                    Vector2.Zero,
-                    1.0f,
-                    isFacingLeft ? SpriteEffects.FlipHorizontally : SpriteEffects.None,
-                    0.0f);
+                    texMonkey, // texture
+                    locMonkey, // location
+                    rectRunFrames[currentRunFrame], // source rectangle
+                    Color.White, // tint
+                    0.0f, // rotation
+                    Vector2.Zero, // origin
+                    1.0f, // scale
+                    isFacingLeft ? SpriteEffects.FlipHorizontally : SpriteEffects.None, // SpriteEffect
+                    0.0f); // depth
             }
             else
             {


Removed arrange does not seem necessary for wpf only

--- Mapsui.Rendering.Xaml/MapRenderer.cs
+++ Mapsui.Rendering.Xaml/MapRenderer.cs
@@ -83,7 +83,6 @@

                 RenderLayer(canvas, viewport, layer, symbolCache, rasterizing);
             }
-            canvas.Arrange(new Rect(0, 0, viewport.Width, viewport.Height));

             canvas.Visibility = Visibility.Visible;
             canvas.EndInit();


Return exit code 1 if any acceptance tests fail

--- MbDotNet.Acceptance.Tests/Program.cs
+++ MbDotNet.Acceptance.Tests/Program.cs
@@ -27,6 +27,11 @@
             runner.Execute();

             Console.WriteLine("\nFINISHED {0} passed, {1} failed, {2} skipped", _passed, _failed, _skipped);
+
+            if (_failed > 0)
+            {
+                Environment.Exit(1);
+            }
         }

         public static void OnTestPassing(string testName, long elapsed)


AddRangeToSet didn't do the right thing at all, which kept batches from working. Implement PersistX, although I'm not sure it's technically required.

--- MemoryStorageWriteOnlyTransaction.cs
+++ MemoryStorageWriteOnlyTransaction.cs
@@ -71,7 +71,7 @@

         public override void AddToSet(string key, string value)
         {
-            AddToSet(key, value, 0.0);
+            this.AddToSet(key, value, 0.0);
         }

         public override void AddToSet(string key, string value, double score)
@@ -342,25 +342,56 @@

         public override void PersistSet(string key)
         {
-            // noop
+            QueueCommand(() =>
+            {
+                var set = Data.GetEnumeration<SetDto>().Where(s => s.Key == key);
+                foreach (var item in set)
+                {
+                    item.ExpireAt = null;
+                }
+            });
         }

         public override void PersistHash(string key)
         {
-            // noop
+            QueueCommand(() =>
+            {
+                var hash = Data.GetEnumeration<HashDto>().Where(s => s.Key == key);
+                foreach (var item in hash)
+                {
+                    item.ExpireAt = null;
+                }
+            });
         }

         public override void PersistList(string key)
         {
-            // noop
+            QueueCommand(() =>
+            {
+                var list = Data.GetEnumeration<ListDto>().Where(s => s.Key == key);
+                foreach (var item in list)
+                {
+                    item.ExpireAt = null;
+                }
+            });
         }

         public override void AddRangeToSet(string key, IList<string> items)
         {
             this.QueueCommand(() =>
             {
-                var set = new SetDto();
-                Data.Create(set);
+
+                var existingSet = Data.GetEnumeration<SetDto>().Where(s => s.Key == key).Select(s => s.Value).ToList();
+                foreach (var item in items.Where(i => !existingSet.Contains(i)))
+                {
+                    var newSet = new SetDto
+                    {
+                        Id = AutoIncrementIdGenerator.GenerateId(typeof(SetDto)),
+                        Key = key,
+                        Value = item
+                    };
+                    Data.Create(newSet);
+                }
             });
         }
     }


Small cleanup on SaveGML code

Small cleanup on SaveGML code

--- NetMining/Graphs/LightWeightGraph.cs
+++ NetMining/Graphs/LightWeightGraph.cs
@@ -457,14 +457,11 @@

                         sw.WriteLine("\t\tgraphics [");

-                        foreach (var kv in nodeGraphicsDescriptors)
+                        foreach (var kv in attributes)
                         {
-                            if (kv.Value.ContainsKey(i))
-                            {
-                                String tag = kv.Key;
-                                String val = kv.Value[i];
-                                sw.WriteLine("\t\t\t{0} {1}", tag, val);
-                            }
+                            String tag = kv.Key;
+                            String val = kv.Value;
+                            sw.WriteLine("\t\t\t{0} {1}", tag, val);
                         }

                         sw.WriteLine("\t\t]");


Remove unneeded variable

Remove unneeded variable

--- NetSparkle/DownloadProgressWindow.cs
+++ NetSparkle/DownloadProgressWindow.cs
@@ -16,7 +16,6 @@
         /// </summary>
         public event EventHandler InstallAndRelaunch;

-        private bool _didFinishDownload = false;
         private bool _shouldLaunchInstallFileOnClose = false;

         /// <summary>
@@ -68,7 +67,6 @@
         /// </summary>
         public void FinishedDownloadingFile(bool isDownloadedFileValid)
         {
-            _didFinishDownload = true;
             progressDownload.Visible = false;
             buttonCancel.Visible = false;
             downloadProgressLbl.Visible = false;


also generate default values

also generate default values

--- tools/protobuf-net-data.TestDataGenerator/Program.cs
+++ tools/protobuf-net-data.TestDataGenerator/Program.cs
@@ -28,7 +28,7 @@
             { typeof(long), () => Convert.ToInt64(random.Next()) },
             { typeof(short), () => Convert.ToInt16(random.Next(short.MaxValue)) },
             { typeof(string), () => new string(new[] { (char)random.Next(65, 90), (char)random.Next(65, 90) }) },
-            { typeof(TimeSpan), () => TimeSpan.FromTicks(random.Next()) },
+            { typeof(TimeSpan), () => TimeSpan.FromTicks(random.Next()) }
         };

         public static void Main(string[] args)
@@ -77,22 +77,34 @@

             for (var columnIndex = 0; columnIndex < generators.Count; columnIndex++)
             {
-                dataTable.Columns.Add($"Table{tableIndex}_Column{columnIndex}", generators.Keys.ElementAt(columnIndex));
+                dataTable.Columns.Add($"Table{tableIndex}_Column{columnIndex + 1}", generators.Keys.ElementAt(columnIndex));
             }

-            dataTable.Rows.Add(CreateDataRow());
+            dataTable.Rows.Add(CreateDataRow(useDefaults: true));
             dataTable.Rows.Add(CreateDataRow());

             return dataTable;
         }

-        private static object[] CreateDataRow()
+        private static object[] CreateDataRow(bool useDefaults = false)
         {
             var values = new object[generators.Values.Count];

             for (var columnIndex = 0; columnIndex < generators.Count; columnIndex++)
             {
-                values[columnIndex] = generators.Values.ElementAt(columnIndex)();
+                if (useDefaults)
+                {
+                    var columnType = generators.Keys.ElementAt(columnIndex);
+
+                    if (columnType.IsValueType)
+                    {
+                        values[columnIndex] = Activator.CreateInstance(columnType);
+                    }
+                }
+                else
+                {
+                    values[columnIndex] = generators.Values.ElementAt(columnIndex)();
+                }
             }

             return values;


Bump version

Bump version

--- Oxygenize/Properties/AssemblyInfo.cs
+++ Oxygenize/Properties/AssemblyInfo.cs
@@ -32,6 +32,6 @@
 // You can specify all the values or you can default the Build and Revision Numbers
 // by using the '*' as shown below:
 // [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.0.4.0")]
-[assembly: AssemblyFileVersion("1.0.4.0")]
+[assembly: AssemblyVersion("1.0.5.0")]
+[assembly: AssemblyFileVersion("1.0.5.0")]
 [assembly: InternalsVisibleTo("Oxygenize.Test")]


more rephrasing

more rephrasing

--- PJenkins.Web/Views/Home/About.cshtml
+++ PJenkins.Web/Views/Home/About.cshtml
@@ -26,10 +26,10 @@

                         I grew up in Indiana and have lived here all my life. I remember playing games on my Dad's old Mac Plus and creating simple interactive point-and-click adventures in HyperCard.
                         I was always encouraged to pursue my artistic abilities, and have been sketching since I was young - even if they were just stick figures at the time.
-                        I have always had a knack for computers and having a parent that is proficient in them as well was a big help. I took design classes in High School back when Dreamweaver was still owned by Macromedia.
+                        I have always had a knack for computers and having a parent that is proficient in them as well was a big help. I have been using Adobe Photoshop most of my life.

-                        Quickly I realized that programming was just another art form, and a language you could speak. As technology exploded, especially after Mobile devices had come out, I started to gain an interest in not just the graphical side, but the core design of software and apps in general. This led me down the path I am currently walking.
+                        I took design classes in High School back when Dreamweaver was still owned by Macromedia. Very quickly, I realized that programming was just another art form, and a language you could speak. As technology exploded, especially after Mobile devices had come out, I started to gain an interest in not just the graphical side, but the core design of software and apps in general. This led me down the path I am currently walking.

@@ -79,12 +79,16 @@

                         In my free time, I am an avid gamer of all facets - board games, card games, and role-playing games. I enjoy modding computer games and dabble in creating my own. I have been involved in several projects building games from scratch as well as editing existing game code.
+

+

                         I am also a freelance illustration artist that works on a commission basis. I have done character illustrations, logos, flyers, and web graphics, in addition to any mock-up work required by the clientele.
                         I have been attempting to break into the realm of webcomics and plan on using ASP.NET MVC to accomplish this task.
+

+

                         I enjoy puzzles, specifically brain-teasers and the Rubik's Cube.
                         I also cannot resist a good book. I read mostly fantasy, such as Neil Gaiman, but enjoy my classics,
                         such as the Hobbit
-                        and Lord of the Rings
+                        and Lord of the Rings.


Updated TeamDeathMatch.cs, added some new features

Added customization to the games, trimmed unnecessary code, etc.

--- fCraft/Games/TeamDeathMatch.cs
+++ fCraft/Games/TeamDeathMatch.cs
@@ -1,4 +1,7 @@
-using System;
+//This game was created by DingusBungus 2013 for use with LegendCraft servers. The code was based on the template used in ZombieGame.cs
+//written by Jonty800. Thanks to everyone who helped me test the game and work out the bugs.
+
+using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
@@ -8,29 +11,33 @@
 {
     class TeamDeathMatch
     {
+        //Team Tags
         public const string redTeam = "&C-Red-";
         public const string blueTeam = "&1*Blue*";
-        private static World world_;
-
+
+        //TDM stats
         public static int blueScore = 0;
         public static int redScore = 0;
-        private static int playerCount = 0;
         public static int redTeamCount = 0;
         public static int blueTeamCount = 0;
+
+        //Timing
         public static int timeLeft = 0;
-
         private static SchedulerTask task_;
         public static TeamDeathMatch instance;
         public static DateTime startTime;
         public static DateTime lastChecked;
+
+        //customization (initialized as defaults)
+        public static int timeLimit = 300;
+        public static int scoreLimit = 50;
+        public static int timeDelay = 20;

+        //TDM Game Bools
         public static bool isOn = false;
         private static bool started = false;

-        private TeamDeathMatch()
-        {
-
-        }
+        private static World world_;

         public static TeamDeathMatch GetInstance(World world)
         {
@@ -39,7 +46,6 @@
                 world_ = world;
                 instance = new TeamDeathMatch();
                 startTime = DateTime.Now;
-                playerCount = world_.Players.Count();
                 task_ = new SchedulerTask(Interval, true).RunForever(TimeSpan.FromSeconds(1));
             }
             return instance;
@@ -49,13 +55,11 @@
         {
             if (world_.Players.Count() < 2)
             {
-                world_.Players.Message("You cannot player a game with less then 2 people!");
+                world_.Players.Message("&WTeam DeathMatch&s requires at least 2 people to play.");
                 return;
             }
             world_.gameMode = GameMode.TeamDeathMatch; //set the game mode
-            List<Player> TDPlayers = new List<Player>(Server.Players.Where(p => p.World.gameMode == GameMode.TeamDeathMatch).ToArray());
-            playerCount = TDPlayers.Count(); //count all players
-            Scheduler.NewTask(t => world_.Players.Message("&WTEAM DEATHMATCH &fwill be starting soon: &WGet ready!"))
+            Scheduler.NewTask(t => world_.Players.Message("&WTEAM DEATHMATCH &fwill be starting in {0} seconds: &WGet ready!", timeDelay))
                 .RunRepeating(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(10), 1);
         }

@@ -82,13 +86,13 @@
             }
             if (!started)
             {
-                if (startTime != null && (DateTime.Now - startTime).TotalSeconds > 20)
-                {
-                    /*if (world_.Players.Length < 3){
-                        world_.Players.Message("&WThe game failed to start: 2 or more players need to be in the world");
-                        Stop(null);
-                        return;
-                    }*/
+                if (world_.Players.Count() < 2) //in case players leave the world or disconnect during the start delay
+                {
+                    world_.Players.Message("&WTeam DeathMatch&s requires at least 2 people to play.");
+                    return;
+                }
+                if (startTime != null && (DateTime.Now - startTime).TotalSeconds > timeDelay)
+                {
                     foreach (Player p in world_.Players)
                     {
                         int x = rand.Next(2, world_.Map.Width);
@@ -103,57 +107,57 @@
                             }
                         }
                         p.TeleportTo(new Position(x, y, z1 + 2).ToVector3I().ToPlayerCoords()); //teleport players to a random position
-                        assignTeams(p);
-                    }
-                    started = true;
+                        assignTeams(p); //assigns teams (who knew?)
+                    }
+                    started = true;   //the game has officially started
                     isOn = true;
                     if (!world_.gunPhysics)
                     {
-                        world_.EnableGunPhysics(Player.Console, true);
-                    }
-                    lastChecked = DateTime.Now;
+                        world_.EnableGunPhysics(Player.Console, true); //enables gun physics if they are not already on
+                    }
+                    lastChecked = DateTime.Now;     //used for intervals
                     return;
                 }
             }

             //check if one of the teams have won
-            if (redScore >= 50)
-            {
-                world_.Players.Message("&sThe &cRed Team&s has won {1} to {0}.", blueScore, redScore);
+            if (redScore >= scoreLimit)
+            {
+                world_.Players.Message("&fThe &cRed Team&f has won {1} to {0}!", blueScore, redScore);
                 Stop(null);
                 return;
             }
-            if (blueScore >= 50)
-            {
-                world_.Players.Message("&sThe &1Blue Team&s has won {1} to {0}.", redScore, blueScore);
+            if (blueScore >= scoreLimit)
+            {
+                world_.Players.Message("&fThe &1Blue Team&f has won {1} to {0}!", redScore, blueScore);
                 Stop(null);
                 return;
             }
-            if (blueScore == 50 && redScore == 50) //if they somehow manage to tie which I am pretty sure is impossible
-            {
-                world_.Players.Message("&sThe teams have tied!");
+            if (blueScore == scoreLimit && redScore == scoreLimit) //if they somehow manage to tie which I am pretty sure is impossible
+            {
+                world_.Players.Message("&fThe teams have tied!");
                 Stop(null);
                 return;
             }

-            //check if 2 minutes is up (300s from start - 20s waiting time = 320)
-            if (started && startTime != null && (DateTime.Now - startTime).TotalSeconds >= 320)
+            //check if time is up (delay time + start time)
+            if (started && startTime != null && (DateTime.Now - startTime).TotalSeconds >= (timeDelay + timeLimit))
             {
                 if (redScore > blueScore)
                 {
-                    world_.Players.Message("&sThe &cRed Team&s has won {0} to {1}.", redScore, blueScore);
+                    world_.Players.Message("&fThe &cRed Team&f has won {0} to {1}.", redScore, blueScore);
                     Stop(null);
                     return;
                 }
                 if (redScore < blueScore)
                 {
-                    world_.Players.Message("&sThe &1Blue Team&s has won {0} to {1}.", blueScore, redScore);
+                    world_.Players.Message("&fThe &1Blue Team&f has won {0} to {1}.", blueScore, redScore);
                     Stop(null);
                     return;
                 }
                 if (redScore == blueScore)
                 {
-                    world_.Players.Message("&sThe teams tied {0} to {1}!", blueScore, redScore);
+                    world_.Players.Message("&fThe teams tied {0} to {1}!", blueScore, redScore);
                     Stop(null);
                     return;
                 }
@@ -164,7 +168,7 @@
                 }
             }

-            if (started && (DateTime.Now - lastChecked).TotalSeconds > 10)
+            if (started && (DateTime.Now - lastChecked).TotalSeconds > 10) //check if players left the world, forfeits if no players of that team left
             {
                 int redCount = world_.Players.Where(p => p.Info.isOnRedTeam).ToArray().Count();
                 int blueCount = world_.Players.Where(p => p.Info.isOnBlueTeam).ToArray().Count();
@@ -174,7 +178,7 @@
                     {
                         if (world_.Players.Count() >= 1)
                         {
-                            world_.Players.Message("&1Blue Team &shas forfeited the game. &cRed Team &swins!");
+                            world_.Players.Message("&1Blue Team &fhas forfeited the game. &cRed Team &fwins!");
                         }
                         Stop(null);
                         return;
@@ -183,7 +187,7 @@
                     {
                         if (world_.Players.Count() >= 1)
                         {
-                            world_.Players.Message("&cRed Team &shas forfeited the game. &1Blue Team &swins!");
+                            world_.Players.Message("&cRed Team &fhas forfeited the game. &1Blue Team &fwins!");
                         }
                         Stop(null);
                         return;
@@ -195,23 +199,23 @@
                     }
                 }
             }
-            timeLeft = Convert.ToInt16((320 - (DateTime.Now - startTime).TotalSeconds));
+            timeLeft = Convert.ToInt16(((timeDelay + timeLimit) - (DateTime.Now - startTime).TotalSeconds));
             //Keep the players updated about the score
-            if (lastChecked != null && (DateTime.Now - lastChecked).TotalSeconds > 29.9 && timeLeft <= 300)
+            if (lastChecked != null && (DateTime.Now - lastChecked).TotalSeconds > 29.9 && timeLeft <= timeLimit)
             {
                 if (redScore > blueScore)
                 {
-                    world_.Players.Message("&sThe &cRed Team&s is winning {0} to {1}.", redScore, blueScore);
+                    world_.Players.Message("&fThe &cRed Team&f is winning {0} to {1}.", redScore, blueScore);
                     world_.Players.Message("&fThere are &W{0}&f seconds left in the game.", timeLeft);
                 }
                 if (redScore < blueScore)
                 {
-                    world_.Players.Message("&sThe &1Blue Team&s is winning {0} to {1}.", blueScore, redScore);
+                    world_.Players.Message("&fThe &1Blue Team&f is winning {0} to {1}.", blueScore, redScore);
                     world_.Players.Message("&fThere are &W{0}&f seconds left in the game.", timeLeft);
                 }
                 if (redScore == blueScore)
                 {
-                    world_.Players.Message("&sThe teams are tied at {0}!", blueScore);
+                    world_.Players.Message("&fThe teams are tied at {0}!", blueScore);
                     world_.Players.Message("&fThere are &W{0}&f seconds left in the game.", timeLeft);
                 }
                 lastChecked = DateTime.Now;
@@ -222,22 +226,22 @@
             }
         }

-        static public void assignTeams(Player p)
+        static public void assignTeams(Player p)    //Assigns teams to all players in the world
         {
             if (redTeamCount == 0) //if there are no players assigned to any team yet
             {
-                p.Message("Let the games Begin! Type &H/Gun"); //start message
-                p.Message("You are on the &cRed Team"); //notifies the player of their team
-                p.iName = Color.Red + p.Name;   //the name above their head will be colored blue or red depending on team
+                p.Message("Let the games Begin! Type &H/Gun");
+                p.Message("You are on the &cRed Team");
+                p.iName = Color.Red + p.Name;
                 p.Info.oldname = p.Info.DisplayedName;
-                p.Info.DisplayedName = "&f(" + redTeam + "&f) " + Color.Red + p.Name;   //changes their displayed name to include a little tag and their real mc username colored their team color
-                p.Info.isOnRedTeam = true;      //assigns to red team
+                p.Info.DisplayedName = "&f(" + redTeam + "&f) " + Color.Red + p.Name;
+                p.Info.isOnRedTeam = true;
                 p.Info.isOnBlueTeam = false;
-                p.Info.isPlayingTD = true;      //they are now officially "playing TD"
-                p.entityChanged = true;         //reloads skin and name above head to become the new ones
+                p.Info.isPlayingTD = true;
+                p.entityChanged = true;
                 p.Info.gameKills = 0;
                 p.Info.gameDeaths = 0;
-                redTeamCount++;                 //add 1 to the red or blue team player count
+                redTeamCount++;
                 return;
             }
             if (blueTeamCount < redTeamCount) //if the red team has more players and the red team has already been assigned at least one player
@@ -290,42 +294,46 @@
             }
         }

-        public static void RevertGame()
+        public static void RevertGame() //Reset game bools/stats and stop timers
         {
             world_.gameMode = GameMode.NULL;
             if (world_.gunPhysics)
             {
                 world_.DisableGunPhysics(Player.Console, true);
             }
-            task_ = null;
+            task_.Stop();
             isOn = false;
             instance = null;
             started = false;
+            world_ = null;
             redScore = 0;
             blueScore = 0;
-            playerCount = 0;
             redTeamCount = 0;
             blueTeamCount = 0;
             RevertNames();
         }

-        public static void RevertNames()
-        {
-            List<PlayerInfo> TDPlayers = new List<PlayerInfo>(PlayerDB.PlayerInfoList.Where(r => r.isOnBlueTeam || r.isOnRedTeam).ToArray());
+        public static void RevertNames()    //reverts names for online players. offline players get reverted upon leaving the game
+        {
+            List<PlayerInfo> TDPlayers = new List<PlayerInfo>(PlayerDB.PlayerInfoList.Where(r => (r.isOnBlueTeam || r.isOnRedTeam) && r.IsOnline).ToArray());
             for (int i = 0; i < TDPlayers.Count(); i++)
             {
                 string p1 = TDPlayers[i].Name.ToString();
-                Player p = Server.FindPlayers(p1, false)[0];
-
-                p.iName = null;
-                p.Info.DisplayedName = p.Info.oldname;
-                p.Info.isOnRedTeam = false;
-                p.Info.isOnBlueTeam = false;
-                p.Info.isPlayingTD = false;
-                p.entityChanged = true;
-                if (p.IsOnline)
-                {
-                    p.Message("Your status has been reverted.");
+                PlayerInfo pI = PlayerDB.FindPlayerInfoExact(p1);
+                Player p = pI.PlayerObject;
+
+                if (p != null)
+                {
+                    p.iName = null;
+                    pI.DisplayedName = pI.oldname;
+                    pI.isOnRedTeam = false;
+                    pI.isOnBlueTeam = false;
+                    pI.isPlayingTD = false;
+                    p.entityChanged = true;
+                    if (p.IsOnline)
+                    {
+                        p.Message("Your status has been reverted.");
+                    }
                 }
             }
         }


TDM bug fix

TDM bug fix

--- fCraft/Games/TeamDeathMatch.cs
+++ fCraft/Games/TeamDeathMatch.cs
@@ -53,11 +53,6 @@

         public static void Start()
         {
-            if (world_.Players.Count() < 2)
-            {
-                world_.Players.Message("&WTeam DeathMatch&s requires at least 2 people to play.");
-                return;
-            }
             world_.gameMode = GameMode.TeamDeathMatch; //set the game mode
             Scheduler.NewTask(t => world_.Players.Message("&WTEAM DEATHMATCH &fwill be starting in {0} seconds: &WGet ready!", timeDelay))
                 .RunRepeating(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(10), 1);


fix execute sequence cancel code

fix execute sequence cancel code

--- mogate.Shared/Behaviors/Execute.cs
+++ mogate.Shared/Behaviors/Execute.cs
@@ -36,7 +36,10 @@
 			var tags = new List<string>(m_actions.Keys);

 			foreach (var tag in tags) {
-				var q = m_actions [tag];
+				Queue<IAction> q;
+				if (!m_actions.TryGetValue (tag, out q))
+					continue;
+
 				if (q.Count == 0)
 					continue;


running on linux info and sources

running on linux info and sources

--- fileserve.server/FileServer.cs
+++ fileserve.server/FileServer.cs
@@ -67,7 +67,9 @@
         {
             // This program would need to be run as admin without first doing:
             //  'netsh http add urlacl url=http://{domain}:{port}/ user=Everyone listen=yes'
-            // I do not yet know if this will work on linux.
+            // Tested on Win10.
+            // For linux, to run on port 80: sudo setcap 'cap_net_bind_service=+ep' /usr/local/bin/mono-sgen
+            // http://stackoverflow.com/questions/2923966 and http://stackoverflow.com/questions/4019466
             const string domain = "+";
             const int port = 80;


[X11] put FullHd res check inside GuessPixelDensity.

--- src/Avalonia.X11/X11Screens.cs
+++ src/Avalonia.X11/X11Screens.cs
@@ -11,6 +11,7 @@
 {
     class X11Screens  : IScreenImpl
     {
+        private const int FullHDWidth = 1920;
         private IX11Screens _impl;

         public X11Screens(IX11Screens impl)
@@ -99,8 +100,6 @@
                         {
                             if (mon.MWidth == 0)
                                 density = 1;
-                            else if (mon.Width <= 1920)
-                                density = 1;
                             else
                                 density = X11Screen.GuessPixelDensity(mon.Width, mon.MWidth);
                         }
@@ -239,14 +238,7 @@
             }
             else if (pixelDensity == null)
             {
-                if (bounds.Width <= 1920)
-                {
-                    PixelDensity = 1;
-                }
-                else
-                {
-                    PixelDensity = GuessPixelDensity(bounds.Width, physicalSize.Value.Width);
-                }
+                PixelDensity = GuessPixelDensity(bounds.Width, physicalSize.Value.Width);
             }
             else
             {
@@ -256,6 +248,6 @@
         }

         public static double GuessPixelDensity(double pixelWidth, double mmWidth)
-            => Math.Max(1, Math.Round(pixelWidth / mmWidth * 25.4 / 96));
+            => pixelWidth <= FullHDWidth ? 1 : Math.Max(1, Math.Round(pixelWidth / mmWidth * 25.4 / 96));
     }
 }


Fixed User.Channels

Fixed User.Channels

--- src/Discord.Net/Models/User.cs
+++ src/Discord.Net/Models/User.cs
@@ -82,7 +82,32 @@

 		/// <summary> Returns a collection of all channels this user is a member of. </summary>
 		[JsonIgnore]
-		public IEnumerable<Channel> Channels => _channels.Select(x => x.Value);
+		public IEnumerable<Channel> Channels
+		{
+			get
+			{
+				if (_server.Id != null)
+				{
+					return _permissions
+						.Where(x => x.Value.ReadMessages)
+						.Select(x =>
+						{
+							Channel channel = null;
+							_channels.TryGetValue(x.Key, out channel);
+							return channel;
+                        })
+						.Where(x => x != null);
+				}
+				else
+				{
+					var privateChannel = PrivateChannel;
+					if (privateChannel != null)
+						return new Channel[] { privateChannel };
+					else
+						return new Channel[0];
+				}
+			}
+		}

 		internal User(DiscordClient client, string id, string serverId)
 			: base(client, id)
@@ -309,17 +334,23 @@

 		internal void AddChannel(Channel channel)
 		{
-			var perms = new ChannelPermissions();
-			perms.Lock();
-			_channels.TryAdd(channel.Id, channel);
-			_permissions.TryAdd(channel.Id, perms);
-			UpdateChannelPermissions(channel);
+			if (_server.Id != null)
+			{
+				var perms = new ChannelPermissions();
+				perms.Lock();
+				_channels.TryAdd(channel.Id, channel);
+				_permissions.TryAdd(channel.Id, perms);
+				UpdateChannelPermissions(channel);
+			}
 		}
 		internal void RemoveChannel(Channel channel)
 		{
-			ChannelPermissions ignored;
-			_channels.TryRemove(channel.Id, out channel);
-			_permissions.TryRemove(channel.Id, out ignored);
+			if (_server.Id != null)
+			{
+				ChannelPermissions ignored;
+				_channels.TryRemove(channel.Id, out channel);
+				_permissions.TryRemove(channel.Id, out ignored);
+			}
 		}

 		public bool HasRole(Role role)


Update ZoomState.cs

Update ZoomState.cs

--- src/Draw2D/Editor/ZoomState.cs
+++ src/Draw2D/Editor/ZoomState.cs
@@ -76,10 +76,10 @@

         public void Pressed(double x, double y)
         {
-            if (InputService?.IsCaptured() == false && IsPanning == false)
+            if (InputService?.IsCaptured?.Invoke() == false && IsPanning == false)
             {
                 IsPanning = true;
-                InputService?.Capture();
+                InputService?.Capture?.Invoke();
                 StartPan(x, y);
                 Invalidate(true);
             }
@@ -89,7 +89,7 @@
         {
             if (IsPanning == true)
             {
-                InputService?.Release();
+                InputService?.Release?.Invoke();
                 Invalidate(true);
                 IsPanning = false;
             }
@@ -112,7 +112,7 @@
             OffsetY = CurrentMatrix.M32;
             if (redraw)
             {
-                InputService.Redraw();
+                InputService.Redraw?.Invoke();
             }
         }


Added matrix.h to .net bindings

Added matrix.h to .net bindings

--- contrib/Ode.NET/Ode/Ode.cs
+++ contrib/Ode.NET/Ode/Ode.cs
@@ -567,6 +567,15 @@
 		public static extern IntPtr CreateTriMesh(IntPtr space, IntPtr data,
 			TriCallback callback, TriArrayCallback arrayCallback, TriRayCallback rayCallback);

+		[DllImport("ode", EntryPoint = "dDot"), SuppressUnmanagedCodeSecurity]
+		public static extern dReal Dot(ref dReal X0, ref dReal X1, int n);
+
+		[DllImport("ode", EntryPoint = "dFactorCholesky"), SuppressUnmanagedCodeSecurity]
+		public static extern int FactorCholesky(ref dReal A00, int n);
+
+		[DllImport("ode", EntryPoint = "dFactorLDLT"), SuppressUnmanagedCodeSecurity]
+		public static extern void FactorLDLT(ref dReal A, out dReal d, int n, int nskip);
+
 		[DllImport("ode", EntryPoint = "dGeomBoxGetLengths"), SuppressUnmanagedCodeSecurity]
 		public static extern void GeomBoxGetLengths(IntPtr geom, out Vector3 len);

@@ -1070,6 +1079,12 @@
 		[DllImport("ode", EntryPoint = "dInitODE"), SuppressUnmanagedCodeSecurity]
 		public static extern void InitODE();

+		[DllImport("ode", EntryPoint = "dIsPositiveDefinite"), SuppressUnmanagedCodeSecurity]
+		public static extern int IsPositiveDefinite(ref dReal A, int n);
+
+		[DllImport("ode", EntryPoint = "dInvertPDMatrix"), SuppressUnmanagedCodeSecurity]
+		public static extern int InvertPDMatrix(ref dReal A, out dReal Ainv, int n);
+
 		[DllImport("ode", EntryPoint = "dJointAddAMotorTorques"), SuppressUnmanagedCodeSecurity]
 		public static extern void JointAddAMotorTorques(IntPtr joint, dReal torque1, dReal torque2, dReal torque3);

@@ -1401,6 +1416,9 @@
 		[DllImport("ode", EntryPoint = "dJointSetUniversalParam"), SuppressUnmanagedCodeSecurity]
 		public static extern void JointSetUniversalParam(IntPtr j, int parameter, dReal value);

+		[DllImport("ode", EntryPoint = "dLDLTAddTL"), SuppressUnmanagedCodeSecurity]
+		public static extern void LDLTAddTL(ref dReal L, ref dReal d, ref dReal a, int n, int nskip);
+
 		[DllImport("ode", EntryPoint = "dMassAdd"), SuppressUnmanagedCodeSecurity]
 		public static extern void MassAdd(ref Mass a, ref Mass b);

@@ -1455,6 +1473,15 @@
 		[DllImport("ode", EntryPoint = "dMassTranslate"), SuppressUnmanagedCodeSecurity]
 		public static extern void MassTranslate(out Mass mass, dReal x, dReal y, dReal z);

+		[DllImport("ode", EntryPoint = "dMultiply0"), SuppressUnmanagedCodeSecurity]
+		public static extern void Multiply0(out dReal A00, ref dReal B00, ref dReal C00, int p, int q, int r);
+
+		[DllImport("ode", EntryPoint = "dMultiply1"), SuppressUnmanagedCodeSecurity]
+		public static extern void Multiply1(out dReal A00, ref dReal B00, ref dReal C00, int p, int q, int r);
+
+		[DllImport("ode", EntryPoint = "dMultiply2"), SuppressUnmanagedCodeSecurity]
+		public static extern void Multiply2(out dReal A00, ref dReal B00, ref dReal C00, int p, int q, int r);
+
 		[DllImport("ode", EntryPoint = "dQuadTreeSpaceCreate"), SuppressUnmanagedCodeSecurity]
 		public static extern IntPtr QuadTreeSpaceCreate(IntPtr space, ref Vector3 center, ref Vector3 extents, int depth);

@@ -1476,6 +1503,18 @@
 		[DllImport("ode", EntryPoint = "dSimpleSpaceCreate"), SuppressUnmanagedCodeSecurity]
 		public static extern IntPtr SimpleSpaceCreate(IntPtr space);

+		[DllImport("ode", EntryPoint = "dSolveCholesky"), SuppressUnmanagedCodeSecurity]
+		public static extern void SolveCholesky(ref dReal L, out dReal b, int n);
+
+		[DllImport("ode", EntryPoint = "dSolveL1"), SuppressUnmanagedCodeSecurity]
+		public static extern void SolveL1(ref dReal L, out dReal b, int n, int nskip);
+
+		[DllImport("ode", EntryPoint = "dSolveL1T"), SuppressUnmanagedCodeSecurity]
+		public static extern void SolveL1T(ref dReal L, out dReal b, int n, int nskip);
+
+		[DllImport("ode", EntryPoint = "dSolveLDLT"), SuppressUnmanagedCodeSecurity]
+		public static extern void SolveLDLT(ref dReal L, ref dReal d, out dReal b, int n, int nskip);
+
 		[DllImport("ode", EntryPoint = "dSpaceAdd"), SuppressUnmanagedCodeSecurity]
 		public static extern void SpaceAdd(IntPtr space, IntPtr geom);

@@ -1508,6 +1547,9 @@

 		[DllImport("ode", EntryPoint = "dSpaceSetCleanup"), SuppressUnmanagedCodeSecurity]
 		public static extern void SpaceSetCleanup(IntPtr space, bool mode);
+
+		[DllImport("ode", EntryPoint = "dVectorScale"), SuppressUnmanagedCodeSecurity]
+		public static extern void VectorScale(out dReal a, ref dReal d, int n);

 		[DllImport("ode", EntryPoint = "dWorldCreate"), SuppressUnmanagedCodeSecurity]
 		public static extern IntPtr WorldCreate();


PR #8559 from manson: fix profile selection for all cameras in C# tutorial 2

--- wrappers/csharp/cs-tutorial-2-capture/Window.xaml.cs
+++ wrappers/csharp/cs-tutorial-2-capture/Window.xaml.cs
@@ -51,13 +51,38 @@
                 // Create and config the pipeline to strem color and depth frames.
                 pipeline = new Pipeline();

-                var cfg = new Config();
-                cfg.EnableStream(Stream.Depth, 640, 480);
-                cfg.EnableStream(Stream.Color, Format.Rgb8);
+                using (var ctx = new Context())
+                {
+                    var devices = ctx.QueryDevices();
+                    var dev = devices[0];

-                var pp = pipeline.Start(cfg);
+                    Console.WriteLine("\nUsing device 0, an {0}", dev.Info[CameraInfo.Name]);
+                    Console.WriteLine("    Serial number: {0}", dev.Info[CameraInfo.SerialNumber]);
+                    Console.WriteLine("    Firmware version: {0}", dev.Info[CameraInfo.FirmwareVersion]);

-                SetupWindow(pp, out updateDepth, out updateColor);
+                    var sensors = dev.QuerySensors();
+                    var depthSensor = sensors[0];
+                    var colorSensor = sensors[1];
+
+                    var depthProfile = depthSensor.StreamProfiles
+                                        .Where(p => p.Stream == Stream.Depth)
+                                        .OrderBy(p => p.Framerate)
+                                        .Select(p => p.As<VideoStreamProfile>()).First();
+
+                    var colorProfile = colorSensor.StreamProfiles
+                                        .Where(p => p.Stream == Stream.Color)
+                                        .OrderBy(p => p.Framerate)
+                                        .Select(p => p.As<VideoStreamProfile>()).First();
+
+                    var cfg = new Config();
+                    cfg.EnableStream(Stream.Depth, depthProfile.Width, depthProfile.Height, depthProfile.Format, depthProfile.Framerate);
+                    cfg.EnableStream(Stream.Color, colorProfile.Width, colorProfile.Height, colorProfile.Format, colorProfile.Framerate);
+
+
+                    var pp = pipeline.Start(cfg);
+
+                    SetupWindow(pp, out updateDepth, out updateColor);
+                }

                 Task.Factory.StartNew(() =>
                 {


Use workingDirectory instead of --include-path to handle spaces in path

--- src/Handlers/LessCssHandler.cs
+++ src/Handlers/LessCssHandler.cs
@@ -96,25 +96,25 @@
             using (lessStream)
             using (var errors = new StringWriter())
             {
-                string dirname = Path.GetDirectoryName(lessFilePath);
-                if (dirname.Contains(' '))
-                    throw new ApplicationException("lessc doesn't support file paths with spaces '" + dirname + "'");
-
                 /*
                     usage: lessc [option option=parameter ...] <source> [destination]

                     If source is set to `-' (dash or hyphen-minus), input is read from stdin.

-                    options:
+                    	options:
                         -h, --help              Print help (this message) and exit.
-                        --include-path          Set include paths. Separated by `:'. Use `;' on Windows.
+                        --include-path=PATHS    Set include paths. Separated by `:'. Use `;' on Windows.
+                        -M, --depends           Output a makefile import dependency list to stdout
                         --no-color              Disable colorized output.
+                        --no-ie-compat          Disable IE compatibility checks.
+                        -l, --lint              Syntax check only (lint).
                         -s, --silent            Suppress output of error messages.
                         --strict-imports        Force evaluation of imports.
                         --verbose               Be verbose.
                         -v, --version           Print version number and exit.
                         -x, --compress          Compress output by removing some whitespaces.
                         --yui-compress          Compress output using ycssmin
+                        --max-line-len=LINELEN  Max line length used by ycssmin
                         -O0, -O1, -O2           Set the parser's optimization level. The lower
                                                 the number, the less nodes it will create in the
                                                 tree. This could matter for debugging, or if you
@@ -125,22 +125,27 @@
                                                 that will output the information within a fake
                                                 media query which is compatible with the SASS
                                                 format, and 'all' which will do both.
-                        -rp, --rootpath         Set rootpath for url rewriting in relative imports and urls.
-                                                Works with or withour the relative-urls option.
+                        -rp, --rootpath=URL     Set rootpath for url rewriting in relative imports and urls.
+                                                Works with or without the relative-urls option.
                         -ru, --relative-urls    re-write relative urls to the base less file.
+                        -sm=on|off              Turn on or off strict math, where in strict mode, math
+                        --strict-math=on|off    requires brackets. This option may default to on and then
+                                                be removed in the future.
+                        -su=on|off              Allow mixed units, e.g. 1px+1em or 1px*1px which have units
+                    --strict-units=on|off   that cannot be represented.
                  */

                 string args = "\"" + _lessc + "\""
                     + " -" // read from stdin
                     + (compress ? " --yui-compress" : "")
-                    + " --include-path=" + dirname
                     + " --no-color"
                     + (lineNumbers != null ? " --line-numbers=" + lineNumbers : "");
                 int exitCode = ProcessUtil.Exec(NodeExe,
                     args: args,
                     stdIn: lessStream,
                     stdOut: output,
-                    stdErr: errors);
+                    stdErr: errors,
+                    workingDirectory: Path.GetDirectoryName(lessFilePath));
                 if (exitCode != 0)
                 {
                     throw new ApplicationException(string.Format("Error {0} in '{1}': \r\n{2}",


Update TcpTransport.cs

Update TcpTransport.cs

--- src/Hprose.RPC/TcpTransport.cs
+++ src/Hprose.RPC/TcpTransport.cs
@@ -27,7 +27,6 @@
     public class TcpTransport : ITransport {
         public static ReadOnlyCollection<string> Schemes { get; } = new ReadOnlyCollection<string>(new string[] { "tcp", "tcp4", "tcp6", "tls", "tls4", "tls6", "ssl", "ssl4", "ssl6" });
         private volatile int counter = 0;
-        private volatile int current = -1;
         public LingerOption LingerState { get; set; } = null;
         public bool NoDelay { get; set; } = true;
         public TimeSpan Timeout { get; set; } = new TimeSpan(0, 0, 30);
@@ -151,10 +150,18 @@
             while (!requests.IsEmpty) {
                 requests.TryPeek(out (int index, Stream stream) request);
                 var index = request.index;
-                if (Interlocked.Exchange(ref current, index) == index) return;
                 if (results.TryGetValue(index, out var result)) {
-                    sended[index] = result;
-                    results.TryRemove(index, out result);
+                    if (!(sended.TryAdd(index, result) && results.TryRemove(index, out result))) {
+#if NET40
+                        await TaskEx.Yield();
+#else
+                        await Task.Yield();
+#endif
+                        continue;
+                    }
+                }
+                else {
+                    return;
                 }
                 var stream = request.stream;
                 try {


:joy:  修复删除方法的调用错误。 :de:

:joy:  修复删除方法的调用错误。 :de:

--- src/Http/HttpControllerBase.cs
+++ src/Http/HttpControllerBase.cs
@@ -115,13 +115,13 @@
 			switch(parts.Length)
 			{
 				case 1:
-					succeed = this.DataService.Delete(parts[0]) > 0;
+					succeed = this.DataService.Delete<string>(parts[0]) > 0;
 					break;
 				case 2:
-					succeed = this.DataService.Delete(parts[0], parts[1]) > 0;
+					succeed = this.DataService.Delete<string, string>(parts[0], parts[1]) > 0;
 					break;
 				case 3:
-					succeed = this.DataService.Delete(parts[0], parts[1], parts[2]) > 0;
+					succeed = this.DataService.Delete<string, string, string>(parts[0], parts[1], parts[2]) > 0;
 					break;
 				default:
 					throw new HttpResponseException(System.Net.HttpStatusCode.BadRequest);


Make HttpService retain standard interface

Make HttpService by default add a correlation header

--- src/HttpService/HttpService.cs
+++ src/HttpService/HttpService.cs
@@ -1,5 +1,6 @@
 using System.Net.Http;
 using System.Threading.Tasks;
+using HttpService.Handlers;
 using Microsoft.AspNetCore.Authentication;
 using Microsoft.AspNetCore.Http;

@@ -32,7 +33,7 @@
 		public HttpService(IContextReader tokenExtractor, HttpClient client = null)
 		{
 			_tokenExtractor = tokenExtractor;
-			_client = client ?? new HttpClient();
+			_client = client ?? new HttpClient(new CorrelationHandler(new HttpClientHandler(), tokenExtractor.GetContextAccessor()));
 		}

 		/// <summary>
@@ -124,6 +125,7 @@
 	public interface IContextReader
 	{
 		Task<string> GetTokenAsync();
+		IHttpContextAccessor GetContextAccessor();
 	}

 	public class HttpContextReader : IContextReader
@@ -135,6 +137,11 @@
 			this._accessor = accessor;
 		}

+		public IHttpContextAccessor GetContextAccessor()
+		{
+			return _accessor;
+		}
+
 		public async Task<string> GetTokenAsync()
 		{
 			var token = await this._accessor.HttpContext.GetTokenAsync("access_token");


Highest cost with duplicates

Highest cost with duplicates

--- 2015/DynamicProgramming/01.KnapsackProblem/Program.cs
+++ 2015/DynamicProgramming/01.KnapsackProblem/Program.cs
@@ -23,6 +23,76 @@
                 new Product("Ракия", 3, 5),
             };
             FindHighestCostAndWeightBagNoDuplicates(products, maxWeight);
+
+            maxWeight = 23;
+            products = new Product[]
+            {
+                new Product("Трошия", 6, 6),
+                new Product("Сланина", 8, 7),
+                new Product("Ракия", 7, 7),
+            };
+            FindHighestCostAndWeightBagWithDuplicates(products, maxWeight);
+        }
+
+        private static void FindHighestCostAndWeightBagNoDuplicates(int[] weights, int[] costs, int maxBasketWeight)
+        {
+            if (weights.Length != costs.Length)
+            {
+                throw new ArgumentException("Weights and costs length should be equal!");
+            }
+
+            bool[] possibleWeights = new bool[maxBasketWeight + 1];
+            int[] possibleCosts = new int[maxBasketWeight + 1];
+            possibleWeights[0] = true;
+            int maxWeight = 0;
+            int tempMaxWeight = 0;
+            int maxCostIndex = 0;
+
+            for (int j = 0; j < weights.Length; j++)
+            {
+                for (int i = maxWeight; i >= 0; i--)
+                {
+                    if (possibleWeights[i])
+                    {
+                        var currentWeight = i + weights[j];
+                        if (currentWeight > maxBasketWeight)
+                        {
+                            continue;
+                        }
+
+                        if (tempMaxWeight < currentWeight)
+                        {
+                            tempMaxWeight = currentWeight;
+                        }
+
+                        var newCost = possibleCosts[i] + costs[j];
+                        if (possibleCosts[currentWeight] < newCost)
+                        {
+                            possibleCosts[currentWeight] = newCost;
+
+                            if (possibleCosts[maxCostIndex] <= newCost)
+                            {
+                                maxCostIndex = currentWeight;
+                            }
+                        }
+
+                        possibleWeights[currentWeight] = true;
+                    }
+                }
+
+                maxWeight = tempMaxWeight;
+            }
+
+            //var maxCostIndex = maxWeight;
+            //for (int i = maxWeight - 1; i >= 0; i--)
+            //{
+            //    if (possibleCosts[i] > possibleCosts[maxCostIndex])
+            //    {
+            //        maxCostIndex = i;
+            //    }
+            //}
+
+            Console.WriteLine("Weight: {0} Cost: {1}", maxCostIndex, possibleCosts[maxCostIndex]);
         }

         private static void FindHighestCostAndWeightBagNoDuplicates(Product[] products, int maxBasketWeight)
@@ -33,6 +103,7 @@
             possibleWeights[0] = true;
             int maxWeight = 0;
             int tempMaxWeight = 0;
+            int maxCostIndex = 0;

             foreach (var product in products)
             {
@@ -64,6 +135,11 @@
                             {
                                 possibleProducts[currentWeight] = currentProducts + ", " + product.Name;
                             }
+
+                            if (possibleCosts[maxCostIndex] <= newCost)
+                            {
+                                maxCostIndex = currentWeight;
+                            }
                         }

                         possibleWeights[currentWeight] = true;
@@ -73,71 +149,55 @@
                 maxWeight = tempMaxWeight;
             }

-            var maxCostIndex = maxWeight;
-            for (int i = maxWeight - 1; i >= 0; i--)
-            {
-                if (possibleWeights[i] && possibleCosts[i] > possibleCosts[maxCostIndex])
-                {
-                    maxCostIndex = i;
-                }
-            }
-
             Console.WriteLine("\nПродукти: {0} \nТегло: {1} \nСтойност: {2}\n", possibleProducts[maxCostIndex], maxCostIndex, possibleCosts[maxCostIndex]);
         }

-        private static void FindHighestCostAndWeightBagNoDuplicates(int[] weights, int[] costs, int maxBasketWeight)
-        {
-            if (weights.Length != costs.Length)
-            {
-                throw new ArgumentException("Weights and costs length should be equal!");
-            }
-
+        private static void FindHighestCostAndWeightBagWithDuplicates(Product[] products, int maxBasketWeight)
+        {
             bool[] possibleWeights = new bool[maxBasketWeight + 1];
             int[] possibleCosts = new int[maxBasketWeight + 1];
+            string[] possibleProducts = new string[maxBasketWeight + 1];
             possibleWeights[0] = true;
-            int maxWeight = 0;
-            int tempMaxWeight = 0;
-
-            for (int j = 0; j < weights.Length; j++)
-            {
-                for (int i = maxWeight; i >= 0; i--)
+            int maxCostIndex = 0;
+
+            foreach (var product in products)
+            {
+                for (int i = 0; i <= maxBasketWeight; i++)
                 {
                     if (possibleWeights[i])
                     {
-                        var currentWeight = i + weights[j];
+                        var currentWeight = i + product.Weight;
                         if (currentWeight > maxBasketWeight)
                         {
                             continue;
                         }

-                        if (tempMaxWeight < currentWeight)
-                        {
-                            tempMaxWeight = currentWeight;
-                        }
-
-                        var newCost = possibleCosts[i] + costs[j];
+                        var newCost = possibleCosts[i] + product.Price;
                         if (possibleCosts[currentWeight] < newCost)
                         {
                             possibleCosts[currentWeight] = newCost;
+                            var currentProducts = possibleProducts[i];
+                            if (currentProducts == null)
+                            {
+                                possibleProducts[currentWeight] = product.Name;
+                            }
+                            else
+                            {
+                                possibleProducts[currentWeight] = currentProducts + ", " + product.Name;
+                            }
+
+                            if (possibleCosts[maxCostIndex] <= newCost)
+                            {
+                                maxCostIndex = currentWeight;
+                            }
                         }

                         possibleWeights[currentWeight] = true;
                     }
                 }
-
-                maxWeight = tempMaxWeight;
-            }
-
-            var maxCostIndex = maxWeight;
-            for (int i = maxWeight - 1; i >= 0; i--)
-            {
-                if (possibleCosts[i] > possibleCosts[maxCostIndex])
-                {
-                    maxCostIndex = i;
-                }
-            }
-
-            Console.WriteLine("Weight: {0} Cost: {1}", maxCostIndex, possibleCosts[maxCostIndex]);
+            }
+
+            Console.WriteLine("\nПродукти: {0} \nТегло: {1} \nСтойност: {2}\n", possibleProducts[maxCostIndex], maxCostIndex, possibleCosts[maxCostIndex]);
         }
     }
 }


Detailed help comment on multi linear interpolation


Bug fix; invalid CreateDirectory

Bug fix; invalid CreateDirectory

--- convSheet/Program.cs
+++ convSheet/Program.cs
@@ -191,7 +191,9 @@
                 }
                 foreach (var kv in dic) {
                     Console.WriteLine("Output: "+kv.Key);
-                    System.IO.Directory.CreateDirectory (System.IO.Path.GetDirectoryName(kv.Key));
+                    var dir = System.IO.Path.GetDirectoryName(kv.Key);
+                    if (!string.IsNullOrEmpty(dir))
+                        System.IO.Directory.CreateDirectory (dir);
                     if (!System.IO.File.Exists(kv.Key) || System.IO.File.ReadAllText (kv.Key) != kv.Value) {
                         System.IO.File.WriteAllText (kv.Key, kv.Value);
                     }
@@ -279,7 +281,9 @@
                 if (!string.IsNullOrEmpty(filename))
                 {
                     Console.WriteLine("Output: " + outputdir + filename);
-                    System.IO.Directory.CreateDirectory (System.IO.Path.GetDirectoryName(outputdir + filename));
+                    var dir = System.IO.Path.GetDirectoryName (outputdir + filename);
+                    if (!string.IsNullOrEmpty(dir))
+                        System.IO.Directory.CreateDirectory (dir);
                     if (!System.IO.File.Exists(outputdir + filename) || System.IO.File.ReadAllText (outputdir + filename) != value) {
                         System.IO.File.WriteAllText (outputdir + filename, value);
                     }