Fix read multiple attributes from Window Covering Cluster

--- window_covering.cpp
+++ window_covering.cpp
@@ -120,7 +120,6 @@
     {
     	while(!stream.atEnd())
     	{
-
     		stream >> attrid;
     		if (isReadAttr)
     		{
@@ -137,83 +136,87 @@
     		{
     			stream >> attrValue;
     		}
+    		// only read 16-bit values, i.e. attrTypeId 0x21,0x31,0x09,0x19,0x29
+    		else if ( ((attrTypeId >> 4) <= 0x03 && (attrTypeId & 0x0F) == 0x01) || // 0x21,0x31
+    		          ((attrTypeId >> 4) <= 0x02 && (attrTypeId & 0x0F) == 0x09))   // 0x09,0x19,0x29
+    		{
+    			quint16 attrVal16;
+    			stream >> attrVal16;
+    		}
     		else
     		{
     			return;
     		}

-
-    		break;
-    	}
-
-    	NodeValue::UpdateType updateType = NodeValue::UpdateByZclReport;
-
-    	if (attrid == 0x0008) // current CurrentPositionLiftPercentage 0-100
-    	{
-            if (lightNode->modelId().startsWith(QLatin1String("lumi.curtain")))
-            {
-                attrValue = 100 - attrValue;
-            }
-        	uint8_t level = attrValue * 255 / 100;
-    		numericValue.u8 = level;
-    		ResourceItem *item = lightNode->item(RStateBri);
-    		if (item && item->toNumber() != level)
+    		NodeValue::UpdateType updateType = NodeValue::UpdateByZclReport;
+
+    		if (attrid == 0x0008) // current CurrentPositionLiftPercentage 0-100
     		{
-    			DBG_Printf(DBG_INFO, "0x%016llX level %u --> %u\n", lightNode->address().ext(), (uint)item->toNumber(), level);
-    			lightNode->clearRead(READ_LEVEL);
-    			item->setValue(level);
-    			Event e(RLights, RStateBri, lightNode->id(), item);
-    			enqueueEvent(e);
-    			updated = true;
-
-    			// also change on-state if bri changes to/from 0
-    			bool on = (attrValue > 0 ? true : false) ;
-    			ResourceItem *itemOn = lightNode->item(RStateOn);
-    			if (itemOn && itemOn->toBool() != on)
+    			if (lightNode->modelId().startsWith(QLatin1String("lumi.curtain")))
     			{
-    				DBG_Printf(DBG_INFO, "0x%016llX onOff %u --> %u\n", lightNode->address().ext(), (uint)item->toNumber(), on);
-    				itemOn->setValue(on);
-    				Event e(RLights, RStateOn, lightNode->id(), itemOn);
+    				attrValue = 100 - attrValue;
+    			}
+    			uint8_t level = attrValue * 255 / 100;
+    			numericValue.u8 = level;
+    			ResourceItem *item = lightNode->item(RStateBri);
+    			if (item && item->toNumber() != level)
+    			{
+    				DBG_Printf(DBG_INFO, "0x%016llX level %u --> %u\n", lightNode->address().ext(), (uint)item->toNumber(), level);
+    				lightNode->clearRead(READ_LEVEL);
+    				item->setValue(level);
+    				Event e(RLights, RStateBri, lightNode->id(), item);
+    				enqueueEvent(e);
+    				updated = true;
+
+    				// also change on-state if bri changes to/from 0
+    				bool on = (attrValue > 0 ? true : false) ;
+    				ResourceItem *itemOn = lightNode->item(RStateOn);
+    				if (itemOn && itemOn->toBool() != on)
+    				{
+    					DBG_Printf(DBG_INFO, "0x%016llX onOff %u --> %u\n", lightNode->address().ext(), (uint)item->toNumber(), on);
+    					itemOn->setValue(on);
+    					Event e(RLights, RStateOn, lightNode->id(), itemOn);
+    					enqueueEvent(e);
+    					updated = true;
+    				}
+    			}
+    			lightNode->setZclValue(updateType, WINDOW_COVERING_CLUSTER_ID, 0x0008, numericValue);
+    		}
+    		else if (attrid == 0x0009) // current CurrentPositionTiltPercentage 0-100
+    		{
+    			uint8_t sat = attrValue * 255 / 100;
+    			numericValue.u8 = sat;
+    			ResourceItem *item = lightNode->item(RStateSat);
+    			if (item && item->toNumber() != sat)
+    			{
+    				item->setValue(sat);
+    				Event e(RLights, RStateSat, lightNode->id(), item);
     				enqueueEvent(e);
     				updated = true;
     			}
+    			lightNode->setZclValue(updateType, WINDOW_COVERING_CLUSTER_ID, 0x0009, numericValue);
     		}
-    		lightNode->setZclValue(updateType, WINDOW_COVERING_CLUSTER_ID, 0x0008, numericValue);
-    	}
-    	else if (attrid == 0x0009) // current CurrentPositionTiltPercentage 0-100
-    	{
-    		uint8_t sat = attrValue * 255 / 100;
-    		numericValue.u8 = sat;
-    		ResourceItem *item = lightNode->item(RStateSat);
-    		if (item && item->toNumber() != sat)
+    		else if (attrid == 0x000A)  // read attribute 0x000A OperationalStatus
     		{
-    			item->setValue(sat);
-    			Event e(RLights, RStateSat, lightNode->id(), item);
-    			enqueueEvent(e);
-    			updated = true;
+    			if (calibrationStep != 0 && ind.srcAddress().ext() == calibrationTask.req.dstAddress().ext())
+    			{
+    				operationalStatus = attrValue;
+    			}
     		}
-    		lightNode->setZclValue(updateType, WINDOW_COVERING_CLUSTER_ID, 0x0009, numericValue);
-    	}
-    	else if (attrid == 0x000A)  // read attribute 0x000A OperationalStatus
-    	{
-    		if (calibrationStep != 0 && ind.srcAddress().ext() == calibrationTask.req.dstAddress().ext())
+    		else if (attrid == 0x0000)  // read attribute 0x0000 WindowConveringType
     		{
-    			operationalStatus = attrValue;
-    		}
-    	}
-    	else if (attrid == 0x0000)  // read attribute 0x0000 WindowConveringType
-    	{
-    		Sensor *sensor = getSensorNodeForAddressAndEndpoint(ind.srcAddress(), 0x02);
-    		if (sensor)
-    		{
-    			ResourceItem *item = 0;
-
-    			item = sensor->item(RConfigWindowCoveringType);
-    			if (item)
+    			Sensor *sensor = getSensorNodeForAddressAndEndpoint(ind.srcAddress(), 0x02);
+    			if (sensor)
     			{
-    				item->setValue(attrValue);
-    		        sensor->setNeedSaveDatabase(true);
-    		        queSaveDb(DB_SENSORS, DB_SHORT_SAVE_DELAY);
+    				ResourceItem *item = nullptr;
+
+    				item = sensor->item(RConfigWindowCoveringType);
+    				if (item)
+    				{
+    					item->setValue(attrValue);
+    					sensor->setNeedSaveDatabase(true);
+    					queSaveDb(DB_SENSORS, DB_SHORT_SAVE_DELAY);
+    				}
     			}
     		}
     	}


update

update

--- src/saf.cc
+++ src/saf.cc
@@ -61,9 +61,5 @@
     sleep(2);
   }
   //  ProfilerStop();
-  char msg[100] = {'\0'};
-  snprintf(msg, sizeof(msg), "total send:%lld\n", server.send_data);
-  perror(msg);
-  sleep(2);
   return 0;
 }


OOps. SOrry. 10l

OOps. SOrry. 10l

--- modules/gui/qt4/components/simple_preferences.cpp
+++ modules/gui/qt4/components/simple_preferences.cpp
@@ -645,7 +645,7 @@
                 CaC( "dvdnav-caching" );
             CaC( "tcp-caching" ); CaC( "vcd-caching" );
             CaC( "fake-caching" ); CaC( "cdda-caching" ); CaC( "file-caching" );
-            CaC( "screen-caching" ); Cac( "bd-caching" );
+            CaC( "screen-caching" ); CaC( "bd-caching" );
             CaCi( "rtsp-caching", 2 ); CaCi( "ftp-caching", 2 );
             CaCi( "http-caching", 2 );
             if (module_exists ("access_realrtsp" ))


Double-check link status after signal comes through

--- src/Vehicle/Vehicle.cc
+++ src/Vehicle/Vehicle.cc
@@ -449,6 +449,11 @@

 void Vehicle::_sendMessageOnLink(LinkInterface* link, mavlink_message_t message)
 {
+    // Make sure this is still a good link
+    if (!link || !_links.contains(link) || !link->isConnected()) {
+        return;
+    }
+
     // Give the plugin a chance to adjust
     _firmwarePlugin->adjustMavlinkMessage(this, &message);


pmmgr: use pmSortInstances() instead of same thing open-coded locally

--- src/pmmgr/pmmgr.cxx
+++ src/pmmgr/pmmgr.cxx
@@ -91,13 +91,6 @@
 }

-extern "C" int
-pmValue_compare (const void* a, const void* b)
-{
-  return ((pmValue *)a)->inst - ((pmValue *)b)->inst;
-}
-
-
 extern "C" void *
 pmmgr_daemon_poll_thread (void* a)
 {
@@ -257,15 +250,12 @@
         continue;
       // NB: after this point, 'continue' must also pmFreeResult(r)

+      // in-place sort value list by indom number
+      pmSortInstances(r);
+
       // only vset[0] will be set, for csb->pmid
       if (r->vset[0]->numval > 0)
         {
-          // in-place sort value list by indom number
-          qsort (r->vset[0]->vlist,
-                 (size_t) r->vset[0]->numval,
-                 sizeof(pmValue),
-                 pmValue_compare);
-
           for (int j=0; j<r->vset[0]->numval; j++) // iterate over instances
             {
               // fetch the string value


httpserver: use own HTTP status codes

httpserver: use own HTTP status codes

Summary:
Before, macros defined in `<event2/http.h>` have been used
for some HTTP status codes.
`<event2/http.h>` is included implicitly and the usage
of its status code macros is inconsistent with the majority
HTTP response implementations in this file.

Now, the `HTTPStatusCode` enum from `<rpc/protocol.h>` is
consistently used for all HTTP response implementations.

This is a backport of Core [[https://github.com/bitcoin/bitcoin/pull/18168 | PR18168]]

Test Plan: `ninja all check-all`

Reviewers: #bitcoin_abc, majcosta

Reviewed By: #bitcoin_abc, majcosta

Differential Revision: https://reviews.bitcoinabc.org/D8779

--- src/httpserver.cpp
+++ src/httpserver.cpp
@@ -249,7 +249,7 @@
         LogPrint(BCLog::HTTP,
                  "HTTP request from %s rejected: Unknown HTTP request method\n",
                  hreq->GetPeer().ToString());
-        hreq->WriteReply(HTTP_BADMETHOD);
+        hreq->WriteReply(HTTP_BAD_METHOD);
         return;
     }

@@ -288,10 +288,11 @@
             LogPrintf("WARNING: request rejected because http work queue depth "
                       "exceeded, it can be increased with the -rpcworkqueue= "
                       "setting\n");
-            item->req->WriteReply(HTTP_INTERNAL, "Work queue depth exceeded");
+            item->req->WriteReply(HTTP_INTERNAL_SERVER_ERROR,
+                                  "Work queue depth exceeded");
         }
     } else {
-        hreq->WriteReply(HTTP_NOTFOUND);
+        hreq->WriteReply(HTTP_NOT_FOUND);
     }
 }

@@ -554,7 +555,7 @@
     if (!replySent) {
         // Keep track of whether reply was sent to avoid request leaks
         LogPrintf("%s: Unhandled request\n", __func__);
-        WriteReply(HTTP_INTERNAL, "Unhandled request");
+        WriteReply(HTTP_INTERNAL_SERVER_ERROR, "Unhandled request");
     }
     // evhttpd cleans up the request, as long as a reply was sent.
 }


thd->query assignment moved out of lock scope

--- sql/log_event.cc
+++ sql/log_event.cc
@@ -1826,8 +1826,8 @@
     thd->set_time((time_t)when);
     thd->current_tablenr = 0;
     thd->query_length= q_len;
+    thd->query= (char *) query;
     VOID(pthread_mutex_lock(&LOCK_thread_count));
-    thd->query = (char*)query;
     thd->query_id = query_id++;
     VOID(pthread_mutex_unlock(&LOCK_thread_count));
     thd->query_error = 0;			// clear error


Add missing includes

Add missing includes

--- src/sdl.cc
+++ src/sdl.cc
@@ -4,6 +4,8 @@
 #endif

 #include "SDL.h"
+#include "sdl.h"
+#include <v8.h>

 using namespace v8;


http: Join worker threads before deleting work queue

This prevents a potential race condition if control flow ends up in
`ShutdownHTTPServer` before the thread gets to `queue->Run()`,
deleting the work queue while workers are still going to use it.

Meant to fix #12362.

