Add GetCurrentWorkingDirectory for Windows platform

--- src/Utils/Files.cpp
+++ src/Utils/Files.cpp
@@ -4,16 +4,22 @@

 #if OS(POSIX)
 #include <unistd.h>
+#elif OS(WIN)
+#include "nucleus/Win/WindowsMixin.h"
 #endif

 namespace nu {

+FilePath getCurrentWorkingDirectory(Allocator* allocator) {
 #if OS(POSIX)
-FilePath getCurrentWorkingDirectory(Allocator* allocator) {
   char buf[PATH_MAX] = {0};
   const char* result = ::getcwd(buf, PATH_MAX);
   return FilePath{String{result, String::npos, allocator}, allocator};
+#elif OS(WIN)
+  char buf[MAX_PATH] = {0};
+  DWORD result = ::GetCurrentDirectoryA(MAX_PATH, buf);
+  return FilePath{String{buf, static_cast<I32>(result), allocator}, allocator};
+#endif
 }
-#endif

 }  // namespace nu


Restore sensor/config/reachable on startup for CLIP sensors

--- sensor.cpp
+++ sensor.cpp
@@ -593,7 +593,9 @@
         ResourceItem *item = itemForIndex(i);
         const ResourceItemDescriptor &rid = item->descriptor();

-        if (item->descriptor().suffix == RConfigReachable)
+        if (type().startsWith(QLatin1String("CLIP")))
+        {}
+        else if (item->descriptor().suffix == RConfigReachable)
         { // set only from live data
             item->setValue(false);
             continue;


skiaserve no longer crashes when no X server is present
GOLD_TRYBOT_URL= https://gold.skia.org/search?issue=2059263002

Review-Url: https://codereview.chromium.org/2059263002

--- tools/skiaserve/Request.cpp
+++ tools/skiaserve/Request.cpp
@@ -71,8 +71,14 @@
 #if SK_SUPPORT_GPU
     GrContextFactory* factory = fContextFactory;
     GLTestContext* gl = factory->getContextInfo(GrContextFactory::kNativeGL_ContextType,
-                                            GrContextFactory::kNone_ContextOptions).glContext();
-    gl->makeCurrent();
+                                                GrContextFactory::kNone_ContextOptions).glContext();
+    if (!gl) {
+        gl = factory->getContextInfo(GrContextFactory::kMESA_ContextType,
+                                     GrContextFactory::kNone_ContextOptions).glContext();
+    }
+    if (gl) {
+        gl->makeCurrent();
+    }
 #endif
     SkASSERT(fDebugCanvas);

@@ -115,10 +121,15 @@

 GrContext* Request::getContext() {
 #if SK_SUPPORT_GPU
-  return fContextFactory->get(GrContextFactory::kNativeGL_ContextType,
-                              GrContextFactory::kNone_ContextOptions);
+    GrContext* result = fContextFactory->get(GrContextFactory::kNativeGL_ContextType,
+                                             GrContextFactory::kNone_ContextOptions);
+    if (!result) {
+        result = fContextFactory->get(GrContextFactory::kMESA_ContextType,
+                                      GrContextFactory::kNone_ContextOptions);
+    }
+    return result;
 #else
-  return nullptr;
+    return nullptr;
 #endif
 }


Removes forward declaration of Xml::Element in src/Xml/XmlNode.hpp

--- src/Xml/XmlNode.hpp
+++ src/Xml/XmlNode.hpp
@@ -7,8 +7,6 @@

 namespace Xml
 {
-
-    class Element;

     /**
      * Defines the abstract class of a node for interface purpose


Clean up and fix log metalogging

Clean up and fix log metalogging

--- lib/log.cpp
+++ lib/log.cpp
@@ -100,7 +100,9 @@
                 if (auto* level = strchr(pattern, ':'))
                     return atoi(level + 1); }

-    // If there's no matching spec, compute a default from the global verbosity level.
+    // If there's no matching spec, compute a default from the global verbosity level,
+    // except for THIS file
+    if (!strcmp(file, "log.cpp")) return 0;
     return verbosity > 0 ? verbosity - 1 : 0;
 }

@@ -177,6 +179,12 @@
     static std::mutex lock;
     std::lock_guard<std::mutex> acquire(lock);
 #endif
+#ifdef CLOCK_MONOTONIC
+    if (!Detail::initTime) {
+        struct timespec ts;
+        clock_gettime(CLOCK_MONOTONIC, &ts);
+        Detail::initTime = ts.tv_sec*1000000000UL + ts.tv_nsec; }
+#endif

     Detail::verbosity++;
     Detail::invalidateCaches(Detail::verbosity - 1);


Fixed an error for zero length files.

Fixed an error for zero length files.

--- tools/testtools/csvdiff.cpp
+++ tools/testtools/csvdiff.cpp
@@ -296,6 +296,9 @@
    * set a preliminary value of nCol
    */
   nCol = maxCommas + 1;
+  if (nScanLines == 0) {
+    nCol = 0;
+  }
   char **strlets = (char **) mdp_alloc_ptr_1(maxCommas+1);

   int doingLineType = LT_TITLELINE;
@@ -575,11 +578,11 @@
   int opt_let;
   char  *fileName1=NULL, *fileName2=NULL; /* Names of the csv files */
   FILE  *fp1=NULL, *fp2=NULL;
-  int    nTitleLines1, nTitleLines2;
-  int    nColTitleLines1, nColTitleLines2;
-  int    nCol1,  nCol2, nColMAX, nColcomparisons;
-  int    nDataRows1, nDataRows2;
-  char  **title1,  **title2;
+  int    nTitleLines1 = 0, nTitleLines2 = 0;
+  int    nColTitleLines1 = 0, nColTitleLines2 = 0;
+  int    nCol1 = 0,  nCol2 = 0, nColMAX = 0, nColcomparisons = 0;
+  int    nDataRows1 = 0, nDataRows2 = 0;
+  char  **title1 = 0,  **title2 = 0;
   int    **compColList = NULL;
   char   ***ColMLNames1 = NULL, ***ColMLNames2 = NULL;
   char   **ColNames1 = NULL, **ColNames2 = NULL;
@@ -689,9 +692,28 @@
    */

   get_sizes(fp1, nTitleLines1, nColTitleLines1, nCol1, nDataRows1);
+  if (nCol1 == 0) {
+    printf("Number of columns in file %s is zero\n", fileName1);
+    testPassed = -1;
+    exit (-1);
+  }
+  if (nDataRows1 == 0) {
+    printf("Number of data rows in file %s is zero\n", fileName1);
+    testPassed = -1;
+    exit (-1);
+  }

   get_sizes(fp2, nTitleLines2, nColTitleLines2, nCol2, nDataRows2);
-
+  if (nCol2 == 0) {
+    printf("Number of columns in file %s is zero\n", fileName2);
+    testPassed = -1;
+    exit (-1);
+  }
+  if (nDataRows2 == 0) {
+    printf("Number of data rows in file %s is zero\n", fileName2);
+    testPassed = -1;
+    exit (-1);
+  }

   if (nTitleLines1 != nTitleLines2) {
     printf("Number o Title Lines differ:, %d %d\n",nTitleLines1, nTitleLines2);
@@ -860,7 +882,7 @@
 	  max_diff = rel_diff;
 	}
 	if (ndiff < 10) {
-	  printf("\tColumn variable %s at data row %d ", ColNames1[i1], j);
+	  printf("\tColumn variable %s at data row %d ", ColNames1[i1], j + 1);
 	  printf(" differ: %g %g\n", curVarValues1[j],
 		 curVarValues2[j]);
 	}
@@ -873,12 +895,12 @@
       if (ndiff < 10) {
 	if (nDataRows1 > nDataRows2) {
 	  for (j = nDataRowsMIN; j < nDataRowsMAX; j++) {
-	    printf("\tColumn variable %s at data row %d ", ColNames1[i1], j);
+	    printf("\tColumn variable %s at data row %d ", ColNames1[i1], j + 1);
 	    printf(" differ: %g      NA\n", curVarValues1[j]);
 	  }
 	} else {
 	  for (j = nDataRowsMIN; j < nDataRowsMAX; j++) {
-	    printf("\tColumn variable %s at data row %d ", ColNames1[i1], j);
+	    printf("\tColumn variable %s at data row %d ", ColNames1[i1], j + 1);
 	    printf(" differ: NA     %g \n", curVarValues2[j]);
 	  }
 	}
@@ -893,7 +915,7 @@
       printf(
 	     "Column variable %s failed comparison test for %d occurances\n",
 	     ColNames1[i1], ndiff);
-      printf("  Largest difference was at data row %d ", jmax);
+      printf("  Largest difference was at data row %d ", jmax + 1);
       printf(": %g %g\n", curVarValues1[jmax],  curVarValues2[jmax]);
       testPassed = 0;
     } else if (Debug_Flag) {


added code to eliminate generalized self interactions in the rcvSynapticInput method

git-svn-id: 602a26e73ae9f2a14e2bb95676f2e137fcc39919@4793 7c0444ca-5550-0410-9008-faecdbe78eb5

--- src/connections/CliqueConn.cpp
+++ src/connections/CliqueConn.cpp
@@ -62,7 +62,9 @@
    assert(a_post_mask != NULL);
    // get linear index of cell at center of patch for self_flag == true
    const int k_post_self = (int) (a_post_size / 2);  // if self_flag == true, a_post_size should be odd
-
+   for (int k_post = 0; k_post < a_post_size; k_post++) {
+      a_post_mask[k_post] = 1;
+   }

    int delay = getDelay(arborId);


size removed

size removed

--- server.cpp
+++ server.cpp
@@ -375,14 +375,14 @@

     std::cout << server.ip << ":" << server.port << " getting size of users in channel" << std::endl;
-    size_t size = user_channels[say->req_channel]->users.size();
+//    size_t size = user_channels[say->req_channel]->users.size();
     std::cout << "req chan: " << say->req_channel << std::endl;
-    std::cout << "size: " << size << std::endl;
+//    std::cout << "size: " << size << std::endl;
     for(auto c : user_channels){
       std::cout << c.first << std::endl;
     }

-    if ((user_channels.find(say->req_channel) != user_channels.end()) && size > 0) {
+    if (user_channels.find(say->req_channel) != user_channels.end()) {
       std::cout << server.ip << ":" << server.port << " sending say to users" << std::endl;
       SendSay(server, *say);
     }


Another bugfix! If you haven't guessed yet, I'm compiling and coding on two different machines.

--- server.cpp
+++ server.cpp
@@ -133,7 +133,7 @@
   bzero((char*)&acceptSockAddr, sizeof(acceptSockAddr));
   acceptSockAddr.sin_family      = AF_INET;
   acceptSockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
-  acceptSockAddr.sin_port        = htons(port);
+  acceptSockAddr.sin_port        = htons(PORT);

   // Open a stream-oriented socket with the Internet address family.
   int serverSd = socket(AF_INET, SOCK_STREAM, 0);


test always send s2sjoin except to sender

--- server.cpp
+++ server.cpp
@@ -211,7 +211,7 @@

   // Sending join for all our channels to all adjacent servers.
   for (auto c : server_channels) {
-    SendS2SJoinRequest(server, c.first);
+    SendS2SJoinRequest(server, c.first, "");
   }
 }

@@ -343,7 +343,7 @@
  * @server is this server's info.
  * @channel is the channel to send to other servers.
  */
-void SendS2SJoinRequest(Server server, std::string channel_name) {
+void SendS2SJoinRequest(Server server, std::string channel_name, std::string request_ip_port) {
   size_t servers_size = servers.size();

   if (servers_size > 0) {
@@ -354,7 +354,8 @@
     size_t message_size = sizeof(struct s2s_request_join);

     for (auto adj_server : servers) {
-      if (adj_server.second->channels.find(channel_name) == adj_server.second->channels.end()) {
+      std::string adj_server_ip_port = adj_server.second->ip + ":" + adj_server.second->port;
+      if (adj_server_ip_port != request_ip_port) {
         struct sockaddr_in server_addr;
         memset(&server_addr, 0, sizeof(struct sockaddr_in));
         server_addr.sin_family = AF_INET;
@@ -506,7 +507,7 @@

   if (server_channels.find(join->req_channel) == server_channels.end()) {
     CreateServerChannel(join->req_channel);
-    SendS2SJoinRequest(server, join->req_channel);
+    SendS2SJoinRequest(server, join->req_channel, request_ip_port);
   }
 }

@@ -743,7 +744,7 @@

   if (server_channels.find(channel->name) == server_channels.end()) {
     CreateServerChannel(channel->name);
-    SendS2SJoinRequest(server, channel->name);
+    SendS2SJoinRequest(server, channel->name, "");
   }
 }


Check contacts file existence

Check contacts file existence

--- src/addressbook.cpp
+++ src/addressbook.cpp
@@ -40,14 +40,17 @@

 	Interface::Instance->add("/"+mUser->name()+"/contacts", this);

-	try {
-	  File file(mFileName, File::Read);
-	  load(file);
-	  file.close();
-	}
-	catch(const Exception &e)
-	{
-		Log("AddressBook", String("Loading failed: ") + e.what());
+	if(File::Exist(mFileName))
+	{
+		try {
+			File file(mFileName, File::Read);
+			load(file);
+			file.close();
+		}
+		catch(const Exception &e)
+		{
+			Log("AddressBook", String("Loading failed: ") + e.what());
+		}
 	}
 }


gjs-tests: Remove fixture test

gjs-tests: Remove fixture test

It doesn't do anything

--- test/gjs-tests.cpp
+++ test/gjs-tests.cpp
@@ -87,23 +87,6 @@
     g_object_unref (context);
 }

-static void
-gjstest_test_func_gjs_context_fixture(void)
-{
-    GjsUnitTestFixture fixture;
-    JSContext *context;
-    JSObject *global;
-
-    _gjs_unit_test_fixture_begin(&fixture);
-    context = fixture.context;
-
-    global = JS_GetGlobalObject(context);
-    JSCompartment *oldCompartment = JS_EnterCompartment(context, global);
-
-    JS_LeaveCompartment(context, oldCompartment);
-    _gjs_unit_test_fixture_finish(&fixture);
-}
-
 #define N_ELEMS 15

 static void
@@ -357,7 +340,6 @@

     g_test_add_func("/gjs/context/construct/destroy", gjstest_test_func_gjs_context_construct_destroy);
     g_test_add_func("/gjs/context/construct/eval", gjstest_test_func_gjs_context_construct_eval);
-    g_test_add_func("/gjs/context/fixture", gjstest_test_func_gjs_context_fixture);
     g_test_add_func("/gjs/jsapi/util/array", gjstest_test_func_gjs_jsapi_util_array);
     g_test_add_func("/gjs/jsapi/util/error/throw", gjstest_test_func_gjs_jsapi_util_error_throw);
     g_test_add_func("/gjs/jsapi/util/string/js/string/utf8", gjstest_test_func_gjs_jsapi_util_string_js_string_utf8);


remove 1<<30

remove 1<<30

--- src/agent/cgroup.cc
+++ src/agent/cgroup.cc
@@ -190,12 +190,9 @@
 }

 void ContainerTaskRunner::PutToCGroup(){
-    int64_t mem_size = m_task_info.required_mem() * (1L << 30);
+    int64_t mem_size = m_task_info.required_mem();
     double cpu_core = m_task_info.required_cpu();
     LOG(INFO, "resource limit cpu %f, mem %ld", cpu_core, mem_size);
-    if (mem_size <= (1L << 30)) {
-        mem_size = (1L << 30);
-    }
     /*
     std::string mem_key = "memory";
     std::string cpu_key = "cpu";


Change BFCGdrAllocator to 102 for priority.

Signed-off-by: Yong Tang <765086fe2e0c1f980161f127fec596800f327f62@outlook.com>

--- tensorflow/contrib/gdr/gdr_memory_manager.cc
+++ tensorflow/contrib/gdr/gdr_memory_manager.cc
@@ -201,7 +201,7 @@
   }
 };

-REGISTER_MEM_ALLOCATOR("BFCGdrAllocator", 101, BFCGdrAllocatorFactory);
+REGISTER_MEM_ALLOCATOR("BFCGdrAllocator", 102, BFCGdrAllocatorFactory);

 GdrMemoryManager::GdrMemoryManager(const string& host, const string& port)
     : host_(host),


Use 2-arg TraceMe constructor to prevent unnecessary StrCat computation when
tracing is disabled.

PiperOrigin-RevId: 165722280

--- tensorflow/core/kernels/captured_function.cc
+++ tensorflow/core/kernels/captured_function.cc
@@ -106,7 +106,7 @@
 Status CapturedFunction::Run(FunctionLibraryRuntime::Options f_opts,
                              gtl::ArraySlice<Tensor> args,
                              std::vector<Tensor>* rets, const string& prefix) {
-  port::Tracing::TraceMe activity(strings::StrCat(prefix, "::Run"));
+  port::Tracing::TraceMe activity(prefix, "::Run");
   Notification n;
   Status s;
   auto done_callback = [&n, &s](Status func_status) {


A slight clean up in query error handling

--- queries.cpp
+++ queries.cpp
@@ -76,13 +76,6 @@
 #ifndef O_BINARY
 #define O_BINARY 0
 #endif
-
-#define memcmp8(a,b) memcmp ((a), (b), 8)
-
-static int mystreq1 (const char *a, const char *b, int l) {
-    if ((int)strlen (a) != l) { return 1; }
-    return memcmp (a, b, l);
-}

 void query::cancel_timer()
 {
@@ -362,6 +355,42 @@
     return 0;
 }

+static bool get_int_from_prefixed_string(int& number, const std::string& prefixed_string, const std::string& prefix)
+{
+    std::string number_string;
+    if (prefixed_string.size() >= prefix.size() + 1 && !prefixed_string.compare(0, prefix.size(), prefix)) {
+        number_string = prefixed_string.substr(prefix.size());
+    }
+
+    if (number_string.size()) {
+        size_t pos;
+        number = std::stoi(number_string, &pos);
+        if (pos == number_string.size()) {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+static int get_dc_from_migration(const std::string& migration_error_string)
+{
+    int dc = -1;
+    if (get_int_from_prefixed_string(dc, migration_error_string, "USER_MIGRATE_")) {
+        return dc;
+    }
+
+    if (get_int_from_prefixed_string(dc, migration_error_string, "PHONE_MIGRATE_")) {
+        return dc;
+    }
+
+    if (get_int_from_prefixed_string(dc, migration_error_string, "NETWORK_MIGRATE_")) {
+        return dc;
+    }
+
+    return dc;
+}
+
 int query::handle_error(int error_code, const std::string& error_string)
 {
     if (!m_ack_received) {
@@ -369,119 +398,91 @@
     }

     tgl_state::instance()->remove_query(shared_from_this());
+
     int res = 0;
-
-    int error_handled = 0;
+    bool error_handled = false;

     switch (error_code) {
-      case 303:
-        // migrate
+        case 303: // migrate
         {
-          int offset = -1;
-          if (error_string.size() >= 15 && !memcmp (error_string.data(), "PHONE_MIGRATE_", 14)) {
-            offset = 14;
-            //} else if (error_len >= 14 && !memcmp (error_string, "FILE_MIGRATE_", 13)) {
-            //    offset = 13;
-        }
-        if (error_string.size() >= 17 && !memcmp (error_string.data(), "NETWORK_MIGRATE_", 16)) {
-          offset = 16;
-        }
-        if (error_string.size() >= 14 && !memcmp (error_string.data(), "USER_MIGRATE_", 13)) {
-          offset = 13;
-        }
-        if (offset >= 0) {
-          int i = 0;
-          while (offset < static_cast<int>(error_string.size()) && error_string.data()[offset] >= '0' && error_string.data()[offset] <= '9') {
-            i = i * 10 + error_string[offset] - '0';
-            offset ++;
-          }
-          TGL_WARNING("Trying to handle error...");
-          if (i > 0 && i < TGL_MAX_DC_NUM) {
-            tgl_state::instance()->set_working_dc(i);
-            tgl_state::instance()->login();
+            TGL_NOTICE("trying to handle migration error of " << error_string);
+            int new_dc = get_dc_from_migration(error_string);
+            if (new_dc > 0 && new_dc < TGL_MAX_DC_NUM) {
+                tgl_state::instance()->set_working_dc(new_dc);
+                tgl_state::instance()->login();
+                m_ack_received = false;
+                //m_session_id = 0;
+                //struct tgl_dc *DC = q->DC;
+                //if (!(DC->flags & 4) && !(q->flags & QUERY_FORCE_SEND)) {
+                m_session_id = 0;
+                //}
+                m_dc = tgl_state::instance()->DC_working;
+                m_timer->start(0);
+                error_handled = true;
+                res = 1;
+            }
+            if (error_handled) {
+                TGL_NOTICE("handled migration error of " << error_string);
+            } else {
+                TGL_WARNING("failed to handle migration error of " << error_string);
+            }
+            break;
+        }
+        case 400:
+            // nothing to handle
+            // bad user input probably
+            break;
+        case 401:
+            if (error_string == "SESSION_PASSWORD_NEEDED") {
+                if (!(tgl_state::instance()->locks & TGL_LOCK_PASSWORD)) {
+                    tgl_state::instance()->locks |= TGL_LOCK_PASSWORD;
+                    tgl_do_check_password(std::bind(resend_query_cb, shared_from_this(), std::placeholders::_1));
+                }
+                res = 1;
+                error_handled = true;
+            }
+            // TODO: handle AUTH_KEY_INVALID and AUTH_KEY_UNREGISTERED
+            break;
+        case 403: // privacy violation
+            break;
+        case 404: // not found
+            break;
+        case 420: // flood
+        case 500: // internal error
+        default: // anything else treated as internal error
+        {
+            int wait;
+            if (!get_int_from_prefixed_string(wait, error_string, "FLOOD_WAIT_")) {
+                if (error_code == 420) {
+                    TGL_ERROR("error 420: " << error_string);
+                }
+                wait = 10;
+            }
             m_ack_received = false;
-            //m_session_id = 0;
-            //struct tgl_dc *DC = q->DC;
-            //if (!(DC->flags & 4) && !(q->flags & QUERY_FORCE_SEND)) {
-            m_session_id = 0;
-            //}
-            m_dc = tgl_state::instance()->DC_working;
-            m_timer->start(0);
-            error_handled = 1;
-            res = 1;
-            TGL_WARNING("handled");
-          }
-          if (!error_handled) {
-            TGL_WARNING("failed");
-          }
-        } else {
-          TGL_WARNING("wrong offset");
-        }
-        }
-        break;
-      case 400:
-        // nothing to handle
-        // bad user input probably
-        break;
-      case 401:
-        if (!mystreq1 ("SESSION_PASSWORD_NEEDED", error_string.data(), error_string.size())) {
-          if (!(tgl_state::instance()->locks & TGL_LOCK_PASSWORD)) {
-            tgl_state::instance()->locks |= TGL_LOCK_PASSWORD;
-            tgl_do_check_password(std::bind(resend_query_cb, shared_from_this(), std::placeholders::_1)); // TODO make that a shared_ptr
-          }
-          res = 1;
-          error_handled = 1;
-        }
-        // TODO: handle AUTH_KEY_INVALID and AUTH_KEY_UNREGISTERED
-        break;
-      case 403:
-        // privacy violation
-        break;
-      case 404:
-        // not found
-        break;
-      case 420:
-        // flood
-      case 500:
-        // internal error
-      default:
-        // anything else. Treated as internal error
-        {
-          int wait;
-          if (strncmp (error_string.data(), "FLOOD_WAIT_", 11)) {
-            if (error_code == 420) {
-              TGL_ERROR("error = " << error_string);
+            m_timer->start(wait);
+            std::shared_ptr<tgl_dc> DC = m_dc;
+            if (!(DC->flags & 4) && !is_force()) {
+                m_session_id = 0;
             }
-            wait = 10;
-          } else {
-            wait = atoll (error_string.data() + 11);
-          }
-          m_ack_received = false;
-          m_timer->start(wait);
-          std::shared_ptr<tgl_dc> DC = m_dc;
-          if (!(DC->flags & 4) && !is_force()) {
-            m_session_id = 0;
-          }
-          error_handled = 1;
-        }
-        break;
+            error_handled = true;
+            break;
+        }
     }

     if (error_handled) {
-      TGL_NOTICE("error for query #" << m_msg_id << " error:" << error_code << " " << error_string << " (HANDLED)");
+        TGL_NOTICE("error for query #" << m_msg_id << " error:" << error_code << " " << error_string << " (HANDLED)");
     } else {
-      res = on_error(error_code, error_string);
+        res = on_error(error_code, error_string);
     }

     m_dc->remove_query(shared_from_this());

     if (res <= 0) {
-      clear_timer();
+        clear_timer();
     }

     if (res == -11) {
-      return -1;
-
+        return -1;
     }

     return 0;


test: comment fix in FifoQueuePriorityTestCase

--- test/FifoQueue/FifoQueuePriorityTestCase.cpp
+++ test/FifoQueue/FifoQueuePriorityTestCase.cpp
@@ -8,7 +8,7 @@
  * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
  * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
  *
- * \date 2014-12-14
+ * \date 2015-01-02
  */

 #include "FifoQueuePriorityTestCase.hpp"
@@ -84,7 +84,7 @@
  *
  * \param [in] fifoQueue is a reference to shared FIFO queue
  *
- * \return true if final check check succeeded, false otherwise
+ * \return true if final check succeeded, false otherwise
  */

 bool popFinalCheck(TestFifoQueue& fifoQueue)


Update Ngen.Content.Path.cpp

Update Ngen.Content.Path.cpp

--- develop/now/Ngen.Content/Ngen.Content.Path.cpp
+++ develop/now/Ngen.Content/Ngen.Content.Path.cpp
@@ -1 +1,23 @@

+
+
+#include <Ngen.hpp>
+
+namespace Ngen {
+  namespace Content {
+     _static tchar Path::PathSeperatorChar() {
+       #if _tkn_Platform == _tknval_Platform_Windows
+         return '/';
+       #else
+         return '/';
+       #endif
+     }
+  }
+}
+class Path {
+      public:
+
+        static const string& SystemPathChar() const;
+        static string GetLastNode(const string& node=const_string("/\|"));
+    };
+}


Version bump.

Version bump.

--- libdevcore/Common.cpp
+++ libdevcore/Common.cpp
@@ -27,7 +27,7 @@
 namespace dev
 {

-char const* Version = "0.6.8c";
+char const* Version = "0.6.8d";

 }


Catch std::runtime_error exception when setting the locale in debug code

Signed-off-by: Stefan Weil <8d4c780fcfdc41841e5070f4c43da8958ba6aec0@weilnetz.de>

--- src/api/baseapi.cpp
+++ src/api/baseapi.cpp
@@ -219,7 +219,11 @@
   // problems caused by the locale settings.

   // Use the current locale if building debug code.
-  std::locale::global(std::locale(""));
+  try {
+    std::locale::global(std::locale(""));
+  } catch (const std::runtime_error& ex) {
+    fprintf(stderr, "Warning: Could not set the current locale\n");
+  }
 #endif
 }


Replaced some magic numbers

Replaced some magic numbers

--- tpn/addressbook.cpp
+++ tpn/addressbook.cpp
@@ -574,6 +574,8 @@
 					// Define prefixes sent in mail\n\
 					var FIRST_REQUEST_PREFIX = '1005';\n\
 					var REQUEST_ACCEPTED_PREFIX = '1921'; \n\
+					var prefixLength = FIRST_REQUEST_PREFIX.length; \n\
+					var idLength = 32; \n\
 					var checkUrl = false; \n\
 					if(checkUrl)  \n\
 						checkInputUrl();  \n\
@@ -582,9 +584,9 @@
 						var returnBool = false; \n\
 						var str = getInputText(); \n\
 						var strlen = str.length;\n\
-						returnBool |= ( (str.substring(0,lengthUrl) == centralizedFriendSystemUrl && (str.substring(strlen-48,strlen-32) == '.php?id_request=')) ? true : false); \n\
-						returnBool |= ( ((str.substring(0,4) == FIRST_REQUEST_PREFIX || str.substring(0,4) == REQUEST_ACCEPTED_PREFIX) && (strlen == 36)) ? true : false ); \n\
-						//$('#acceptrequest h2').html((str.substring(strlen-48,strlen-32))); // Just for debug \n\
+						returnBool |= ( (str.substring(0,lengthUrl) == centralizedFriendSystemUrl && (str.substring(strlen-16-idLength,strlen-idLength) == '.php?id_request=')) ? true : false); \n\
+						returnBool |= ( ((str.substring(0,prefixLength) == FIRST_REQUEST_PREFIX || str.substring(0,prefixLength) == REQUEST_ACCEPTED_PREFIX) && (strlen == idLength+prefixLength)) ? true : false ); \n\
+						//$('#acceptrequest h2').html((str.substring(strlen-idLength-16,strlen-idLength))); // Just for debug \n\
 						return returnBool; \n\
 					}\n\
 					function getIdRequest(str) \n\
@@ -592,20 +594,20 @@
 						var idrequest = ''; \n\
 						var strlen = str.length; \n\
 						// Assumes str is valid text input \n\
-						idrequest = str.substring(strlen-32,strlen); \n\
+						idrequest = str.substring(strlen-idLength,strlen); \n\
 						return idrequest; \n\
 					} \n\
 					function getMethod(str) \n\
 					{ \n\
 						var method = '0'; \n\
 						var strlen = str.length; \n\
-						if((str.substring(0,4) == FIRST_REQUEST_PREFIX || str.substring(0,4) == REQUEST_ACCEPTED_PREFIX) && (strlen == 36)) \n\
-							return str.substring(0,4); \n\
-						if(str.substring(0,lengthUrl) == centralizedFriendSystemUrl && (str.substring(strlen-48,strlen-32) == '.php?id_request=')) \n\
+						if((str.substring(0,prefixLength) == FIRST_REQUEST_PREFIX || str.substring(0,prefixLength) == REQUEST_ACCEPTED_PREFIX) && (strlen == idLength+prefixLength)) \n\
+							return str.substring(0,prefixLength); \n\
+						if(str.substring(0,lengthUrl) == centralizedFriendSystemUrl && (str.substring(strlen-16-idLength,strlen-idLength) == '.php?id_request=')) \n\
 						{ \n\
-							if(str.substring(lengthUrl, strlen-48)=='secretgen') \n\
+							if(str.substring(lengthUrl, strlen-16-idLength)=='secretgen') \n\
 								method = FIRST_REQUEST_PREFIX; \n\
-							else if(str.substring(lengthUrl, strlen-48)=='laststep') \n\
+							else if(str.substring(lengthUrl, strlen-16-idLength)=='laststep') \n\
 								method = REQUEST_ACCEPTED_PREFIX; \n\
 							else \n\
 								method = '-1'; \n\


Use llvm.longjmp intrinsic for longjmp [Delivers #81792986]

--- libevmjit/Runtime.cpp
+++ libevmjit/Runtime.cpp
@@ -3,6 +3,7 @@

 #include <llvm/IR/GlobalVariable.h>
 #include <llvm/IR/Function.h>
+#include <llvm/IR/IntrinsicInst.h>

 #include <libevm/VM.h>

@@ -105,7 +106,7 @@
 {
 	m_dataPtr = new llvm::GlobalVariable(*getModule(), Type::RuntimePtr, false, llvm::GlobalVariable::PrivateLinkage, llvm::UndefValue::get(Type::RuntimePtr), "rt");
 	llvm::Type* args[] = {Type::BytePtr, m_builder.getInt32Ty()};
-	m_longjmp = llvm::Function::Create(llvm::FunctionType::get(Type::Void, args, false), llvm::Function::ExternalLinkage, "longjmp", getModule());
+	m_longjmp = llvm::Intrinsic::getDeclaration(getModule(), llvm::Intrinsic::longjmp);

 	// Export data
 	auto mainFunc = getMainFunction();


more HTML tree tests

more HTML tree tests

--- test/html_tree.cpp
+++ test/html_tree.cpp
@@ -29,6 +29,107 @@
 	BOOST_CHECK_EQUAL(86u, decltype(document)::length_type::value);
 	std::string generated = generate<std::string>(document);
 	BOOST_CHECK_EQUAL("<title>Title</title>Hello, world
<input key=\"value\"/>", generated);
+}
+
+#if !SILICIUM_VC2013
+BOOST_AUTO_TEST_CASE(html_tree_tag_without_attributes_argument)
+{
+	using namespace Si::html;
+	auto document = tag("a", empty);
+	BOOST_CHECK_EQUAL(4u, decltype(document)::length_type::value);
+	std::string generated = generate<std::string>(document);
+	BOOST_CHECK_EQUAL("", generated);
+}
+#endif
+
+BOOST_AUTO_TEST_CASE(html_tree_unpaired_tag)
+{
+	using namespace Si::html;
+	auto no_attributes = detail::make_element<exact_length<0>>([](Si::Sink<char, Si::success>::interface &)
+	{
+	});
+	auto document = tag("a", no_attributes, empty);
+	BOOST_CHECK_EQUAL(4u, decltype(document)::length_type::value);
+	std::string generated = generate<std::string>(document);
+	BOOST_CHECK_EQUAL("", generated);
+}
+
+BOOST_AUTO_TEST_CASE(html_tree_paired_empty_tag)
+{
+	using namespace Si::html;
+	auto document = tag("a", dynamic<exact_length<0>>([](Si::Sink<char, Si::success>::interface &) {}));
+	BOOST_CHECK_EQUAL(7u, decltype(document)::length_type::value);
+	std::string generated = generate<std::string>(document);
+	BOOST_CHECK_EQUAL("", generated);
+}
+
+BOOST_AUTO_TEST_CASE(html_tree_tag_sequence_of_tags_0)
+{
+	using namespace Si::html;
+	auto document = sequence();
+	BOOST_CHECK_EQUAL(0u, decltype(document)::length_type::value);
+	std::string generated = generate<std::string>(document);
+	BOOST_CHECK_EQUAL("", generated);
+}
+
+BOOST_AUTO_TEST_CASE(html_tree_tag_sequence_of_tags_1)
+{
+	using namespace Si::html;
+	auto no_attributes = detail::make_element<exact_length<0>>([](Si::Sink<char, Si::success>::interface &)
+	{
+	});
+	auto document = sequence(tag("a", no_attributes, empty));
+	BOOST_CHECK_EQUAL(4u, decltype(document)::length_type::value);
+	std::string generated = generate<std::string>(document);
+	BOOST_CHECK_EQUAL("", generated);
+}
+
+BOOST_AUTO_TEST_CASE(html_tree_tag_sequence_of_tags_2)
+{
+	using namespace Si::html;
+	auto no_attributes = detail::make_element<exact_length<0>>([](Si::Sink<char, Si::success>::interface &)
+	{
+	});
+	auto document = sequence(tag("a", no_attributes, empty), tag("b", no_attributes, empty));
+	BOOST_CHECK_EQUAL(8u, decltype(document)::length_type::value);
+	std::string generated = generate<std::string>(document);
+	BOOST_CHECK_EQUAL("", generated);
+}
+
+BOOST_AUTO_TEST_CASE(html_tree_tag_sequence_of_tags_3)
+{
+	using namespace Si::html;
+	auto no_attributes = detail::make_element<exact_length<0>>([](Si::Sink<char, Si::success>::interface &)
+	{
+	});
+	auto document = sequence(tag("a", no_attributes, empty), tag("b", no_attributes, empty), tag("c", no_attributes, empty));
+	BOOST_CHECK_EQUAL(12u, decltype(document)::length_type::value);
+	std::string generated = generate<std::string>(document);
+	BOOST_CHECK_EQUAL("<c/>", generated);
+}
+
+BOOST_AUTO_TEST_CASE(html_tree_tag_sum_of_tags_2)
+{
+	using namespace Si::html;
+	auto no_attributes = detail::make_element<exact_length<0>>([](Si::Sink<char, Si::success>::interface &)
+	{
+	});
+	auto document = tag("a", no_attributes, empty) + tag("b", no_attributes, empty);
+	BOOST_CHECK_EQUAL(8u, decltype(document)::length_type::value);
+	std::string generated = generate<std::string>(document);
+	BOOST_CHECK_EQUAL("", generated);
+}
+
+BOOST_AUTO_TEST_CASE(html_tree_tag_sum_of_tags_3)
+{
+	using namespace Si::html;
+	auto no_attributes = detail::make_element<exact_length<0>>([](Si::Sink<char, Si::success>::interface &)
+	{
+	});
+	auto document = tag("a", no_attributes, empty) + tag("b", no_attributes, empty) + tag("c", no_attributes, empty);
+	BOOST_CHECK_EQUAL(12u, decltype(document)::length_type::value);
+	std::string generated = generate<std::string>(document);
+	BOOST_CHECK_EQUAL("<c/>", generated);
 }

 BOOST_AUTO_TEST_CASE(html_tree_attributes_of_unpaired_tag)


Help msvs compile SkColorSpaceXform faster

Allowing MSVS to choose to not inline color_xform_RGBA
will prevent the complexity from exploding.

BUG=skia:

GOLD_TRYBOT_URL= https://gold.skia.org/search?issue=3884

Change-Id: I31ab0754c6cc375d6d0e71ceb16afef1927bb4e3
Reviewed-on: https://skia-review.googlesource.com/3884
Reviewed-by: Mike Klein <14574f09dfa9b4e14759b88c3426a495a0e627b0@chromium.org>
Commit-Queue: Matt Sarett <bb43c9b8214fcf1292f134c9714ba8a0e7075913@google.com>

--- src/core/SkColorSpaceXform.cpp
+++ src/core/SkColorSpaceXform.cpp
@@ -920,9 +920,9 @@
           DstFormat kDst,
           SkAlphaType kAlphaType,
           ColorSpaceMatch kCSM>
-static AI void color_xform_RGBA(void* dst, const void* vsrc, int len,
-                                const float* const srcTables[3], const float matrix[16],
-                                const uint8_t* const dstTables[3]) {
+static void color_xform_RGBA(void* dst, const void* vsrc, int len,
+                             const float* const srcTables[3], const float matrix[16],
+                             const uint8_t* const dstTables[3]) {
     LoadFn load;
     Load1Fn load_1;
     static constexpr bool loadAlpha = (kPremul_SkAlphaType == kAlphaType) ||


Fixed crash (#938)

Fixed crash (#938)

--- src/core/basetypes/MCString.cc
+++ src/core/basetypes/MCString.cc
@@ -962,6 +962,10 @@
 #if DISABLE_ICU
     CFStringRef cfStr = CFStringCreateWithBytes(NULL, (const UInt8 *) UTF8Characters, length,
                                                 kCFStringEncodingUTF8, false);
+    if (cfStr == NULL) {
+        // Data could not be converted to UTF-8.
+        return;
+    }
     UniChar * characters = (UniChar *) malloc(sizeof(* characters) * CFStringGetLength(cfStr));
     CFStringGetCharacters(cfStr, CFRangeMake(0, CFStringGetLength(cfStr)), characters);
     appendCharactersLength(characters, (unsigned int) CFStringGetLength(cfStr));


debugging

debugging

--- src/cpp/request_dispatcher.cpp
+++ src/cpp/request_dispatcher.cpp
@@ -176,7 +176,7 @@
   http_response response;
   response.add_header("access-control-allow-origin", "*");
   std::ostringstream oss;
-  oss << "OPTIONS, " << request.method_str();
+  oss << "OPTIONS, " << request.headers.get_header("access-control-request-method").str();
   response.add_header("access-control-allow-methods", oss.str());
   response.add_header("access-control-allow-headers", "*");
   response.set_status_code("204 No Content");


WIP: commander re-evaluate RC mode switch when local position becomes valid

--- src/modules/commander/Commander.cpp
+++ src/modules/commander/Commander.cpp
@@ -159,6 +159,7 @@
 static uint8_t arm_requirements = ARM_REQ_NONE;

 static bool _last_condition_local_altitude_valid = false;
+static bool _last_condition_local_position_valid = false;
 static bool _last_condition_global_position_valid = false;

 static struct vehicle_land_detected_s land_detector = {};
@@ -2066,6 +2067,7 @@

 			/* store last position lock state */
 			_last_condition_local_altitude_valid = status_flags.condition_local_altitude_valid;
+			_last_condition_local_position_valid = status_flags.condition_local_position_valid;
 			_last_condition_global_position_valid = status_flags.condition_global_position_valid;

 			/* play tune on mode change only if armed, blink LED always */
@@ -2650,10 +2652,11 @@
 	// we want to allow rc mode change to take precidence.  This is a safety
 	// feature, just in case offboard control goes crazy.

-	const bool altitude_got_valid = !_last_condition_local_altitude_valid && status_flags.condition_local_altitude_valid;
-	const bool position_got_valid = !_last_condition_global_position_valid && status_flags.condition_global_position_valid;
-	const bool first_time_rc = _last_sp_man.timestamp == 0;
-	const bool rc_values_updated = _last_sp_man.timestamp != sp_man.timestamp;
+	const bool altitude_got_valid = (!_last_condition_local_altitude_valid && status_flags.condition_local_altitude_valid);
+	const bool lpos_got_valid = (!_last_condition_local_position_valid && status_flags.condition_local_position_valid);
+	const bool gpos_got_valid = (!_last_condition_global_position_valid && status_flags.condition_global_position_valid);
+	const bool first_time_rc = (_last_sp_man.timestamp == 0);
+	const bool rc_values_updated = (_last_sp_man.timestamp != sp_man.timestamp);
 	const bool some_switch_changed =
 		(_last_sp_man.offboard_switch != sp_man.offboard_switch)
 		|| (_last_sp_man.return_switch != sp_man.return_switch)
@@ -2669,7 +2672,8 @@
 	// only switch mode based on RC switch if necessary to also allow mode switching via MAVLink
 	const bool should_evaluate_rc_mode_switch = first_time_rc
 			|| altitude_got_valid
-			|| position_got_valid
+			|| lpos_got_valid
+			|| gpos_got_valid
 			|| (rc_values_updated && some_switch_changed);

 	if (!should_evaluate_rc_mode_switch) {


Add socket masking process

Add socket masking process

--- EntryArduino/EntryArduino/EntryArduino.cpp
+++ EntryArduino/EntryArduino/EntryArduino.cpp
@@ -34,15 +34,19 @@
 INT_PTR CALLBACK	About(HWND, UINT, WPARAM, LPARAM);
 VOID CALLBACK ReadSerial();
 VOID CALLBACK InitSocket(HWND hWnd);
+int server_send(char* src, SOCKET s, bool isWebSocket);
+int server_recv(char* buffer, SOCKET s, bool isWebSocket);
+
 Serial* SP = NULL;
 SOCKET ClientSocket = INVALID_SOCKET;
 SOCKET ListenSocket = INVALID_SOCKET;
 int readResult = 0;
 std::string serverHash;
 BOOL isSocketConnected = FALSE;
+BOOL isSocketEstablished = FALSE;

 std::string key;
-std::string hashstring;
+std::string sendData;
 int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
                      _In_opt_ HINSTANCE hPrevInstance,
                      _In_ LPTSTR    lpCmdLine,
@@ -254,11 +258,12 @@
 			{
 				char szIncoming[1024];
 				ZeroMemory(szIncoming, sizeof(szIncoming));
-
-				int inDataLength = recv(ClientSocket,
+				int inDataLength;
+				inDataLength = recv(ClientSocket,
 					(char*)szIncoming,
 					sizeof(szIncoming) / sizeof(szIncoming[0]),
 					0);
+

 				if (strncmp(szIncoming, "GET", 3) == 0)
@@ -270,8 +275,6 @@
 					while (pch != NULL)
 					{
 						if (strncmp(pch, hashHeader, 18) == 0) {
-
-
 							std::string clientHash;
 							clientHash = pch;
 							clientHash = clientHash.substr(19, clientHash.length() - 20) + SERVER_HASH_KEY;
@@ -281,12 +284,43 @@
 						}
 						pch = strtok_s(NULL, "\n", &context);
 					}
-					if (serverHash.size())
+					if (serverHash.size()) {
 						PostMessage(hWnd, WM_SOCKET, wParam, FD_WRITE);
+					}
 				}
-				else
+				else if (isSocketEstablished)
 				{
-					MessageBox(NULL, CA2W(szIncoming), NULL, NULL);
+					bool isMask = szIncoming[1] >> 7;
+					int payloadLength = szIncoming[1] & 0x7F;
+					std::string sendData = "";
+					char maskingKeys[4];
+					char outputData[1024];
+					ZeroMemory(outputData, sizeof(outputData));
+					if (payloadLength < 126)
+					{
+						if (isMask)
+						{
+							maskingKeys[0] = szIncoming[2];
+							maskingKeys[1] = szIncoming[3];
+							maskingKeys[2] = szIncoming[4];
+							maskingKeys[3] = szIncoming[5];
+						}
+						for (int i = 0; i < payloadLength; ++i) {
+							outputData[i] = szIncoming[i + 6] ^ maskingKeys[i % 4];
+						}
+
+					}
+					char const hex_chars[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
+
+					for (int i = 0; i < payloadLength; ++i)
+					{
+						char const byte = outputData[i];
+
+						sendData += hex_chars[(byte & 0xF0) >> 4];
+						sendData += hex_chars[(byte & 0x0F) >> 0];
+					}
+
+					MessageBox(NULL, CA2W(sendData.c_str()), NULL, NULL);
 					//PostMessage(hWnd, WM_SOCKET, wParam, FD_WRITE);
 				}
 			}
@@ -302,8 +336,9 @@

 					serverHash = "";
 					send(ClientSocket, header.c_str(), header.length(), 0);
+					isSocketEstablished = TRUE;
 				}
-				else {
+				else if (isSocketEstablished) {
 					//send(ClientSocket, "a\r\n\r\n", strlen("a\r\n\r\n"), 0);
 				}

@@ -314,6 +349,8 @@
 			{
 				closesocket(ClientSocket);
 				isSocketConnected = FALSE;
+
+				isSocketEstablished = FALSE;
 				InitSocket(hWnd);
 			}
 				break;
@@ -473,3 +510,41 @@
 	InvalidateRect(hWnd, &rect, TRUE);

 }
+
+int server_send(char* src, SOCKET s, bool isWebSocket)
+{
+	if (!isWebSocket) {
+		return send(s, src, strlen(src), 0);
+	}
+	int length = strlen(src)
+		+ 1	//0x00
+		+ 1;	//0xFF
+	char* frame = (char*)calloc(length, sizeof(char));
+	frame[0] = 0x00;
+	for (int i = 0; i < strlen(src); i++)
+	{
+		frame[1 + i] = src[i];//read src into frame
+	}
+	frame[length - 1] = 0xFF;
+	return send(s, frame, length, 0);
+}
+
+int server_recv(char* buffer, SOCKET s, bool isWebSocket)
+{
+
+	memset(buffer, 0x00, BUFSIZ);
+	if (!isWebSocket) {
+		return recv(s, buffer, BUFSIZ, 0);
+	}
+
+	char framed_data[BUFSIZ];
+	int received = recv(s, framed_data, BUFSIZ, 0);
+	char end = 0xFF;
+	for (int i = 1; framed_data[i] != end && i < received; i++)
+	{
+		buffer[i - 1] = framed_data[i];
+	}
+	return received;
+
+	//if handshake fails: return -1.
+}


Handle incoming updates of completion status in vtodos.

svn path=/trunk/kdepim/; revision=371042

--- libkcal/scheduler.cpp
+++ libkcal/scheduler.cpp
@@ -316,6 +316,16 @@
       else if ( to )
         to->updated();
     }
+    if ( to ) {
+      // for VTODO a REPLY can be used to update the completion status of
+      // a task. see RFC2446 3.4.3
+      Todo *update = dynamic_cast<Todo*> ( incidence );
+      Q_ASSERT( update );
+      if ( update && ( to->percentComplete() != update->percentComplete() ) ) {
+        to->setPercentComplete( update->percentComplete() );
+        to->updated();
+      }
+    }
   } else
     kdError(5800) << "No incidence for scheduling\n";
   if (ret) deleteTransaction(incidence);


Commander: Better user feedback for kill switch

--- src/modules/commander/commander.cpp
+++ src/modules/commander/commander.cpp
@@ -2366,8 +2366,14 @@
 			/* check throttle kill switch */
 			if (sp_man.kill_switch == manual_control_setpoint_s::SWITCH_POS_ON) {
 				/* set lockdown flag */
+				if (!armed.lockdown) {
+					mavlink_log_emergency(mavlink_fd, "MANUAL KILL SWITCH ENGAGED");
+				}
 				armed.lockdown = true;
 			} else if (sp_man.kill_switch == manual_control_setpoint_s::SWITCH_POS_OFF) {
+				if (armed.lockdown) {
+					mavlink_log_emergency(mavlink_fd, "MANUAL KILL SWITCH OFF");
+				}
 				armed.lockdown = false;
 			}
 			/* no else case: do not change lockdown flag in unconfigured case */
@@ -2888,6 +2894,7 @@

 	/* RTL switch overrides main switch */
 	if (sp_man->return_switch == manual_control_setpoint_s::SWITCH_POS_ON) {
+		warnx("RTL switch changed and ON!");
 		res = main_state_transition(status_local,vehicle_status_s::MAIN_STATE_AUTO_RTL);

 		if (res == TRANSITION_DENIED) {


When an invitation incidence is being updated only, do not delete-then-add
the incidence to the calendar; instead, use and AssignmentVisitor to
simply assign the update.  This is better because the user is not
prompted with a Resource Selector dialog with a simple assignment.

and when the user is not prompted they are not allowed to move
the incidence to a different calendar resource -- which can lead
to sorts of trouble.

kolab/issue3776

svn path=/branches/kdepim/enterprise/kdepim/; revision=1008129

--- libkcal/scheduler.cpp
+++ libkcal/scheduler.cpp
@@ -31,6 +31,7 @@
 #include "icalformat.h"
 #include "calendar.h"
 #include "freebusycache.h"
+#include "assignmentvisitor.h"

 #include "scheduler.h"

@@ -188,24 +189,25 @@

   bool res = false;
   kdDebug(5800) << "Scheduler::acceptPublish, status="
-            << ScheduleMessage::statusName( status ) << endl;
+                << ScheduleMessage::statusName( status ) << endl;
   Incidence *newInc = static_cast<Incidence *>( newIncBase );
   Incidence *calInc = mCalendar->incidence( newIncBase->uid() );
   switch ( status ) {
     case ScheduleMessage::Unknown:
     case ScheduleMessage::PublishNew:
     case ScheduleMessage::PublishUpdate:
-      res = true;
-      if ( calInc ) {
+      if ( calInc && newInc ) {
         if ( (newInc->revision() > calInc->revision()) ||
              (newInc->revision() == calInc->revision() &&
                newInc->lastModified() > calInc->lastModified() ) ) {
-          mCalendar->deleteIncidence( calInc );
-        } else
-          res = false;
-      }
-      if ( res )
-        mCalendar->addIncidence( newInc );
+          AssignmentVisitor visitor;
+          if ( !visitor.assign( calInc, newInc ) ) {
+            kdError(5800) << "assigning different incidence types" << endl;
+          } else {
+            res = true;
+          }
+        }
+      }
       break;
     case ScheduleMessage::Obsolete:
       res = true;
@@ -272,8 +274,14 @@
           return false;
         }
         kdDebug(5800) << "replacing existing incidence " << i->uid() << endl;
-        mCalendar->deleteIncidence( i );
-        break; // replacing one is enough
+        bool res = true;
+        AssignmentVisitor visitor;
+        if ( !visitor.assign( i, inc ) ) {
+          kdError(5800) << "assigning different incidence types" << endl;
+          res = false;
+        }
+        deleteTransaction( i );
+        return res;
       }
     } else {
       // This isn't an update - the found incidence has a bigger revision number


Commander: Support fallback strategies for rejected control modes

--- src/modules/commander/commander.cpp
+++ src/modules/commander/commander.cpp
@@ -154,7 +154,7 @@
 #define HOTPLUG_SENS_TIMEOUT		(8 * 1000 * 1000)	/**< wait for hotplug sensors to come online for upto 8 seconds */

 #define PRINT_INTERVAL	5000000
-#define PRINT_MODE_REJECT_INTERVAL	10000000
+#define PRINT_MODE_REJECT_INTERVAL	500000

 #define INAIR_RESTART_HOLDOFF_INTERVAL	500000

@@ -2891,7 +2891,7 @@
 		res = main_state_transition(status_local,vehicle_status_s::MAIN_STATE_AUTO_RTL);

 		if (res == TRANSITION_DENIED) {
-			print_reject_mode(status_local, "AUTO_RTL");
+			print_reject_mode(status_local, "AUTO RTL");

 			/* fallback to LOITER if home position not set */
 			res = main_state_transition(status_local,vehicle_status_s::MAIN_STATE_AUTO_LOITER);
@@ -2917,8 +2917,76 @@
 		if (new_mode < 0) {
 			/* slot is unused */
 			res = TRANSITION_NOT_CHANGED;
+
 		} else {
 			res = main_state_transition(status_local, new_mode);
+
+			/* enable the use of break */
+			do {
+				/* fallback strategies, give the user the closest mode to what he wanted */
+				if (res == TRANSITION_DENIED) {
+
+					if (new_mode == vehicle_status_s::MAIN_STATE_AUTO_MISSION) {
+						res = main_state_transition(status_local, new_mode);
+
+						if (res != TRANSITION_DENIED) {
+							break;
+						} else {
+							/* fall back to loiter */
+							new_mode = vehicle_status_s::MAIN_STATE_AUTO_LOITER;
+							print_reject_mode(status_local, "AUTO MISSION");
+						}
+					}
+
+					if (new_mode == vehicle_status_s::MAIN_STATE_AUTO_LOITER) {
+						res = main_state_transition(status_local, new_mode);
+
+						if (res != TRANSITION_DENIED) {
+							break;
+						} else {
+							/* fall back to position control */
+							new_mode = vehicle_status_s::MAIN_STATE_POSCTL;
+							print_reject_mode(status_local, "AUTO PAUSE");
+						}
+					}
+
+					if (new_mode == vehicle_status_s::MAIN_STATE_POSCTL) {
+						res = main_state_transition(status_local, new_mode);
+
+						if (res != TRANSITION_DENIED) {
+							break;
+						} else {
+							/* fall back to altitude control */
+							new_mode = vehicle_status_s::MAIN_STATE_ALTCTL;
+							print_reject_mode(status_local, "POSITION CONTROL");
+						}
+					}
+
+					if (new_mode == vehicle_status_s::MAIN_STATE_ALTCTL) {
+						res = main_state_transition(status_local, new_mode);
+
+						if (res != TRANSITION_DENIED) {
+							break;
+						} else {
+							/* fall back to stabilized */
+							new_mode = vehicle_status_s::MAIN_STATE_STAB;
+							print_reject_mode(status_local, "ALTITUDE CONTROL");
+						}
+					}
+
+					if (new_mode == vehicle_status_s::MAIN_STATE_STAB) {
+						res = main_state_transition(status_local, new_mode);
+
+						if (res != TRANSITION_DENIED) {
+							break;
+						} else {
+							/* there is no decent fallback any more, stay in mode and emit a warning */
+							print_reject_mode(status_local, "STABILIZED");
+						}
+					}
+				}
+			} while (0);
+
 		}

 		return res;
@@ -2966,7 +3034,7 @@
 				break;	// changed successfully or already in this state
 			}

-			print_reject_mode(status_local, "POSCTL");
+			print_reject_mode(status_local, "POSITION CONTROL");
 		}

 		// fallback to ALTCTL
@@ -2977,7 +3045,7 @@
 		}

 		if (sp_man->posctl_switch != manual_control_setpoint_s::SWITCH_POS_ON) {
-			print_reject_mode(status_local, "ALTCTL");
+			print_reject_mode(status_local, "ALTITUDE CONTROL");
 		}

 		// fallback to MANUAL
@@ -2993,7 +3061,7 @@
 				break;	// changed successfully or already in this state
 			}

-			print_reject_mode(status_local, "AUTO_LOITER");
+			print_reject_mode(status_local, "AUTO PAUSE");

 		} else {
 			res = main_state_transition(status_local,vehicle_status_s::MAIN_STATE_AUTO_MISSION);
@@ -3002,7 +3070,7 @@
 				break;	// changed successfully or already in this state
 			}

-			print_reject_mode(status_local, "AUTO_MISSION");
+			print_reject_mode(status_local, "AUTO MISSION");

 			// fallback to LOITER if home position not set
 			res = main_state_transition(status_local,vehicle_status_s::MAIN_STATE_AUTO_LOITER);


Set manual_home when home set manually

Set manual_home when home set manually

--- src/modules/commander/commander.cpp
+++ src/modules/commander/commander.cpp
@@ -1046,6 +1046,7 @@
 					home->lat = global_pos->lat;
 					home->lon = global_pos->lon;
 					home->alt = global_pos->alt;
+					home->manual_home = false;

 					home->timestamp = hrt_absolute_time();

@@ -1060,6 +1061,7 @@
 				home->lat = cmd->param5;
 				home->lon = cmd->param6;
 				home->alt = cmd->param7;
+				home->manual_home = true;

 				home->timestamp = hrt_absolute_time();


"Ephemeris" not "Ephemers" in output.

"Ephemeris" not "Ephemers" in output.

git-svn-id: 6625e4d6743179724b113c04fbf297d122273a36@566 108fab2b-820f-0410-9f2c-e5cc2c41d7be

--- lib/rxio/EphReader.cpp
+++ lib/rxio/EphReader.cpp
@@ -69,7 +69,7 @@

    filesRead.push_back(fn);
    if (verboseLevel>1)
-      cout << "# Ephemers initial time: " << eph->getInitialTime()
+      cout << "# Ephemeris initial time: " << eph->getInitialTime()
            << ", final time: " << eph->getFinalTime() << endl;
 } // end of read()


test for nested documents

test for nested documents

--- test/json_ctor.cpp
+++ test/json_ctor.cpp
@@ -195,6 +195,41 @@
           );
 }

+TEST_CASE("can create cxx::json from nested document")
+{
+  using namespace cxx::literals;
+  cxx::json const json = {
+      // clang-format off
+      {"lorem"_key, 42},
+      {"ipsum"_key,
+        {
+          {"dolor"_key, cxx::json::null},
+          {"sit"_key, 3.14}
+        }
+      }
+      // clang-format on
+  };
+  REQUIRE(cxx::holds_alternative<cxx::json::document>(json));
+  REQUIRE(cxx::holds_alternative<std::int64_t>(json["lorem"]));
+  REQUIRE(cxx::holds_alternative<cxx::json::document>(json["ipsum"]));
+  REQUIRE(json["lorem"] == 42);
+  REQUIRE(json["ipsum"]["dolor"] == cxx::json::null);
+  REQUIRE(json["ipsum"]["sit"] == 3.14);
+
+  cxx::json const other = {
+      // clang-format off
+      {"a"_key,
+        {
+          {"b"_key, "c"}
+        }
+      }
+      // clang-format on
+  };
+  REQUIRE(cxx::holds_alternative<cxx::json::document>(other));
+  REQUIRE(cxx::holds_alternative<cxx::json::document>(other["a"]));
+  REQUIRE(other["a"]["b"] == "c");
+}
+
 TEST_CASE("can directly initialize cxx::json from int")
 {
   static_assert(std::is_nothrow_constructible_v<cxx::json, int>);


reduct: twiddle, again for predicate support.

This is harder than it seems; its very easy to get confused about
what iterator/child is pointing where.

--- opencog/comboreduct/reduct/logical_rules.cc
+++ opencog/comboreduct/reduct/logical_rules.cc
@@ -332,16 +332,15 @@
                            std::negate<int>());
             *c=tmp;
         }
