Allocate mutex before using it

Allocate mutex before using it

--- dashel/dashel-posix.cpp
+++ dashel/dashel-posix.cpp
@@ -948,6 +948,8 @@
 			abort();
 		hTerminate = terminationPipes;

+		streamsLock = new pthread_mutex_t;
+
 		pthread_mutex_init((pthread_mutex_t*)streamsLock, NULL);

 		// commented because we let the users manage the signal themselves
@@ -966,6 +968,10 @@

 		for (StreamsSet::iterator it = streams.begin(); it != streams.end(); ++it)
 			delete *it;
+
+		pthread_mutex_destroy((pthread_mutex_t*)streamsLock);
+
+		delete (pthread_mutex_t*) streamsLock;
 	}

 	Stream* Hub::connect(const std::string &target)


Add binary search in bit in log(n)

Add binary search in bit in log(n)

--- data-structures/bit.cpp
+++ data-structures/bit.cpp
@@ -10,3 +10,18 @@
   for (p+=2; p; p-=p&-p) r += bit[p];
   return r;
 }
+
+// --- Binary Search in o(log(n)) ---
+const int M = 20
+const int N = 1 << M
+
+int binary_search(int val){ //ans => first greater than x
+  int ans = 0, sum = 0;
+  for(int i = M - 1; i >= 0; i--){
+    int x = ans + (1 << i);
+    if(sum + bit[x] < val)
+      ans = x, sum += bit[x];
+  }
+
+  return ans + 1;
+}


Fixed typo in camera unit tests

Fixed typo in camera unit tests

--- modules/camera/test/o3d3xx-camera-tests.cpp
+++ modules/camera/test/o3d3xx-camera-tests.cpp
@@ -207,10 +207,10 @@
             dev->ExtrinsicCalibTransZ());
   EXPECT_EQ(std::stod(params.at("ExtrinsicCalibRotX")),
             dev->ExtrinsicCalibRotX());
-  EXPECT_EQ(std::stod(params.at("ExtrinsicCalibRotZ")),
+  EXPECT_EQ(std::stod(params.at("ExtrinsicCalibRotY")),
             dev->ExtrinsicCalibRotY());
   EXPECT_EQ(std::stod(params.at("ExtrinsicCalibRotZ")),
-            dev->ExtrinsicCalibRotY());
+            dev->ExtrinsicCalibRotZ());
   EXPECT_EQ(std::stoi(params.at("EvaluationFinishedMinHoldTime")),
             dev->EvaluationFinishedMinHoldTime());
   EXPECT_EQ(o3d3xx::stob(params.at("SaveRestoreStatsOnApplSwitch")),


Set initialize to false when reloading so the browser can redo the initialization process

--- modules/skybrowser/skybrowsermodule_lua.inl
+++ modules/skybrowser/skybrowsermodule_lua.inl
@@ -54,6 +54,7 @@
     if (id != "all") {
         TargetBrowserPair* pair = module->pair(id);
         if (pair) {
+            pair->browser()->setIsInitialized(false);
             pair->browser()->reload();
         }
     }


r2000/sofa-dev : BUGFIX: MechanicalObject::replaceValue, swapValues, renumberValues - check possible NULL pointers and vector ranges. Code like for (i=0;i<vectorsCoord.size();i++) VecCoord& vector = *vectorsCoord[i]; did not work, because vectorsCoord[i] may be NULL.

--- modules/sofa/component/MechanicalObject.inl
+++ modules/sofa/component/MechanicalObject.inl
@@ -226,14 +226,17 @@
 template <class DataTypes>
 void MechanicalObject<DataTypes>::replaceValue (const int inputIndex, const int outputIndex)
 {
+    const int maxIndex = std::max(inputIndex, outputIndex);
+
     // standard state vectors
     // Note that the x,v,f,dx,xfree,vfree and internalForces vectors (but
     // not x0, v0, reset_position, and externalForces) are present in the
     // array of all vectors, so then don't need to be processed separatly.
     //(*x) [outputIndex] = (*x) [inputIndex];
-    (*x0)[outputIndex] = (*x0)[inputIndex];
+    if((*x0).size() > maxIndex)
+        (*x0)[outputIndex] = (*x0)[inputIndex];
     //(*v) [outputIndex] = (*v) [inputIndex];
-    if (v0 != NULL)
+    if (v0 != NULL && (*v0).size() > maxIndex)
         (*v0)[outputIndex] = (*v0)[inputIndex];
     //if ((*f).size()>0)
     //    (*f) [outputIndex] = (*f) [inputIndex];
@@ -242,26 +245,32 @@
     // forces
     //if ((*internalForces).size()>0)
     //    (*internalForces)[outputIndex] = (*internalForces)[inputIndex];
-    if ((*externalForces).size()>0)
+    if ((*externalForces).size() > maxIndex)
         (*externalForces)[outputIndex] = (*externalForces)[inputIndex];

     // Note: the following assumes that topological changes won't be reset
-    if (reset_position != NULL)
+    if (reset_position != NULL && (*reset_position).size() > maxIndex)
         (*reset_position)[outputIndex] = (*reset_position)[inputIndex];

     // temporary state vectors
     unsigned int i;
     for (i=0; i<vectorsCoord.size(); i++)
     {
-        VecCoord& vector = *vectorsCoord[i];
-        if (vector.size()>0)
-            vector[outputIndex]=vector[inputIndex];
+        if(vectorsCoord[i] != NULL)
+        {
+            VecCoord& vector = *vectorsCoord[i];
+            if (vector.size() > maxIndex)
+                vector[outputIndex]=vector[inputIndex];
+        }
     }
     for ( i=0; i<vectorsDeriv.size(); i++)
     {
-        VecDeriv& vector = *vectorsDeriv[i];
-        if (vector.size()>0)
-            vector[outputIndex]=vector[inputIndex];
+        if(vectorsDeriv[i] != NULL)
+        {
+            VecDeriv& vector = *vectorsDeriv[i];
+            if (vector.size() > maxIndex)
+                vector[outputIndex]=vector[inputIndex];
+        }
     }

 }
@@ -269,6 +278,8 @@
 template <class DataTypes>
 void MechanicalObject<DataTypes>::swapValues (const int idx1, const int idx2)
 {
+    const int maxIndex = std::max(idx1, idx2);
+
     // standard state vectors
     // Note that the x,v,f,dx,xfree,vfree and internalForces vectors (but
     // not x0, v0, reset_position, and externalForces) are present in the
@@ -279,18 +290,22 @@
     //(*x) [idx1] = (*x) [idx2];
     //(*x) [idx2] = tmp;

-    tmp = (*x0)[idx1];
-    (*x0)[idx1] = (*x0)[idx2];
-    (*x0)[idx2] = tmp;
-
+    if((*x0).size() > maxIndex)
+    {
+        tmp = (*x0)[idx1];
+        (*x0)[idx1] = (*x0)[idx2];
+        (*x0)[idx2] = tmp;
+    }
     //tmp2 = (*v)[idx1];
     //(*v) [idx1] = (*v) [idx2];
     //(*v) [idx2] = tmp2;

-    tmp2 = (*v0) [idx1];
-    (*v0)[idx1] = (*v0)[idx2];
-    (*v0)[idx2] = tmp2;
-
+    if(v0 != NULL && (*v0).size() > maxIndex)
+    {
+        tmp2 = (*v0) [idx1];
+        (*v0)[idx1] = (*v0)[idx2];
+        (*v0)[idx2] = tmp2;
+    }
     //tmp2 = (*f) [idx1];
     //(*f) [idx1] = (*f)[idx2];
     //(*f) [idx2] = tmp2;
@@ -303,7 +318,7 @@
     //tmp2 = (*internalForces)[idx1];
     //(*internalForces)[idx1] = (*internalForces)[idx2];
     //(*internalForces)[idx2] = tmp2;
-    if (externalForces->size()>0)
+    if ((*externalForces).size() > maxIndex)
     {
         tmp2 = (*externalForces)[idx1];
         (*externalForces)[idx1] = (*externalForces)[idx2];
@@ -311,28 +326,42 @@
     }

     // Note: the following assumes that topological changes won't be reset
-    tmp = (*reset_position)[idx1];
-    (*reset_position)[idx1] = (*reset_position)[idx2];
-    (*reset_position)[idx2] = tmp;
+    if (reset_position != NULL && (*reset_position).size() > maxIndex)
+    {
+        tmp = (*reset_position)[idx1];
+        (*reset_position)[idx1] = (*reset_position)[idx2];
+        (*reset_position)[idx2] = tmp;
+    }

     // temporary state vectors
     unsigned int i;
     for (i=0; i<vectorsCoord.size(); i++)
     {
-        VecCoord& vector = *vectorsCoord[i];
-        tmp = vector[idx1];
-        vector[idx1] = vector[idx2];
-        vector[idx2] = tmp;
-    }
-    for ( i=0; i<vectorsDeriv.size(); i++)
-    {
-        VecDeriv& vector = *vectorsDeriv[i];
-        tmp2 = vector[idx1];
-        vector[idx1] = vector[idx2];
-        vector[idx2] = tmp2;
-    }
-}
-
+        if(vectorsCoord[i] != NULL)
+        {
+            VecCoord& vector = *vectorsCoord[i];
+            if(vector.size() > maxIndex)
+            {
+                tmp = vector[idx1];
+                vector[idx1] = vector[idx2];
+                vector[idx2] = tmp;
+            }
+        }
+    }
+    for (i=0; i<vectorsDeriv.size(); i++)
+    {
+        if(vectorsDeriv[i] != NULL)
+        {
+            VecDeriv& vector = *vectorsDeriv[i];
+            if(vector.size() > maxIndex)
+            {
+                tmp2 = vector[idx1];
+                vector[idx1] = vector[idx2];
+                vector[idx2] = tmp2;
+            }
+        }
+    }
+}

 template <class DataTypes>
@@ -359,13 +388,15 @@
     vecCoord_cp.resize( vectorsCoord.size() );
     for (unsigned int i = 0; i < vectorsCoord.size(); ++i)
     {
-        vecCoord_cp[i] = ( *(vectorsCoord[i]) );
+        if(vectorsCoord[i] != NULL)
+            vecCoord_cp[i] = *(vectorsCoord[i]);
     }
     sofa::helper::vector< VecDeriv > vecDeriv_cp;
     vecDeriv_cp.resize( vectorsDeriv.size() );
     for (unsigned int i = 0; i < vectorsDeriv.size(); ++i)
     {
-        vecDeriv_cp[i] = ( *(vectorsDeriv[i]) );
+        if(vectorsDeriv[i] != NULL)
+            vecDeriv_cp[i] = *(vectorsDeriv[i]);
     }

     for (unsigned int i = 0; i < index.size(); ++i)
@@ -381,11 +412,16 @@
         //(*internalForces)[i] = intern_cp[ index[i] ];

         for (unsigned j = 0; j < vectorsCoord.size(); ++j)
-            (*vectorsCoord[j])[i] = vecCoord_cp[j][ index[i] ];
+        {
+            if(vectorsCoord[j] != NULL)
+                (*vectorsCoord[j])[i] = vecCoord_cp[j][ index[i] ];
+        }

         for (unsigned j = 0; j < vectorsDeriv.size(); ++j)
-            (*vectorsDeriv[j])[i] = vecDeriv_cp[j][ index[i] ];
-
+        {
+            if(vectorsDeriv[j] != NULL)
+                (*vectorsDeriv[j])[i] = vecDeriv_cp[j][ index[i] ];
+        }

     }
     if (externalForces->size()>0)
@@ -831,7 +867,7 @@
     else if (v.type == VecId::V_DERIV)
     {
         for (unsigned int i=v.index; i < vectorsDeriv.size(); ++i)
-            if (vectorsDeriv[i] && ! vectorsDeriv[i]->empty())
+            if (vectorsDeriv[i] != NULL && ! (*vectorsDeriv[i]).empty())
                 v.index = i+1;
     }
 }