Signed-off-by: Wladimir J. van der Laan <bbc07dc96bb50bf6868a2ddfc4dae14fbed703d9@gmail.com>
Github-Pull: #12366
Rebased-From: b1c2370dde9ade180c638e5d9a4797f085322b5b
Tree-SHA512: 7fbe8e562ba0e1138f95deb42e84cda734bef0d7058349728b3e1602b9f65777c5b1be0f6bd5a7e513ac38487dc82e62fd0a6ee4ed985cbf36c90a7eec18eced

--- src/httpserver.cpp
+++ src/httpserver.cpp
@@ -449,6 +449,7 @@

 std::thread threadHTTP;
 std::future<bool> threadResult;
+static std::vector<std::thread> g_thread_http_workers;

 bool StartHTTPServer()
 {
@@ -460,8 +461,7 @@
     threadHTTP = std::thread(std::move(task), eventBase, eventHTTP);

     for (int i = 0; i < rpcThreads; i++) {
-        std::thread rpc_worker(HTTPWorkQueueRun, workQueue);
-        rpc_worker.detach();
+        g_thread_http_workers.emplace_back(HTTPWorkQueueRun, workQueue);
     }
     return true;
 }
@@ -487,6 +487,10 @@
     if (workQueue) {
         LogPrint(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n");
         workQueue->WaitExit();
+        for (auto& thread: g_thread_http_workers) {
+            thread.join();
+        }
+        g_thread_http_workers.clear();
         delete workQueue;
         workQueue = nullptr;
     }


Fix preprocessor syntax error.

Fix preprocessor syntax error.

--- Simbody/Visualizer/src/VisualizerProtocol.cpp
+++ Simbody/Visualizer/src/VisualizerProtocol.cpp
@@ -238,9 +238,9 @@
             Pathname::getEnvironmentVariable("SIMBODY_VISUALIZER_NAME");
     } else {
         vizExecutableName = "simbody-visualizer";
-#ifndef NDEBUG
-        vizExecutableName += "_d";
-#endif;
+        #ifndef NDEBUG
+            vizExecutableName += "_d";
+        #endif
     }

     Array_<String> actualSearchPath;


vogleditor: Fix crash when closing settings dialog due to accessing a deleted object.

--- src/vogleditor/vogleditor_qsettingsdialog.cpp
+++ src/vogleditor/vogleditor_qsettingsdialog.cpp
@@ -111,9 +111,8 @@

 vogleditor_QSettingsDialog::~vogleditor_QSettingsDialog()
 {
+    clearLayout(ui->verticalLayout_tabGroups);
     delete ui;
-    clearLayout(ui->verticalLayout_tabGroups);
-
 } // destructor

 void vogleditor_QSettingsDialog::clearLayout(QLayout *layout)


refactor: Enable -Wswitch for FeeEstimateHorizon

--- src/policy/fees.cpp
+++ src/policy/fees.cpp
@@ -12,21 +12,18 @@
 #include <txmempool.h>
 #include <util/system.h>

-static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
+static const char* FEE_ESTIMATES_FILENAME = "fee_estimates.dat";

 static constexpr double INF_FEERATE = 1e99;

-std::string StringForFeeEstimateHorizon(FeeEstimateHorizon horizon) {
-    static const std::map<FeeEstimateHorizon, std::string> horizon_strings = {
-        {FeeEstimateHorizon::SHORT_HALFLIFE, "short"},
-        {FeeEstimateHorizon::MED_HALFLIFE, "medium"},
-        {FeeEstimateHorizon::LONG_HALFLIFE, "long"},
-    };
-    auto horizon_string = horizon_strings.find(horizon);
-
-    if (horizon_string == horizon_strings.end()) return "unknown";
-
-    return horizon_string->second;
+std::string StringForFeeEstimateHorizon(FeeEstimateHorizon horizon)
+{
+    switch (horizon) {
+    case FeeEstimateHorizon::SHORT_HALFLIFE: return "short";
+    case FeeEstimateHorizon::MED_HALFLIFE: return "medium";
+    case FeeEstimateHorizon::LONG_HALFLIFE: return "long";
+    } // no default case, so the compiler can warn about missing cases
+    assert(false);
 }

 /**
@@ -644,7 +641,7 @@

 CFeeRate CBlockPolicyEstimator::estimateRawFee(int confTarget, double successThreshold, FeeEstimateHorizon horizon, EstimationResult* result) const
 {
-    TxConfirmStats* stats;
+    TxConfirmStats* stats = nullptr;
     double sufficientTxs = SUFFICIENT_FEETXS;
     switch (horizon) {
     case FeeEstimateHorizon::SHORT_HALFLIFE: {
@@ -660,10 +657,8 @@
         stats = longStats.get();
         break;
     }
-    default: {
-        throw std::out_of_range("CBlockPolicyEstimator::estimateRawFee unknown FeeEstimateHorizon");
-    }
-    }
+    } // no default case, so the compiler can warn about missing cases
+    assert(stats);

     LOCK(m_cs_fee_estimator);
     // Return failure if trying to analyze a target we're not tracking
@@ -693,10 +688,8 @@
     case FeeEstimateHorizon::LONG_HALFLIFE: {
         return longStats->GetMaxConfirms();
     }
-    default: {
-        throw std::out_of_range("CBlockPolicyEstimator::HighestTargetTracked unknown FeeEstimateHorizon");
-    }
-    }
+    } // no default case, so the compiler can warn about missing cases
+    assert(false);
 }

 unsigned int CBlockPolicyEstimator::BlockSpan() const


Perception: consolidate lane_sample

Perception: consolidate lane_sample

--- modules/perception/inference/tools/lane_sample.cc
+++ modules/perception/inference/tools/lane_sample.cc
@@ -35,7 +35,6 @@

 int main(int argc, char **argv) {
   google::ParseCommandLineFlags(&argc, &argv, true);
-  std::vector<float> output_data_vec1;
   std::vector<cv::Scalar> color_table;
   color_table.push_back(cv::Scalar(0, 97, 255));    // for other >0 mask values
   color_table.push_back(cv::Scalar(0, 0, 255));     // for mask value = 1
@@ -61,7 +60,7 @@

   apollo::perception::inference::load_data<std::string>(FLAGS_names_file,
                                                         &outputs);
-  for (auto name : outputs) {
+  for (auto &name : outputs) {
     ADEBUG << name;
   }

@@ -90,7 +89,8 @@
                                                         &image_lists);
   std::vector<float> output_data_vec;

-  for (auto image_file : image_lists) {
+  const int count = width * height;
+  for (auto &image_file : image_lists) {
     cv::Mat img =
         cv::imread(FLAGS_image_root + image_file + FLAGS_image_ext, CV_8UC1);
     ADEBUG << img.channels();
@@ -99,9 +99,8 @@
     img_roi.copyTo(img);
     cv::resize(img, img, cv::Size(width, height));

-    const int count = 1 * width * height;
     std::vector<float> input(count);
-    for (int i = 0; i < count; i++) {
+    for (int i = 0; i < count; ++i) {
       input[i] = static_cast<float>(img.data[i] - 128) * 0.0078125f;
     }
     cudaMemcpy(input_blob->mutable_gpu_data(), &input[0], count * sizeof(float),
@@ -110,7 +109,7 @@
     rt_net->Infer();
     cudaDeviceSynchronize();

-    for (auto output_name : outputs) {
+    for (auto &output_name : outputs) {
       auto blob = rt_net->get_blob(output_name);
       std::vector<float> tmp_vec(blob->cpu_data(),
                                  blob->cpu_data() + blob->count());


More status-es in qstatusbar

More status-es in qstatusbar

--- src/DGLGui/dglcontoller.cpp
+++ src/DGLGui/dglcontoller.cpp
@@ -147,6 +147,7 @@
     m_Connected = false;
     m_NotifierRead.reset();
     m_NotifierWrite.reset();
+    newStatus("Disconnected.");
 }

 bool DglController::isConnected() {
@@ -177,6 +178,7 @@
     assert(isConnected());
     dglnet::ContinueBreakMessage message(true);
     m_DglClient->sendMessage(&message);
+    newStatus("Interrupting...");
 }

 void DglController::debugStep() {
@@ -185,6 +187,7 @@
     assert(isConnected());
     dglnet::ContinueBreakMessage message(dglnet::ContinueBreakMessage::STEP_CALL);
     m_DglClient->sendMessage(&message);
+    newStatus("Running...");
 }

 void DglController::debugStepDrawCall() {
@@ -193,6 +196,7 @@
     assert(isConnected());
     dglnet::ContinueBreakMessage message(dglnet::ContinueBreakMessage::STEP_DRAW_CALL);
     m_DglClient->sendMessage(&message);
+    newStatus("Running...");
 }

 void DglController::debugStepFrame() {
@@ -201,6 +205,7 @@
     assert(isConnected());
     dglnet::ContinueBreakMessage message(dglnet::ContinueBreakMessage::STEP_FRAME);
     m_DglClient->sendMessage(&message);
+    newStatus("Running...");
 }

 void DglController::onSetStatus(std::string str) {
@@ -238,6 +243,7 @@

     m_ResourceManager.emitQueries();

+    newStatus("Breaked execution.");
 }

 void DglController::doHandle(const dglnet::CallTraceMessage& msg) {


Backport of the fix for bug#25421 to 5.0.

Calculating the estimated number of records for a range scan
may take a significant time, and it was impossible for a user
to interrupt that process by killing the connection or the
query.

Fixed by checking the thread's 'killed' status in
check_quick_keys() and interrupting the calculation process if
it is set to a non-zero value.

--- sql/opt_range.cc
+++ sql/opt_range.cc
@@ -6066,6 +6066,9 @@
     tmp_max_flag=max_key_flag | key_tree->max_flag;
   }

+  if (unlikely(param->thd->killed != 0))
+    return HA_POS_ERROR;
+
   keynr=param->real_keynr[idx];
   param->range_count++;
   if (!tmp_min_flag && ! tmp_max_flag &&


Avoid a compile error on hosts with libevent too old for EVENT_LOG_WARN.

This uses _EVENT_LOG_WARN instead, which appears to be defined in the
 old versions of libevent that I have on some systems.

--- src/httpserver.cpp
+++ src/httpserver.cpp
@@ -365,6 +365,10 @@
 /** libevent event log callback */
 static void libevent_log_cb(int severity, const char *msg)
 {
+#ifndef EVENT_LOG_WARN
+// EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed.
+# define EVENT_LOG_WARN _EVENT_LOG_WARN
+#endif
     if (severity >= EVENT_LOG_WARN) // Log warn messages and higher without debug category
         LogPrintf("libevent: %s\n", msg);
     else


Fixed rotation output.

Fixed rotation output.

--- Source/DTrackPlugin/Private/FDTrackPlugin.cpp
+++ Source/DTrackPlugin/Private/FDTrackPlugin.cpp
@@ -107,7 +107,7 @@
 			break;
 	}

-	return r_adapted.Rotator();
+	return r_adapted.GetTransposed().Rotator();
 }

 std::string to_string(const FString &n_string) {
@@ -123,7 +123,7 @@
 	m_trafo_normal.M[0][0] = 0; m_trafo_normal.M[0][1] = 1; m_trafo_normal.M[0][2] = 0; m_trafo_normal.M[0][3] = 0;
 	m_trafo_normal.M[1][0] = 1; m_trafo_normal.M[1][1] = 0; m_trafo_normal.M[1][2] = 0; m_trafo_normal.M[1][3] = 0;
 	m_trafo_normal.M[2][0] = 0; m_trafo_normal.M[2][1] = 0; m_trafo_normal.M[2][2] = 1; m_trafo_normal.M[2][3] = 0;
-	m_trafo_normal.M[3][0] = 0; m_trafo_normal.M[3][1] = 0; m_trafo_normal.M[3][2] = 0; m_trafo_normal.M[3][3] = -1;
+	m_trafo_normal.M[3][0] = 0; m_trafo_normal.M[3][1] = 0; m_trafo_normal.M[3][2] = 0; m_trafo_normal.M[3][3] = 1;

 	// transposed is cached
 	m_trafo_normal_transposed = m_trafo_normal.GetTransposed();


Detect ICE header, handle ICE-style If statements

--- src/TypeHandlers/TH_Tokenized.cpp
+++ src/TypeHandlers/TH_Tokenized.cpp
@@ -148,8 +148,12 @@
         if (has_option(options, "lang"))
         {
             lang = options.at("lang");
+        } else if (str_orig.size() > 1 && str_orig[0] == '.' && (str_orig[1] == '.' || ::isalpha(str_orig[1]))) {
+            lang = PRGMLANG_AXE;
+        } else if (str_orig.size() > 0 && str_orig[0] == '\uf02f') {
+            lang = PRGMLANG_ICE;
         } else {
-            lang = (str_orig.size() > 1 && str_orig[0] == '.' && (str_orig[1] == '.' || ::isalpha(str_orig[1]))) ? PRGMLANG_AXE : PRGMLANG_BASIC;
+            lang = PRGMLANG_BASIC;
         }

         std::string str(str_orig);
@@ -220,7 +224,7 @@
             {
                 line.first--;
             }
-            if (nextIndent > 0 && (is_in_vector(closingTokens, firstCommand) || (oldFirstCommand == "If" && firstCommand != "Then" && lang != PRGMLANG_AXE)))
+            if (nextIndent > 0 && (is_in_vector(closingTokens, firstCommand) || (oldFirstCommand == "If" && firstCommand != "Then" && lang != PRGMLANG_AXE && lang != PRGMLANG_ICE)))
             {
                 nextIndent--;
             }


corrected case

corrected case

--- src/slowhttptest.cc
+++ src/slowhttptest.cc
@@ -292,7 +292,7 @@
   }
   // Content-type
   if(content_type != 0 && strlen(content_type)) {
-    content_type_.append("Content-type: ");
+    content_type_.append("Content-Type: ");
     content_type_.append(content_type);
     content_type_.append(crlf);
   } else {


Windows: build fix

Windows: build fix

--- src/ppk_modules.cpp
+++ src/ppk_modules.cpp
@@ -55,10 +55,10 @@
 		//char dir_path[2048];
 		//unsigned int len=GetEnvironmentVariableA("ppasskeeperMods", dir_path, (DWORD)sizeof(dir_path));
 		char dir_path[512];
-		getRegistryValue("mods_path", tmpBuf, sizeof(tmpBuf));
+		getRegistryValue("mods_path", dir_path, sizeof(dir_path));
 		std::string dirpath=dir_path;

-		debug("--------------- <PPassKeeper> ---------------\nIf you don't want to see theses messages, recompile ppasskeeper with the cmake switch '-DPPK_DEBUG=OFF'\n")
+		debug("--------------- <PPassKeeper> ---------------\nIf you don't want to see theses messages, recompile ppasskeeper with the cmake switch '-DPPK_DEBUG=OFF'\n");

 		hSearch = FindFirstFile((dirpath+"\\*.dll").c_str(), &File);
 		if (hSearch != INVALID_HANDLE_VALUE)


Implement version of lowercase that only check a to z, instead of all characters, and don't rely on functionality provided in the transcoders.

git-svn-id: 3ec853389310512053d525963cab269c063bb453@176372 13f79535-47bb-0310-9956-ffa450edef68

--- src/xercesc/dom/impl/DOMConfigurationImpl.cpp
+++ src/xercesc/dom/impl/DOMConfigurationImpl.cpp
@@ -131,7 +131,7 @@
     XMLCh* lowerCaseName = XMLString::replicate(name, fMemoryManager);
     ArrayJanitor<XMLCh> janName(lowerCaseName, fMemoryManager);

-    XMLString::lowerCase(lowerCaseName);
+    XMLString::lowerCaseASCII(lowerCaseName);

     DOMConfigurationFeature whichFlag;
     try {


- fixed newly added DBUG_RETURN to DBUG_VOID_RETURN (compile failed with    "DBUG_RETURN undeclared" on Mac OS X)

--- sql/sql_class.cc
+++ sql/sql_class.cc
@@ -426,7 +426,7 @@
     vio_close(active_vio);
     active_vio = 0;
   }
-  DBUG_RETURN;
+  DBUG_VOID_RETURN;
 }
 #endif