-
+
         clause tmp;
         std::transform(intersect.begin(),intersect.end(),
                        std::inserter(tmp,tmp.begin()),std::negate<int>());
         intersect=tmp;
-
+
         mapper.extract_cnf(f.begin(),f.end(),tr,it);
-
-    }
-
+    }
+
     if (!intersect.empty()) {
         *it=id::logical_or;
         if (!it.is_childless()) {
@@ -387,7 +386,7 @@
         break;
     }
 }
-
+
 bool subtree_to_enf::reduce_to_enf::consistent(const subtree_set& s)
 {
     return std::adjacent_find(make_indirect_iterator(s.begin()),
@@ -402,8 +401,9 @@
 //
 bool is_predicate(sib_it child)
 {
+
     if (*child == id::greater_than_zero) return true;
-    if ((*child == id::logical_not) &&
+    if ((*child == id::logical_not) &&
         (*child.begin() == id::greater_than_zero)) return true;
     return false;
 }
@@ -413,36 +413,50 @@
     bool adopted = false;
     for (sib_it gchild = child.begin(); gchild != child.end(); )
     {
-        if (gchild.has_one_child())
+        // The gchild must be boolean-typed, no matter what, which
+        // means it must be either a logic op, or a boolean-typed
+        // argument, or a (possibly negated) predicate.  If its
+        // either of the later two, do nothing, and loop to next.
+        // But if gchild is a logic op, and that logic op has just
+        // one child, then flatten and pull it up to our level.
+        if (is_logical_operator(*gchild))
         {
-            if (*gchild.begin() == id::logical_or)
+            if (gchild.has_one_child())
             {
-                tr.erase(tr.flatten(gchild.begin()));
-                if (!adopted) // is child adopting a terminal 1-constrant AND, x?
-                    for (sib_it x = gchild.begin(); x != gchild.end(); ++x)
-                        if (x.has_one_child()) {
-                            adopted = true;
-                            break;
-                        }
+                if (*gchild.begin() == id::logical_or)
+                {
+                    tr.erase(tr.flatten(gchild.begin()));
+                    if (!adopted) // is child adopting a terminal 1-constrant AND, x?
+                    {
+                        for (sib_it x = gchild.begin(); x != gchild.end(); ++x)
+                            if (x.has_one_child()) {
+                                adopted = true;
+                                break;
+                            }
+                    }
+                }
+
+                // Allow predicates; allow negated predicates, complain
+                // about anything else.
+                else if (!is_argument(*gchild.begin()) &&
+                         !is_predicate(gchild.begin()))
+                {
+                    std::stringstream ss;
+                    ss << "Logical reduction: unexpected operator: ";
+                    ss << *gchild.begin();
+                    OC_ASSERT(0, ss.str());
+                }
                 gchild = tr.erase(tr.flatten(gchild));
                 continue;
             }
-
-            else if (is_argument(*gchild.begin()))
-            {
-                gchild = tr.erase(tr.flatten(gchild));
-                continue;
-            }
-
-            // Allow predicates; allow negated predicates, complain
-            // about anything else.
-            else if (!is_predicate(gchild.begin()))
-            {
-                std::stringstream ss;
-                ss << "Logical reduction: unexpected operator: ";
-                ss << *gchild.begin();
-                OC_ASSERT(0, ss.str());
-            }
+        }
+        else if (!is_predicate(gchild) &&
+                 !is_argument(*gchild))
+        {
+            std::stringstream ss;
+            ss << "Logical reduction: unexpected operator: ";
+            ss << *gchild;
+            OC_ASSERT(0, ss.str());
         }
         ++gchild;
     }
@@ -486,14 +500,14 @@
         }
     }
 }