Hack around GCC 2.96 having a different prototype and implementation of
std::string::compare() than other compilers.  Grr.

git-svn-id: 769d22dfa2d22aad706b9a451492fb87c0735f19@11125 08b38cba-cd3b-11de-854e-f91c5b6e4272

--- modules/tweek/tweek/Client/CorbaService.cpp
+++ modules/tweek/tweek/Client/CorbaService.cpp
@@ -322,9 +322,25 @@
       if ( CosNaming::ncontext != binding.binding_type )
       {
          const std::string subj_mgr_name("SubjectManager");
-
-         // Furthermore, we only care about SubjectManager instances.
-         if ( subj_mgr_name.compare(0, 14, binding.binding_name[0].id) )
+         bool substr_match(false);
+
+         vprDEBUG(vprDBG_ALL, 0) << "subj_mgr_name.size(): "
+                                 << subj_mgr_name.size() << std::endl
+                                 << vprDEBUG_FLUSH;
+
+#if defined(__GNUC__) && __GNUC__ == 2
+         // XXX: This is a hack to deal with GCC 2.96 (and earlier?) having
+         // a std::string::compare() method that does not match the actual
+         // STL prototype.
+         substr_match = (subj_mgr_name.compare(binding.binding_name[0].id, 0,
+                                               subj_mgr_name.size()) == 0);
+#else
+         substr_match = (subj_mgr_name.compare(0, subj_mgr_name.size(),
+                                               binding.binding_name[0].id));
+#endif
+
+         // Furthermore, we only care about SubjectManager* instances.
+         if ( substr_match )
          {
             CosNaming::Name name_comp = binding.binding_name;


Revert "Set encodedWidth/encodedHeight to actual coded resolution."

This reverts commit 16beea7c90e161ce82764bf046d588e87d38191f.

Reason for revert: breaks internal tests.

Original change's description:
> Set encodedWidth/encodedHeight to actual coded resolution.
>
> This fixes mismatch between resolution of coded frame indicated by VP9
> encoder wrapper and actual coded resolution. If internal resize is
> enabled VP9 encoder might downscale input frame when bitrate is too low
> to keep good spatial quality. Before this fix VP9 wrapper always set
> coded resolution equal to input resolution. Now it sets it to actual
> coded resolution which it reads from frame pkt.
>
> Bug: webrtc:5749
> Change-Id: I7dc8ba89947e99213a3b4c3cd4d974b662f090c4
> Reviewed-on: https://webrtc-review.googlesource.com/39661
> Reviewed-by: Åsa Persson <asapersson@webrtc.org>
> Reviewed-by: Rasmus Brandt <brandtr@webrtc.org>
> Commit-Queue: Sergey Silkin <fc631354f276613a5410ea259cf4618b2846d39b@webrtc.org>
> Cr-Commit-Position: refs/heads/master@{#21651}

TBR=brandtr@webrtc.org,asapersson@webrtc.org,fc631354f276613a5410ea259cf4618b2846d39b@webrtc.org

Change-Id: I32cb1271c863cf435f3fc3b465e11232cbd6a888
No-Presubmit: true
No-Tree-Checks: true
No-Try: true
Bug: webrtc:5749
Reviewed-on: https://webrtc-review.googlesource.com/40161
Reviewed-by: Sergey Silkin <fc631354f276613a5410ea259cf4618b2846d39b@webrtc.org>
Commit-Queue: Sergey Silkin <fc631354f276613a5410ea259cf4618b2846d39b@webrtc.org>
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#21655}

--- modules/video_coding/codecs/vp9/vp9_impl.cc
+++ modules/video_coding/codecs/vp9/vp9_impl.cc
@@ -716,8 +716,8 @@
     encoded_image_.content_type_ = (codec_.mode == kScreensharing)
                                        ? VideoContentType::SCREENSHARE
                                        : VideoContentType::UNSPECIFIED;
-    encoded_image_._encodedHeight = pkt->data.frame.height;
-    encoded_image_._encodedWidth = pkt->data.frame.width;
+    encoded_image_._encodedHeight = raw_->d_h;
+    encoded_image_._encodedWidth = raw_->d_w;
     encoded_image_.timing_.flags = TimingFrameFlags::kInvalid;
     int qp = -1;
     vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);


Provide default pagers

Provide default pagers

Borrowed from systemd.

--- src/libmain/shared.cc
+++ src/libmain/shared.cc
@@ -291,8 +291,9 @@

 RunPager::RunPager()
 {
-    string pager = getEnv("PAGER");
-    if (!isatty(STDOUT_FILENO) || pager.empty()) return;
+    if (!isatty(STDOUT_FILENO)) return;
+    string pager = getEnv("PAGER", "default");
+    if (pager == "" || pager == "cat") return;

     /* Ignore SIGINT. The pager will handle it (and we'll get
        SIGPIPE). */
@@ -312,7 +313,11 @@
             throw SysError("dupping stdin");
         if (!getenv("LESS"))
             setenv("LESS", "FRSXMK", 1);
-        execl("/bin/sh", "sh", "-c", pager.c_str(), NULL);
+        if (pager != "default")
+            execl("/bin/sh", "sh", "-c", pager.c_str(), NULL);
+        execlp("pager", "pager", NULL);
+        execlp("less", "less", NULL);
+        execlp("more", "more", NULL);
         throw SysError(format("executing ‘%1%’") % pager);
     });


Filter build-chroot-dirs entries that conflict with derivation outputs

Fixes https://github.com/NixOS/nixpkgs/issues/9504.

Note that this means we may have a non-functional /bin/sh in the
chroot while rebuilding Bash or one of its dependencies. Ideally those
packages don't rely on /bin/sh though.

--- src/libstore/build.cc
+++ src/libstore/build.cc
@@ -1998,13 +1998,13 @@
             }
         }

-        /* If we're repairing or checking, it's possible that we're
+        /* If we're repairing, checking or rebuilding part of a
+           multiple-outputs derivation, it's possible that we're
            rebuilding a path that is in settings.dirsInChroot
            (typically the dependencies of /bin/sh).  Throw them
            out. */
-        if (buildMode != bmNormal)
-            for (auto & i : drv->outputs)
-                dirsInChroot.erase(i.second.path);
+        for (auto & i : drv->outputs)
+            dirsInChroot.erase(i.second.path);

 #elif SANDBOX_ENABLED
         /* We don't really have any parent prep work to do (yet?)


Barf when using a diverted store on macOS

Fixes #1792.

--- src/libstore/build.cc
+++ src/libstore/build.cc
@@ -1810,8 +1810,13 @@
             useChroot = !fixedOutput && get(drv->env, "__noChroot") != "1";
     }

-    if (worker.store.storeDir != worker.store.realStoreDir)
-        useChroot = true;
+    if (worker.store.storeDir != worker.store.realStoreDir) {
+        #if __linux__
+            useChroot = true;
+        #else
+            throw Error("building using a diverted store is not supported on this platform");
+        #endif
+    }

     /* If `build-users-group' is not empty, then we have to build as
        one of the members of that group. */


BT 2.0 helloworld very close to working correctly now

--- src/bt-helloworld/app-src/HelloWorldApp.cpp
+++ src/bt-helloworld/app-src/HelloWorldApp.cpp
@@ -11,7 +11,8 @@
 #include <batterytech/platform/platformgeneral.h>
 #include <batterytech/Logger.h>
 #include <batterytech/platform/platformgl.h>
-
+#include <batterytech/render/MenuRenderer.h>
+#include <batterytech/render/RenderContext.h>
 #include <string.h>

 Context* btAppCreateContext(GraphicsConfiguration *graphicsConfig) {
@@ -45,6 +46,8 @@
 	glDisable(GL_CULL_FACE);
 	glDisable(GL_DEPTH_TEST);
 	glDisable(GL_DITHER);
+	glEnable(GL_BLEND);
+	glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
 	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
 	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
 	glViewport(0, 0, context->gConfig->viewportWidth, context->gConfig->viewportHeight);
@@ -53,9 +56,9 @@
 void HelloWorldApp::update() {
 	if (!initialized || context->wasSuspended) {
 		logmsg("Initializing Renderers");
-		//context->worldRenderer->init(TRUE);
 		setupGL();
 		textRenderer->init(TRUE);
+		context->menuRenderer->init(TRUE);
 		context->wasSuspended = FALSE;
 		initialized = TRUE;
 	}
@@ -64,6 +67,18 @@
 void HelloWorldApp::render() {
 	if (initialized) {
 		glClear(GL_COLOR_BUFFER_BIT);
+		context->renderContext->colorFilter = Vector4f(1, 1, 1, 1);
+		if (context->gConfig->useShaders) {
+			context->renderContext->projMatrix.identity();
+			context->renderContext->mvMatrix.identity();
+			context->renderContext->projMatrix.ortho(0, context->gConfig->width, context->gConfig->height, 0, -1, 1);
+		} else {
+			glMatrixMode(GL_PROJECTION);
+			glLoadIdentity();
+			glOrthof(0, context->gConfig->width, context->gConfig->height, 0, -1, 1);
+			glMatrixMode(GL_MODELVIEW);
+			glLoadIdentity();
+		}
 		textRenderer->startText();
 		textRenderer->render("Hello World!", 300, 300, 1.0f);
 		textRenderer->finishText();


paper 3

paper 3

--- src/lilypond/lpsr.cpp
+++ src/lilypond/lpsr.cpp
@@ -2314,6 +2314,7 @@
       "paper-width" << " = " <<
       setprecision(4) << fPaperWidth << "\\cm" <<
       endl;
+
     emptyPaper = false;
   }

@@ -2323,6 +2324,7 @@
       "paper-height" << " = " <<
       setprecision(4) << fPaperHeight << "\\cm" <<
       endl;
+
     emptyPaper = false;
   }

@@ -2332,6 +2334,7 @@
       "top-margin" << " = " <<
       setprecision(4) << fTopMargin << "\\cm" <<
       endl;
+
     emptyPaper = false;
   }

@@ -2341,6 +2344,7 @@
       "bottom-margin" << " = " <<
       setprecision(4) << fBottomMargin << "\\cm" <<
       endl;
+
     emptyPaper = false;
   }

@@ -2350,6 +2354,7 @@
       "left-margin" << " = " <<
       setprecision(4) << fLeftMargin << "\\cm" <<
       endl;
+
     emptyPaper = false;
   }

@@ -2359,6 +2364,7 @@
       "right-margin" << " = " <<
       setprecision(4) << fRightMargin << "\\cm" <<
       endl;
+
     emptyPaper = false;
   }

@@ -2370,6 +2376,8 @@
     "between-system-space" << " = " <<
     setprecision(4) << fBetweenSystemSpace << "\\cm" <<
     endl;
+
+    emptyPaper = false;
   }

   if (fPageTopSpace > 0) {
@@ -2378,6 +2386,9 @@
     "page-top-space" << " = " <<
     setprecision(4) << fPageTopSpace << "\\cm" <<
     endl;
+
+    emptyPaper = false;
+  }

   // headers and footers

@@ -2387,6 +2398,9 @@
     "oddHeaderMarkup" << " = " <<
     fOddHeaderMarkup <<
     endl;
+
+    emptyPaper = false;
+  }

   if (fEvenHeaderMarkup.size ()) {
     os << idtr << left <<
@@ -2394,6 +2408,9 @@
     "evenHeaderMarkup" << " = " <<
     fEvenHeaderMarkup <<
     endl;
+
+    emptyPaper = false;
+  }

   if (fOddFooterMarkup.size ()) {
     os << idtr << left <<
@@ -2401,6 +2418,9 @@
     "oddFooterMarkup" << " = " <<
     fOddFooterMarkup <<
     endl;
+
+    emptyPaper = false;
+  }

   if (fEvenFooterMarkup.size ()) {
     os << idtr << left <<
@@ -2408,13 +2428,17 @@
     "evenFooterMarkup" << " = " <<
     fEvenFooterMarkup <<
     endl;
+
+    emptyPaper = false;
+  }

   // otherwise