Trimming of embedded library code

Trimming of embedded library code

sql/sql_parse.cc:
  It's better to check for HAVE_REPLICATION here instead of EMBEDDED_LIBRARY

--- sql/sql_parse.cc
+++ sql/sql_parse.cc
@@ -1155,7 +1155,7 @@
       mysql_log.write(thd,command,"%s",thd->db);
     break;
   }
-#ifndef EMBEDDED_LIBRARY
+#ifdef HAVE_REPLICATION
   case COM_REGISTER_SLAVE:
   {
     if (!register_slave(thd, (uchar*)packet, packet_length))
@@ -1661,7 +1661,7 @@
     }
 #endif
   }
-#endif /* EMBEDDED_LIBRARY */
+#endif /* !EMBEDDED_LIBRARY */
   /*
     TODO: make derived tables processing 'inside' SELECT processing.
     TODO: solve problem with depended derived tables in subselects
@@ -1837,7 +1837,7 @@
     break;
   }

-#ifndef EMBEDDED_LIBRARY
+#ifdef HAVE_REPLICATION
   case SQLCOM_SHOW_SLAVE_HOSTS:
   {
     if (check_global_access(thd, REPL_SLAVE_ACL))
@@ -1883,7 +1883,7 @@
   }

-#ifndef EMBEDDED_LIBRARY
+#ifdef HAVE_REPLICATION
   case SQLCOM_CHANGE_MASTER:
   {
     if (check_global_access(thd, SUPER_ACL))
@@ -1920,7 +1920,7 @@
     else
       res = load_master_data(thd);
     break;
-#endif /* EMBEDDED_LIBRARY */
+#endif /* HAVE_REPLICATION */

 #ifdef HAVE_INNOBASE_DB
   case SQLCOM_SHOW_INNODB_STATUS:
@@ -1932,7 +1932,7 @@
     }
 #endif

-#ifndef EMBEDDED_LIBRARY
+#ifdef HAVE_REPLICATION
   case SQLCOM_LOAD_MASTER_TABLE:
   {
     if (!tables->db)
@@ -1964,7 +1964,7 @@
     UNLOCK_ACTIVE_MI;
     break;
   }