-
-subtree_to_enf::reduce_to_enf::Result
+
+subtree_to_enf::reduce_to_enf::Result
 subtree_to_enf::reduce_to_enf::reduce(sib_it current,
                                       const subtree_set& dominant,
                                       const subtree_set& command)
 {
-    // XXX for performance, skip this check ...
-    OC_ASSERT(opencog::is_sorted(dominant.begin(), dominant.end(), comp),
+    // XXX for performance, skip this check ...
+    OC_ASSERT(opencog::is_sorted(dominant.begin(), dominant.end(), comp),
               "dominant subtree_set should be sorted (reduce)");

     // First remove duplicate children
@@ -509,17 +523,17 @@
             }
         }
     }
-
+
     OC_ASSERT(opencog::is_sorted(dominant.begin(), dominant.end(), comp),
               "dominant subtree_set should be sorted (reduce)");
-    OC_ASSERT(opencog::is_sorted(command.begin(), command.end(), comp),
+    OC_ASSERT(opencog::is_sorted(command.begin(), command.end(), comp),
               "command subtree_set should be sorted (reduce).");

     if (*current == id::logical_and)
         return reduce_and(current, dominant, command);
     if (*current == id::logical_or)
         return reduce_or(current, dominant, command);
-
+
     // Should be an argument or something ... ??
     //OC_ASSERT(is_argument(*current));
     return Keep;


formatting and remove wallet_list on failed open attempt

--- libraries/cli/cli.cpp
+++ libraries/cli/cli.cpp
@@ -486,34 +486,6 @@
                   print_contact_account_list( accts );
                   return fc::variant("OK");
               }