-  if (emptyPaper)
+  if (emptyPaper) {
     os << idtr <<
       " " << "nothing specified" <<
       endl;
+  }

   idtr--;
 }


If AVX2 is present, use a faster version of cross product


More fix on TIFF2 predictor

More fix on TIFF2 predictor

--- pngtopdf.cc
+++ pngtopdf.cc
@@ -728,31 +728,31 @@
 apply_tiff2_filter (std::string& raster,
                     int32_t width, int32_t height, int8_t bpc, int8_t num_comp)
 {
-  uint16_t prev[4] = {0, 0, 0, 0};
-
   if (bpc < 8 || num_comp > 4)
     return QPDFObjectHandle::newNull(); // Not supported yet

   for (int32_t j = 0; j < height; j++) {
+    uint16_t prev[4] = {0, 0, 0, 0};
     for (int32_t i = 0; i < width; i++) {
       int32_t pos = (bpc / 8) * num_comp * (width * j + i);
       for (int c = 0; c < num_comp; c++) {
         switch (bpc) {
         case 8:
           {
-            uint8_t right = (i == width-1) ? 0 : raster[pos+c+num_comp];
-            uint8_t sub   = (right - prev[c]);
-            prev[c]       = right;
+            uint8_t cur   = raster[pos+c];
+            int32_t sub   = cur - prev[c];
+            prev[c]       = cur;
             raster[pos+c] = sub;
           }
           break;
+
+
         case 16:
           {
-            uint16_t right = (i == width-1) ? 0 :
-                               ((uint16_t) raster[pos+2*c+2*num_comp]) * 256 +
-                                (uint16_t) raster[pos+2*c+2*num_comp+1];
-            uint16_t sub   = right - prev[c];
-            prev[c]        = right;
+            uint16_t cur = ((uint8_t)raster[pos+2*c])*256 +
+                             (uint8_t)raster[pos+2*c+1];
+            uint16_t sub  = cur - prev[c];
+            prev[c]       = cur;
             raster[pos+2*c  ] = (sub >> 8) & 0xff;
             raster[pos+2*c+1] = sub & 0xff;
           }
@@ -1008,13 +1008,14 @@
   // actual NComps.
   QPDFObjectHandle parms = QPDFObjectHandle::newNull();
   if (config.options.useFlatePredictorTIFF2) {
-    int NComps = use_cmyk ? 4 :
+    int NComps =
+     use_cmyk ? 4 :
                  (has_smask ? src.getNComps() - 1 : src.getNComps()); // Ugh
     if (src.getBPC() >= 8 && src.getNComps() <= 4) {
       parms = apply_tiff2_filter(raster,
                                  src.getWidth(), src.getHeight(),
                                  src.getBPC(), NComps);
-      image_dict.replaceKey("/DecodeParms", parms);
+      image_dict.replaceKey("/DecodeParme", parms);
     }
   }
   image.replaceStreamData(raster,
@@ -1248,12 +1249,13 @@
   extern int        optind;
   Margins           margin;
   struct permission perm = {qpdf_r3p_full, qpdf_r3m_all, true, true};
-  std::string       outfile, upasswd, opasswd;
+  std::string       outfile, xmpfile, upasswd, opasswd;
   bool              nocompress = false, linearize = false, encrypt = false,
                     use_RC4 = false;
   int               keysize = 40;

-  while ((opt = getopt(argc, argv, "bBcCfFgGsSi:o:v:m:zZlLeEK:U:O:P:R")) != -1)
+  while ((opt = getopt(argc,
+                       argv, "bBcCfFgGsSi:o:v:m:x:zZlLeEK:U:O:P:R")) != -1)
   {
     switch (opt) {
     // Some options actually are toggle switches. Use lowercase for enable
@@ -1341,6 +1343,11 @@
       error   = optarg_parse_margins(optarg, margin);
       break;

+    // XMP metadata
+    case 'x':
+      xmpfile = std::string(optarg);
+      break;
+
     // Disable compression -- useful for debugging purpose.
     case 'z': nocompress = false; break;
     case 'Z': nocompress = true;  break;
@@ -1407,6 +1414,10 @@
     docResources.CMYKProfile = QPDFObjectHandle::newNull();
   }

+  // Predictor filter must be disabled if not compressed.
+  if (nocompress)
+      config.options.useFlatePredictorTIFF2 = false;
+
   // Main part
   for ( ;!error && optind < argc; optind++) {
     try
@@ -1417,6 +1428,22 @@
     {
       std::cerr << e.what() << std::endl;
       error_exit("Error occured while processing file(s). No output written.");
+    }
+  }
+
+  // Document Metadata
+  if (!xmpfile.empty()) {
+    if (config.PDF.version < "1.4") {
+      message_unavailable("Metadata", config.PDF.version, "1.4", "ignored");
+    } else {
+      QPDFObjectHandle catalog  = qpdf.getRoot();
+      QPDFObjectHandle metadata = newStreamFromFile(qpdf, xmpfile);
+      if (metadata.isStream()) {
+        QPDFObjectHandle dict = metadata.getDict();
+        dict.replaceKey("/Type", QPDFObjectHandle::newName("/Metadata"));
+        dict.replaceKey("/Subtype", QPDFObjectHandle::newName("/XML"));
+        catalog.replaceKey("/Metadata", qpdf.makeIndirectObject(metadata));
+      }
     }
   }

@@ -1496,10 +1523,6 @@
     }
   }

-  // Predictor filter must be disabled if not compressed.
-  if (nocompress)
-      config.options.useFlatePredictorTIFF2 = false;
-
   // Set PDF version
   if (config.PDF.autoIncrementVersion)
     w.setMinimumPDFVersion(config.PDF.version);


Added a TODO with caching options to consider.

--- src/map.cpp
+++ src/map.cpp
@@ -464,6 +464,7 @@
 	    }
 	}

+	// TODO:  Per arch. caches/files?  Compile to cubin and cache per arch.?
 	void write_to_disk(std::string  cache_key,
                      std::string  kernel_name,
                      std::string  ptx,


Always export catch_exception_raise.

Always export catch_exception_raise.

Patch by Jeremy Moskovich <jeremy@chromium.org>

Code review URL: http://breakpad.appspot.com/37001

git-svn-id: 7939527bf0a06ad24ad020f729d5600cb42ed5d7@428 4c0a9323-5329-0410-9bdc-e9ce6186880e

--- src/client/mac/handler/exception_handler.cc
+++ src/client/mac/handler/exception_handler.cc
@@ -92,12 +92,15 @@
   boolean_t exc_server(mach_msg_header_t *request,
                        mach_msg_header_t *reply);

+  // This symbol must be visible to dlsym() - see
+  // http://code.google.com/p/google-breakpad/issues/detail?id=345 for details.
   kern_return_t catch_exception_raise(mach_port_t target_port,
                                       mach_port_t failed_thread,
                                       mach_port_t task,
                                       exception_type_t exception,
                                       exception_data_t code,
-                                      mach_msg_type_number_t code_count);
+                                      mach_msg_type_number_t code_count)
+      __attribute__((visibility("default")));

   kern_return_t ForwardException(mach_port_t task,
                                  mach_port_t failed_thread,


client: print more info on read errors

client: print more info on read errors

--- src/client/src/org/xtreemfs/client/file.cpp
+++ src/client/src/org/xtreemfs/client/file.cpp
@@ -118,13 +118,14 @@

       org::xtreemfs::interfaces::ObjectData object_data;
       parent_volume->get_osd_proxy_mux()->read( file_credentials, file_credentials.get_xcap().get_file_id(), object_number, 0, object_offset, static_cast<uint32_t>( object_size ), object_data );
+      YIELD::auto_Buffer data = object_data.get_data();
+      uint32_t zero_padding = object_data.get_zero_padding();

       log->getStream( YIELD::Log::LOG_INFO ) <<
-        "org::xtreemfs::client::File: read " << object_data.get_data()->size() <<
+        "org::xtreemfs::client::File: read " << data->size() <<
         " bytes from file " << file_credentials.get_xcap().get_file_id() <<
-        " with " << object_data.get_zero_padding() << " bytes of zero padding.";
-
-      YIELD::auto_Buffer data = object_data.get_data();
+        " with " << zero_padding << " bytes of zero padding.";
+
       if ( !data->empty() )
       {
         if ( data->size() <= RBUF_REMAINING )
@@ -135,13 +136,12 @@
         }
         else
         {
-          log->getStream( YIELD::Log::LOG_ERR ) << "org::xtreemfs::client::File: received data (size=" << data->size() << ") larger than available buffer space (" << RBUF_REMAINING << ")";
+          log->getStream( YIELD::Log::LOG_ERR ) << "org::xtreemfs::client::File: received data (data size=" << data->size() << ", zero_padding=" << zero_padding << ") larger than available buffer space (" << RBUF_REMAINING << ")";
           YIELD::ExceptionResponse::set_errno( EIO );
           return -1;
         }
       }

-      uint32_t zero_padding = object_data.get_zero_padding();
       if ( zero_padding > 0 )
       {
         if ( zero_padding <= RBUF_REMAINING )
@@ -152,7 +152,7 @@
         }
         else
         {
-          log->getStream( YIELD::Log::LOG_ERR ) << "org::xtreemfs::client::File: received zero_padding (" << zero_padding << ") larger than available buffer space (" << ( size - static_cast<size_t>( rbuf_p - rbuf_start ) );
+          log->getStream( YIELD::Log::LOG_ERR ) << "org::xtreemfs::client::File: received zero_padding (data size=" << data->size() << ", zero_padding=" << zero_padding << ") larger than available buffer space (" << RBUF_REMAINING << ")";
           YIELD::ExceptionResponse::set_errno( EIO );
           return -1;
         }


DIV does not erase the result

DIV does not erase the result

--- src/ltac/Operator.cpp
+++ src/ltac/Operator.cpp
@@ -11,12 +11,15 @@
 using eddic::ltac::Operator;

 bool ltac::erase_result(ltac::Operator op){
-   return op == Operator::MOV
-       || op == Operator::FMOV
-       || op == Operator::MUL3
-       || op == Operator::XOR
-       || op == Operator::OR
-       || (op >= Operator::LEA && op <= Operator::CMOVLE);
+    return op != Operator::DIV
+        && (
+                   op == Operator::MOV
+                || op == Operator::FMOV
+                || op == Operator::MUL3
+                || op == Operator::XOR
+                || op == Operator::OR
+                || (op >= Operator::LEA && op <= Operator::CMOVLE)
+         );
 }

 bool ltac::erase_result_complete(ltac::Operator op){


[mg sh] Kill socket lingerage

[mg sh] Kill socket lingerage

--- src/main/c/server.cpp
+++ src/main/c/server.cpp
@@ -299,14 +299,6 @@
 		LS_ERROR(_logger, "Unable to accept: " << getLastError());
 		return;
 	}
-	struct linger linger;
-	linger.l_linger = 500; // 5 seconds
-	linger.l_onoff = true;
-	if (setsockopt(fd, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger)) == -1) {
-		LS_ERROR(_logger, "Unable to set linger socket option: " << getLastError());
-		::close(fd);
-		return;
-	}
 	if (!configureSocket(fd)) {
 		::close(fd);
 		return;


gemmi-mtz: when invoked without options print the same as with --dump

--- src/mtz.cpp
+++ src/mtz.cpp
@@ -165,7 +165,9 @@
   mtz.read_main_headers(stream);
   mtz.read_history_and_batch_headers(stream);
   mtz.setup_spacegroup();
-  if (options[Dump])
+  if (options[Dump] ||
+      !(options[PrintTsv] || options[PrintStats] || options[CheckAsu] ||
+        options[Headers]))
     dump(mtz);
   if (options[PrintTsv] || options[PrintStats] || options[CheckAsu]) {
     mtz.read_raw_data(stream);


Increase the ping timeout from one second to five seconds.

Turns out, one second is not enough and on very busy machines, the server can be perfectly healthy and still take more than a second to answer.

When the port is not open, it will return quickly anyway.

--
MOS_MIGRATED_REVID=127537803

--- src/main/cpp/blaze.cc
+++ src/main/cpp/blaze.cc
@@ -1935,7 +1935,7 @@

   grpc::ClientContext context;
   context.set_deadline(
-      std::chrono::system_clock::now() + std::chrono::seconds(1));
+      std::chrono::system_clock::now() + std::chrono::seconds(5));

   command_server::PingRequest request;
   command_server::PingResponse response;


Fix variable name

Fix variable name

--- src/main/cpp/main.cpp
+++ src/main/cpp/main.cpp
@@ -20,8 +20,8 @@
         perft->run();
       }
     } else {
-      std::unique_ptr<pulse::Pulse> uci(new pulse::Pulse());
-      uci->run();
+      std::unique_ptr<pulse::Pulse> pulse(new pulse::Pulse());
+      pulse->run();
     }
   } catch (std::exception e) {
     std::cout << "Exiting Pulse due to an exception: " << e.what() << std::endl;


ThreadOpenMasternodeConnections should process only one mn at a time (#2080)

--- src/net.cpp
+++ src/net.cpp
@@ -1969,22 +1969,30 @@
         if (interruptNet)
             return;

+        // NOTE: Process only one pending masternode at a time
+
         LOCK(cs_vPendingMasternodes);
-        std::vector<CService>::iterator it = vPendingMasternodes.begin();
-        while (it != vPendingMasternodes.end()) {
-            if (!IsMasternodeOrDisconnectRequested(*it)) {
-                OpenNetworkConnection(CAddress(*it, NODE_NETWORK), false, nullptr, nullptr, false, false, false, true);
-                // should be in the list now if connection was opened
-                ForNode(*it, [&](CNode* pnode) {
-                    if (pnode->fDisconnect) {
-                        return false;
-                    }
-                    grant.MoveTo(pnode->grantMasternodeOutbound);
-                    return true;
-                });
-            }
-            it = vPendingMasternodes.erase(it);
-        }
+        if (vPendingMasternodes.empty()) {
+            // nothing to do, keep waiting
+            continue;
+        }
+
+        const CService addr = vPendingMasternodes.front();
+        vPendingMasternodes.erase(vPendingMasternodes.begin());
+        if (IsMasternodeOrDisconnectRequested(addr)) {
+            // nothing to do, try the next one
+            continue;
+        }
+
+        OpenNetworkConnection(CAddress(addr, NODE_NETWORK), false, nullptr, nullptr, false, false, false, true);
+        // should be in the list now if connection was opened
+        ForNode(addr, [&](CNode* pnode) {
+            if (pnode->fDisconnect) {
+                return false;
+            }
+            grant.MoveTo(pnode->grantMasternodeOutbound);
+            return true;
+        });
     }
 }