-#endif /* EMBEDDED_LIBRARY */
+#endif /* HAVE_REPLICATION */

   case SQLCOM_CREATE_TABLE:
   {
@@ -2081,7 +2081,7 @@
       res = mysql_create_index(thd, tables, lex->key_list);
     break;

-#ifndef EMBEDDED_LIBRARY
+#ifdef HAVE_REPLICATION
   case SQLCOM_SLAVE_START:
   {
     LOCK_ACTIVE_MI;
@@ -2114,7 +2114,7 @@
     UNLOCK_ACTIVE_MI;
     break;
   }
-#endif
+#endif /* HAVE_REPLICATION */

   case SQLCOM_ALTER_TABLE:
 #if defined(DONT_ALLOW_SHOW_COMMANDS)
@@ -4376,7 +4376,7 @@
     refresh_status();
   if (options & REFRESH_THREADS)
     flush_thread_cache();
-#ifndef EMBEDDED_LIBRARY
+#ifdef HAVE_REPLICATION
   if (options & REFRESH_MASTER)
   {
     tmp_write_to_binlog= 0;
@@ -4391,7 +4391,7 @@
        result=load_des_key_file(des_key_file);
    }
 #endif
-#ifndef EMBEDDED_LIBRARY
+#ifdef HAVE_REPLICATION
  if (options & REFRESH_SLAVE)
  {
    tmp_write_to_binlog= 0;


Removed the forkedProcessReady event.

Removed the forkedProcessReady event.

The event was used to wait for the child process to map the memory, but it's
not required since the memory is already VirtualProtect(ed).

--- src/Win32_Interop/Win32_QFork.cpp
+++ src/Win32_Interop/Win32_QFork.cpp
@@ -178,7 +178,6 @@
     LPVOID heapStart;

     OperationType typeOfOperation;
-    HANDLE forkedProcessReady;
     HANDLE operationComplete;
     HANDLE operationFailed;

@@ -264,8 +263,6 @@
         // duplicate handles and stuff into control structure (parent protected by PAGE_WRITECOPY)
         SmartHandle dupHeapFileHandle(shParent, sfvParentQForkControl->heapMemoryMapFile);
         g_pQForkControl->heapMemoryMapFile = dupHeapFileHandle;
-        SmartHandle dupForkedProcessReady(shParent, sfvParentQForkControl->forkedProcessReady);
-        g_pQForkControl->forkedProcessReady = dupForkedProcessReady;
         SmartHandle dupOperationComplete(shParent, sfvParentQForkControl->operationComplete);
         g_pQForkControl->operationComplete = dupOperationComplete;
         SmartHandle dupOperationFailed(shParent, sfvParentQForkControl->operationFailed);
@@ -299,9 +296,6 @@
         if( SetDLMallocGlobalState(g_pQForkControl->DLMallocGlobalStateSize, g_pQForkControl->DLMallocGlobalState) != 0) {
             throw std::runtime_error("DLMalloc global state copy failed.");
         }
-
-        // signal parent that we are ready
-        SetEvent(g_pQForkControl->forkedProcessReady);

         // copy redis globals into fork process
         SetupGlobals(g_pQForkControl->globalData.globalData, g_pQForkControl->globalData.globalDataSize, g_pQForkControl->globalData.dictHashSeed);
@@ -567,13 +561,6 @@
         }

         g_pQForkControl->typeOfOperation = OperationType::otINVALID;
-        g_pQForkControl->forkedProcessReady = CreateEvent(NULL,TRUE,FALSE,NULL);
-        if (g_pQForkControl->forkedProcessReady == NULL) {
-            throw std::system_error(
-                GetLastError(),
-                system_category(),
-                "CreateEvent failed.");
-        }
         g_pQForkControl->operationComplete = CreateEvent(NULL,TRUE,FALSE,NULL);
         if (g_pQForkControl->operationComplete == NULL) {
             throw std::system_error(
@@ -775,10 +762,6 @@

     if( g_pQForkControl != NULL )
     {
-        if (g_pQForkControl->forkedProcessReady != NULL) {
-            CloseHandle(g_pQForkControl->forkedProcessReady);
-            g_pQForkControl->forkedProcessReady = NULL;
-        }
         if (g_pQForkControl->operationComplete != NULL) {
             CloseHandle(g_pQForkControl->operationComplete);
             g_pQForkControl->operationComplete = NULL;
@@ -863,12 +846,6 @@
         throw std::system_error(
             GetLastError(),
             system_category(),
-            "BeginForkOperation: ResetEvent() failed.");
-    }
-    if (ResetEvent(g_pQForkControl->forkedProcessReady) == FALSE) {
-        throw std::system_error(
-            GetLastError(),
-            system_category(),
             "BeginForkOperation: ResetEvent() failed.");
     }

@@ -926,14 +903,6 @@

         CloseHandle(pi.hThread);

-        // wait for "forked" process to map memory
-        if (WaitForSingleObject(g_pQForkControl->forkedProcessReady, cDeadForkWait) != WAIT_OBJECT_0) {
-            throw system_error(
-                GetLastError(),
-                system_category(),
-                "Forked Process did not respond in a timely manner.");
-        }
-
         return pi.dwProcessId;
     }
     catch(std::system_error syserr) {
@@ -1017,7 +986,7 @@
         return OperationStatus::osFAILED;
     }

-    if (g_hForkedProcess && WaitForSingleObject(g_pQForkControl->forkedProcessReady, 0) == WAIT_OBJECT_0) {
+    if (g_hForkedProcess) {
         // Verify if the child process is still running
         if (WaitForSingleObject(g_hForkedProcess, 0) == WAIT_OBJECT_0) {
             // The child process is not running, close the handle and report the status
@@ -1166,12 +1135,6 @@
             throw std::system_error(
                 GetLastError(),
                 system_category(),
-                "EndForkOperation: ResetEvent() failed.");
-        }
-        if (ResetEvent(g_pQForkControl->forkedProcessReady) == FALSE) {
-            throw std::system_error(
-                GetLastError(),
-                system_category(),
                 "EndForkOperation: ResetEvent() failed.");
         }


Support for DRV_DISP_ADAGFX_ILI9341_T3_BL - blackketter/ILI9341_T3

--- src/GUIslice_drv_adagfx.cpp
+++ src/GUIslice_drv_adagfx.cpp
@@ -48,7 +48,7 @@

   // Almost all GFX-compatible libraries depend on Adafruit-GFX
   // There are a couple exceptions that do not require it
-  #if !defined(DRV_DISP_ADAGFX_ILI9341_T3)
+  #if !defined(DRV_DISP_ADAGFX_ILI9341_T3) && !defined(DRV_DISP_ADAGFX_ILI9341_T3_BL)
     #include <Adafruit_GFX.h>
     #include <gfxfont.h>
   #endif // ILI9341_T3
@@ -66,7 +66,7 @@
       #include <SD.h>   // Include support for SD card access
     #endif
     #include <SPI.h>
-  #elif defined(DRV_DISP_ADAGFX_ILI9341_T3)
+  #elif defined(DRV_DISP_ADAGFX_ILI9341_T3) || defined(DRV_DISP_ADAGFX_ILI9341_T3_BL)
     #include <ILI9341_t3.h>
     #if (GSLC_SD_EN)
       #include <SD.h>   // Include support for SD card access
@@ -175,6 +175,13 @@
   //ILI9341_t3 m_disp = ILI9341_t3 (ADAGFX_PIN_CS, ADAGFX_PIN_DC, ADAGFX_PIN_RST, ADAGFX_PIN_MOSI, ADAGFX_PIN_CLK, ADAGFX_PIN_MISO); // Alternate HW-SPI pinout

 // ------------------------------------------------------------------------
+#elif defined(DRV_DISP_ADAGFX_ILI9341_T3_BL)
+  const char* m_acDrvDisp = "ADA_ILI9341_T3_BL";
+  ILI9341_t3 m_disp = ILI9341_t3(ADAGFX_PIN_CS, ADAGFX_PIN_DC); // Default HW-SPI pinout
+  //ILI9341_t3 m_disp = ILI9341_t3(ADAGFX_PIN_CS, ADAGFX_PIN_DC, ADAGFX_PIN_RST); // Default HW-SPI pinout
+  //ILI9341_t3 m_disp = ILI9341_t3 (ADAGFX_PIN_CS, ADAGFX_PIN_DC, ADAGFX_PIN_RST, ADAGFX_PIN_MOSI, ADAGFX_PIN_CLK, ADAGFX_PIN_MISO); // Alternate HW-SPI pinout
+
+// ------------------------------------------------------------------------
 #elif defined(DRV_DISP_ADAGFX_ILI9341_STM)
   #if (ADAGFX_SPI_HW) // Use hardware SPI or software SPI (with custom pins)
     const char* m_acDrvDisp = "ADA_ILI9341_STM(SPI-HW)";
@@ -341,7 +348,7 @@
       uint16_t identifier = m_disp.readID();
       m_disp.begin(identifier);

-    #elif defined(DRV_DISP_ADAGFX_ILI9341_T3)
+    #elif defined(DRV_DISP_ADAGFX_ILI9341_T3) || defined(DRV_DISP_ADAGFX_ILI9341_T3_BL)
       m_disp.begin();

     #elif defined(DRV_DISP_ADAGFX_SSD1306)
@@ -553,6 +560,7 @@
   uint16_t  nTxtScale = 0;

 #if defined(DRV_DISP_ADAGFX_ILI9341_T3)
+  // Use PaulStoffregen/ILI9341_t3

   // For now, only support the default Adafruit font
   // - See below for reasoning
@@ -609,9 +617,34 @@
   // - Alternately, there are other forks of ILI9341_t3 that have introduced
   //   some of these missing text sizing APIs.

-  GSLC_DEBUG_PRINT("DBG:GetTxtSize: [%s]=%u pixellen=%d scale=%d textsize=%d\n",
-	  pStr, *pnTxtSzW,m_disp.strPixelLen((char*)pStr),nTxtScale,m_disp.getTextSize()); //xxx
+  //GSLC_DEBUG_PRINT("DBG:GetTxtSize: [%s]=%u pixellen=%d scale=%d textsize=%d\n",
+  //  pStr, *pnTxtSzW,m_disp.strPixelLen((char*)pStr),nTxtScale,m_disp.getTextSize()); //xxx
+
   return true;
+
+#elif defined(DRV_DISP_ADAGFX_ILI9341_T3_BL)
+  // Use blackketter/ILI9341_t3
+
+  m_disp.setFontAdafruit();
+
+  nTxtScale = pFont->nSize;
+  m_disp.setTextSize(nTxtScale);
+
+  //int16_t nStrLen = strlen(pStr);
+
+  // Hardcoded dimension of default Adafruit-GFX font
+  //*pnTxtSzW = nTxtScale * nStrLen * 6;
+  //*pnTxtSzH = nTxtScale * 8;
+  *pnTxtSzW = m_disp.measureTextWidth(pStr,0);
+  *pnTxtSzH = m_disp.measureTextHeight(pStr,0);
+
+  GSLC_DEBUG_PRINT("DBG:GetTxtSize: [%s] w=%d h=%d scale=%d\n",
+    pStr, *pnTxtSzW,*pnTxtSzH,nTxtScale); //xxx
+
+  *pnTxtX = 0;
+  *pnTxtY = 0;
+
+
 #else

   nTxtScale = pFont->nSize;
@@ -659,7 +692,7 @@
   char      ch;

   // Initialize the font and positioning
-#if defined(DRV_DISP_ADAGFX_ILI9341_T3)
+#if defined(DRV_DISP_ADAGFX_ILI9341_T3) || defined(DRV_DISP_ADAGFX_ILI9341_T3_BL)
   // TODO
 #else
   m_disp.setFont((const GFXfont *)pFont->pvFont);
@@ -754,7 +787,7 @@
   #endif // DRV_DISP_ADAGFX_RA8875

   // Restore the font
-#if defined(DRV_DISP_ADAGFX_ILI9341_T3)
+#if defined(DRV_DISP_ADAGFX_ILI9341_T3) || defined(DRV_DISP_ADAGFX_ILI9341_T3_BL)
   // TODO
 #else
   m_disp.setFont();
@@ -1865,7 +1898,7 @@
       nOutputX = nInputX;
       nOutputY = nInputY;
     #endif  // DRV_TOUCH_TYPE_RES
-
+
     #ifdef DBG_TOUCH
     GSLC_DEBUG_PRINT("DBG: PreRotate: x=%u y=%u\n", nOutputX, nOutputY);
     GSLC_DEBUG_PRINT("DBG: RotateCfg: remap=%u nSwapXY=%u nFlipX=%u nFlipY=%u\n",
@@ -1951,7 +1984,7 @@

   // Inform the display to adjust the orientation and
   // update the saved display dimensions
-  #if defined(DRV_DISP_ADAGFX_ILI9341) || defined(DRV_DISP_ADAGFX_ILI9341_STM) || defined(DRV_DISP_ADAGFX_ILI9341_T3)
+  #if defined(DRV_DISP_ADAGFX_ILI9341) || defined(DRV_DISP_ADAGFX_ILI9341_STM) || defined(DRV_DISP_ADAGFX_ILI9341_T3) || defined(DRV_DISP_ADAGFX_ILI9341_T3_BL)
     pGui->nDisp0W = ILI9341_TFTWIDTH;
     pGui->nDisp0H = ILI9341_TFTHEIGHT;
     m_disp.setRotation(pGui->nRotation);


sql_parse.cc:
  URGENT: MONTY AND SERGEI should check this patch! The patch fixes the memory corruption reported by a user. It happened because the code did not keep correct a count of how many connections a user has, and the user object got freed too soon if the same user had more than 1 connection. Also fix a typo by Sanja: 'and' is not a C operator, I think it should be &&

sql/sql_parse.cc:
  URGENT: MONTY AND SERGEI should check this patch! The patch fixes the memory corruption reported by a user. It happened because the code did not keep correct a count of how many connections a user has, and the user object got freed too soon if the same user had more than 1 connection. Also fix a typo by Sanja: 'and' is not a C operator, I think it should be &&

--- sql/sql_parse.cc
+++ sql/sql_parse.cc
@@ -157,7 +157,7 @@
     uc->user_len= user_len;
     uc->host=uc->user + uc->user_len +  1;
     uc->len = temp_len;
-    uc->connections = 1;
+    uc->connections = 0;	/* BUG FIX by Heikki Oct 25, 2003 */
     uc->questions=uc->updates=uc->conn_per_hour=0;
     uc->user_resources=*mqh;
     if (max_user_connections && mqh->connections > max_user_connections)
@@ -314,11 +314,29 @@
       thd->db_access=0;

       /* Don't allow user to connect if he has done too many queries */
-      if ((ur.questions || ur.updates ||
-           ur.connections || max_user_connections) &&
+
+      /*
+      BUG FIX by Heikki Oct 25, 2003: since get_or_create_user_conn()
+      creates or finds the user object and does NOT check anything about ur,
+      we should call it always.
+      */
+
+      if ( /* (ur.questions || ur.updates ||
+           ur.connections || max_user_connections) && */
           get_or_create_user_conn(thd,thd->user,thd->host_or_ip,&ur))
         DBUG_RETURN(1);
-      if (thd->user_connect && thd->user_connect->user_resources.connections &&
+
+      /*
+      BUG FIX by Heikki Oct 25, 2003: since
+      check_for_max_user_connections() keeps the count of user connections,
+      and we delete the user object when the number of connections drops to
+      zero, we must call it always to keep the count right! Otherwise the
+      user object can get deleted too early, which caused memory corruption
+      to a user in Oct 2003.
+      */
+
+      if (thd->user_connect &&
+		/* thd->user_connect->user_resources.connections && */
           check_for_max_user_connections(thd, thd->user_connect))
         DBUG_RETURN(1);

@@ -390,6 +408,13 @@
   int error=0;
   DBUG_ENTER("check_for_max_user_connections");

+  /*
+  FIX by Heikki Oct 25, 2003: protect the operation with a mutex: is there
+  a race condition here otherwise?
+  */
+
+  (void) pthread_mutex_lock(&LOCK_user_conn);
+
   if (max_user_connections &&
       (max_user_connections <  (uint) uc->connections))
   {
@@ -397,7 +422,9 @@
     error=1;
     goto end;
   }
+
   uc->connections++;
+
   if (uc->user_resources.connections &&
       uc->conn_per_hour++ >= uc->user_resources.connections)
   {
@@ -407,6 +434,9 @@
     error=1;
   }
 end:
+
+  (void) pthread_mutex_unlock(&LOCK_user_conn);
+
   DBUG_RETURN(error);
 }

@@ -414,13 +444,23 @@
 static void decrease_user_connections(USER_CONN *uc)
 {
   DBUG_ENTER("decrease_user_connections");
+
+  /*
+  FIX by Heikki Oct 25, 2003: protect the operation with a mutex: is there
+  a race condition here otherwise?
+  */
+
+  (void) pthread_mutex_lock(&LOCK_user_conn);
+
   if ((uc->connections && !--uc->connections) && !mqh_used)
   {
     /* Last connection for user; Delete it */
-    (void) pthread_mutex_lock(&LOCK_user_conn);
+
     (void) hash_delete(&hash_user_connections,(byte*) uc);
-    (void) pthread_mutex_unlock(&LOCK_user_conn);
-  }
+  }
+
+  (void) pthread_mutex_unlock(&LOCK_user_conn);
+
   DBUG_VOID_RETURN;
 }

@@ -4673,10 +4713,10 @@
 				bool all,
 				SELECT_LEX *select_lex)
 {
-  if ((cmp == &comp_eq_creator) and !all)       //  = ANY <=> IN
+  if ((cmp == &comp_eq_creator) && !all)       //  = ANY <=> IN
     return new Item_in_subselect(left_expr, select_lex);

-  if ((cmp == &comp_ne_creator) and all)	// <> ALL <=> NOT IN
+  if ((cmp == &comp_ne_creator) && all)	// <> ALL <=> NOT IN
     return new Item_func_not(new Item_in_subselect(left_expr, select_lex));

   Item_allany_subselect *it=


Added missing #ifdef HAVE_INNOBASE_DB:s in sql_parse.cc.

--- sql/sql_parse.cc
+++ sql/sql_parse.cc
@@ -2234,7 +2234,9 @@
   /* Locked closure of all tables */
   TABLE_LIST *locked_tables= NULL;
   /* Saved variable value */
+#ifdef HAVE_INNOBASE_DB
   my_bool old_innodb_table_locks= thd->variables.innodb_table_locks;
+#endif
   DBUG_ENTER("mysql_execute_command");

   /*
@@ -2330,7 +2332,9 @@
 	{
 	  if ((locked_tables= sp_hash_to_table_list(thd, &lex->sptabs)))
 	  {
+#ifdef HAVE_INNOBASE_DB
 	    thd->variables.innodb_table_locks= FALSE;
+#endif
 	    sp_open_and_lock_tables(thd, locked_tables);
 	  }
 	}
@@ -4346,7 +4350,9 @@

   if (locked_tables)
   {
+#ifdef HAVE_INNOBASE_DB
     thd->variables.innodb_table_locks= old_innodb_table_locks;
+#endif
     if (thd->locked_tables)
       sp_unlock_tables(thd);
   }


#ifdef out a function only used by #ifdef'd code.

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@20700 91177308-0d34-0410-b5e6-96231b3b80d8

--- lib/Analysis/DataStructure/DataStructureAA.cpp
+++ lib/Analysis/DataStructure/DataStructureAA.cpp
@@ -100,6 +100,7 @@
   return 0;
 }

+#if 0
 // isSinglePhysicalObject - For now, the only case that we know that there is
 // only one memory object in the node is when there is a single global in the
 // node, and the only composition bit set is Global.
@@ -109,6 +110,7 @@
   return N->isGlobalNode() && N->getGlobals().size() == 1 &&
          !N->isHeapNode() && !N->isAllocaNode() && !N->isUnknownNode();
 }
+#endif

 // alias - This is the only method here that does anything interesting...
 AliasAnalysis::AliasResult DSAA::alias(const Value *V1, unsigned V1Size,


In select(), 'numWithEvents' was being set to the value of 'result' even
when select(2) failed.  This assginment should only be made when one or
more of the file descriptors is ready.

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

--- modules/vapor/vpr/md/POSIX/IO/SelectorImplBSD.cpp
+++ modules/vapor/vpr/md/POSIX/IO/SelectorImplBSD.cpp
@@ -220,9 +220,9 @@
             (*i).out_flags |= SelectorBase::VPR_EXCEPT;
          }
       }
-   }
-
-   numWithEvents = result;
+
+      numWithEvents = result;
+   }

    return ret_val;
 }


Implement Graphics::GetMultiSampleLevels() on OpenGL by querying GL_MAX_SAMPLES. Closes #1774.

--- Source/Urho3D/Graphics/OpenGL/OGLGraphics.cpp
+++ Source/Urho3D/Graphics/OpenGL/OGLGraphics.cpp
@@ -2082,8 +2082,14 @@
     PODVector<int> ret;
     // No multisampling always supported
     ret.Push(1);
-    /// \todo Implement properly, if possible
-
+
+#ifndef GL_ES
+    int maxSamples = 0;
+    glGetIntegerv(GL_MAX_SAMPLES, &maxSamples);
+    for (int i = 2; i <= maxSamples && i <= 16; i *= 2)
+        ret.Push(i);
+#endif
+
     return ret;
 }


[GL] Forgot to also set the state cache manager after recreating it.

--HG--
branch : v1-9

--- RenderSystems/GL/src/OgreGLRenderSystem.cpp
+++ RenderSystems/GL/src/OgreGLRenderSystem.cpp
@@ -202,6 +202,8 @@

         if(!mStateCacheManager)
             mStateCacheManager = OGRE_NEW GLStateCacheManager();
+
+        mGLSupport->setStateCacheManager(mStateCacheManager);

         // Create the texture manager
 		mTextureManager = new GLTextureManager(*mGLSupport);


branch boyceg: working to improve performance of initializeSpringLevelData()

git-svn-id: 668c94791126b0c8906896ca082e88e0811ecee5@2675 d09065f7-430b-272c-15e1-d58225cc4d83

--- src/IB/IBStandardForceGen.C
+++ src/IB/IBStandardForceGen.C
@@ -389,6 +389,7 @@
     // The LMesh object provides the set of local Lagrangian nodes.
     const Pointer<LMesh> mesh = l_data_manager->getLMesh(level_number);
     const std::vector<LNode*>& local_nodes = mesh->getLocalNodes();
+    const int num_local_nodes = local_nodes.size();

     // Quick return if local_nodes is empty.
     if (local_nodes.empty())
@@ -416,11 +417,39 @@
         return;
     }

+    // Loop unrolling parameters.
+    static const int BLOCKSIZE = 128;  // This parameter needs to be tuned.
+    int k, kblock, kunroll;
+
     // Determine how many springs are associated with the present MPI process.
     int num_springs = 0;
-    for (std::vector<LNode*>::const_iterator cit = local_nodes.begin(); cit != local_nodes.end(); ++cit)
-    {
-        const LNode* const node_idx = *cit;
+    for (k = 0; k < BLOCKSIZE && k < num_local_nodes; ++k)
+    {
+        const LNode* const node_idx = local_nodes[k];
+        const IBSpringForceSpec* const force_spec = node_idx->getNodeDataItem<IBSpringForceSpec>();
+        PREFETCH_READ_NTA(force_spec);
+    }
+    kblock = 0;
+    for ( ; kblock < (num_local_nodes-1)/BLOCKSIZE-1; ++kblock)  // ensure that the last TWO blocks are NOT handled by this first loop
+    {
+        for (kunroll = 0; kunroll < BLOCKSIZE; ++kunroll)
+        {
+            k = (kblock+1)*BLOCKSIZE+kunroll;
+            const LNode* const node_idx = local_nodes[k];
+            const IBSpringForceSpec* const force_spec = node_idx->getNodeDataItem<IBSpringForceSpec>();
+            PREFETCH_READ_NTA(force_spec);
+        }
+        for (kunroll = 0; kunroll < BLOCKSIZE; ++kunroll)
+        {
+            k = (kblock+1)*BLOCKSIZE+kunroll;
+            const LNode* const node_idx = local_nodes[k];
+            const IBSpringForceSpec* const force_spec = node_idx->getNodeDataItem<IBSpringForceSpec>();
+            if (force_spec != NULL) num_springs += force_spec->getNumberOfSprings();
+        }
+    }
+    for (k = kblock*BLOCKSIZE; k < num_local_nodes; ++k)
+    {
+        const LNode* const node_idx = local_nodes[k];
         const IBSpringForceSpec* const force_spec = node_idx->getNodeDataItem<IBSpringForceSpec>();
         if (force_spec != NULL) num_springs += force_spec->getNumberOfSprings();
     }
@@ -450,8 +479,6 @@
     if (num_springs == 0) return;

     // Setup the data structures used to compute spring forces.
-    static const int BLOCKSIZE = 16;  // This parameter needs to be tuned.
-    int k, kblock, kunroll, idx;
     int current_spring = 0;
     if (d_constant_material_properties)
     {
@@ -490,71 +517,9 @@
     }
     else
     {
-        const int num_local_nodes = local_nodes.size();
-        for (k = 0; k < BLOCKSIZE && k < num_local_nodes; ++k)
-        {
-            const LNode* const node_idx = local_nodes[k];
-            const IBSpringForceSpec* const force_spec = node_idx->getNodeDataItem<IBSpringForceSpec>();
-            if (force_spec == NULL) continue;
-            const unsigned int num_springs = force_spec->getNumberOfSprings();
-            PREFETCH_READ_NTA_BLOCK(&force_spec->getSlaveNodeIndices    ()[0], num_springs);
-            PREFETCH_READ_NTA_BLOCK(&force_spec->getForceFunctionIndices()[0], num_springs);
-            PREFETCH_READ_NTA_BLOCK(&force_spec->getStiffnesses         ()[0], num_springs);
-            PREFETCH_READ_NTA_BLOCK(&force_spec->getRestingLengths      ()[0], num_springs);
-        }
-        kblock = 0;
-        for ( ; kblock < (num_local_nodes-1)/BLOCKSIZE-1; ++kblock)  // ensure that the last TWO blocks are NOT handled by this first loop
-        {
-            for (kunroll = 0; kunroll < BLOCKSIZE; ++kunroll)
-            {
-                k = (kblock+1)*BLOCKSIZE+kunroll;
-                const LNode* const node_idx = local_nodes[k];
-                const IBSpringForceSpec* const force_spec = node_idx->getNodeDataItem<IBSpringForceSpec>();
-                if (force_spec == NULL) continue;
-                const unsigned int num_springs = force_spec->getNumberOfSprings();
-                PREFETCH_READ_NTA_BLOCK(&force_spec->getSlaveNodeIndices    ()[0], num_springs);
-                PREFETCH_READ_NTA_BLOCK(&force_spec->getForceFunctionIndices()[0], num_springs);
-                PREFETCH_READ_NTA_BLOCK(&force_spec->getStiffnesses         ()[0], num_springs);
-                PREFETCH_READ_NTA_BLOCK(&force_spec->getRestingLengths      ()[0], num_springs);
-            }
-            for (kunroll = 0; kunroll < BLOCKSIZE; ++kunroll)
-            {
-                k = kblock*BLOCKSIZE+kunroll;
-                const LNode* const node_idx = local_nodes[k];
-                const IBSpringForceSpec* const force_spec = node_idx->getNodeDataItem<IBSpringForceSpec>();
-                if (force_spec == NULL) continue;
-
-                const int lag_idx = node_idx->getLagrangianIndex();
-#ifdef DEBUG_CHECK_ASSERTIONS
-                TBOX_ASSERT(lag_idx == force_spec->getMasterNodeIndex());
-#endif
-                const int petsc_idx = node_idx->getGlobalPETScIndex();
-                const std::vector<int>& slv = force_spec->getSlaveNodeIndices();
-                const std::vector<int>& fcn = force_spec->getForceFunctionIndices();
-                const std::vector<double>& stf = force_spec->getStiffnesses();
-                const std::vector<double>& rst = force_spec->getRestingLengths();
-                const unsigned int num_springs = force_spec->getNumberOfSprings();
-#ifdef DEBUG_CHECK_ASSERTIONS
-                TBOX_ASSERT(num_springs == slv.size());
-                TBOX_ASSERT(num_springs == fcn.size());
-                TBOX_ASSERT(num_springs == stf.size());
-                TBOX_ASSERT(num_springs == rst.size());
-#endif
-                for (unsigned int k = 0; k < num_springs; ++k)
-                {
-                    lag_mastr_node_idxs  (current_spring) = lag_idx;
-                    lag_slave_node_idxs  (current_spring) = slv[k];
-                    petsc_mastr_node_idxs(current_spring) = petsc_idx;
-                    force_fcns           (current_spring) = d_spring_force_fcn_map[fcn[k]];
-                    dynamic_stiffnesses  (current_spring) = &stf[k];
-                    dynamic_rest_lengths (current_spring) = &rst[k];
-                    ++current_spring;
-                }
-            }
-        }
-        for (k = kblock*BLOCKSIZE; k < num_local_nodes; ++k)
-        {
-            const LNode* const node_idx = local_nodes[k];
+        for (std::vector<LNode*>::const_iterator cit = local_nodes.begin(); cit != local_nodes.end(); ++cit)
+        {
+            const LNode* const node_idx = *cit;
             const IBSpringForceSpec* const force_spec = node_idx->getNodeDataItem<IBSpringForceSpec>();
             if (force_spec == NULL) continue;

@@ -592,14 +557,11 @@
     petsc_slave_node_idxs = lag_slave_node_idxs;
     l_data_manager->mapLagrangianToPETSc(petsc_slave_node_idxs, level_number);

-    // Determine the global node offset and the number of local nodes.
-    const int global_node_offset = l_data_manager->getGlobalNodeOffset(level_number);
-    const int num_local_nodes = l_data_manager->getNumberOfLocalNodes(level_number);
-
     // Determine the ghost nodes required to compute spring forces.
     //
     // NOTE: Only slave nodes can be "off processor".  Master nodes are
     // guaranteed to be "on processor".
+    const int global_node_offset = l_data_manager->getGlobalNodeOffset(level_number);
     for (int k = 0; k < petsc_slave_node_idxs.size(); ++k)
     {
         const int idx = petsc_slave_node_idxs(k);


[backport#13551] tests: Fix incorrect documentation for test case cuckoocache_hit_rate_ok

Summary:
Fix incorrect documentation for test case cuckoocache_hit_rate_ok (practicalswift)

https://github.com/bitcoin/bitcoin/pull/13551/commits/ea49e06c8211d8642a52a4b120c7b3d41836ea03

---

Backport of Core [[https://github.com/bitcoin/bitcoin/pull/13551 | PR13551]]

Test Plan:
  none

Reviewers: #bitcoin_abc, jasonbcox

Reviewed By: #bitcoin_abc, jasonbcox

Differential Revision: https://reviews.bitcoinabc.org/D7276

--- src/test/cuckoocache_tests.cpp
+++ src/test/cuckoocache_tests.cpp
@@ -185,7 +185,7 @@
     return hits * std::max(load, 1.0);
 }

-/** Check the hit rate on loads ranging from 0.1 to 2.0 */
+/** Check the hit rate on loads ranging from 0.1 to 1.6 */
 BOOST_AUTO_TEST_CASE(cuckoocache_hit_rate_ok) {
     /**
      * Arbitrarily selected Hit Rate threshold that happens to work for this


Add comment about non-obvious but vital side effect

--- src/algo_factory/algo_factory.cpp
+++ src/algo_factory/algo_factory.cpp
@@ -126,6 +126,11 @@
 std::vector<std::string>
 Algorithm_Factory::providers_of(const std::string& algo_spec)
    {
+   /* The checks with if(prototype_X(algo_spec)) have the effect of
+      forcing a full search, since otherwise there might not be any
+      providers at all in the cache.
+   */
+
    if(prototype_block_cipher(algo_spec))
       return block_cipher_cache.providers_of(algo_spec);
    else if(prototype_stream_cipher(algo_spec))


Fixing that database privileges are also taken into account. Before this change LOCK TABLES worked only with global and table level privileges.

--- sql/sql_parse.cc
+++ sql/sql_parse.cc
@@ -2223,7 +2223,8 @@
     }
     if (check_db_used(thd,tables) || end_active_trans(thd))
       goto error;
-    if (grant_option && check_grant(thd,SELECT_ACL | INSERT_ACL | UPDATE_ACL | DELETE_ACL,tables))
+    if (check_table_access(thd, SELECT_ACL | INSERT_ACL | UPDATE_ACL | DELETE_ACL , tables)
+	|| (grant_option && check_grant(thd,SELECT_ACL | INSERT_ACL | UPDATE_ACL | DELETE_ACL,tables)))
       goto error;
     thd->in_lock_tables=1;
     thd->options|= OPTION_TABLE_LOCK;


Updated for bug fix in GMTL.

Updated for bug fix in GMTL.

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

--- modules/vrjuggler/vrj/Display/SurfaceViewport.cpp
+++ modules/vrjuggler/vrj/Display/SurfaceViewport.cpp
@@ -169,6 +169,8 @@

    // Calculate the surfaceRotMat using law of cosines
    mSurfaceRotation = gmtl::makeDirCos<gmtl::Matrix44f>(x_base, y_base, z_base );
+   gmtl::invert(mSurfaceRotation);
+
    //mSurfaceRotation.makeDirCos(x_base,y_base,z_base);      // surfMbase
    //mSurfaceRotation.invert(mSurfRotInv);              // baseMsurf
 }


Native processing

Native processing

--- native/recog/main.cpp
+++ native/recog/main.cpp
@@ -12,8 +12,12 @@
 	ImageMessage imageMessage(message);

 	auto image = imageMessage.headImage();
-
-	return "foo";
+	Jzon::Object root;
+	root.add("accepted", true);
+	Jzon::Writer writer(root, Jzon::NoFormat);
+	writer.Write();
+
+	return writer.GetResult();
 }

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


Workaround for broken hardware mipmap generation on Intel 915G's (at least - for the moment disable for all Intel chipsets)

--HG--
branch : v1-6

--- RenderSystems/GL/src/OgreGLRenderSystem.cpp
+++ RenderSystems/GL/src/OgreGLRenderSystem.cpp
@@ -237,6 +237,12 @@
 			if (rsc->getVendor() == GPU_ATI)
 				disableAutoMip = true;
 #endif
+			// The Intel 915G frequently corrupts textures when using hardware mip generation
+			// I'm not currently sure how many generations of hardware this affects,
+			// so for now, be safe.
+			if (rsc->getVendor() == GPU_INTEL)
+				disableAutoMip = true;
+
 			if (!disableAutoMip)
 				rsc->setCapability(RSC_AUTOMIPMAP);
         }


enabled test

enabled test

--- tests/core/post_hash_table_test.cpp
+++ tests/core/post_hash_table_test.cpp
@@ -196,7 +196,7 @@
     ASSERT_EQ(1u, table.NumItems());
 }

-TEST_F(PostTable, DISABLED_MultipleEmitters) {
+TEST_F(PostTable, MultipleEmitters) {
     std::vector<int> vec1;

     auto key_ex = [](int in) {


branch boyceg: working to improve performance of initializeSpringLevelData()

git-svn-id: 668c94791126b0c8906896ca082e88e0811ecee5@2676 d09065f7-430b-272c-15e1-d58225cc4d83

--- src/IB/IBStandardForceGen.C
+++ src/IB/IBStandardForceGen.C
@@ -441,7 +441,7 @@
         }
         for (kunroll = 0; kunroll < BLOCKSIZE; ++kunroll)
         {
-            k = (kblock+1)*BLOCKSIZE+kunroll;
+            k = kblock*BLOCKSIZE+kunroll;
             const LNode* const node_idx = local_nodes[k];
             const IBSpringForceSpec* const force_spec = node_idx->getNodeDataItem<IBSpringForceSpec>();
             if (force_spec != NULL) num_springs += force_spec->getNumberOfSprings();


Output libav error text on av_audio_convert failure

--- src/algorithms/io/audioloader.cpp
+++ src/algorithms/io/audioloader.cpp
@@ -480,11 +480,14 @@
         int ostride[6]      = { av_get_bytes_per_sample(AV_SAMPLE_FMT_S16)     };
         int totalsamples    = _dataSize / istride[0]; // == num_samp_per_channel * num_channels

-        if (av_audio_convert(_audioConvert, obuf, ostride, ibuf, istride, totalsamples) < 0) {
+        if (int result = av_audio_convert(_audioConvert, obuf, ostride, ibuf, istride, totalsamples) < 0) {
+            char errstring[1204];
+            av_strerror(result, errstring, sizeof(errstring));
             ostringstream msg;
             msg << "AudioLoader: Error converting "
                 << " from " << av_get_sample_fmt_name(_audioCtx->sample_fmt)
-                << " to "   << av_get_sample_fmt_name(AV_SAMPLE_FMT_S16);
+                << " to "   << av_get_sample_fmt_name(AV_SAMPLE_FMT_S16)
+                << ". " << errstring;
             throw EssentiaException(msg);
         }


fixed std::endl issue with dump writer test

--- src/test/unit/io/dump_test.cpp
+++ src/test/unit/io/dump_test.cpp
@@ -616,13 +616,19 @@
 }

 template <typename T>
-void testWriteVal(const::std::string& expected,
+void testWriteVal(const::std::string& expected_number_string,
                   T x) {
   std::stringstream s;
   stan::io::dump_writer writer(s);
   writer.write("foo", x);
   std::string written = s.str();
-  EXPECT_EQ("\"foo\" <- \n" + expected, written);
+
+  std::stringstream ss_expected;
+  ss_expected << "\"foo\" <- "
+             << std::endl
+             << expected_number_string;
+  std::string expected = ss_expected.str();
+  EXPECT_EQ(expected, written);
 }

 TEST(ioDump, writeVal) {


Implement InstCombine/select.ll:test15*

Implement InstCombine/select.ll:test15*

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@14095 91177308-0d34-0410-b5e6-96231b3b80d8

--- lib/Transforms/Scalar/InstructionCombining.cpp
+++ lib/Transforms/Scalar/InstructionCombining.cpp
@@ -934,6 +934,13 @@
   return CS->getValue() == Val+1;
 }

+// isOneBitSet - Return true if there is exactly one bit set in the specified
+// constant.
+static bool isOneBitSet(const ConstantInt *CI) {
+  uint64_t V = CI->getRawValue();
+  return V && (V & (V-1)) == 0;
+}
+
 /// getSetCondCode - Encode a setcc opcode into a three bit mask.  These bits
 /// are carefully arranged to allow folding of expressions such as:
 ///
@@ -1063,17 +1070,17 @@
       // Adding a one to a single bit bit-field should be turned into an XOR
       // of the bit.  First thing to check is to see if this AND is with a
       // single bit constant.
-      unsigned long long AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
+      uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();

       // Clear bits that are not part of the constant.
       AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;

       // If there is only one bit set...
-      if ((AndRHSV & (AndRHSV-1)) == 0) {
+      if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
         // Ok, at this point, we know that we are masking the result of the
         // ADD down to exactly one bit.  If the constant we are adding has
         // no bits set below this bit, then we can eliminate the ADD.
-        unsigned long long AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
+        uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();

         // Check to see if any bits below the one bit set in AndRHSV are set.
         if ((AddRHS & (AndRHSV-1)) == 0) {
@@ -1476,61 +1483,66 @@
   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
       if (LHSI->hasOneUse())
-        if (LHSI->getNumOperands() == 2 &&
-            isa<ConstantInt>(LHSI->getOperand(1))) {
-          // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
-          // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
-          // happens a LOT in code produced by the C front-end, for bitfield
-          // access.
-          if (LHSI->getOpcode() == Instruction::And &&
-              LHSI->getOperand(0)->hasOneUse())
-            if (ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0)))
-              if (ConstantUInt *ShAmt =
-                  dyn_cast<ConstantUInt>(Shift->getOperand(1))) {
-                ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
-
-                // We can fold this as long as we can't shift unknown bits into
-                // the mask.  This can only happen with signed shift rights, as
-                // they sign-extend.
-                const Type *Ty = Shift->getType();
-                if (Shift->getOpcode() != Instruction::Shr ||
-                    Shift->getType()->isUnsigned() ||
-                    // To test for the bad case of the signed shr, see if any of
-                    // the bits shifted in could be tested after the mask.
-                    ConstantExpr::getAnd(ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), ConstantUInt::get(Type::UByteTy, Ty->getPrimitiveSize()*8-ShAmt->getValue())), AndCST)->isNullValue()) {
-                  unsigned ShiftOp = Shift->getOpcode() == Instruction::Shl
-                    ? Instruction::Shr : Instruction::Shl;
-                  I.setOperand(1, ConstantExpr::get(ShiftOp, CI, ShAmt));
-                  LHSI->setOperand(1, ConstantExpr::get(ShiftOp, AndCST,ShAmt));
-                  LHSI->setOperand(0, Shift->getOperand(0));
-                  WorkList.push_back(Shift); // Shift is probably dead.
-                  AddUsesToWorkList(I);
-                  return &I;
+        switch (LHSI->getOpcode()) {
+        case Instruction::And:
+          if (isa<ConstantInt>(LHSI->getOperand(1))) {
+
+
+            // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
+            // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
+            // happens a LOT in code produced by the C front-end, for bitfield
+            // access.
+            if (LHSI->getOperand(0)->hasOneUse())
+              if (ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0)))
+                if (ConstantUInt *ShAmt =
+                    dyn_cast<ConstantUInt>(Shift->getOperand(1))) {
+                  ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
+
+                  // We can fold this as long as we can't shift unknown bits
+                  // into the mask.  This can only happen with signed shift
+                  // rights, as they sign-extend.
+                  const Type *Ty = Shift->getType();
+                  if (Shift->getOpcode() != Instruction::Shr ||
+                      Shift->getType()->isUnsigned() ||
+                      // To test for the bad case of the signed shr, see if any
+                      // of the bits shifted in could be tested after the mask.
+                      ConstantExpr::getAnd(ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), ConstantUInt::get(Type::UByteTy, Ty->getPrimitiveSize()*8-ShAmt->getValue())), AndCST)->isNullValue()) {
+                    unsigned ShiftOp = Shift->getOpcode() == Instruction::Shl
+                      ? Instruction::Shr : Instruction::Shl;
+                    I.setOperand(1, ConstantExpr::get(ShiftOp, CI, ShAmt));
+                    LHSI->setOperand(1,ConstantExpr::get(ShiftOp,AndCST,ShAmt));
+                    LHSI->setOperand(0, Shift->getOperand(0));
+                    WorkList.push_back(Shift); // Shift is probably dead.
+                    AddUsesToWorkList(I);
+                    return &I;
+                  }
                 }
-              }
-        } else if (SelectInst *SI = dyn_cast<SelectInst>(LHSI)) {
+          }
+          break;
+        case Instruction::Select:
           // If either operand of the select is a constant, we can fold the
           // comparison into the select arms, which will cause one to be
           // constant folded and the select turned into a bitwise or.
           Value *Op1 = 0, *Op2 = 0;
-          if (Constant *C = dyn_cast<Constant>(SI->getOperand(1))) {
+          if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
             // Fold the known value into the constant operand.
             Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
             // Insert a new SetCC of the other select operand.
             Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
-                                                      SI->getOperand(2), CI,
+                                                      LHSI->getOperand(2), CI,
                                                       I.getName()), I);
-          } else if (Constant *C = dyn_cast<Constant>(SI->getOperand(2))) {
+          } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
             // Fold the known value into the constant operand.
             Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
             // Insert a new SetCC of the other select operand.
             Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
-                                                      SI->getOperand(1), CI,
+                                                      LHSI->getOperand(1), CI,
                                                       I.getName()), I);
           }

           if (Op1)