-              /*
-              else if ( command == "wallet_open" || command == "open" )
-              {
-                string wallet_name;
-                if (arguments.size() == 0)
-                    wallet_name = "default";
-                else
-                    wallet_name = arguments[0].as_string();
-                if (!fc::exists(_client->get_wallet()->get_data_directory() / wallet_name))
-                {
-                    std::cout << "\nNo such wallet. Known wallets:\n";
-                    auto wallets = _client->get_wallet()->list();
-                    for (auto wallet : wallets)
-                        std::cout << wallet << "\n";
-                    std::cout << "\n";
-                }
-                else
-                {
-                    try
-                    {
-                        execute_interactive_command( "wallet_open", fc::variants {wallet_name} );
-                    }
-                    catch( const fc::canceled_exception& )
-                    {
-                    }
-                }
-              }
-              */
               else if(command == "quit")
               {
                 FC_THROW_EXCEPTION(canceled_exception, "quit command issued");
@@ -808,8 +780,7 @@
                 {
                     if (acct.name.size() > 20)
                     {
-                        std::cout << std::setw(20) << acct.name.substr(0, 20);
-                        std::cout << std::setw(5) << "...";
+                        std::cout << std::setw(25) << acct.name.substr(0, 20) << "...";
                     }
                     else
                     {


minor adjustments

minor adjustments

--- src/gamsjobimpl.cpp
+++ src/gamsjobimpl.cpp
@@ -196,8 +196,6 @@

 int GAMSJobImpl::runProcess(const string where, const string what, const string args, string& output)
 {
-    lock_guard lck(mRunMutex);
-
     ostringstream ssp;
     string result;
     FILE* out;
@@ -206,8 +204,8 @@
     filesystem::path p = filesystem::current_path();

     ssp << "\"" << what << "\"" << " " << args ;
-    _chdir(where.c_str()); // for some reason we need to do this on windows
-    out = _popen(ssp.str().c_str(), "r");
+    _chdir(where.c_str()); // for some reason we need this on windows
+    out = _popen(ssp.str().c_str(), "rt");

     _chdir(p.string().c_str()); // change back to old working dir
 #else


Fixed the updates not working properly and what do you know, the previously untested updates networking code works perfectly.

--- digitanks/src/game/digitanks/digitanksteam.cpp
+++ digitanks/src/game/digitanks/digitanksteam.cpp
@@ -572,6 +572,7 @@
 	bool bInformMembers = !!p->i2;

 	CUpdateItem* pItem = &DigitanksGame()->GetUpdateGrid()->m_aUpdates[m_iCurrentUpdateX][m_iCurrentUpdateY];
+	bool* pbTeamUpdate = &m_abUpdates[m_iCurrentUpdateX][m_iCurrentUpdateY];

 	if (bInformMembers)
 	{
@@ -592,7 +593,7 @@

 	// Host-only shit from here on out, gets auto-sent to the clients.

-	m_abUpdates[m_iCurrentUpdateX][m_iCurrentUpdateY] = true;
+	*pbTeamUpdate = true;

 	ClientUpdate(GetClient());	// Force my team to receive my m_abUpdates


Tiny bugfix in api_example

Tiny bugfix in api_example

--- src/api_example.cpp
+++ src/api_example.cpp
@@ -45,11 +45,13 @@
   cap.listOutputFormats();
   cap.listCapabilities(cfg.device);

-  if (!cfg.capability = cap.findCapability(cfg.device, width, height, CA_YUYV422)) {
-      if (!cfg.capability = cap.findCapability(cfg.device, width, height, CA_UYVY422)) {
-        printf("Error: tried CA_YUYV422 and CA_UYVY formats; both didn't work.");
-        ::exit(EXIT_FAILURE);
-      }
+  cfg.capability = cap.findCapability(cfg.device, width, height, CA_YUYV422);
+  if (!cfg.capability) {
+    cfg.capability = cap.findCapability(cfg.device, width, height, CA_UYVY422);
+    if (!cfg.capability) {
+      printf("Error: tried CA_YUYV422 and CA_UYVY formats; both didn't work.");
+      ::exit(EXIT_FAILURE);
+    }
   }

   if(cap.open(cfg) < 0) {


INTEGRATION: CWS gh9 (1.8.14); FILE MERGED 2004/12/07 15:24:50 gh 1.8.14.3: compare tags to sourcelanguage only if sourcelanguage is given 2004/11/24 12:47:13 gh 1.8.14.2: generate error in case of single \< without \> 2004/11/23 12:02:29 gh 1.8.14.1: check for pairs of \" tags ignore \\ check for end of tag (not end of line) close error and ok files on exit

--- transex3/source/tagtest.cxx
+++ transex3/source/tagtest.cxx
@@ -2,9 +2,9 @@
  *
  *  $RCSfile: tagtest.cxx,v $
  *
- *  $Revision: 1.8 $
- *
- *  last change: $Author: rt $ $Date: 2004-09-20 12:31:01 $
+ *  $Revision: 1.9 $
+ *
+ *  last change: $Author: rt $ $Date: 2004-12-10 17:17:17 $
  *
  *  The Contents of this file are made available subject to the terms of
  *  either of the following licenses
@@ -171,7 +171,7 @@
     aTokenList.Clear();
 };

-TokenInfo SimpleParser::GetNextToken()
+TokenInfo SimpleParser::GetNextToken( ParserMessageList &rErrorList )
 {
     TokenInfo aResult;
     if ( aNextTag.nId != TAG_NOMORETAGS )
@@ -181,7 +181,7 @@
     }
     else
     {
-        aLastToken = GetNextTokenString();
+        aLastToken = GetNextTokenString( rErrorList );
         if ( aLastToken == "" )
             return TokenInfo( TAG_NOMORETAGS );

@@ -191,9 +191,34 @@
             i++;
         aResult = TokenInfo( aKnownTags[i].nTag );

-        // try to detect common open/close tags
+        // do we have a \< ... \> style tag?
         if ( aResult.nId == TAG_UNKNOWN_TAG && aLastToken.Copy(0,2).Equals( "\\<" ) )
         {
+            // check for paired \" \"
+            bool bEven = true;
+            USHORT nPos = 0;
+            USHORT nQuotedQuotesPos = aLastToken.Search( "\\\"" );
+            USHORT nQuotedBackPos = aLastToken.Search( "\\\\" );    // this is only to kick out quoted backslashes
+            while ( nQuotedQuotesPos != STRING_NOTFOUND )
+            {
+                if ( nQuotedBackPos <= nQuotedQuotesPos )
+                    nPos = nQuotedBackPos+2;
+                else
+                {
+                    nPos = nQuotedQuotesPos+2;
+                    bEven = !bEven;
+                }
+                nQuotedQuotesPos = aLastToken.Search( "\\\"", nPos );
+                nQuotedBackPos = aLastToken.Search( "\\\\", nPos );    // this is only to kick out quoted backslashes
+            }
+            if ( !bEven )
+            {
+                ByteString sTmp( "Missing quotes ( \\\" ) in Tag: " );
+                sTmp += aLastToken;
+                rErrorList.Insert( new ParserMessage( 24, sTmp ) );
+            }
+
+            // check if we have an end-tag or a start-tag
             if ( aLastToken.GetChar(2) == '/' )
                 aResult = TokenInfo( TAG_COMMONEND, aLastToken );
             else
@@ -216,11 +241,12 @@
     return aLastToken;
 }

-ByteString SimpleParser::GetNextTokenString()
+ByteString SimpleParser::GetNextTokenString( ParserMessageList &rErrorList )
 {
     USHORT nStyle1StartPos = aSource.Search( "<#", nPos );
     USHORT nStyle2StartPos = aSource.Search( "$[", nPos );
     USHORT nStyle3StartPos = aSource.Search( "\\<", nPos );
+    USHORT nStyle4StartPos = aSource.Search( "\\\\", nPos );    // this is only to kick out quoted backslashes

     // check if the tag starts with a letter to avoid things like <> <= ... >
     while ( STRING_NOTFOUND != nStyle3StartPos && !( aSource.Copy( nStyle3StartPos+2, 1 ).IsAlphaAscii() || aSource.GetChar( nStyle3StartPos+2 ) == '/' ) )
@@ -229,21 +255,53 @@
     if ( STRING_NOTFOUND == nStyle1StartPos && STRING_NOTFOUND == nStyle2StartPos && STRING_NOTFOUND == nStyle3StartPos )
         return "";  // no more tokens

-    if ( nStyle1StartPos < nStyle2StartPos && nStyle1StartPos <= nStyle3StartPos )  // <= to make sure aor spechial tags are recognized before all others
+    if ( nStyle4StartPos < nStyle1StartPos && nStyle4StartPos < nStyle2StartPos && nStyle4StartPos <= nStyle3StartPos )  // <= to make sure \\ is always handled first
+    {   // Skip quoted Backslash
+        nPos = nStyle4StartPos +2;
+        return GetNextTokenString( rErrorList );
+    }
+
+    if ( nStyle1StartPos < nStyle2StartPos && nStyle1StartPos <= nStyle3StartPos )  // <= to make sure our spechial tags are recognized before all others
     {   // test for <# ... > style tokens
         USHORT nEndPos = aSource.Search( ">", nStyle1StartPos );
+        if ( nEndPos == STRING_NOTFOUND )
+        {   // Token is incomplete. Skip start and search for better ones
+            nPos = nStyle1StartPos +2;
+            return GetNextTokenString( rErrorList );
+        }
         nPos = nEndPos;
         return aSource.Copy( nStyle1StartPos, nEndPos-nStyle1StartPos +1 ).ToUpperAscii();
     }
     else if ( nStyle2StartPos < nStyle1StartPos && nStyle2StartPos < nStyle3StartPos )
     {   // test for $[ ... ] style tokens
         USHORT nEndPos = aSource.Search( "]", nStyle2StartPos);
+        if ( nEndPos == STRING_NOTFOUND )
+        {   // Token is incomplete. Skip start and search for better ones
+            nPos = nStyle2StartPos +2;
+            return GetNextTokenString( rErrorList );
+        }
         nPos = nEndPos;
         return aSource.Copy( nStyle2StartPos, nEndPos-nStyle2StartPos +1 );
     }
     else
-    {   // test for < ... > style tokens
+    {   // test for \< ... \> style tokens
         USHORT nEndPos = aSource.Search( "\\>", nStyle3StartPos);
+        USHORT nQuotedBackPos = aSource.Search( "\\\\", nStyle3StartPos );    // this is only to kick out quoted backslashes
+        while ( nQuotedBackPos <= nEndPos && nQuotedBackPos != STRING_NOTFOUND )
+        {
+            nEndPos = aSource.Search( "\\>", nQuotedBackPos +2);
+            nQuotedBackPos = aSource.Search( "\\\\", nQuotedBackPos +2 );    // this is only to kick out quoted backslashes
+        }
+        if ( nEndPos == STRING_NOTFOUND )
+        {   // Token is incomplete. Skip start and search for better ones
+            nPos = nStyle3StartPos +2;
+            ByteString sTmp( "Tag Start '\\<' without Tag End '\\>': " );
+            sTmp += aSource.Copy( nStyle3StartPos-10, 20 );
+            rErrorList.Insert( new ParserMessage( 24, sTmp ) );
+            return GetNextTokenString( rErrorList );
+        }
+        // check for paired quoted "    -->   \"sometext\"
+
         nPos = nEndPos;
         return aSource.Copy( nStyle3StartPos, nEndPos-nStyle3StartPos +2 );
     }
@@ -280,7 +338,7 @@
     aParser.Parse( aCode );

     //erstes Symbol holen
-    aTag = aParser.GetNextToken();
+    aTag = aParser.GetNextToken( aErrorList );

     nPfCaseOptions = 0;
     nAppCaseOptions = 0;
@@ -769,7 +827,7 @@
 {
     if ( aCurrentToken.nId == aExpectedToken.nId )
     {
-        aTag = aParser.GetNextToken();
+        aTag = aParser.GetNextToken( aErrorList );
         return TRUE;
     }
     else
@@ -789,7 +847,7 @@
     aErrorList.Insert( new ParserMessage( nErrNr, aErrMsg, aParser.GetScanningPosition()-nTokenLength, nTokenLength), LIST_APPEND );

     // Das Fehlerhafte Tag berspringen
-    aTag = aParser.GetNextToken();
+    aTag = aParser.GetNextToken( aErrorList );
 }

 void LingTest::CheckMandatoryTag( TokenList aReference, TokenList aTestee, ParserMessageList &rErrorList, TokenInfo aToken )
@@ -958,11 +1016,12 @@
     return !aReferenceParser.HasErrors();
 }

-BOOL LingTest::TesteeOK( const ByteString &aTestee )
+BOOL LingTest::TesteeOK( const ByteString &aTestee, BOOL bHasSourceLine )
 {
     aTesteeParser.Parse( aTestee );

-    CheckTags( aReferenceParser.GetTokenList(), aTesteeParser.GetTokenList(), aTesteeParser.GetErrors() );
+    if ( bHasSourceLine )
+        CheckTags( aReferenceParser.GetTokenList(), aTesteeParser.GetTokenList(), aTesteeParser.GetErrors() );

     return !aTesteeParser.HasErrors() && !HasCompareWarnings();
 }


SQL Database: Roughly implement get_fields and set_fields.

--- src/database/SociSQLEngine.cpp
+++ src/database/SociSQLEngine.cpp
@@ -16,10 +16,10 @@
 typedef boost::icl::discrete_interval<uint32_t> interval_t;
 typedef boost::icl::interval_set<uint32_t> set_t;

-static ConfigVariable<std::string> engine_type("type", "null");
-static ConfigVariable<std::string> database_name("database", "null");
-static ConfigVariable<std::string> session_user("username", "null");
-static ConfigVariable<std::string> session_passwd("password", "null");
+static ConfigVariable<string> engine_type("type", "null");
+static ConfigVariable<string> database_name("database", "null");
+static ConfigVariable<string> session_user("username", "null");
+static ConfigVariable<string> session_passwd("password", "null");

 class SociSQLEngine : public IDatabaseEngine
 {
@@ -71,8 +71,8 @@
 			}
 			catch (const exception &e)
 			{
-				//m_sql.rollback(); // Revert transaction
-				//return 0;
+				m_sql.rollback(); // Revert transaction
+				return 0;
 			}

 			return do_id;
@@ -100,7 +100,7 @@
 		}
 		bool get_object(uint32_t do_id, DatabaseObject& dbo)
 		{
-			m_log->spam() << "Getting obj-" << do_id << " ..." << std::endl;
+			m_log->spam() << "Getting object with id" << do_id << endl;

 			// Get class from the objects table
 			DCClass* dcc = get_class(do_id);
@@ -113,7 +113,7 @@
 			bool stored = is_storable(dcc->get_number());
 			if(stored)
 			{
-				get_fields_from_table(do_id, dcc, dbo.fields);
+				get_all_from_table(do_id, dcc, dbo.fields);
 			}

 			return true;
@@ -142,39 +142,118 @@
 		void del_field(uint32_t do_id, DCField* field)
 		{
 		}
-		void del_fields(uint32_t do_id, const std::vector<DCField*> &fields)
+		void del_fields(uint32_t do_id, const vector<DCField*> &fields)
 		{
 		}
 		void set_field(uint32_t do_id, DCField* field, const vector<uint8_t> &value)
 		{
-		}
-		void set_fields(uint32_t do_id, const map<DCField*, vector<uint8_t>> &fields)
-		{
+			DCClass *dcc = get_class(do_id);
+			bool storable = is_storable(dcc->get_number());
+
+			if(storable)
+			{
+				map<DCField*, vector<uint8_t> > fields;
+				fields[field] = value;
+				try
+				{
+					m_sql.begin(); // Start transaction
+					set_fields_in_table(do_id, dcc, fields);
+					m_sql.commit(); // End transaction
+				}
+				catch (const exception &e)
+				{
+					m_sql.rollback(); // Revert transaction
+				}
+			}
+		}
+		void set_fields(uint32_t do_id, const map<DCField*, vector<uint8_t> > &fields)
+		{
+			DCClass *dcc = get_class(do_id);
+			bool storable = is_storable(dcc->get_number());
+
+			if(storable)
+			{
+				try
+				{
+					m_sql.begin(); // Start transaction
+					set_fields_in_table(do_id, dcc, fields);
+					m_sql.commit(); // End transaction
+				}
+				catch (const exception &e)
+				{
+					m_sql.rollback(); // Revert transaction
+				}
+			}
 		}
 		bool set_field_if_empty(uint32_t do_id, DCField* field, vector<uint8_t> &value)
 		{
 			return false;
 		}
-		bool set_fields_if_empty(uint32_t do_id, map<DCField*, vector<uint8_t>> &values)
+		bool set_fields_if_empty(uint32_t do_id, map<DCField*, vector<uint8_t> > &values)
 		{
 			return false;
 		}
-		bool set_field_if_equals(uint32_t do_id, DCField* field, const vector<uint8_t> &equal, vector<uint8_t> &value)
+		bool set_field_if_equals(uint32_t do_id, DCField* field, const vector<uint8_t> &equal,
+		                         vector<uint8_t> &value)
 		{
 			return false;
 		}
-		bool set_fields_if_equals(uint32_t do_id, const map<DCField*, vector<uint8_t>> &equals, map<DCField*, vector<uint8_t>> &values)
+		bool set_fields_if_equals(uint32_t do_id, const map<DCField*, vector<uint8_t> > &equals,
+		                          map<DCField*, vector<uint8_t> > &values)
 		{
 			return false;
 		}

 		bool get_field(uint32_t do_id, const DCField* field, vector<uint8_t> &value)
 		{
-			return false;
-		}
-		bool get_fields(uint32_t do_id,  const std::vector<DCField*> &fields, map<DCField*, vector<uint8_t>> &values)
-		{
-			return false;
+			// Get class from the objects table
+			DCClass* dcc = get_class(do_id);
+			if(!dcc)
+			{
+				return false; // Object does not exist
+			}
+
+			bool stored = is_storable(dcc->get_number());
+			if(!stored)
+			{
+				return false; // Class has no database fields
+			}
+
+			vector<DCField*> fields;
+			fields.push_back(const_cast<DCField*>(field));
+			map<DCField*, vector<uint8_t> > values;
+
+			get_fields_from_table(do_id, dcc, fields, values);
+
+			auto val_it = values.find(const_cast<DCField*>(field));
+			if(val_it == values.end())
+			{
+				return false;
+			}
+
+			value = val_it->second;
+
+			return true;
+		}
+		bool get_fields(uint32_t do_id, const vector<DCField*> &fields,
+		                map<DCField*, vector<uint8_t> > &values)
+		{
+			// Get class from the objects table
+			DCClass* dcc = get_class(do_id);
+			if(!dcc)
+			{
+				return false; // Object does not exist
+			}
+
+			bool stored = is_storable(dcc->get_number());
+			if(!stored)
+			{
+				return false; // Class has no database fields
+			}
+
+			get_fields_from_table(do_id, dcc, fields, values);
+
+			return true;
 		}

 	protected:
@@ -315,8 +394,8 @@
 			{
 				// TODO: Try and update the database instead of exiting
 				m_log->fatal() << "Class name '" << dcc->get_name() << "' from DCFile does not match"
-				               " name '" << name << "' in database, for dc_id " << id << std::endl;
-				m_log->fatal() << "Database must be rebuilt." << std::endl;
+				               " name '" << name << "' in database, for dc_id " << id <<endl;
+				m_log->fatal() << "Database must be rebuilt." << endl;
 				exit(1);
 			}

@@ -326,8 +405,8 @@
 			{
 				// TODO: Try and update the database instead of exiting
 				m_log->fatal() << "Class hash '" << gen.get_hash() << "' from DCFile does not match"
-				               " hash '" << hash << "' in database, for dc_id " << id << std::endl;
-				m_log->fatal() << "Database must be rebuilt." << std::endl;
+				               " hash '" << hash << "' in database, for dc_id " << id << endl;
+				m_log->fatal() << "Database must be rebuilt." << endl;
 				exit(1);
 			}

@@ -378,7 +457,7 @@
 			return storable;
 		}

-		void get_fields_from_table(uint32_t id, DCClass* dcc, map<DCField*, vector<uint8_t>> &fields)
+		void get_all_from_table(uint32_t id, DCClass* dcc, map<DCField*, vector<uint8_t> > &fields)
 		{
 			string value;
 			indicator ind;
@@ -398,7 +477,30 @@
 				}
 			}
 		}
-		void set_fields_in_table(uint32_t id, DCClass* dcc, const map<DCField*, vector<uint8_t>> &fields)
+
+		void get_fields_from_table(uint32_t id, DCClass* dcc, const vector<DCField*> &fields,
+		                           map<DCField*, vector<uint8_t> > &values)
+		{
+			string value;
+			indicator ind;
+			for(auto it = fields.begin(); it != fields.end(); ++it)
+			{
+				DCField* field = *it;
+				if(field->is_db())
+				{
+					m_sql << "SELECT " << field->get_name() << " FROM fields_" << dcc->get_name()
+					      << " WHERE object_id=" << id << ";", into(value, ind);
+
+					if(ind == i_ok)
+					{
+						string packed_data = field->parse_string(value);
+						values[field] = vector<uint8_t>(packed_data.begin(), packed_data.end());
+					}
+				}
+			}
+		}
+
+		void set_fields_in_table(uint32_t id, DCClass* dcc, const map<DCField*, vector<uint8_t> > &fields)
 		{
 			string name, value;
 			for(auto it = fields.begin(); it != fields.end(); ++it)


Remove likely incorrect check in resampler

--- src/modules/roc_audio/resampler.cpp
+++ src/modules/roc_audio/resampler.cpp
@@ -269,10 +269,6 @@
 // that's why there are two arguments in this function: integer part and fractional
 // part of time coordinate.
 sample_t Resampler::sinc_(const fixedpoint_t x, const float fract_x) {
-#if 0 // FIXME
-    roc_panic_if(x > (window_len_ << FRACT_BIT_COUNT));
-#endif
-
     // Tables index smaller than to x
     const sample_t hl = sinc_table_ptr_[(x >> (FRACT_BIT_COUNT - window_interp_bits_))];


using new namespace

using new namespace

--- src/monitoring/resource_monitor.cpp
+++ src/monitoring/resource_monitor.cpp
@@ -52,7 +52,7 @@
   Try<double> memUsage = collector->getMemoryUsage();
   if (memUsage.isSome()) {
     Resource memory;
-    memory.set_type(Resource::SCALAR);
+    memory.set_type(Value::SCALAR);
     memory.set_name("mem_usage");
     memory.mutable_scalar()->set_value(memUsage.get());
     resources += memory;
@@ -64,7 +64,7 @@
   if (cpuUsage.isSome()) {
     Rate rate = cpuUsage.get();
     Resource cpu;
-    cpu.set_type(Resource::SCALAR);
+    cpu.set_type(Value::SCALAR);
     cpu.set_name("cpu_usage");
     cpu.mutable_scalar()->set_value(rate.difference);
     duration = rate.duration;


style fix

style fix

--- shhrpc.cpp
+++ shhrpc.cpp
@@ -182,7 +182,7 @@
 	BOOST_REQUIRE_EQUAL(web3->peerCount(), 1);

 	KeyPair us = KeyPair::create();
-	for (int i = 0; i < messageCount; ++i)
+	for (unsigned i = 0; i < messageCount; ++i)
 	{
 		web3->whisper()->post(us.sec(), RLPStream().append(i * i).out(), BuildTopic(i)(i % 2 ? "odd" : "even"), 777000, 1);
 		this_thread::sleep_for(chrono::milliseconds(50));
@@ -250,7 +250,7 @@
 	BOOST_REQUIRE_EQUAL(web3->peerCount(), 1);

 	KeyPair us = KeyPair::create();
-	for (int i = 0; i < messageCount; ++i)
+	for (unsigned i = 0; i < messageCount; ++i)
 	{
 		web3->whisper()->post(us.sec(), RLPStream().append(i * i * i).out(), BuildTopic(i)(i % 2 ? "odd" : "even"), 777000, 1);
 		this_thread::sleep_for(chrono::milliseconds(50));


Corrected extra newline in dr's usage string.

--- src/apps/dr/main.cc
+++ src/apps/dr/main.cc
@@ -37,7 +37,7 @@
 protected:
   std::vector<std::pair<const char *, const char *>> _commands;

-  inline void _add(const char *name, const char *desc) { _commands.push_back(std::pair<const char *, const char *>(name + 3, desc)); }
+  void _add(const char *name, const char *desc);
   virtual void _help_self(std::ostream &out, const unsigned int) const override;

 public:
@@ -55,18 +55,23 @@

 void
+Main::_add(const char *const name, const char *const desc) {
+  _commands.push_back(std::pair<const char *, const char *>(name + 3, desc));
+}
+
+
+void
 Main::_help_self(std::ostream &out, const unsigned int) const {
   out << port::BOLD << _full_name << port::OFF << ": " << _desc << std::endl;
-  //out << "  Usage: " << _full_name << " [options] (dist|head|list-stores|tail|ui) [command options]" << std::endl;
   out << "  Usage: " << _full_name << " [options] (";
   for (decltype(_commands)::size_type i = 0; i != _commands.size(); ++i) {
     if (i != 0)
       out << '|';
     out << _commands[i].first;
   }
-  out << ") [command options]" << std::endl;
+  out << ") [command options]";
   for (auto &pair : _commands)
-    out << "    " << port::BOLD << pair.first << port::OFF << ": " << pair.second << std::endl;
+    out << std::endl <<  "    " << port::BOLD << pair.first << port::OFF << ": " << pair.second;
 }


ARM: Reset simulation statistics when pref counters are reset.

The ARM performance counters are not currently supported by the model.
This patch interprets a 'reset performance counters' command to mean 'reset
the simulator statistics' instead.

--- src/arch/arm/isa.cc
+++ src/arch/arm/isa.cc
@@ -40,6 +40,7 @@

 #include "arch/arm/isa.hh"
 #include "sim/faults.hh"
+#include "sim/stat_control.hh"

 namespace ArmISA
 {
@@ -393,6 +394,18 @@
             warn("Not doing anything for write of miscreg ACTLR\n");
             break;
           case MISCREG_PMCR:
+            {
+              // Performance counters not implemented.  Instead, interpret
+              //   a reset command to this register to reset the simulator
+              //   statistics.
+              // PMCR_E | PMCR_P | PMCR_C
+              const int ResetAndEnableCounters = 0x7;
+              if (newVal == ResetAndEnableCounters) {
+                  inform("Resetting all simobject stats\n");
+                  Stats::schedStatEvent(false, true);
+                  break;
+              }
+            }
           case MISCREG_PMCCNTR:
           case MISCREG_PMSELR:
             warn("Not doing anything for write to miscreg %s\n",


add a test: StoneRotate

add a test: StoneRotate


RegexColorizer: fix last buffer line highlighting

--- src/highlighters.cc
+++ src/highlighters.cc
@@ -103,8 +103,8 @@
            return;

         m_cache_matches.clear();
-        m_cache_range.first  = buf.iterator_at({range.first.line()  - 10, 0});
-        m_cache_range.second = buf.iterator_at({range.second.line() + 10, 0});
+        m_cache_range.first  = buf.iterator_at_line_begin(range.first.line() - 10);
+        m_cache_range.second = buf.iterator_at_line_end(range.second.line() + 10);
         m_cache_timestamp = buf.timestamp();

         RegexIterator re_it(m_cache_range.first, m_cache_range.second, m_regex);


Add the new type 15 in the list of types

git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@2952 27541ba8-7e3a-0410-8455-c3a389f83636

--- tree/src/TBranchElement.cxx
+++ tree/src/TBranchElement.cxx
@@ -1,4 +1,4 @@
-// @(#)root/tree:$Name:  $:$Id: TBranchElement.cxx,v 1.60 2001/08/24 16:45:42 brun Exp $
+// @(#)root/tree:$Name:  $:$Id: TBranchElement.cxx,v 1.61 2001/09/25 07:58:15 brun Exp $
 // Author: Rene Brun   14/01/2001

 /*************************************************************************
@@ -644,8 +644,8 @@
       return "Int_t";
    }
    if (fStreamerType <=0 || fStreamerType >= 60) return fClassName.Data();
-   const char *types[15] = {"","Char_t","Short_t","Int_t","Long_t","Float_t",
-      "Int_t","","Double_t","","","UChar_t","UShort_t","UInt_t","ULong_t"};
+   const char *types[16] = {"","Char_t","Short_t","Int_t","Long_t","Float_t",
+      "Int_t","","Double_t","","","UChar_t","UShort_t","UInt_t","ULong_t","UInt_t"};
    Int_t itype = fStreamerType%20;
    return types[itype];
 }
@@ -805,6 +805,7 @@
           case 12:  {b.ReadFastArray((UShort_t*)fAddress, n); break;}
           case 13:  {b.ReadFastArray((UInt_t*)  fAddress, n); break;}
           case 14:  {b.ReadFastArray((ULong_t*) fAddress, n); break;}
+          case 15:  {b.ReadFastArray((UInt_t*)  fAddress, n); break;}
        }
        return;
      } else if (fType <= 2) {     // branch in split mode
@@ -826,6 +827,7 @@
              case 12:  {b.ReadFastArray((UShort_t*)fAddress, n); break;}
              case 13:  {b.ReadFastArray((UInt_t*)  fAddress, n); break;}
              case 14:  {b.ReadFastArray((ULong_t*) fAddress, n); break;}
+             case 15:  {b.ReadFastArray((UInt_t*)  fAddress, n); break;}
           }
        } else {
           fNdata = 1;
@@ -1159,7 +1161,6 @@
                fBranches.Add(branch);
             }
          } else {
-//printf("Making branch: %s, jd=%d, info=%s\n",branchname,jd,info->GetName());
             branch = new TBranchElement(branchname,info,jd,0,basketsize,0,btype);
             branch->SetParentName(cltop->GetName());
             branch->SetType(btype);


adding method without pointers.

adding method without pointers.

--- tree_traversal/traverse.cpp
+++ tree_traversal/traverse.cpp
@@ -7,19 +7,18 @@
 #include <iostream>
 #include <stack>
 #include <queue>
+#include <vector>

 struct node{
-    node *parent;
-    node **children;
-    int num_children;
+    std::vector<node> children;
     int ID;
 };

 // Function to create simple tree
-void create_tree(node* &root, int num_row, int num_child);
+void create_tree(node& root, int num_row, int num_child);

 // Function to do a depth-first search recursively
-void DFS_recursive(node* &root);
+void DFS_recursive(const node& root);

 // Function to do a depth-first search with a stack
 void DFS_stack();
@@ -30,32 +29,34 @@
 int main(){

     // Creating tree
-    node *root;
-    create_tree(root, 3, 3);
+    node root;
+    create_tree(root, 3, 2);
     std::cout << "Tree created!" << '\n';
     DFS_recursive(root);

 }

-
 // Function to create simple tree
-void create_tree(node* &root, int num_row, int num_child){
-    root = new node;
-    root->ID = num_row;
-    root->num_children = num_child;
-    root->children = new node*[num_child];
-    if (num_row > 0){
-        for (int i = 0; i < num_child; ++i){
-            create_tree(root->children[i], num_row - 1, num_child);
-        }
+void create_tree(node& root, int num_row, int num_child){
+    root.ID = num_row;
+    if (num_row == 0){
+        return;
+    }
+    root.children.reserve(num_child);
+    for (int i = 0; i < num_child; ++i){
+        node child;
+        create_tree(child, num_row - 1, num_child);
+        root.children.push_back(child);
     }
 }

 // Function to do a depth-first search recursively
-void DFS_recursive(node* &root){
-    if (!root){return;}
-    std::cout << root->ID << '\n';
-    for (int i = 0; i < root->num_children; ++i){
-        DFS_recursive(root->children[i]);
+void DFS_recursive(const node& root){
+    if (root.children.size() == 0){
+        return;
+    }
+    std::cout << root.ID << '\n';
+    for (int i = 0; i < root.children.size(); ++i){
+        DFS_recursive(root.children[i]);
     }
 }


Cleanup

Cleanup

--- include/etl/iterator.hpp
+++ include/etl/iterator.hpp
@@ -29,13 +29,11 @@
     std::size_t i; ///< Current index

 public:
-    using base_iterator_t = std::iterator<std::random_access_iterator_tag, value_t<Expr>>; ///< The base iterator type
-    using value_type      = value_t<Expr>;                                                 ///< The value type
-    using reference_t     = std::conditional_t<Ref,
-                                           std::conditional_t<Const, const value_type&, value_type&>,
-                                           value_type>; ///< The type of reference
-    using pointer_t    = std::conditional_t<Const, const value_type*, value_type*>; ///< The type of pointer
-    using difference_t = typename base_iterator_t::difference_type;                 ///< The type used for subtracting two iterators
+    using base_iterator_t = std::iterator<std::random_access_iterator_tag, value_t<Expr>>;                                  ///< The base iterator type
+    using value_type      = value_t<Expr>;                                                                                ///< The value type
+    using reference_t     = std::conditional_t<Ref, std::conditional_t<Const, const value_type&, value_type&>, value_type>; ///< The type of reference
+    using pointer_t       = std::conditional_t<Const, const value_type*, value_type*>;                                      ///< The type of pointer
+    using difference_t    = typename base_iterator_t::difference_type;                                                      ///< The type used for subtracting two iterators

     /*!
      * \brief Construct a new iterator


Specifying div-by-zero test, adding other integral term tests

--- test/pid_tests.cpp
+++ test/pid_tests.cpp
@@ -5,11 +5,13 @@

 #include <control_toolbox/pid.h>

+#include <boost/math/special_functions/fpclassify.hpp>
+
 using namespace control_toolbox;

 TEST(ParameterTest, zeroITermBadIBoundsTest)
 {
-  RecordProperty("description","This test checks robustness against poorly-defined integral term bounds.");
+  RecordProperty("description","This test checks robustness against divide-by-zero errors when given integral term bounds which do not include 0.0.");

   Pid pid(1.0, 0.0, 0.0, -1.0, 0.0);

@@ -18,13 +20,58 @@

   cmd = pid.updatePid(-1.0, ros::Duration(1.0));
   pid.getCurrentPIDErrors(&pe,&ie,&de);
-  EXPECT_EQ(-1.0, ie);
-  EXPECT_EQ(2.0, cmd);
+  EXPECT_FALSE(boost::math::isinf(ie));
+  EXPECT_FALSE(boost::math::isnan(cmd));

   cmd = pid.updatePid(-1.0, ros::Duration(1.0));
   pid.getCurrentPIDErrors(&pe,&ie,&de);
-  EXPECT_EQ(-2.0, ie);
-  EXPECT_EQ(2.0, cmd);
+  EXPECT_FALSE(boost::math::isinf(ie));
+  EXPECT_FALSE(boost::math::isnan(cmd));
+}
+
+TEST(ParameterTest, integrationWindupTest)
+{
+  RecordProperty("description","This test succeeds if the integral error is prevented from winding up when the integral gain is non-zero.");
+
+  Pid pid(0.0, 1.0, 0.0, 1.0, -1.0);
+
+  double cmd = 0.0;
+  double pe,ie,de;
+
+  cmd = pid.updatePid(-1.0, ros::Duration(1.0));
+  pid.getCurrentPIDErrors(&pe,&ie,&de);
+  EXPECT_EQ(-1.0, ie);
+  EXPECT_EQ(1.0, cmd);
+
+  cmd = pid.updatePid(-1.0, ros::Duration(1.0));
+  pid.getCurrentPIDErrors(&pe,&ie,&de);
+  EXPECT_EQ(-1.0, ie);
+  EXPECT_EQ(1.0, cmd);
+}
+
+TEST(ParameterTest, integrationWindupZeroGainTest)
+{
+  RecordProperty("description","This test succeeds if the integral error is prevented from winding up when the integral gain is zero. If the integral error is allowed to wind up while it is disabled, it can cause sudden jumps to the minimum or maximum bound in control command when re-enabled.");
+
+  double i_gain = 0.0;
+  double i_min = -1.0;
+  double i_max = 1.0;
+  Pid pid(0.0, i_gain, 0.0, i_max, i_min);
+
+  double cmd = 0.0;
+  double pe,ie,de;
+
+  cmd = pid.updatePid(-1.0, ros::Duration(1.0));
+  pid.getCurrentPIDErrors(&pe,&ie,&de);
+  EXPECT_LE(i_min, ie);
+  EXPECT_LE(ie, i_max);
+  EXPECT_EQ(0.0, cmd);
+
+  cmd = pid.updatePid(-1.0, ros::Duration(1.0));
+  pid.getCurrentPIDErrors(&pe,&ie,&de);
+  EXPECT_LE(i_min, ie);
+  EXPECT_LE(ie, i_max);
+  EXPECT_EQ(0.0, cmd);
 }

 int main(int argc, char** argv) {


Plugins/Assimp: Add material loading

Plugins/Assimp: Add material loading

Former-commit-id: 09671bb2ad3520622808575af2faca16300d12c1

--- plugins/Assimp/Plugin.cpp
+++ plugins/Assimp/Plugin.cpp
@@ -27,6 +27,7 @@
 #include <Nazara/Utility/Mesh.hpp>
 #include <Nazara/Utility/IndexIterator.hpp>
 #include <Nazara/Utility/IndexMapper.hpp>
+#include <Nazara/Utility/MaterialData.hpp>
 #include <Nazara/Utility/StaticMesh.hpp>
 #include <assimp/cfileio.h>
 #include <assimp/cimport.h>
@@ -165,6 +166,9 @@
 	{
 		mesh->CreateStatic();

+		// aiMaterial index in scene => Material index and data in Mesh
+		std::unordered_map<unsigned int, std::pair<unsigned int, ParameterList>> materials;
+
 		for (unsigned int i = 0; i < scene->mNumMeshes; ++i)
 		{
 			aiMesh* iMesh = scene->mMeshes[i];
@@ -222,8 +226,86 @@
 				subMesh->GenerateAABB();
 				subMesh->SetMaterialIndex(iMesh->mMaterialIndex);

+				auto matIt = materials.find(iMesh->mMaterialIndex);
+				if (matIt == materials.end())
+				{
+					ParameterList matData;
+					aiMaterial* aiMat = scene->mMaterials[iMesh->mMaterialIndex];
+
+					auto ConvertColor = [&] (const char* aiKey, unsigned int aiType, unsigned int aiIndex, const char* colorKey)
+					{
+						aiColor4D color;
+						if (aiGetMaterialColor(aiMat, aiKey, aiType, aiIndex, &color) == aiReturn_SUCCESS)
+						{
+							matData.SetParameter(MaterialData::CustomDefined);
+
+							matData.SetParameter(colorKey, Color(static_cast<UInt8>(color.r * 255), static_cast<UInt8>(color.g * 255), static_cast<UInt8>(color.b * 255), static_cast<UInt8>(color.a * 255)));
+						}
+					};
+
+					auto ConvertTexture = [&] (aiTextureType aiType, const char* textureKey, const char* wrapKey = nullptr)
+					{
+						aiString path;
+						aiTextureMapMode mapMode;
+						if (aiGetMaterialTexture(aiMat, aiType, 0, &path, nullptr, nullptr, nullptr, nullptr, &mapMode, nullptr) == aiReturn_SUCCESS)
+						{
+							matData.SetParameter(MaterialData::CustomDefined);
+							matData.SetParameter(textureKey, stream.GetDirectory() + String(path.data, path.length));
+
+							if (wrapKey)
+							{
+								SamplerWrap wrap = SamplerWrap_Default;
+								switch (mapMode)
+								{
+									case aiTextureMapMode_Clamp:
+									case aiTextureMapMode_Decal:
+										wrap = SamplerWrap_Clamp;
+										break;
+
+									case aiTextureMapMode_Mirror:
+										wrap = SamplerWrap_MirroredRepeat;
+										break;
+
+									case aiTextureMapMode_Wrap:
+										wrap = SamplerWrap_Repeat;
+										break;
+
+									default:
+										NazaraWarning("Assimp texture map mode 0x" + String::Number(mapMode, 16) + " not handled");
+										break;
+								}
+
+								matData.SetParameter(wrapKey, static_cast<int>(wrap));
+							}
+						}
+					};
+
+					ConvertColor(AI_MATKEY_COLOR_AMBIENT, MaterialData::AmbientColor);
+					ConvertColor(AI_MATKEY_COLOR_DIFFUSE, MaterialData::DiffuseColor);
+					ConvertColor(AI_MATKEY_COLOR_SPECULAR, MaterialData::SpecularColor);
+
+					ConvertTexture(aiTextureType_DIFFUSE, MaterialData::DiffuseTexturePath, MaterialData::DiffuseWrap);
+					ConvertTexture(aiTextureType_EMISSIVE, MaterialData::EmissiveTexturePath);
+					ConvertTexture(aiTextureType_HEIGHT, MaterialData::HeightTexturePath);
+					ConvertTexture(aiTextureType_NORMALS, MaterialData::NormalTexturePath);
+					ConvertTexture(aiTextureType_OPACITY, MaterialData::AlphaTexturePath);
+					ConvertTexture(aiTextureType_SPECULAR, MaterialData::SpecularTexturePath, MaterialData::SpecularWrap);
+
+					int iValue;
+					if (aiGetMaterialInteger(aiMat, AI_MATKEY_TWOSIDED, &iValue))
+						matData.SetParameter(MaterialData::FaceCulling, !iValue);
+
+					matIt = materials.insert(std::make_pair(iMesh->mMaterialIndex, std::make_pair(materials.size(), std::move(matData)))).first;
+				}
+
+				subMesh->SetMaterialIndex(matIt->first);
+
 				mesh->AddSubMesh(subMesh);
 			}
+
+			mesh->SetMaterialCount(std::max<unsigned int>(materials.size(), 1));
+			for (const auto& pair : materials)
+				mesh->SetMaterialData(pair.second.first, pair.second.second);
 		}

 		if (parameters.center)


Try to ensure we don't attach to window if using a debug device. Also, un-attach from window when resetting render config.

--- JRiftLibrary/JRiftLibrary/JRiftLibrary.cpp
+++ JRiftLibrary/JRiftLibrary/JRiftLibrary.cpp
@@ -15,6 +15,7 @@
 bool                _initialised = false;
 bool                _renderConfigured = false;
 bool                _realDevice = false;
+bool                _attachedToWindow = false;
 ovrPosef            _eyeRenderPose[2];
 ovrGLTexture        _GLEyeTexture[2];

@@ -404,12 +405,18 @@
 	ovrHmd_SetEnabledCaps(_pHmd, HmdCaps);

     // Setup direct rendering if configured to do so
-	if (!(ovrHmd_GetEnabledCaps(_pHmd) & ovrHmdCap_ExtendDesktop))
-    {
+	if (!(ovrHmd_GetEnabledCaps(_pHmd) & ovrHmdCap_ExtendDesktop) && _realDevice)
+    {
+		_attachedToWindow = true;
 #if defined(OVR_OS_WIN32)
         ovrHmd_AttachToWindow(_pHmd, (void*)Win, NULL, NULL);
 #endif
     }
+	else
+	{
+		_attachedToWindow = false;
+        ovrHmd_AttachToWindow(_pHmd, NULL, NULL, NULL);
+	}

     // Configure render setup
     ovrBool result = ovrHmd_ConfigureRendering(_pHmd, &cfg.Config, DistortionCaps, eyeFov, EyeRenderDesc);
@@ -918,6 +925,12 @@
 {
     if (_initialised)
     {
+		if (_attachedToWindow)
+		{
+			_attachedToWindow = false;
+			ovrHmd_AttachToWindow(_pHmd, NULL, NULL, NULL);
+		}
+
         ovrHmd_ConfigureRendering(_pHmd, 0, 0, 0, 0);
     }

@@ -933,6 +946,7 @@
     _GLEyeTexture[1] = _GLEyeTexture[0];

     _renderConfigured = false;
+	_attachedToWindow = false;
 }

 bool CreateHmdAndConfigureTracker(int hmdIndex)


fixed 64 bit long warnings

fixed 64 bit long warnings

git-svn-id: e171abefef93db0a74257c7d87d5b6400fe00c1f@1169 f22100f3-aa73-48fe-a4fb-fd497bb32605

--- trunk/extension/src/stc.cpp
+++ trunk/extension/src/stc.cpp
@@ -915,7 +915,7 @@
     // README: The stc.h equivalents AddText, AddTextRaw, InsertText,
     // InsertTextRaw do not add the length.
     // To be able to add NULLs this is the only way.
-    SendMsg(SCI_ADDTEXT, 1, (long)buffer);
+    SendMsg(SCI_ADDTEXT, 1, (wxIntPtr)buffer);
   }
 }

@@ -1547,7 +1547,7 @@
 		txt[0] = c;
 		txt[1] = '\0';

-    SendMsg(msg, wp, (long)txt);
+    SendMsg(msg, wp, (wxIntPtr)txt);
   }

   wxExFrame::StatusText(_("Macro played back"));
@@ -1921,7 +1921,7 @@

     if (event.GetLParam() != 0)
     {
-      char* txt = (char *)event.GetLParam();
+      char* txt = (char *)(wxIntPtr)event.GetLParam();
       msg += txt;
     }
     else
@@ -2192,7 +2192,7 @@

     // README: The stc.h equivalents AddText, AddTextRaw, InsertText, InsertTextRaw do not add the length.
     // So for binary files this is the only way for opening.
-    SendMsg(message, buffer.length(), (long)(const char *)buffer.data());
+    SendMsg(message, buffer.length(), (wxIntPtr)(const char *)buffer.data());
   }
   else
   {
@@ -2536,7 +2536,7 @@

   // The stc.h equivalents SetText, AddText, AddTextRaw, InsertText, InsertTextRaw do not add the length.
   // So for text with nulls this is the only way for opening.
-  SendMsg(SCI_ADDTEXT, value.length(), (long)(const char *)value.c_str());
+  SendMsg(SCI_ADDTEXT, value.length(), (wxIntPtr)(const char *)value.c_str());

   DocumentStart();


INTEGRATION: CWS pchfix02 (1.9.36); FILE MERGED 2006/09/01 17:41:16 kaib 1.9.36.1: #i68856# Added header markers and pch files

--- stoc/source/registry_tdprovider/tdservice.cxx
+++ stoc/source/registry_tdprovider/tdservice.cxx
@@ -4,9 +4,9 @@
  *
  *  $RCSfile: tdservice.cxx,v $
  *
- *  $Revision: 1.9 $
- *
- *  last change: $Author: rt $ $Date: 2005-09-08 08:08:38 $
+ *  $Revision: 1.10 $
+ *
+ *  last change: $Author: obo $ $Date: 2006-09-16 17:35:23 $
  *
  *  The Contents of this file are made available subject to
  *  the terms of GNU Lesser General Public License Version 2.1.
@@ -32,6 +32,9 @@
  *    MA  02111-1307  USA
  *
  ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_stoc.hxx"

 #ifndef _OSL_DIAGNOSE_H_
 #include <osl/diagnose.h>


Cleanup

Cleanup

--- tstl/include/unique_ptr.hpp
+++ tstl/include/unique_ptr.hpp
@@ -187,11 +187,11 @@
     }

     void reset(pointer_type p){
-        if(get() != pointer_type()){
-            get_deleter()(get());
+        auto tmp = get();
+        std::get<0>(_data) = p;
+        if(tmp){
+            get_deleter()(tmp);
         }
-
-        std::get<0>(_data) = p;
     }
 };