Added some missing log statements for scheduler calls.

Some Scheduler API calls ('KILL'/'SHUTDOWN') were missing info
level logging statements. In the case of `KILL', the logging
statement was there but was invoked in `killTask()` but was
not consistent with how we were logging for the other calls
in the continuation helper.

Review: https://reviews.apache.org/r/54913/

--- src/master/master.cpp
+++ src/master/master.cpp
@@ -4661,9 +4661,6 @@
     const FrameworkID& frameworkId,
     const TaskID& taskId)
 {
-  LOG(INFO) << "Asked to kill task " << taskId
-            << " of framework " << frameworkId;
-
   Framework* framework = getFramework(frameworkId);

   if (framework == nullptr) {
@@ -4693,11 +4690,14 @@
 {
   CHECK_NOTNULL(framework);

-  ++metrics->messages_kill_task;
-
   const TaskID& taskId = kill.task_id();
   const Option<SlaveID> slaveId =
     kill.has_slave_id() ? Option<SlaveID>(kill.slave_id()) : None();
+
+  LOG(INFO) << "Processing KILL call for task '" << taskId << "'"
+            << " of framework " << *framework;
+
+  ++metrics->messages_kill_task;

   if (framework->pendingTasks.contains(taskId)) {
     // Remove from pending tasks.
@@ -5938,11 +5938,17 @@
     return;
   }

-  Slave* slave = slaves.registered.get(shutdown.slave_id());
+  const SlaveID& slaveId = shutdown.slave_id();
+  const ExecutorID& executorId = shutdown.executor_id();
+
+  Slave* slave = slaves.registered.get(slaveId);
   CHECK_NOTNULL(slave);

+  LOG(INFO) << "Processing SHUTDOWN call for executor '" << executorId
+            << "' of framework " << *framework << " on agent " << slaveId;
+
   ShutdownExecutorMessage message;
-  message.mutable_executor_id()->CopyFrom(shutdown.executor_id());
+  message.mutable_executor_id()->CopyFrom(executorId);
   message.mutable_framework_id()->CopyFrom(framework->id());
   send(slave->pid, message);
 }


Do not kill connections on recv buffer overflow

Instead of killing a connection when the receive buffer overflows,
just temporarily halt receiving before that happens. Also, no
matter what, always allow at least one full message in the receive
buffer (otherwise blocks larger than the configured buffer size
would pause indefinitely).

--- src/net.cpp
+++ src/net.cpp
@@ -841,18 +841,38 @@
             {
                 if (pnode->hSocket == INVALID_SOCKET)
                     continue;
+                FD_SET(pnode->hSocket, &fdsetError);
+                hSocketMax = max(hSocketMax, pnode->hSocket);
+                have_fds = true;
+
+                // Implement the following logic:
+                // * If there is data to send, select() for sending data. As this only
+                //   happens when optimistic write failed, we choose to first drain the
+                //   write buffer in this case before receiving more. This avoids
+                //   needlessly queueing received data, if the remote peer is not themselves
+                //   receiving data. This means properly utilizing TCP flow control signalling.
+                // * Otherwise, if there is no (complete) message in the receive buffer,
+                //   or there is space left in the buffer, select() for receiving data.
+                // * (if neither of the above applies, there is certainly one message
+                //   in the receiver buffer ready to be processed).
+                // Together, that means that at least one of the following is always possible,
+                // so we don't deadlock:
+                // * We send some data.
+                // * We wait for data to be received (and disconnect after timeout).
+                // * We process a message in the buffer (message handler thread).
                 {
                     TRY_LOCK(pnode->cs_vSend, lockSend);
-                    if (lockSend) {
-                        // do not read, if draining write queue
-                        if (!pnode->vSendMsg.empty())
-                            FD_SET(pnode->hSocket, &fdsetSend);
-                        else
-                            FD_SET(pnode->hSocket, &fdsetRecv);
-                        FD_SET(pnode->hSocket, &fdsetError);
-                        hSocketMax = max(hSocketMax, pnode->hSocket);
-                        have_fds = true;
+                    if (lockSend && !pnode->vSendMsg.empty()) {
+                        FD_SET(pnode->hSocket, &fdsetSend);
+                        continue;
                     }
+                }
+                {
+                    TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
+                    if (lockRecv && (
+                        pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() ||
+                        pnode->GetTotalRecvSize() <= ReceiveFloodSize()))
+                        FD_SET(pnode->hSocket, &fdsetRecv);
                 }
             }
         }
@@ -959,12 +979,7 @@
                 TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
                 if (lockRecv)
                 {
-                    if (pnode->GetTotalRecvSize() > ReceiveFloodSize()) {
-                        if (!pnode->fDisconnect)
-                            printf("socket recv flood control disconnect (%u bytes)\n", pnode->GetTotalRecvSize());
-                        pnode->CloseSocketDisconnect();
-                    }
-                    else {
+                    {
                         // typical socket buffer is 8K-64K
                         char pchBuf[0x10000];
                         int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);


Update copyright header

Update copyright header

--- src/decoration/qgnomeplatformdecoration.cpp
+++ src/decoration/qgnomeplatformdecoration.cpp
@@ -1,5 +1,6 @@
 /****************************************************************************
 **
+** Copyright (C) 2019-2021 Jan Grulich <jgrulich@redhat.com>
 ** Copyright (C) 2016 Robin Burchell <robin.burchell@viroteck.net>
 ** Copyright (C) 2016 The Qt Company Ltd.
 ** Contact: https://www.qt.io/licensing/


Exemplary clean-up of one function in Geometry.cpp


add seed node

add seed node

--- src/net.cpp
+++ src/net.cpp
@@ -1230,6 +1230,7 @@
 // The second name should resolve to a list of seed addresses.
 static const char *strDNSSeed[][2] = {
     {"eddicoin1.dynalias.org", "eddicoin2.dynalias.org"},
+    {"Eddie1.dynu.net", "Eddie1.dynu.net"},
   };

 void ThreadDNSAddressSeed(void* parg)


Replace std::isnan() with boost::math::isnan()

This replaces the usage of std::isnan() with
boost::math::isnan() which is more portable.

--- src/md/forcefield.cpp
+++ src/md/forcefield.cpp
@@ -35,6 +35,8 @@

 #include "forcefield.h"

+#include <boost/math/special_functions/fpclassify.hpp>
+
 #include <chemkit/atom.h>
 #include <chemkit/foreach.h>
 #include <chemkit/geometry.h>
@@ -515,7 +517,7 @@
         // simulation exploded so we reset the initial atom
         // positions and then 'wiggle' each atom by one
         // Angstrom in a random direction
-        if(std::isnan(finalEnergy)){
+        if((boost::math::isnan)(finalEnergy)){
             for(int atomIndex = 0; atomIndex < atomCount(); atomIndex++){
                 d->atoms[atomIndex]->setPosition(initialPositions[atomIndex]);
                 d->atoms[atomIndex]->moveBy(Vector3::Random().normalized());


prevent SOCKET leak in BindListenPort()

prevent SOCKET leak in BindListenPort()

- the call to CloseSocket() is placed after the WSAGetLastError(), because
  a CloseSocket() can trigger an error also, which we don't want for the
  logging in this two cases

--- src/net.cpp
+++ src/net.cpp
@@ -1658,6 +1658,7 @@
         else
             strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr));
         LogPrintf("%s\n", strError);
+        CloseSocket(hListenSocket);
         return false;
     }
     LogPrintf("Bound to %s\n", addrBind.ToString());
@@ -1667,6 +1668,7 @@
     {
         strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
         LogPrintf("%s\n", strError);
+        CloseSocket(hListenSocket);
         return false;
     }


Refactor: Move failure conditions to the top of AcceptConnection

--- src/net.cpp
+++ src/net.cpp
@@ -706,6 +706,13 @@
         return;
     }

+    if (CNode::IsBanned(addr) && !whitelisted)
+    {
+        LogPrintf("connection from %s dropped (banned)\n", addr.ToString());
+        CloseSocket(hSocket);
+        return;
+    }
+
     if (nInbound >= nMaxInbound)
     {
         LogPrint("net", "connection from %s dropped (full)\n", addr.ToString());
@@ -716,13 +723,6 @@
     if (!whitelisted && (nInbound >= (nMaxInbound - nWhiteConnections)))
     {
         LogPrint("net", "connection from %s dropped (non-whitelisted)\n", addr.ToString());
-        CloseSocket(hSocket);
-        return;
-    }
-
-    if (CNode::IsBanned(addr) && !whitelisted)
-    {
-        LogPrintf("connection from %s dropped (banned)\n", addr.ToString());
         CloseSocket(hSocket);
         return;
     }


fixed issue #14: compiler error with newer versions the boost library

--- src/net.cpp
+++ src/net.cpp
@@ -61,7 +61,7 @@
 static CNode* pnodeLocalHost = NULL;
 CAddress addrSeenByPeer(CService("0.0.0.0", 0), nLocalServices);
 uint64 nLocalHostNonce = 0;
-array<int, THREAD_MAX> vnThreadsRunning;
+boost::array<int, THREAD_MAX> vnThreadsRunning;
 static std::vector<SOCKET> vhListenSocket;
 CAddrMan addrman;


Allocate receive buffers in on the fly

Allocate receive buffers in on the fly

--- src/net.cpp
+++ src/net.cpp
@@ -675,7 +675,6 @@

     // switch state to reading message data
     in_data = true;
-    vRecv.resize(hdr.nMessageSize);

     return nCopy;
 }
@@ -684,6 +683,11 @@
 {
     unsigned int nRemaining = hdr.nMessageSize - nDataPos;
     unsigned int nCopy = std::min(nRemaining, nBytes);
+
+    if (vRecv.size() < nDataPos + nCopy) {
+        // Allocate up to 256 KiB ahead, but never more than the total message size.
+        vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
+    }

     memcpy(&vRecv[nDataPos], pch, nCopy);
     nDataPos += nCopy;


Remove vladimir's DNS seed, at his request.

--- src/net.cpp
+++ src/net.cpp
@@ -1210,7 +1210,6 @@

 static const char *strDNSSeed[] = {
     "bitseed.xf2.org",
-    "bitseed.bitcoin.org.uk",
     "dnsseed.bluematt.me",
 };


Node Added

Node Added

New Node Added.


Add InstantTX to relay

Add InstantTX to relay

--- src/net.cpp
+++ src/net.cpp
@@ -2276,11 +2276,35 @@

 void RelayTransaction(const CTransaction& tx)
 {
-    CInv inv(MSG_TX, tx.GetHash());
+    uint256 hash = tx.GetHash();
+    int nInv = static_cast<bool>(CPrivateSend::GetDSTX(hash)) ? MSG_DSTX :
+                (instantsend.HasTxLockRequest(hash) ? MSG_TXLOCK_REQUEST : MSG_TX);
+    CInv inv(nInv, hash);
+    {
+        LOCK(cs_mapRelay);
+        // Expire old relay messages
+        while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
+        {
+            mapRelay.erase(vRelayExpiration.front().second);
+            vRelayExpiration.pop_front();
+        }
+
+        // Save original serialized message so newer versions are preserved
+        mapRelay.insert(std::make_pair(inv, ss));
+        vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
+    }
     LOCK(cs_vNodes);
     BOOST_FOREACH(CNode* pnode, vNodes)
     {
-        pnode->PushInventory(inv);
+        if(!pnode->fRelayTxes)
+            continue;
+        LOCK(pnode->cs_filter);
+        if (pnode->pfilter)
+        {
+            if (pnode->pfilter->IsRelevantAndUpdate(tx))
+                pnode->PushInventory(inv);
+        } else
+            pnode->PushInventory(inv);
     }
 }


[estimation] Removed spurious prints

[estimation] Removed spurious prints

--- src/estimation/src/SimpleLeggedOdometry.cpp
+++ src/estimation/src/SimpleLeggedOdometry.cpp
@@ -306,18 +306,10 @@
         return Transform::Identity();
     }

-    std::cerr << m_fixedLinkIndex << std::endl;
-    std::cerr << m_base_H_link.getNrOfLinks() << std::endl;
-
     assert(m_fixedLinkIndex < m_base_H_link.getNrOfLinks());
     Transform base_H_fixed = m_base_H_link(m_fixedLinkIndex);
     Transform base_H_link =  m_base_H_link(link_index);

-    std::cerr << "base_H_fixed " << base_H_fixed.toString() << std::endl;
-    std::cerr << "base_H_link " << base_H_link.toString() << std::endl;
-    std::cerr << "m_world_H_fixedLink " << m_world_H_fixedLink.toString() << std::endl;
-
-
     return m_world_H_fixedLink*base_H_fixed.inverse()*base_H_link;
 }


Refactor Win32 #ifndef for BindListenPort

--- src/net.cpp
+++ src/net.cpp
@@ -1902,30 +1902,17 @@
         LogPrintf("%s\n", strError);
         return false;
     }
-
+#ifndef WIN32
 #ifdef SO_NOSIGPIPE
     // Different way of disabling SIGPIPE on BSD
     setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
 #endif
-
-#ifndef WIN32
     // Allow binding if the port is still in TIME_WAIT state after
-    // the program was closed and restarted.  Not an issue on windows.
+    // the program was closed and restarted.
     setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
-#endif
-
-
-#ifdef WIN32
-    // Set to non-blocking, incoming connections will also inherit this
-    if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
 #else
-    if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
-#endif
-    {
-        strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
-        LogPrintf("%s\n", strError);
-        return false;
-    }
+    setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&nOne, sizeof(int));
+#endif

     // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
     // and enable it by default or not. Try to enable it, if possible.
@@ -2649,4 +2636,4 @@

     LogPrint("net", "Flushed %d banned node ips/subnets to banlist.dat  %dms\n",
         banmap.size(), GetTimeMillis() - nStart);
-}+}


Fix elem-vs-node unique_id conflict in NemesisIO

--- src/mesh/nemesis_io.C
+++ src/mesh/nemesis_io.C
@@ -847,9 +847,10 @@
           uelem->subdomain_id() = subdomain_id;
           uelem->processor_id() = this->processor_id();
           uelem->set_id()       = my_next_elem++;
-#ifdef LIBMESH_ENABLE_UNIQUE_ID
-          uelem->set_unique_id(uelem->id());
-#endif
+
+          // Leave unique_id numbering up to the mesh; with each
+          // element pre-partitioned our automatic assignment won't
+          // create any conflicts.

           // Mark that we have seen an element of the current element's
           // dimension.


updated seed nodes

updated seed nodes

--- src/net.cpp
+++ src/net.cpp
@@ -1192,6 +1192,7 @@
 // The first name is used as information source for addrman.
 // The second name should resolve to a list of seed addresses.
 static const char *strMainNetDNSSeed[][2] = {
+    {"monseed.meningslos.info", "monseed.meningslos.info"},
     {"mon-seed.etyd.org", "mon-seed.etyd.org"},
     {"mon-seed2.etyd.org", "mon-seed2.etyd.org"},
     {"monexplorer.vertcoin.org", "monexplorer.vertcoin.org"},


Fix mesh_pipeline help message.

Fix mesh_pipeline help message.

Some of the comments were stale, and some of the options were
missing.

Also improved the explanations, and added human-readable versions
of each option.

Tested: Displays correctly on Mac and Linux.
Change-Id: I84d0dd1798a771e630b0d3380a518c04199c8867

--- src/mesh_pipeline.cpp
+++ src/mesh_pipeline.cpp
@@ -1680,7 +1680,7 @@
       args->log_level = kLogInfo;

       // -b switch
-    } else if (arg == "-b") {
+    } else if (arg == "-b" || arg == "--base-dir") {
       if (i + 1 < argc - 1) {
         args->asset_base_dir = std::string(argv[i + 1]);
         i++;
@@ -1689,7 +1689,7 @@
       }

       // -r switch
-    } else if (arg == "-r") {
+    } else if (arg == "-r" || arg == "--relative-dir") {
       if (i + 1 < argc - 1) {
         args->asset_rel_dir = std::string(argv[i + 1]);
         i++;
@@ -1697,7 +1697,7 @@
         valid_args = false;
       }

-    } else if (arg == "-e") {
+    } else if (arg == "-e" || arg == "--texture-extension") {
       if (i + 1 < argc - 1) {
         args->texture_extension = std::string(argv[i + 1]);
         i++;
@@ -1714,7 +1714,7 @@
       args->recenter = true;

       // -f switch
-    } else if (arg == "-f") {
+    } else if (arg == "-f" || arg == "--texture-formats") {
       if (i + 1 < argc - 1) {
         valid_args = ParseTextureFormats(
             std::string(argv[i + 1]), log, &args->texture_formats);
@@ -1727,7 +1727,7 @@
       }

       // -m switch
-    } else if (arg == "-m") {
+    } else if (arg == "-m" || arg == "--blend-mode") {
       if (i + 1 < argc - 1) {
         args->blend_mode = ParseBlendMode(argv[i + 1]);
         valid_args = args->blend_mode >= 0;
@@ -1760,55 +1760,71 @@
   if (!valid_args) {
     log.Log(
         kLogImportant,
-        "Usage: mesh_pipeline [-v|-d] [-b ASSET_BASE_DIR] [-r ASSET_REL_DIR]\n"
-        "                     [-c] [-f TEXTURE_FORMATS] FBX_FILE\n"
+        "Usage: mesh_pipeline [-b ASSET_BASE_DIR] [-r ASSET_REL_DIR]\n"
+        "                     [-e TEXTURE_EXTENSION] [-f TEXTURE_FORMATS]\n"
+        "                     [-m BLEND_MODE] [-h] [-c] [-v|-d|-i] FBX_FILE\n"
+        "\n"
         "Pipeline to convert FBX mesh data into FlatBuffer mesh data.\n"
-        "We output a .fplmesh file with the same base name as FBX_FILE.\n"
-        "For every texture referenced by the FBX, we output a .fplmat file\n"
-        "to load the texture. The .fplmesh file references all .fplmat files\n"
-        "by names relative to ASSET_BASE_DIR.\n\n"
+        "We output a .fplmesh file and (potentially several) .fplmat files,\n"
+        "one for each material. The files have the same base name as\n"
+        "FBX_FILE, with a number appended to the .fplmat files if required.\n"
+        "The .fplmesh file references the .fplmat files.\n"
+        "The .fplmat files reference the textures.\n"
+        "\n"
         "Options:\n"
-        "  -v, --verbose        output all informative messages\n"
-        "  -d, --details        output important informative messages\n"
-        "  -i, --info           output more than details, less than verbose\n"
-        "  -b ASSET_BASE_DIR    directory from which all assets are loaded;\n"
-        "                       material file paths are relative to here.\n"
-        "                       If unspecified, current directory.\n"
-        "  -r ASSET_REL_DIR     directory to put all output files; relative\n"
-        "                       to ASSET_BASE_DIR. If unspecified, current\n"
-        "                       directory.\n"
-        "  -e TEXTURE_EXTENSION material files use this extension for texture\n"
-        "                       files. Useful if your textures are externally\n"
-        "                       converted to a different file format.\n"
-        "                       If unspecified, uses original file extension.\n"
-        "  -h, --hierarchy      output vertices relative to local pivot\n"
-        "                       of each sub-mesh. The transforms from parent\n"
-        "                       pivot to local pivot are also output.\n"
-        "                       This option is necessary for animated meshes.\n"
-        "  -c, --center         ensure world origin is inside geometry\n"
-        "                       bounding box by adding a translation if\n"
-        "                       required.\n"
-        "  -f TEXTURE_FORMATS   comma-separated list of formats for each\n"
-        "                       output texture. For example, if a mesh has\n"
-        "                       two textures then `AUTO,F_888` will ensure\n"
-        "                       the second texture's material has 8-bits of\n"
-        "                       RGB precision. Default is %s.\n"
-        "                       Valid possibilities:\n",
+        "  -b, --base-dir ASSET_BASE_DIR\n"
+        "  -r, --relative-dir ASSET_REL_DIR\n"
+        "                The .fplmesh file and the .fplmat files are output\n"
+        "                to the ASSET_BASE_DIR/ASSET_REL_DIR directory.\n"
+        "                ASSET_BASE_DIR is the working directory of your app,\n"
+        "                from which all files are loaded. The .fplmesh file\n"
+        "                references the .fplmat file relative to\n"
+        "                ASSET_BASE_DIR, that is, by prefixing ASSET_REL_DIR.\n"
+        "                If ASSET_BASE_DIR is unspecified, use current\n"
+        "                directory. If ASSET_REL_DIR is unspecified, output\n"
+        "                and reference files from ASSET_BASE_DIR.\n"
+        "  -e, --texture-extension TEXTURE_EXTENSION\n"
+        "                material files use this extension for texture files.\n"
+        "                Useful if your textures are externally converted\n"
+        "                to a different file format.\n"
+        "                If unspecified, uses original file extension.\n"
+        "  -f, --texture-formats TEXTURE_FORMATS\n"
+        "                comma-separated list of formats for each output\n"
+        "                texture. For example, if a mesh has two textures\n"
+        "                then `AUTO,F_888` will ensure the second texture's\n"
+        "                material has 8-bits of RGB precision.\n"
+        "                Default is %s.\n"
+        "                Valid possibilities:\n",
         matdef::EnumNameTextureFormat(kDefaultTextureFormat));
     for (const char** format = matdef::EnumNamesTextureFormat();
          *format != nullptr; ++format) {
       log.Log(kLogImportant, "                           %s\n", *format);
     }
+
     log.Log(
         kLogImportant,
-        "  -m BLEND_MODE        rendering blend mode for the generated\n"
-        "                       materials. If texture format has an alpha\n"
-        "                       channel, defaults to ALPHA. Otherwise,\n"
-        "                       defaults to OFF. Valid possibilities:\n");
+        "  -m, --blend-mode BLEND_MODE\n"
+        "                rendering blend mode for the generated materials.\n"
+        "                If texture format has an alpha channel, defaults to\n"
+        "                ALPHA. Otherwise, defaults to OFF.\n"
+        "                Valid possibilities:\n");
     for (const char** mode = matdef::EnumNamesBlendMode();
          *mode != nullptr; ++mode) {
       log.Log(kLogImportant, "                           %s\n", *mode);
     }
+
+    log.Log(
+        kLogImportant,
+        "  -h, --hierarchy\n"
+        "                output vertices relative to local pivot of each\n"
+        "                sub-mesh. The transforms from parent pivot to local\n"
+        "                pivot are also output.\n"
+        "                This option is necessary for animated meshes.\n"
+        "  -c, --center  ensure world origin is inside geometry bounding box\n"
+        "                by adding a translation if required.\n"
+        "  -v, --verbose output all informative messages\n"
+        "  -d, --details output important informative messages\n"
+        "  -i, --info    output more than details, less than verbose\n");
   }

   return valid_args;


Use unique_ptr for upnp_thread (boost::thread)

--- src/net.cpp
+++ src/net.cpp
@@ -1534,22 +1534,20 @@

 void MapPort(bool fUseUPnP)
 {
-    static boost::thread* upnp_thread = nullptr;
+    static std::unique_ptr<boost::thread> upnp_thread;

     if (fUseUPnP)
     {
         if (upnp_thread) {
             upnp_thread->interrupt();
             upnp_thread->join();
-            delete upnp_thread;
-        }
-        upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort));
+        }
+        upnp_thread.reset(new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort)));
     }
     else if (upnp_thread) {
         upnp_thread->interrupt();
         upnp_thread->join();
-        delete upnp_thread;
-        upnp_thread = nullptr;
+        upnp_thread.reset();
     }
 }


STYLE: Remove tabs from metaFEMObject.cxx.

--- src/metaFEMObject.cxx
+++ src/metaFEMObject.cxx
@@ -345,7 +345,7 @@
   // we read 1)node, 2) material, 3) element and 4) load  and the input should be in the afore
   // mentioned order.

-  int segment_read = 0;	// to keep track of what is being read. corresponds to enumerated types in the header file
+  int segment_read = 0; // to keep track of what is being read. corresponds to enumerated types in the header file
   /* then we start reading objects from stream */
   do
     {
@@ -360,7 +360,7 @@
     if(segment_read > 3)
       {
       this->SkipWhiteSpace();
-      return true;	// end of FEM segment in spatial object reader.
+      return true; // end of FEM segment in spatial object reader.
       }

     l = this->m_ReadStream->tellg();     // remember the stream position
@@ -405,8 +405,8 @@
     if ( s == "END" )
       {
       /*
-		 * We can ignore this token. Start again by reading the next object.
-		 */
+       * We can ignore this token. Start again by reading the next object.
+       */
       segment_read++;
       }
     else
@@ -421,9 +421,9 @@
         return false;  // class not found
         }
       /*
-	     * Now we have to read additional data, which is
-	     * specific to the class of object we just created
-	     */
+       * Now we have to read additional data, which is
+       * specific to the class of object we just created
+       */

       switch ( segment_read )
         {
@@ -441,7 +441,7 @@
           break;
         }
       }
-    }while(segment_read <= 3);	// end of FEM segment in spatial object reader.
+    }while(segment_read <= 3); // end of FEM segment in spatial object reader.
   return true;
 }

@@ -1354,40 +1354,46 @@
 {
   if((c_string == "Element2DC0LinearLineStress") || (c_string == "Element2DC1Beam"))
     {
-    info[0] = 2;	info[1] = 2;
+    info[0] = 2;
+    info[1] = 2;
     }

   if((c_string == "Element2DC0LinearTriangularMembrane") ||
      (c_string == "Element2DC0LinearTriangularStrain") ||
      (c_string == "Element2DC0LinearTriangularStress"))
     {
-    info[0] = 3;	info[1] = 2;
+    info[0] = 3;
+    info[1] = 2;
     }

   if((c_string == "Element2DC0LinearQuadrilateralMembrane") ||
      (c_string == "Element2DC0LinearQuadrilateralStrain") ||
      (c_string == "Element2DC0LinearQuadrilateralStress"))
     {
-    info[0] = 4;	info[1] = 2;
+    info[0] = 4;
+    info[1] = 2;
     }

   if((c_string == "Element2DC0QuadraticTriangularStrain") ||
      (c_string == "Element2DC0QuadraticTriangularStress"))
     {
-    info[0] = 6;	info[1] = 2;
+    info[0] = 6;
+    info[1] = 2;
     }

   if((c_string == "Element3DC0LinearHexahedronMembrane") ||
      (c_string == "Element3DC0LinearHexahedronStrain"))
     {
-    info[0] = 8;	info[1] = 3;
+    info[0] = 8;
+    info[1] = 3;
     }

   if((c_string == "Element3DC0LinearTetrahedronMembrane") ||
      (c_string == "Element3DC0LinearTetrahedronStrain"))
     {
-    info[0] = 4;	info[1] = 3;
+    info[0] = 4;
+    info[1] = 3;
     }

   return info;


Fixes a race condition in the MBED usbserial implementation.

--- src/freertos_drivers/nxp/mbed_usbserial.cpp
+++ src/freertos_drivers/nxp/mbed_usbserial.cpp
@@ -86,11 +86,14 @@

     void Transmit()
     {
-	if (txPending) return;
+	// Without this critical section there were cases when we deadlocked
+	// with txPending == true but no interrupt coming in to clear it.
+	taskENTER_CRITICAL();
+	if (txPending) {
+	    taskEXIT_CRITICAL();
+	    return;
+	}
 	txPending = true;
-	// At this point we know there is no outstading send, thus there can't
-	// be an incoming TX interrupt either. Thus we don't need a critical
-	// section.
 	int count;
 	for (count = 0; count < TX_DATA_SIZE; count++)
 	{
@@ -101,6 +104,7 @@
 	    }
 	}
 	TxHelper(count);
+	taskEXIT_CRITICAL();
     }

 protected:
@@ -116,6 +120,7 @@
     virtual bool EP2_IN_callback()
     {
 	int count;
+	configASSERT(txPending);
 	for (count = 0; count < MAX_TX_PACKET_LENGTH; count++)
 	{
 	    if (os_mq_receive_from_isr(serialPriv->txQ, &txData[count]) != OS_MQ_NONE)
@@ -149,8 +154,8 @@
 	    serialPriv->overrunCount += count;
 	    return;
 	}
+	txPending = true;
 	sendNB(txData, count);
-	txPending = true;
     }

     void RxThread()


Update net.cpp

Update net.cpp

--- src/net.cpp
+++ src/net.cpp
@@ -1192,13 +1192,12 @@
 // The first name is used as information source for addrman.
 // The second name should resolve to a list of seed addresses.
 static const char *strMainNetDNSSeed[][2] = {
-    {"plncoin.org", "plncoin.org"},
-    {"pool.plncoin.org", "pool.plncoin.org"}
+    {"plncoin.org", "seed.plncoin.org"},
+    {"plncoin.org", "pool.plncoin.org"}
 };

 static const char *strTestNetDNSSeed[][2] = {
-    {"plncoin.org", "plncoin.org"},
-    {"pool.plncoin.org", "pool.plncoin.org"}
+    {NULL, NULL}
 };

 void ThreadDNSAddressSeed()


LOCK vNodes before use

LOCK vNodes before use

--- src/net.cpp
+++ src/net.cpp
@@ -755,8 +755,13 @@
                 }
             }
         }
-        if (vNodes.size() != nPrevNodeCount) {
-            nPrevNodeCount = vNodes.size();
+        size_t vNodesSize;
+        {
+            LOCK(cs_vNodes);
+            vNodesSize = vNodes.size();
+        }
+        if(vNodesSize != nPrevNodeCount) {
+            nPrevNodeCount = vNodesSize;
             uiInterface.NotifyNumConnectionsChanged(nPrevNodeCount);
         }


Use uniform initialization syntax.

Use uniform initialization syntax.

--- src/min_element01.cpp
+++ src/min_element01.cpp
@@ -6,10 +6,9 @@

 int main()
 {
-    std::vector<double> v = {1.0, 2.0, 3.0};
+    std::vector<double> v{1.0, 2.0, 3.0};
     auto min_value = *std::min_element(std::begin(v), std::end(v));
     std::cout << "Minimal value: " << min_value << "\n";

     return 0;
 }
-


[Logging] - Move socket errors below net category

--- src/net.cpp
+++ src/net.cpp
@@ -431,7 +431,7 @@
     {
         if (!IsSelectableSocket(hSocket))
         {
-            LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
+            LogPrint("net", "Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
             CloseSocket(hSocket);
             return nullptr;
         }
@@ -729,8 +729,8 @@
                 int nErr = WSAGetLastError();
                 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
                 {
-                    LogPrintf("socket send error '%s' to %s (%d)\n", NetworkErrorString(nErr), pnode->addrName.c_str(),
-                        pnode->id);
+                    LogPrint("net", "socket send error '%s' to %s (%d)\n", NetworkErrorString(nErr),
+                        pnode->addrName.c_str(), pnode->id);
                     pnode->fDisconnect = true;
                 }
             }
@@ -907,20 +907,20 @@

     if (hSocket != INVALID_SOCKET)
         if (!addr.SetSockAddr((const struct sockaddr *)&sockaddr))
-            LogPrintf("Warning: Unknown socket family\n");
+            LogPrint("net", "Warning: Unknown socket family\n");

     bool whitelisted = hListenSocket.whitelisted || dosMan.IsWhitelistedRange(addr);
     if (hSocket == INVALID_SOCKET)
     {
         int nErr = WSAGetLastError();
         if (nErr != WSAEWOULDBLOCK)
-            LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr));
+            LogPrint("net", "socket error accept failed: %s\n", NetworkErrorString(nErr));
         return;
     }

     if (!IsSelectableSocket(hSocket))
     {
-        LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToString());
+        LogPrint("net", "connection from %s dropped: non-selectable socket\n", addr.ToString());
         CloseSocket(hSocket);
         return;
     }
@@ -1210,7 +1210,7 @@
             if (have_fds)
             {
                 int nErr = WSAGetLastError();
-                LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
+                LogPrint("net", "socket select error %s\n", NetworkErrorString(nErr));

                 for (SOCKET hSocket : setSocket)
                     FD_SET(hSocket, &fdsetRecv);
@@ -1298,7 +1298,7 @@
                                 nErr != WSAEINPROGRESS)
                             {
                                 if (!pnode->fDisconnect)
-                                    LogPrintf("Node %s socket recv error '%s'\n", pnode->addrName.c_str(),
+                                    LogPrint("net", "Node %s socket recv error '%s'\n", pnode->addrName.c_str(),
                                         NetworkErrorString(nErr));
                                 pnode->fDisconnect = true;
                             }
@@ -2420,7 +2420,8 @@
     {
         if (hListenSocket.socket != INVALID_SOCKET)
             if (!CloseSocket(hListenSocket.socket))
-                LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
+                LogPrint(
+                    "net", "CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
     }

     // clean up some globals (to help leak detection)


Simplify comparisons lessthan

Simplify comparisons lessthan

--- src/mipp_impl_AVX.hxx
+++ src/mipp_impl_AVX.hxx
@@ -1985,22 +1985,22 @@

 	template <>
 	inline msk cmplt<int64_t>(const reg v1, const reg v2) {
-		return notb<N<int64_t>()>(cmpge<int64_t>(v1, v2));
+		return cmpgt<int64_t>(v2, v1);
 	}

 	template <>
 	inline msk cmplt<int32_t>(const reg v1, const reg v2) {
-		return notb<N<int32_t>()>(cmpge<int32_t>(v1, v2));
+		return cmpgt<int32_t>(v2, v1);
 	}

 	template <>
 	inline msk cmplt<int16_t>(const reg v1, const reg v2) {
-		return notb<N<int16_t>()>(cmpge<int16_t>(v1, v2));
+		return cmpgt<int16_t>(v2, v1);
 	}

 	template <>
 	inline msk cmplt<int8_t>(const reg v1, const reg v2) {
-		return notb<N<int8_t>()>(cmpge<int8_t>(v1, v2));
+		return cmpgt<int8_t>(v2, v1);
 	}

 	// ------------------------------------------------------------------------------------------------------------ add


Fix super-unlikely race introduced in 236618061a445d2cb11e72

Once the CNode has been added to vNodes, it is possible that it is
disconnected+deleted in the socket handler thread. However, after
that we now call InitializeNode, which accesses the pnode.

helgrind managed to tickle this case (somehow), but I suspect it
requires in immensely braindead scheduler.

--- src/net.cpp
+++ src/net.cpp
@@ -1531,11 +1531,11 @@
     if (fFeeler)
         pnode->fFeeler = true;

+    GetNodeSignals().InitializeNode(pnode, *this);
     {
         LOCK(cs_vNodes);
         vNodes.push_back(pnode);
     }
-    GetNodeSignals().InitializeNode(pnode, *this);

     return true;
 }


[NFC] Group aligned new/delete definitions together in new.cpp

This patch is cleanup to prepare for future changes

git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@292560 91177308-0d34-0410-b5e6-96231b3b80d8

--- src/new.cpp
+++ src/new.cpp
@@ -64,6 +64,94 @@
 }

 _LIBCPP_WEAK
+void*
+operator new(size_t size, const std::nothrow_t&) _NOEXCEPT
+{
+    void* p = 0;
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    try
+    {
+#endif  // _LIBCPP_NO_EXCEPTIONS
+        p = ::operator new(size);
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    }
+    catch (...)
+    {
+    }
+#endif  // _LIBCPP_NO_EXCEPTIONS
+    return p;
+}
+
+_LIBCPP_WEAK
+void*
+operator new[](size_t size) _THROW_BAD_ALLOC
+{
+    return ::operator new(size);
+}
+
+_LIBCPP_WEAK
+void*
+operator new[](size_t size, const std::nothrow_t&) _NOEXCEPT
+{
+    void* p = 0;
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    try
+    {
+#endif  // _LIBCPP_NO_EXCEPTIONS
+        p = ::operator new[](size);
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    }
+    catch (...)
+    {
+    }
+#endif  // _LIBCPP_NO_EXCEPTIONS
+    return p;
+}
+
+_LIBCPP_WEAK
+void
+operator delete(void* ptr) _NOEXCEPT
+{
+    if (ptr)
+        ::free(ptr);
+}
+
+_LIBCPP_WEAK
+void
+operator delete(void* ptr, const std::nothrow_t&) _NOEXCEPT
+{
+    ::operator delete(ptr);
+}
+
+_LIBCPP_WEAK
+void
+operator delete(void* ptr, size_t) _NOEXCEPT
+{
+    ::operator delete(ptr);
+}
+
+_LIBCPP_WEAK
+void
+operator delete[] (void* ptr) _NOEXCEPT
+{
+    ::operator delete(ptr);
+}
+
+_LIBCPP_WEAK
+void
+operator delete[] (void* ptr, const std::nothrow_t&) _NOEXCEPT
+{
+    ::operator delete[](ptr);
+}
+
+_LIBCPP_WEAK
+void
+operator delete[] (void* ptr, size_t) _NOEXCEPT
+{
+    ::operator delete[](ptr);
+}
+
+_LIBCPP_WEAK
 void *
 operator new(std::size_t size, std::align_val_t alignment) _THROW_BAD_ALLOC
 {
@@ -97,14 +185,14 @@

 _LIBCPP_WEAK
 void*
-operator new(size_t size, const std::nothrow_t&) _NOEXCEPT
+operator new(size_t size, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
 {
     void* p = 0;
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
 #endif  // _LIBCPP_NO_EXCEPTIONS
-        p = ::operator new(size);
+        p = ::operator new(size, alignment);
 #ifndef _LIBCPP_NO_EXCEPTIONS
     }
     catch (...)
@@ -116,14 +204,21 @@

 _LIBCPP_WEAK
 void*
-operator new(size_t size, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
+operator new[](size_t size, std::align_val_t alignment) _THROW_BAD_ALLOC
+{
+    return ::operator new(size, alignment);
+}
+
+_LIBCPP_WEAK
+void*
+operator new[](size_t size, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
 {
     void* p = 0;
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
 #endif  // _LIBCPP_NO_EXCEPTIONS
-        p = ::operator new(size, alignment);
+        p = ::operator new[](size, alignment);
 #ifndef _LIBCPP_NO_EXCEPTIONS
     }
     catch (...)
@@ -131,66 +226,6 @@
     }
 #endif  // _LIBCPP_NO_EXCEPTIONS
     return p;
-}
-
-_LIBCPP_WEAK
-void*
-operator new[](size_t size) _THROW_BAD_ALLOC
-{
-    return ::operator new(size);
-}
-
-_LIBCPP_WEAK
-void*
-operator new[](size_t size, std::align_val_t alignment) _THROW_BAD_ALLOC
-{
-    return ::operator new(size, alignment);
-}
-
-_LIBCPP_WEAK
-void*
-operator new[](size_t size, const std::nothrow_t&) _NOEXCEPT
-{
-    void* p = 0;
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    try
-    {
-#endif  // _LIBCPP_NO_EXCEPTIONS
-        p = ::operator new[](size);
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    }
-    catch (...)
-    {
-    }
-#endif  // _LIBCPP_NO_EXCEPTIONS
-    return p;
-}
-
-_LIBCPP_WEAK
-void*
-operator new[](size_t size, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
-{
-    void* p = 0;
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    try
-    {
-#endif  // _LIBCPP_NO_EXCEPTIONS
-        p = ::operator new[](size, alignment);
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    }
-    catch (...)
-    {
-    }
-#endif  // _LIBCPP_NO_EXCEPTIONS
-    return p;
-}
-
-_LIBCPP_WEAK
-void
-operator delete(void* ptr) _NOEXCEPT
-{
-    if (ptr)
-        ::free(ptr);
 }

 _LIBCPP_WEAK
@@ -207,13 +242,6 @@

 _LIBCPP_WEAK
 void
-operator delete(void* ptr, const std::nothrow_t&) _NOEXCEPT
-{
-    ::operator delete(ptr);
-}
-
-_LIBCPP_WEAK
-void
 operator delete(void* ptr, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
 {
     ::operator delete(ptr, alignment);
@@ -221,13 +249,6 @@

 _LIBCPP_WEAK
 void
-operator delete(void* ptr, size_t) _NOEXCEPT
-{
-    ::operator delete(ptr);
-}
-
-_LIBCPP_WEAK
-void
 operator delete(void* ptr, size_t, std::align_val_t alignment) _NOEXCEPT
 {
     ::operator delete(ptr, alignment);
@@ -235,13 +256,6 @@

 _LIBCPP_WEAK
 void
-operator delete[] (void* ptr) _NOEXCEPT
-{
-    ::operator delete(ptr);
-}
-
-_LIBCPP_WEAK
-void
 operator delete[] (void* ptr, std::align_val_t alignment) _NOEXCEPT
 {
     ::operator delete(ptr, alignment);
@@ -249,23 +263,9 @@

 _LIBCPP_WEAK
 void
-operator delete[] (void* ptr, const std::nothrow_t&) _NOEXCEPT
-{
-    ::operator delete[](ptr);
-}
-
-_LIBCPP_WEAK
-void
 operator delete[] (void* ptr, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
 {
     ::operator delete[](ptr, alignment);
-}
-
-_LIBCPP_WEAK
-void
-operator delete[] (void* ptr, size_t) _NOEXCEPT
-{
-    ::operator delete[](ptr);
 }

 _LIBCPP_WEAK


Function fix

Function fix

--- src/ntp.cpp
+++ src/ntp.cpp
@@ -1,4 +1,3 @@
-
 #ifdef WIN32
 #include <winsock2.h>
 #else
@@ -508,7 +507,7 @@
                 nNtpOffset = INT64_MAX;
                 int nSleepMinutes = 1 + GetRandInt(4); // Sleep for 1-5 minutes.
                 for (int i = 0; i < nSleepMinutes * 60 && !fShutdown; i++)
-                    Sleep(1000);
+                    sleep(1000);
                 continue;
             }
         }
@@ -526,7 +525,7 @@

         int nSleepHours = 1 + GetRandInt(5); // Sleep for 1-6 hours.
         for (int i = 0; i < nSleepHours * 3600 && !fShutdown; i++)
-            Sleep(1000);
+            sleep(1000);
     }

     vnThreadsRunning[THREAD_NTP]--;


use add request functions instead of duplicated code

--- src/motor_hardware.cc
+++ src/motor_hardware.cc
@@ -129,34 +129,8 @@
 	//requestVelocity();
 	//requestVersion();

-	MotorMessage left_odom;
-	left_odom.setRegister(MotorMessage::REG_LEFT_ODOM);
-	left_odom.setType(MotorMessage::TYPE_READ);
-	left_odom.setData(0);
-	commands.push_back(left_odom);
-
-	MotorMessage right_odom;
-	right_odom.setRegister(MotorMessage::REG_RIGHT_ODOM);
-	right_odom.setType(MotorMessage::TYPE_READ);
-	right_odom.setData(0);
-	commands.push_back(right_odom);
-
-
-
-
-	MotorMessage left_vel;
-	left_vel.setRegister(MotorMessage::REG_LEFT_SPEED_MEASURED);
-	left_vel.setType(MotorMessage::TYPE_READ);
-	left_vel.setData(0);
-	commands.push_back(left_vel);
-
-	MotorMessage right_vel;
-	right_vel.setRegister(MotorMessage::REG_RIGHT_SPEED_MEASURED);
-	right_vel.setType(MotorMessage::TYPE_READ);
-	right_vel.setData(0);
-	commands.push_back(right_vel);
-
-
+	_addOdometryRequest(commands);
+	_addVelocityRequest(commands);

 	MotorMessage left;
@@ -194,13 +168,11 @@
 	motor_serial_->transmitCommands(commands);
 }

-
 void MotorHardware::requestVelocity(){
 	std::vector<MotorMessage> commands;
 	_addVelocityRequest(commands);
 	motor_serial_->transmitCommands(commands);
 }
-

 void MotorHardware::setPid(int32_t p_set, int32_t i_set, int32_t d_set, int32_t denominator_set){
 	p_value = p_set;


Fixed up proto3_lite_unittest.cc

Fixed up proto3_lite_unittest.cc

--- src/google/protobuf/proto3_lite_unittest.cc
+++ src/google/protobuf/proto3_lite_unittest.cc
@@ -32,13 +32,13 @@
 #include <memory>
 #include <vector>

-#include <google/protobuf/unittest_proto3.pb.h>
+#include <google/protobuf/unittest_proto3_lite.pb.h>
 #include <google/protobuf/arena.h>
 #include <google/protobuf/testing/googletest.h>
 #include <gtest/gtest.h>

 namespace google {
-using proto3_unittest::TestAllTypes;
+using proto3_lite_unittest::TestAllTypes;

 namespace protobuf {
 namespace {
@@ -51,9 +51,9 @@
   m->mutable_optional_nested_message()->set_bb(42);
   m->mutable_optional_foreign_message()->set_c(43);
   m->set_optional_nested_enum(
-      proto3_unittest::TestAllTypes_NestedEnum_BAZ);
+      proto3_lite_unittest::TestAllTypes_NestedEnum_BAZ);
   m->set_optional_foreign_enum(
-      proto3_unittest::FOREIGN_BAZ);
+      proto3_lite_unittest::FOREIGN_BAZ);
   m->mutable_optional_lazy_message()->set_bb(45);
   m->add_repeated_int32(100);
   m->add_repeated_string("asdf");
@@ -61,9 +61,9 @@
   m->add_repeated_nested_message()->set_bb(46);
   m->add_repeated_foreign_message()->set_c(47);
   m->add_repeated_nested_enum(
-      proto3_unittest::TestAllTypes_NestedEnum_BAZ);
+      proto3_lite_unittest::TestAllTypes_NestedEnum_BAZ);
   m->add_repeated_foreign_enum(
-      proto3_unittest::FOREIGN_BAZ);
+      proto3_lite_unittest::FOREIGN_BAZ);
   m->add_repeated_lazy_message()->set_bb(49);

   m->set_oneof_uint32(1);
@@ -79,9 +79,9 @@
   EXPECT_EQ(42, m.optional_nested_message().bb());
   EXPECT_EQ(true, m.has_optional_foreign_message());
   EXPECT_EQ(43, m.optional_foreign_message().c());
-  EXPECT_EQ(proto3_unittest::TestAllTypes_NestedEnum_BAZ,
+  EXPECT_EQ(proto3_lite_unittest::TestAllTypes_NestedEnum_BAZ,
             m.optional_nested_enum());
-  EXPECT_EQ(proto3_unittest::FOREIGN_BAZ,
+  EXPECT_EQ(proto3_lite_unittest::FOREIGN_BAZ,
             m.optional_foreign_enum());
   EXPECT_EQ(true, m.has_optional_lazy_message());
   EXPECT_EQ(45, m.optional_lazy_message().bb());
@@ -97,15 +97,15 @@
   EXPECT_EQ(1, m.repeated_foreign_message_size());
   EXPECT_EQ(47, m.repeated_foreign_message(0).c());
   EXPECT_EQ(1, m.repeated_nested_enum_size());
-  EXPECT_EQ(proto3_unittest::TestAllTypes_NestedEnum_BAZ,
+  EXPECT_EQ(proto3_lite_unittest::TestAllTypes_NestedEnum_BAZ,
             m.repeated_nested_enum(0));
   EXPECT_EQ(1, m.repeated_foreign_enum_size());
-  EXPECT_EQ(proto3_unittest::FOREIGN_BAZ,
+  EXPECT_EQ(proto3_lite_unittest::FOREIGN_BAZ,
             m.repeated_foreign_enum(0));
   EXPECT_EQ(1, m.repeated_lazy_message_size());
   EXPECT_EQ(49, m.repeated_lazy_message(0).bb());

-  EXPECT_EQ(proto3_unittest::TestAllTypes::kOneofString,
+  EXPECT_EQ(proto3_lite_unittest::TestAllTypes::kOneofString,
             m.oneof_field_case());
   EXPECT_EQ("test", m.oneof_string());
 }


fix: Deselect TILE_HITBOX if the frame is not solid

--- src/gui/controllers/metasprite/selected.hpp
+++ src/gui/controllers/metasprite/selected.hpp
@@ -8,9 +8,20 @@
     : _controller(controller)
     , _type(SelectedType::NONE)
 {
+    _controller.frameController().signal_dataChanged().connect(
+        [this](void) {
+            // deselect TILE_HITBOX is frame is not solid
+            if (_type == SelectedType::TILE_HITBOX) {
+                auto& f = _controller.frameController().selected();
+                if (f.solid == false) {
+                    selectFrame();
+                }
+            }
+        });
+
     _controller.frameController().signal_mapChanged().connect(
         [this](void) {
-            if (_type == SelectedType::FRAME) {
+            if (_type == SelectedType::FRAME || _type == SelectedType::TILE_HITBOX) {
                 _signal_listChanged.emit();
             }
         });
@@ -120,14 +131,14 @@
 template <class T>
 void SelectedController<T>::selectTileHitbox()
 {
-    if (_controller.frameController().hasSelected()) {
+    if (_controller.frameController().selected().solid) {
         if (_type != SelectedType::TILE_HITBOX) {
             _type = SelectedType::TILE_HITBOX;
             _signal_selectedChanged.emit();
         }
     }
     else {
-        selectNone();
+        selectFrame();
     }
 }


Spread out extra spaghetti infill volume proportionally

CURA-3987

Apply the extra spaghetti infill volume proportional to the infill
volume of each step. This solves the problem that when stepping is
enabled, the extra volume is added to each step, which results in adding
way more volume than expected.

--- src/infill/SpaghettiInfillPathGenerator.cpp
+++ src/infill/SpaghettiInfillPathGenerator.cpp
@@ -20,6 +20,7 @@
     const int64_t infill_shift = 0;
     const int64_t outline_offset = 0;
     const double layer_height_mm = (layer_nr == 0)? mesh.getSettingInMillimeters("layer_height_0") : mesh.getSettingInMillimeters("layer_height");
+    const double default_spaghetti_infill_extra_volume = mesh.getSettingInCubicMillimeters("spaghetti_infill_extra_volume");

     // For each part on this layer which is used to fill that part and parts below:
     for (const std::pair<Polygons, double>& filling_area : part.spaghetti_infill_volumes)
@@ -28,7 +29,9 @@
         Polygons infill_polygons;

         const Polygons& area = filling_area.first; // Area of the top within which to move while extruding (might be empty if the spaghetti_inset was too large)
-        const double total_volume = filling_area.second * mesh.getSettingAsRatio("spaghetti_flow") + mesh.getSettingInCubicMillimeters("spaghetti_infill_extra_volume"); // volume to be extruded
+        // the extra infill volume will be spread out proportionally to each step
+        const double extra_infill_volume = filling_area.second / mesh.total_infill_volume_mm3 * default_spaghetti_infill_extra_volume;
+        const double total_volume = filling_area.second * mesh.getSettingAsRatio("spaghetti_flow") + extra_infill_volume; // volume to be extruded
         if (total_volume <= 0.0)
         {
             continue;


Fix possible memory leaks and crashes in new QDnsLookup based resolver

--- src/irisnet/corelib/netinterface_qtname.cpp
+++ src/irisnet/corelib/netinterface_qtname.cpp
@@ -40,6 +40,11 @@

 	}

+	~IrisQtName()
+	{
+		qDeleteAll(lookups);
+	}
+
 	bool supportsSingle() const
 	{
 		return true;
@@ -63,14 +68,16 @@
 		int id = currentId++;
 		lookup->setProperty("iid", id);
 		lookups.insert(id, lookup);
-		lookup->lookup();
+		QMetaObject::invokeMethod(lookup, "lookup", Qt::QueuedConnection);
 		return id;
 	}

 	void resolve_stop(int id)
 	{
-		QDnsLookup *lookup = lookups.take(id);
-		lookup->abort();
+		QDnsLookup *lookup = lookups.value(id);
+		if (lookup) {
+			lookup->abort(); // handleLookup will catch it and delete
+		}
 	}

 private slots:
@@ -97,7 +104,10 @@
 					e = XMPP::NameResolver::ErrorGeneric;
 					break;
 			}
-			emit resolve_error(id, e);
+			if (lookup->error() != QDnsLookup::OperationCancelledError) { // don't report after resolve_stop()
+				emit resolve_error(id, e);
+			}
+			lookup->deleteLater();
 			return;
 		}


ngx_base_fetch: fix extra chunks and race condition

We were sometimes failing to set last_buf when we should, but being protected
from the consequences by another bug that made us usually send additional extra
buffers with last_buf set.

See discussion in #78, pull request was #94.

--- src/ngx_base_fetch.cc
+++ src/ngx_base_fetch.cc
@@ -68,7 +68,7 @@
 void NgxBaseFetch::CopyHeadersFromTable(ngx_list_t* headers_from,
                                         HeadersT* headers_to) {
   // http_version is the version number of protocol; 1.1 = 1001. See
-  // NGX_HTTP_VERSION_* in ngx_http_request.h
+  // NGX_HTTP_VERSION_* in ngx_http_request.h
   headers_to->set_major_version(request_->http_version / 1000);
   headers_to->set_minor_version(request_->http_version % 1000);

@@ -104,8 +104,9 @@
 }

 ngx_int_t NgxBaseFetch::CopyBufferToNginx(ngx_chain_t** link_ptr) {
-  // TODO(jefftk): if done_called_ && last_buf_sent_, should we just short
-  // circuit (return NGX_OK) here?
+  if (done_called_ && last_buf_sent_) {
+    return NGX_DECLINED;
+  }

   int rc = ngx_psol::string_piece_to_buffer_chain(
       request_->pool, buffer_, link_ptr, done_called_ /* send_last_buf */);
@@ -248,7 +249,12 @@
 }

 void NgxBaseFetch::HandleDone(bool success) {
+  // TODO(jefftk): it's possible that instead of locking here we can just modify
+  // CopyBufferToNginx to only read done_called_ once.
+  Lock();
   done_called_ = true;
+  Unlock();
+
   close(pipe_fd_);  // Indicates to nginx that we're done with the rewrite.
   pipe_fd_ = -1;
 }


Re-enable debugging

Re-enable debugging

--- src/nomlib_config.hpp
+++ src/nomlib_config.hpp
@@ -45,7 +45,7 @@
 // nomlib debugging

 // Standard debug level; logging of warnings & errors
-//#define NOMLIB_DEBUG
+#define NOMLIB_DEBUG

 // Internal development; logging of class object construction and destruction
 #define NOMLIB_DEBUG_ALL


use configuration for up/down

use configuration for up/down

git-svn-id: 39e099a8ed5324aded674b764a67f7a08796d9a7@311 662fdd30-d327-0410-a531-f549c87e1e9e

--- src/object/player.cpp
+++ src/object/player.cpp
@@ -820,10 +820,10 @@
 		}
 		*/

-		if ( keyboard[ Keyboard::Key_UP ] ){
+		if ( keyboard[ getKey( PAIN_KEY_UP ) ] ){
 			// setZ( getZ() - 1);
 			moveZ( -getSpeed() );
-		} else if ( keyboard[ Keyboard::Key_DOWN ] ){
+		} else if ( keyboard[ getKey( PAIN_KEY_DOWN ) ] ){
 			// setZ( getZ() + 1 );
 			moveZ( getSpeed() );
 		}