-            return new SelectInst(SI->getCondition(), Op1, Op2);
+            return new SelectInst(LHSI->getOperand(0), Op1, Op2);
+          break;
         }

     // Simplify seteq and setne instructions...
@@ -1591,6 +1603,16 @@
             if (!ConstantExpr::get(Instruction::And, CI,
                                    NotConstant(BOC))->isNullValue())
               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
+
+            // If we have ((X & C) == C), turn it into ((X & C) != 0).
+            if (CI == BOC) {
+              // Don't infinite loop if C is null and the & isn't folded yet.
+              if (CI->isNullValue())
+                return ReplaceInstUsesWith(I, ConstantBool::get(!isSetNE));
+              return new SetCondInst(isSetNE ? Instruction::SetEQ :
+                                     Instruction::SetNE, Op0,
+                                     Constant::getNullValue(CI->getType()));
+            }

             // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
             // to be a signed value as appropriate.
@@ -2258,6 +2280,34 @@
                                                "not."+CondVal->getName()), SI);
         return new CastInst(NotCond, SI.getType());
       }
+
+      // If one of the constants is zero (we know they can't both be) and we
+      // have a setcc instruction with zero, and we have an 'and' with the
+      // non-constant value, eliminate this whole mess.  This corresponds to
+      // cases like this: ((X & 27) ? 27 : 0)
+      if (TrueValC->isNullValue() || FalseValC->isNullValue())
+        if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
+          if ((IC->getOpcode() == Instruction::SetEQ ||
+               IC->getOpcode() == Instruction::SetNE) &&
+              isa<ConstantInt>(IC->getOperand(1)) &&
+              cast<Constant>(IC->getOperand(1))->isNullValue())
+            if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
+              if (ICA->getOpcode() == Instruction::And &&
+                  isa<ConstantInt>(ICA->getOperand(1)) &&
+                  (ICA->getOperand(1) == TrueValC ||
+                   ICA->getOperand(1) == FalseValC) &&
+                  isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
+                // Okay, now we know that everything is set up, we just don't
+                // know whether we have a setne or seteq and whether the true or
+                // false val is the zero.
+                bool ShouldNotVal = !TrueValC->isNullValue();
+                ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
+                Value *V = ICA;
+                if (ShouldNotVal)
+                  V = InsertNewInstBefore(BinaryOperator::create(
+                                  Instruction::Xor, V, ICA->getOperand(1)), SI);
+                return ReplaceInstUsesWith(SI, V);
+              }
     }

   // See if we are selecting two values based on a comparison of the two values.


after merge fix

after merge fix

--- sql/sql_parse.cc
+++ sql/sql_parse.cc
@@ -908,7 +908,7 @@
     db + passwd_len + 1 : 0;
   uint db_len= db ? strlen(db) : 0;

-  if (passwd + passwd_len + db_len > net->read_pos + pkt_len)
+  if (passwd + passwd_len + db_len > (char *)net->read_pos + pkt_len)
   {
     inc_host_errors(&thd->remote.sin_addr);
     return ER_HANDSHAKE_ERROR;
@@ -1388,13 +1388,13 @@
     uint db_len= *(uchar*) packet;
     if (db_len >= packet_length || db_len > NAME_LEN)
     {
-      send_error(&thd->net, ER_UNKNOWN_COM_ERROR);
+      send_error(thd, ER_UNKNOWN_COM_ERROR);
       break;
     }
     uint tbl_len= *(uchar*) (packet + db_len + 1);
     if (db_len+tbl_len+2 > packet_length || tbl_len > NAME_LEN)
     {
-      send_error(&thd->net, ER_UNKNOWN_COM_ERROR);
+      send_error(thd, ER_UNKNOWN_COM_ERROR);
       break;
     }


feat: makes blur switchable through Java code

--- card.io/src/main/jni/nativeRecognizer.cpp
+++ card.io/src/main/jni/nativeRecognizer.cpp
@@ -28,7 +28,7 @@
 static ScannerState scannerState;
 static bool detectOnly;
 static bool flipped;
-static bool lastFrameWasUsable;
+static int blur;
 static float minFocusScore;

 static struct {
@@ -151,14 +151,15 @@
 }

 extern "C"
-JNIEXPORT void JNICALL Java_io_card_payment_CardScanner_nSetup(JNIEnv *env, jobject thiz,
-    jboolean shouldOnlyDetectCard, jfloat jMinFocusScore) {
+JNIEXPORT void JNICALL Java_io_card_payment_CardScanner_nSetup__ZFI(JNIEnv *env, jobject thiz,
+    jboolean shouldOnlyDetectCard, jfloat jMinFocusScore, jint jBlur) {
   dmz_debug_log("Java_io_card_payment_CardScanner_nSetup");
   dmz_trace_log("dmz trace enabled");

   detectOnly = shouldOnlyDetectCard;
   minFocusScore = jMinFocusScore;
+  blur = jBlur;
   flipped = false;
   lastFrameWasUsable = false;

@@ -172,6 +173,12 @@
   dmz_refcount++;

   cvSetErrMode(CV_ErrModeParent);
+}
+
+extern "C"
+JNIEXPORT void JNICALL Java_io_card_payment_CardScanner_nSetup__ZF(JNIEnv *env, jobject thiz,
+    jboolean shouldOnlyDetectCard, jfloat jMinFocusScore) {
+    return Java_io_card_payment_CardScanner_nSetup__ZFI(env, thiz, shouldOnlyDetectCard, jMinFocusScore, 12);
 }

 extern "C"
@@ -295,7 +302,7 @@
     // blur cardnumber
     int num_y = state->mostRecentUsableVSeg.y_offset - 1;
     int num_h = kNumberHeight + 2;
-    for (int i = 0; i < state->mostRecentUsableHSeg.n_offsets; i++) {
+    for (int i = 0; i < state->mostRecentUsableHSeg.n_offsets && i < blur; i++) {
         int num_x = state->mostRecentUsableHSeg.offsets[i] - 1;
         int num_w = state->mostRecentUsableHSeg.number_width + 2;
         cvSetImageROI(cardResult, cvRect(num_x, num_y, num_w, num_h));


provide access to QAbstractSocket error string on error

When a socket error occurs the string version of the error is now
stored in QAmqpClient's internal errorString variable, providing
access to the string to users of the client.

--- src/qamqpclient.cpp
+++ src/qamqpclient.cpp
@@ -189,6 +189,7 @@
     // per spec, on any error we need to close the socket immediately
     // and send no more data;
     socket->close();
+    errorString = socket->errorString();

     if (autoReconnect) {
         qAmqpDebug() << "trying to reconnect after: " << timeout << "ms";


add test of equivalence of a cluster with separate suffstats

--- tests/test_cluster.cpp
+++ tests/test_cluster.cpp
@@ -17,13 +17,45 @@
   cout << "Begin:: test_cluster" << endl;
   RandomNumberGenerator rng;

+  int max_value = 20;
+  int num_rows = 3;
+  int num_cols = 3;
+  Cluster<double> cd(num_cols);
+  vector<Suffstats<double> > sd_v;
+  for(int row_idx=0; row_idx<num_rows; row_idx++) {
+    Suffstats<double> sd;
+    sd_v.push_back(sd);
+  }
+  for(int row_idx=0; row_idx<num_rows; row_idx++) {
+    vector<double> row_data;
+    for(int col_idx=0; col_idx<num_cols; col_idx++) {
+      double new_value = (rng.nexti(max_value) + 1) * rng.next();
+      sd_v[col_idx].insert_el(new_value);
+      row_data.push_back(new_value);
+    }
+    cd.insert_row(row_data, row_idx);
+  }
+  vector<double> score_v;
+  double sum_scores = 0;
+  for(int col_idx=0; col_idx<num_cols; col_idx++) {
+    double suff_score = sd_v[col_idx].get_score();
+    score_v.push_back(suff_score);
+    sum_scores += suff_score;
+  }
+  cout << "vector off separate suffstats scores: " << score_v << endl;
+  cout << "sum separate scores: " << sum_scores << endl;
+  cout << "Cluster score with same data: " << cd.get_score() << endl;
+  cout << endl;
+  //
+  assert(is_almost(sum_scores, cd.get_score(), 1E-10));
+
   double sum_sum_score_deltas;

   boost::numeric::ublas::matrix<double> Data;
   LoadData("SynData2.csv", Data);
   // std::cout << Data << std::endl;

-  Cluster<double> cd(5); //hard code # columns
+  cd = Cluster<double>(5); //hard code # columns
   std::cout << std::endl << "Init cluster" << std::endl;
   std::cout << cd << std::endl;


AudioLoader Leak Fix

AudioLoader Leak Fix

--- src/algorithms/io/audioloader.cpp
+++ src/algorithms/io/audioloader.cpp
@@ -197,6 +197,9 @@
     // Close the codec
     avcodec_close(_audioCtx);

+    // free AVPacket
+    av_free_packet(&_packet);
+
     // Close the audio file
     avformat_close_input(&_demuxCtx);

@@ -241,7 +244,7 @@

     decodePacket();
     copyFFmpegOutput();
-
+    av_free_packet(&_packet);
     return OK;
 }


Limit the search depth of MaskedValueIsZero to 6 instructions, to avoid
bad cases.  This fixes Markus's second testcase in PR639, and should
seal it for good.

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@24123 91177308-0d34-0410-b5e6-96231b3b80d8

--- lib/Transforms/Scalar/InstructionCombining.cpp
+++ lib/Transforms/Scalar/InstructionCombining.cpp
@@ -389,7 +389,8 @@
 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
 /// this predicate to simplify operations downstream.  V and Mask are known to
 /// be the same type.
-static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask) {
+static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask,
+                              unsigned Depth = 0) {
   // Note, we cannot consider 'undef' to be "IsZero" here.  The problem is that
   // we cannot optimize based on the assumption that it is zero without changing
   // to to an explicit zero.  If we don't change it to zero, other code could
@@ -400,6 +401,8 @@
     return true;
   if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
     return ConstantExpr::getAnd(CI, Mask)->isNullValue();
+
+  if (Depth == 6) return false;  // Limit search depth.

   if (Instruction *I = dyn_cast<Instruction>(V)) {
     switch (I->getOpcode()) {
@@ -408,21 +411,21 @@
       if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1))) {
         ConstantIntegral *C1C2 =
           cast<ConstantIntegral>(ConstantExpr::getAnd(CI, Mask));
-        if (MaskedValueIsZero(I->getOperand(0), C1C2))
+        if (MaskedValueIsZero(I->getOperand(0), C1C2, Depth+1))
           return true;
       }
       // If either the LHS or the RHS are MaskedValueIsZero, the result is zero.
-      return MaskedValueIsZero(I->getOperand(1), Mask) ||
-             MaskedValueIsZero(I->getOperand(0), Mask);
+      return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) ||
+             MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
     case Instruction::Or:
     case Instruction::Xor:
       // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
-      return MaskedValueIsZero(I->getOperand(1), Mask) &&
-             MaskedValueIsZero(I->getOperand(0), Mask);
+      return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) &&
+             MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
     case Instruction::Select:
       // If the T and F values are MaskedValueIsZero, the result is also zero.
-      return MaskedValueIsZero(I->getOperand(2), Mask) &&
-             MaskedValueIsZero(I->getOperand(1), Mask);
+      return MaskedValueIsZero(I->getOperand(2), Mask, Depth+1) &&
+             MaskedValueIsZero(I->getOperand(1), Mask, Depth+1);
     case Instruction::Cast: {
       const Type *SrcTy = I->getOperand(0)->getType();
       if (SrcTy == Type::BoolTy)
@@ -440,7 +443,7 @@
           Constant *NewMask =
           ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
           return MaskedValueIsZero(I->getOperand(0),
-                                   cast<ConstantIntegral>(NewMask));
+                                   cast<ConstantIntegral>(NewMask), Depth+1);
         }
       }
       break;
@@ -449,7 +452,8 @@
       // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
       if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
         return MaskedValueIsZero(I->getOperand(0),
-                    cast<ConstantIntegral>(ConstantExpr::getUShr(Mask, SA)));
+                    cast<ConstantIntegral>(ConstantExpr::getUShr(Mask, SA)),
+                                 Depth+1);
       break;
     case Instruction::Shr:
       // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0


avoid extra copy

avoid extra copy

--- moveit_core/planning_scene/src/planning_scene.cpp
+++ moveit_core/planning_scene/src/planning_scene.cpp
@@ -766,9 +766,8 @@
       }
       else
       {
-        moveit_msgs::CollisionObject co;
-        getCollisionObjectMsg(co, it->first);
-        scene_msg.world.collision_objects.push_back(co);
+        scene_msg.world.collision_objects.emplace_back();
+        getCollisionObjectMsg(scene_msg.world.collision_objects.back(), it->first);
       }
     }
     if (do_omap)
@@ -856,9 +855,8 @@
   for (std::size_t i = 0; i < ns.size(); ++i)
     if (ns[i] != OCTOMAP_NS)
     {
-      moveit_msgs::CollisionObject co;
-      getCollisionObjectMsg(co, ns[i]);
-      collision_objs.push_back(co);
+      collision_objs.emplace_back();
+      getCollisionObjectMsg(collision_objs.back(), ns[i]);
     }
 }


Delete kernel.cpp

Delete kernel.cpp

--- kernel.cpp
+++ kernel.cpp
@@ -1,387 +0,0 @@
-// Copyright (c) 2012-2013 The PPCoin developers
-// Distributed under the MIT/X11 software license, see the accompanying
-// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-
-#include <boost/assign/list_of.hpp>
-
-#include "kernel.h"
-#include "txdb.h"
-
-using namespace std;
-
-typedef std::map<int, unsigned int> MapModifierCheckpoints;
-
-// Hard checkpoints of stake modifiers to ensure they are deterministic
-static std::map<int, unsigned int> mapStakeModifierCheckpoints =
-    boost::assign::map_list_of
-        ( 0, 0x0e00670bu )
-    ;
-
-// Hard checkpoints of stake modifiers to ensure they are deterministic (testNet)
-static std::map<int, unsigned int> mapStakeModifierCheckpointsTestNet =
-    boost::assign::map_list_of
-        ( 0, 0x0e00670bu )
-    ;
-
-// Get time weight
-int64_t GetWeight(int64_t nIntervalBeginning, int64_t nIntervalEnd)
-{
-    // Kernel hash weight starts from 0 at the min age
-    // this change increases active coins participating the hash and helps
-    // to secure the network when proof-of-stake difficulty is low
-
-    return min(nIntervalEnd - nIntervalBeginning - nStakeMinAge, (int64_t)nStakeMaxAge);
-}
-
-// Get the last stake modifier and its generation time from a given block
-static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64_t& nStakeModifier, int64_t& nModifierTime)
-{
-    if (!pindex)
-        return error("GetLastStakeModifier: null pindex");
-    while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())
-        pindex = pindex->pprev;
-    if (!pindex->GeneratedStakeModifier())
-        return error("GetLastStakeModifier: no generation at genesis block");
-    nStakeModifier = pindex->nStakeModifier;
-    nModifierTime = pindex->GetBlockTime();
-    return true;
-}
-
-// Get selection interval section (in seconds)
-static int64_t GetStakeModifierSelectionIntervalSection(int nSection)
-{
-    assert (nSection >= 0 && nSection < 64);
-    return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1))));
-}
-
-// Get stake modifier selection interval (in seconds)
-static int64_t GetStakeModifierSelectionInterval()
-{
-    int64_t nSelectionInterval = 0;
-    for (int nSection=0; nSection<64; nSection++)
-        nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection);
-    return nSelectionInterval;
-}
-
-// select a block from the candidate blocks in vSortedByTimestamp, excluding
-// already selected blocks in vSelectedBlocks, and with timestamp up to
-// nSelectionIntervalStop.
-static bool SelectBlockFromCandidates(vector<pair<int64_t, uint256> >& vSortedByTimestamp, map<uint256, const CBlockIndex*>& mapSelectedBlocks,
-    int64_t nSelectionIntervalStop, uint64_t nStakeModifierPrev, const CBlockIndex** pindexSelected)
-{
-    bool fSelected = false;
-    uint256 hashBest = 0;
-    *pindexSelected = (const CBlockIndex*) 0;
-    BOOST_FOREACH(const PAIRTYPE(int64_t, uint256)& item, vSortedByTimestamp)
-    {
-        if (!mapBlockIndex.count(item.second))
-            return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str());
-        const CBlockIndex* pindex = mapBlockIndex[item.second];
-        if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)
-            break;
-        if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)
-            continue;
-        // compute the selection hash by hashing its proof-hash and the
-        // previous proof-of-stake modifier
-        CDataStream ss(SER_GETHASH, 0);
-        ss << pindex->hashProof << nStakeModifierPrev;
-        uint256 hashSelection = Hash(ss.begin(), ss.end());
-        // the selection hash is divided by 2**32 so that proof-of-stake block
-        // is always favored over proof-of-work block. this is to preserve
-        // the energy efficiency property
-        if (pindex->IsProofOfStake())
-            hashSelection >>= 32;
-        if (fSelected && hashSelection < hashBest)
-        {
-            hashBest = hashSelection;
-            *pindexSelected = (const CBlockIndex*) pindex;
-        }
-        else if (!fSelected)
-        {
-            fSelected = true;
-            hashBest = hashSelection;
-            *pindexSelected = (const CBlockIndex*) pindex;
-        }
-    }
-    if (fDebug && GetBoolArg("-printstakemodifier"))
-        printf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str());
-    return fSelected;
-}
-
-// Stake Modifier (hash modifier of proof-of-stake):
-// The purpose of stake modifier is to prevent a txout (coin) owner from
-// computing future proof-of-stake generated by this txout at the time
-// of transaction confirmation. To meet kernel protocol, the txout
-// must hash with a future stake modifier to generate the proof.
-// Stake modifier consists of bits each of which is contributed from a
-// selected block of a given block group in the past.
-// The selection of a block is based on a hash of the block's proof-hash and
-// the previous stake modifier.
-// Stake modifier is recomputed at a fixed time interval instead of every
-// block. This is to make it difficult for an attacker to gain control of
-// additional bits in the stake modifier, even after generating a chain of
-// blocks.
-bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64_t& nStakeModifier, bool& fGeneratedStakeModifier)
-{
-    nStakeModifier = 0;
-    fGeneratedStakeModifier = false;
-    if (!pindexPrev)
-    {
-        fGeneratedStakeModifier = true;
-        return true;  // genesis block's modifier is 0
-    }
-    // First find current stake modifier and its generation block time
-    // if it's not old enough, return the same stake modifier
-    int64_t nModifierTime = 0;
-    if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime))
-        return error("ComputeNextStakeModifier: unable to get last modifier");
-    if (fDebug)
-    {
-        printf("ComputeNextStakeModifier: prev modifier=0x%016"PRIx64" time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str());
-    }
-    if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval)
-        return true;
-
-    // Sort candidate blocks by timestamp
-    vector<pair<int64_t, uint256> > vSortedByTimestamp;
-    vSortedByTimestamp.reserve(64 * nModifierInterval / nTargetSpacing);
-    int64_t nSelectionInterval = GetStakeModifierSelectionInterval();
-    int64_t nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval;
-    const CBlockIndex* pindex = pindexPrev;
-    while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart)
-    {
-        vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
-        pindex = pindex->pprev;
-    }
-    int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
-    reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
-    sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
-
-    // Select 64 blocks from candidate blocks to generate stake modifier
-    uint64_t nStakeModifierNew = 0;
-    int64_t nSelectionIntervalStop = nSelectionIntervalStart;
-    map<uint256, const CBlockIndex*> mapSelectedBlocks;
-    for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++)
-    {
-        // add an interval section to the current selection round
-        nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);
-        // select a block from the candidates of current round
-        if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex))
-            return error("ComputeNextStakeModifier: unable to select block at round %d", nRound);
-        // write the entropy bit of the selected block
-        nStakeModifierNew |= (((uint64_t)pindex->GetStakeEntropyBit()) << nRound);
-        // add the selected block from candidates to selected list
-        mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));
-        if (fDebug && GetBoolArg("-printstakemodifier"))
-            printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n", nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
-    }
-
-    // Print selection map for visualization of the selected blocks
-    if (fDebug && GetBoolArg("-printstakemodifier"))
-    {
-        string strSelectionMap = "";
-        // '-' indicates proof-of-work blocks not selected
-        strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
-        pindex = pindexPrev;
-        while (pindex && pindex->nHeight >= nHeightFirstCandidate)
-        {
-            // '=' indicates proof-of-stake blocks not selected
-            if (pindex->IsProofOfStake())
-                strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "=");
-            pindex = pindex->pprev;
-        }
-        BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks)
-        {
-            // 'S' indicates selected proof-of-stake blocks
-            // 'W' indicates selected proof-of-work blocks
-            strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? "S" : "W");
-        }
-        printf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str());
-    }
-    if (fDebug)
-    {
-        printf("ComputeNextStakeModifier: new modifier=0x%016"PRIx64" time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str());
-    }
-
-    nStakeModifier = nStakeModifierNew;
-    fGeneratedStakeModifier = true;
-    return true;
-}
-
-// The stake modifier used to hash for a stake kernel is chosen as the stake
-// modifier about a selection interval later than the coin generating the kernel
-static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64_t& nStakeModifier, int& nStakeModifierHeight, int64_t& nStakeModifierTime, bool fPrintProofOfStake)
-{
-    nStakeModifier = 0;
-    if (!mapBlockIndex.count(hashBlockFrom))
-        return error("GetKernelStakeModifier() : block not indexed");
-    const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];
-    nStakeModifierHeight = pindexFrom->nHeight;
-    nStakeModifierTime = pindexFrom->GetBlockTime();
-    int64_t nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();
-    const CBlockIndex* pindex = pindexFrom;
-    // loop to find the stake modifier later by a selection interval
-    while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval)
-    {
-        if (!pindex->pnext)
-        {   // reached best block; may happen if node is behind on block chain
-            if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime()))
-                return error("GetKernelStakeModifier() : reached best block %s at height %d from block %s",
-                    pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str());
-            else
-                return false;
-        }
-        pindex = pindex->pnext;
-        if (pindex->GeneratedStakeModifier())
-        {
-            nStakeModifierHeight = pindex->nHeight;
-            nStakeModifierTime = pindex->GetBlockTime();
-        }
-    }
-    nStakeModifier = pindex->nStakeModifier;
-    return true;
-}
-
-// ppcoin kernel protocol
-// coinstake must meet hash target according to the protocol:
-// kernel (input 0) must meet the formula
-//     hash(nStakeModifier + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDayWeight
-// this ensures that the chance of getting a coinstake is proportional to the
-// amount of coin age one owns.
-// The reason this hash is chosen is the following:
-//   nStakeModifier: scrambles computation to make it very difficult to precompute
-//                  future proof-of-stake at the time of the coin's confirmation
-//   txPrev.block.nTime: prevent nodes from guessing a good timestamp to
-//                       generate transaction for future advantage
-//   txPrev.offset: offset of txPrev inside block, to reduce the chance of
-//                  nodes generating coinstake at the same time
-//   txPrev.nTime: reduce the chance of nodes generating coinstake at the same
-//                 time
-//   txPrev.vout.n: output number of txPrev, to reduce the chance of nodes
-//                  generating coinstake at the same time
-//   block/tx hash should not be used here as they can be generated in vast
-//   quantities so as to generate blocks faster, degrading the system back into
-//   a proof-of-work situation.
-//
-bool CheckStakeKernelHash(unsigned int nBits, const CBlock& blockFrom, unsigned int nTxPrevOffset, const CTransaction& txPrev, const COutPoint& prevout, unsigned int nTimeTx, uint256& hashProofOfStake, uint256& targetProofOfStake, bool fPrintProofOfStake)
-{
-    if (nTimeTx < txPrev.nTime)  // Transaction timestamp violation
-        return error("CheckStakeKernelHash() : nTime violation");
-
-    unsigned int nTimeBlockFrom = blockFrom.GetBlockTime();
-    if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement
-        return error("CheckStakeKernelHash() : min age violation");
-
-    CBigNum bnTargetPerCoinDay;
-    bnTargetPerCoinDay.SetCompact(nBits);
-    int64_t nValueIn = txPrev.vout[prevout.n].nValue;
-
-    uint256 hashBlockFrom = blockFrom.GetHash();
-
-    CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64_t)txPrev.nTime, (int64_t)nTimeTx) / COIN / (24 * 60 * 60);
-    targetProofOfStake = (bnCoinDayWeight * bnTargetPerCoinDay).getuint256();
-
-    // Calculate hash
-    CDataStream ss(SER_GETHASH, 0);
-    uint64_t nStakeModifier = 0;
-    int nStakeModifierHeight = 0;
-    int64_t nStakeModifierTime = 0;
-
-    if (!GetKernelStakeModifier(hashBlockFrom, nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake))
-        return false;
-    ss << nStakeModifier;
-
-    ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx;
-    hashProofOfStake = Hash(ss.begin(), ss.end());
-    if (fPrintProofOfStake)
-    {
-        printf("CheckStakeKernelHash() : using modifier 0x%016"PRIx64" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
-            nStakeModifier, nStakeModifierHeight,
-            DateTimeStrFormat(nStakeModifierTime).c_str(),
-            mapBlockIndex[hashBlockFrom]->nHeight,
-            DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
-        printf("CheckStakeKernelHash() : check modifier=0x%016"PRIx64" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
-            nStakeModifier,
-            nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
-            hashProofOfStake.ToString().c_str());
-    }
-
-    // Now check if proof-of-stake hash meets target protocol
-    if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay)
-        return false;
-    if (fDebug && !fPrintProofOfStake)
-    {
-        printf("CheckStakeKernelHash() : using modifier 0x%016"PRIx64" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
-            nStakeModifier, nStakeModifierHeight,
-            DateTimeStrFormat(nStakeModifierTime).c_str(),
-            mapBlockIndex[hashBlockFrom]->nHeight,
-            DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
-        printf("CheckStakeKernelHash() : pass modifier=0x%016"PRIx64" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
-            nStakeModifier,
-            nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
-            hashProofOfStake.ToString().c_str());
-    }
-    return true;
-}
-
-// Check kernel hash target and coinstake signature
-bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake)
-{
-    if (!tx.IsCoinStake())
-        return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str());
-
-    // Kernel (input 0) must match the stake hash target per coin age (nBits)
-    const CTxIn& txin = tx.vin[0];
-
-    // First try finding the previous transaction in database
-    CTxDB txdb("r");
-    CTransaction txPrev;
-    CTxIndex txindex;
-    if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
-        return tx.DoS(1, error("CheckProofOfStake() : INFO: read txPrev failed"));  // previous transaction not in main chain, may occur during initial download
-
-    // Verify signature
-    if (!VerifySignature(txPrev, tx, 0, 0))
-        return tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str()));
-
-    // Read block header
-    CBlock block;
-    if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
-        return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction
-
-    if (!CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, targetProofOfStake, fDebug))
-        return tx.DoS(1, error("CheckProofOfStake() : INFO: check kernel failed on coinstake %s, hashProof=%s", tx.GetHash().ToString().c_str(), hashProofOfStake.ToString().c_str())); // may occur during initial download or if behind on block chain sync
-
-    return true;
-}
-
-// Check whether the coinstake timestamp meets protocol
-bool CheckCoinStakeTimestamp(int64_t nTimeBlock, int64_t nTimeTx)
-{
-    // v0.3 protocol
-    return (nTimeBlock == nTimeTx);
-}
-
-// Get stake modifier checksum
-unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex)
-{
-    assert (pindex->pprev || pindex->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
-    // Hash previous checksum with flags, hashProofOfStake and nStakeModifier
-    CDataStream ss(SER_GETHASH, 0);
-    if (pindex->pprev)
-        ss << pindex->pprev->nStakeModifierChecksum;
-    ss << pindex->nFlags << (pindex->IsProofOfStake() ? pindex->hashProof : 0) << pindex->nStakeModifier;
-    uint256 hashChecksum = Hash(ss.begin(), ss.end());
-    hashChecksum >>= (256 - 32);
-    return hashChecksum.Get64();
-}
-
-// Check stake modifier hard checkpoints
-bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)
-{
-    MapModifierCheckpoints& checkpoints = (fTestNet ? mapStakeModifierCheckpointsTestNet : mapStakeModifierCheckpoints);
-
-    if (checkpoints.count(nHeight))
-        return nStakeModifierChecksum == checkpoints[nHeight];
-    return true;
-}


Fix compile problem - line missing.

Fix compile problem - line missing.

--- sql/sql_parse.cc
+++ sql/sql_parse.cc
@@ -147,6 +147,7 @@
     error= -1;
   else
   {
+    LEX *lex= thd->lex;
     thd->options= ((thd->options & (ulong) ~(OPTION_STATUS_NO_TRANS_UPDATE)) |
 		   OPTION_BEGIN);
     thd->server_status|= SERVER_STATUS_IN_TRANS;