vendredi 8 mai 2015

Boost::geometry query returning indexes

I want to have class, which uses boost::geometry::index::rtree for spatial indexers. This class alone should know about boost, so I use something like this:

struct VeryImportantInfo
{
    ...
    float x;
    float y;
}

class Catalogue
{
    ...
public:
    std::vector<std::shared_ptr<VeryImportantInfo> > FindIn(float x1, float x2, float y1, float y2);

protected:
    using point = bg::model::point<float, 2, bg::cs::cartesian>;
    using value = std::pair<point, std::shared_ptr<VeryImportantInfo> >;
    using box = bg::model::box<point>;        

    boost::geometry::index::rtree< value, bgi::quadratic<16> > rtree;
}

std::vector<std::shared_ptr<VeryImportantInfo> > Catalogue::FindIn(float x1, float y1, float x2, float y2)
{
    box query_box(point(x1, y1), point(x2, y2));
    ???
}

I don't know how to do query properly (Please don't look at this awful vector return by copy, it is just for example sake). I can do this:

std::vector<std::shared_ptr<VeryImportantInfo> > Catalogue::FindIn(float x1, float y1, float x2, float y2)
{
    box query_box(point(x1, y1), point(x2, y2));
    std::vector<value> result_s;
    rtree.query(bgi::intersects(query_box), std::back_inserter(result_s));
    std::vector<std::shared_ptr<VeryImportantInfo> > results;
    results.reserve(result_s.size());
    for( auto& p : result_s)
    {
        results.emplace_back(p.second);
    }
    return results;
}

I want to know, how can I get rid of internal copy(not return copy, results.emplace_back(p.second); - this one). Because I can have more that 10k results in result_s and it will be a waste.

Thank you!

field ‘value’ has incomplete type

I have a C++ interdependence problem and i can not understand where the problem is...

Here are my headers:

json.array.h

#ifndef __JSON_ARRAY__
#define __JSON_ARRAY__

#include "json.object.h"

class JSON_OBJECT;

/* JSON_ARRAY */
class JSON_ARRAY {
    int size;
    custom_list<JSON_OBJECT> * container;

...
};

#endif

json.object.h

#ifndef __JSON_OBJECT__
#define __JSON_OBJECT__

#include "hash.h"
#include "elem_info.h"
#include "json.type.h"

class JSON_TYPE;
class elem_info;

/* JSON_OBJECT */
class JSON_OBJECT {
    custom_list<elem_info> *H;
    int HMAX;
    unsigned int (*hash) (std::string);
...
};

#endif

json.type.h

#ifndef __JSON_TYPE__
#define __JSON_TYPE__

#include "json.object.h"
#include "json.array.h"

class JSON_OBJECT;
class JSON_ARRAY;

class JSON_TYPE {
    JSON_ARRAY * _JSON_ARRAY_;
    JSON_OBJECT * _JSON_OBJECT_;
    std::string _JSON_OTHER_;
    std::string _JSON_TYPE_;
...
};

#endif

elem_info.h

#ifndef __ELEM_INFO__
#define __ELEM_INFO__

#include "json.type.h"
class JSON_TYPE;

class elem_info {
public:
    std::string key;
    JSON_TYPE value;
...
}; 

#endif

main.cpp

#include <iostream>
#include <string>

#include "custom_list.h" // it inculdes cpp also
#include "json.type.h"
#include "elem_info.h"
#include "json.object.h"
#include "json.array.h"
#include "json.type.cpp"
#include "elem_info.cpp"
#include "json.object.cpp"
#include "json.array.cpp"


int main()
{
    JSON_ARRAY * root = new JSON_ARRAY;
    JSON_OBJECT obj;
    JSON_OBJECT obj1;
    JSON_OBJECT * obj2 = new JSON_OBJECT;
    JSON_TYPE * type = new JSON_TYPE;
...
}

When i try to compile my code, i have this error:

elem_info.h:10:15: error: field ‘value’ has incomplete type JSON_TYPE value;

It looks like it cant find JSON_TYPE. I cant understand where is the problem. Thanks for your help.

WINAPI cursor click position on application window

I need to write a small program that can know where the user click the button or somehow on a application windows whatever the application windows change the size .

Through use the windows API, now I can only get the global cursor click position.

I find a small program from china that have similar function using AHK to implement it. Maybe the author use this (WinGetPos) see the image below:

enter image description here

So, Is the any windows api or other QT5, C++ function can help me get the application windows cursor click position. (I develop in QT5)

post some code on here:

GetCursorPos (&screenpoint);
hwndFoundWindow = WindowFromPoint (screenpoint);
mp.DisplayInfoOnFoundWindow(QString::fromLocal8Bit("L"), hwndFoundWindow, pMouseStruct->pt.x, pMouseStruct->pt.y);

Compilation and execution when code is not dislosed; use of ellipsis in code

In an interview I was asked following question

Given the code fragments below, where the ellipsis (…) represents code that has not been disclosed to you:

class X { … };  class Y { public: explicit Y(const X& x); … }; 

what can you say about the compilation and execution of each of the following statements? Describe each of the operations that occur as this code executes.

Y func(Y y) { … }
X x;
Y y = func(Y(x));

I could not understand the question properly hence was not able to answer. if some one could explain me what answer was expected of me or share any link which I can go through, that would be really nice. Many Thanks.

How to embed a custom font in my application

I want to add a custom font to my application, and I have already added to my resource file.

And my code as the following:

int id = QFontDatabase::addApplicationFont(":/fonts/ae_AlMateen.ttf");
QMessageBox::information(this,"Message",QString::number(id));

But the problem is that the addApplicationFont always returns -1.

Note that when change the :/fonts/ae_AlMateen.ttf to direct path ex:C://ae_AlMateen.ttf it works fine.

I dont know what is the problem.

A segmentation fault

I have try the following code to judge prime:

const int N = 200000;
long prime[N] = {0};
long num_prime = 0;
int is_not_prime[N]={1,1};
void Prime_sort(void)
{
    for( long i = 2 ; i<N ; i++ )
    {
        if( !is_not_prime[i] )
        {
            prime[num_prime++] = i;
        }
        for( long j = 0; j<num_prime && i*prime[i]<N ; j++ )
        {
            is_not_prime[i*prime[j]] = 1;
        }   
    }   
}

But when I run it, it cause a segmentation fault! That fault I have never meet.And I searched Google,and it explain segmentation fault as follow:

A segmentation fault (often shortened to segfault) is a particular error condition that can occur during the operation of computer software. In short, a segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed

But I don't know where cause this fault in my code.Please help me.

Finding all parents from node to the root in a tree by recursion

I have a class Graph, modelling a Tree. Graph contain a pointer Graph* to the parent of my current instance (my current node).

class Graph
{
private:

    Graph*           parent;
public:
    Graph*           getparent();
}

Graph*          Graph::getparent()
{
    return this->parent;
}

parent is at nullptr if root.

I'm trying to find the distance from a node to the root, starting from the node.

Here is my try :

int Graph::howManyParents(Graph* unparent)
{
    int nbParents(0);
    if(unparent != nullptr)
    {
        nbParents++;
        nbParents =+ howManyParents(this->parent);
    }
    return nbParents;
}

It compiles but crashes. Debbugger show me lots of call to the method, but end up SegFaulting. Is there something wrong with my algorithm ?

Accessing Private Members with Cin inside Class

I'm little confused.. My Code is Below

#include <iostream>
using namespace std;
class Test {
    private:
    int x, y;
  public:
    void get(){
        cin>>x;
        cin >>y;
        cout << x;
        cout << y;
    }
};

int main ()
{
  Test obj;
  obj.get();
  return 0;
}

In this code I'm accessing private members using cin..!! Is it fine? because I think user can send values or access private members directly after program run..!!

std::reference_wrapper on MS Visual Studio 2013

I try to compile some code which is very similar to:

#include <string>
#include <unordered_map>

class A{
};

int main(int argc, char* argv[]){
  std::unordered_map<std::string, std::reference_wrapper<const A>> stringToRef;
  A a;
  const A& b = a;
  stringToRef.insert(std::make_pair("Test", b));
  return 0;
}

But can't figure out, why it's not compiling. I'm pretty sure, that the same code compiled fine on MS Visual Studio 2012 - but on Visual Studio 2013, it reports the following compilation error:

error C2280: std::reference_wrapper<const A>::reference_wrapper(_Ty &&): attempting to reference a deleted function

I tried to add copy, move, assignment operators to my class - but couldn't get rid of this error. How can I find out exactly, which deleted function this error refers to?

Permute rows of a eigen matrix with specific indexes

Following the indications published in this previous question, I'm trying to permute the rows of a Eigen matrix using specific indexes.

Basically I have a function that performs the next steps:

    PermutationMatrix<Dynamic, Dynamic, size_t> perm(indices.size());
    copy(indices.begin(), indices.end(), perm.indices().data());
    return perm * mat; // permute rows

But writing some unit tests I realized that in most of the cases the permutation is done incorrectly. This unit tests can corroborate what I just stated (fmatrix_t is a type defined by myself which basically wrap a eigen dynamic mat with float values):

    fmatrix_t m;
    m.resize(8,1);
    m << 0, 1, 2, 3, 4, 5, 6, 7;

    indices_t indices {2,1,4,0,3,7,6,5};
    fmatrix_t m2 = apply_permutation(m, indices);
    BOOST_CHECK_NE(m, m2);
    for (size_t i = 0; i < indices.size(); ++i)
    {
            BOOST_CHECK_EQUAL(m2(i,0), indices[i]);
    }

However when indices is {0,1,2,3,4,5,6,7} or {7,6,5,4,3,2,1,0} the permutation is done correctly. Am I doing something wrong or it could be a Eigen bug?

Why isn't std::condition_variable templated by lock type?

It's useful to have the ability to assert in debug mode, with reasonably small overhead, whether a mutex is locked. Viewing the known options, I've chosen to implement this using an std::mutex subclass due to the low overheads.

The interface of the subclass is a superset of that of std::mutex, and so most things work well with it. E.g., std::unique_lock is templated to utilize any lock type that has a specific interface.

The problem is with std::condition_variable, in particular the wait members, e.g.:

template<class Predicate>
void wait(std::unique_lock<std::mutex> &lock, Predicate pred);

As can be seen, the method requires a very specific unique_lock/mutex combination. Unfortunately, also, the Liskov principle doesn't extend for container<derived> being converted into container<base>.

I don't understand

  1. why this is so?

Even if the intent was to enforce the use of std::unique_lock, then why couldn't the following be used:

template<class Predicate, class Lock=std::mutex>
void wait(std::unique_lock<Lock> &lock, Predicate pred);

  1. how to reasonably get around this?

Edit

As explained by @Lingxi, and further pointed out by @T.C, the absolutely correct and very simple solution here is to use condition_variable_any, which was designed for stuff like this.

Qt OpenCV - SIGSEGV when displaying transformed frames

I have an app that has to pull frames from video, transform one a little, transform one a lot, and simultaneously display them in GUI. In a worker thread, there's an OpenCV loop:

while(1) {
    cv::VideoCapture kalibrowanyPlik; 
    kalibrowanyPlik.open(kalibracja.toStdString()); //open file from url
    int maxFrames = kalibrowanyPlik.get(CV_CAP_PROP_FRAME_COUNT);
    for(int i=0; i<maxFrames; i++) //I thought it crashed when finished reading the first time around
    {
        cv::Mat frame;
        cv::Mat gray;
        cv::Mat color;

        kalibrowanyPlik.read(frame);
        cv::cvtColor(frame, gray, CV_BGR2GRAY);
        cv::cvtColor(frame, color, CV_BGR2RGB);

        QImage image((uchar*)color.data, color.cols, color.rows,QImage::Format_RGB888);
        QImage processedImage((uchar*)gray.data, gray.cols, gray.rows,QImage::Format_Indexed8);

        emit progressChanged(image, processedImage);
        QThread::msleep(50);
    }
}

And this is how frames are placed in GUI

void MainWindow::onProgressChagned(QImage image, QImage processedImage) {
    QPixmap processed = QPixmap::fromImage(processedImage);
    processed = processed.scaledToHeight(379);
    ui->labelHsv->clear();
    ui->labelHsv->setPixmap(processed);

    QPixmap original = QPixmap::fromImage(image); //debug points SIGSEGV here
    original = original.scaledToHeight(379);
    ui->labelKalibracja->clear();
    ui->labelKalibracja->setPixmap(original);
}

The RGB image always crashes, grayscale image never crashes (tested). Why is the RGB image crashing?

edit: I've just discovered that if I change msleep(50) to msleep(100) it executes perfectly. But I don't want that. I need at least 25 frames per second, 10 is not acceptable... why would that cause a SIGSEGV

Detect geometric object on video stream and reconstruct its contours

I'm trying to detect a plastic object on video stream using OpenCV 2.4.9 on C++. The object has six angles and its contour looks like :original image.
For each frame I'm doing some kind of segmentation and edges detection. After these operations i got some binary image containing corrupted contours of the object and some noise from background.
For example: enter image description here or enter image description here

I need somehow to detect my object here and restore contours. Could you advise some methods? I need a fast method since I want to run this program on android phone.

I know the proportions of my object. And the camera is always approximately at normal angle to the object's surface.
Sometimes when the contour is not corrupted much i can find the correct bounding box, but in other cases I can't.
I think that I need to use somehow the information about object's geometry here. I will appreciate any help!

UPD:
If I have found a partial contour of the object, is it possible to fit My shape somehow inside found contour to obtain missing lines?

About the local variables of functions in c++

I have been reading the C++ primer 5th edition. In the third paragraph of Function Parameter List of Chapter 6.1 . It writes "Moreover, local variables at the outermost scope of the function may not use the same name as any parameter". What does it mean?

I am not native English speaker. I don't understand the actual meanings of "outermost scope" of the function.

C++ ODB USB Interface

i want to to connect a OBD-USB (http://ift.tt/1EUU0gd) Device to my Laptop and stream the received data to c++ program. Problem is i have no idea how i can communicate with Tool via USB, if there is any library or protocol-standard that describes the way the datas are sent from such OBD-Usb-Tools.

Does anyone have some experience or can name some tools/sites that can help me?

Thanks in advance

Edit: Wow getting many downvotes but not even a comment what's wrong ...

EMGU CV Face Recognition from Image

I've been working with OpenCV before for C++ work and It was working great. Now, I'm developing a C# project and using EMGU CV for gender recognition. I've got problem with predict function. Every time I ran it, program crashed. Here's my code:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
     FaceRecognizer face = new FisherFaceRecognizer(0, 3500);
     face.Load("colorFisherFaceModel.yml");                
     Image<Bgr, Byte> img1 = new Image<Bgr, Byte>("C:\\Users\\sguthesis\\Pictures\\me.jpg");
     cascade = new CascadeClassifier("C:\\Users\\sguthesis\\documents\\visual studio 2013\\Projects\\EmguCV FFR with Image\\EmguCV FFR with Image\\haarcascade_frontalface_alt_tree.xml");
     FaceRecognizer.PredictionResult predictedLabel = face.Predict(img1);
}

Also, I want to get an output, 1 or 2. 1 for male and 2 for female. I have trained many data that saved on colorFisherFaceModel.yml. It was run well on OpenCV. But I don't know how to use it in EMGU CV.

Setting up GLEW with QOpenGLWidget

community,

I have a Problem Setting up GLEW in Qt. Here is my class

#ifndef MYQOPENGLWIDGET_H
#define MYQOPENGLWIDGET_H

#define QT_NO_OPENGL_ES_2

#define GLEW_STATIC
#include <GL/glew.h>
#include <QOpenGLWidget>
#include <QMessageBox>

#include <iostream>


class MyQOpenGLWidget : public QOpenGLWidget{

public:
MyQOpenGLWidget(QWidget *parent = 0): QOpenGLWidget(parent){}

void initializeGL()
{



    GLenum err = glewInit();

    if(err != GLEW_OK)
    {
        QMessageBox::information(0, "Error!", QString("Failed to initialize GLEW ") + reinterpret_cast<const char*>(glewGetErrorString(err)), QMessageBox::Yes );
        exit(1);
    }
    else
    {
        QMessageBox::information(0, "Success!", QString("Succeded to initialize GLEW! "), QMessageBox::Yes );

    }

    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
    glEnable(GL_DEPTH_TEST);

    std::cout << "Leaving initializeGL" << std::endl;
}

void paintGL()
{
    std::cout << "paintGL()" << std::endl;
}


void resizeGL(int w, int h)
{
    if(h == 0)
      h=1;
    glViewport(0,0,w,h);

    std::cout << "resizeGL()" << std::endl;

    glOrtho(-1, 1, -1, 1, -1, 1);

}

};

#endif // MYQOPENGLWIDGET_H

In my pro-file I succesfully link to GLEW (which is included in gltools.lib which Comes form the OpenGLSuperbible )

QT       += core gui widgets

QT += opengl

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = untitled2
TEMPLATE = app

INCLUDEPATH += "C:/Users/fin/Documents/GLEWTEst/include"
LIBS += "C:/Users/fin/Documents/GLEWTEst/lib/gltools.lib"

SOURCES += main.cpp\
        mainwindow.cpp

HEADERS  += mainwindow.h \
    myqopenglwidget.h

FORMS    += mainwindow.ui

DISTFILES += \
    ../build-untitled2-Desktop_Qt_5_4_1_MSVC2012_OpenGL_32bit-Debug/debug/untitled2.exe

Now what happens is, the Programm starts, and initializes GLEW correctly and calls initializeGL(), resizeGL() and then paintGL() Then it says the Programm was terminated with Exit code 1. So just a program Crash without any error message. Can anyone help me solve this?

Are there any alternatives to using OpenCV's imdecode? It is too slow

I have created a DLL where the user can either read an image from a file name or from a stream as follows:

std::string filePath = "SomeImage.bmp";

// (1) Reading from a file
Image2D img1;
img1.readImage(filePath);

// (2) Reading from a stream
std::ifstream imgStream (filePath.c_str(), std::ios::binary);
Image2D img2;
img2.readImage(imgStream);

The first readImage(filePath) is implemented using cv::imread(filePath) which is reasonably fast (on average 0.001 seconds for a 600 x 900 image). However, the second version readImage(fileStream) is implemented using cv::imdecode which is considerably slower (on average 2.5 seconds for the same image).

Are there any alternatives to cv::imdecode where I can decode an image from a memory buffer without taking such a long time? This is for the core component of an application that is frequently used, so it has to be quick.

Any assistance would be appreciated. Thanks in advance.

EDIT:

I measure the timings using a timer. It didn't make sense to me too. I don't understand why there is such a large disparity in the time. Image2D is just a class that has an OpenCV matrix as a member. The implementation of the readImage functions are simplified as follows:

int Image2D::readImage(std::ifstream& input)
{       
    input.seekg(0, std::ios::end);
    size_t fileSize = input.tellg();
    input.seekg(0, std::ios::beg);

    if (fileSize == 0) {
        return 1;
    }

    std::vector<unsigned char> data(fileSize);
    input.read(reinterpret_cast<char*>(&data[0]), sizeof(unsigned char) * fileSize);

    if (!input) {
        return 1;
    }

    StopWatch stopWatch;
    mImg = cv::imdecode(cv::Mat(data), CV_LOAD_IMAGE_COLOR);
    std::cout << "Time to decode: " << stopWatch.getElapsedTime() << std::endl;

    return 0;
}


int Image2D::readImage(const std::string& fileName)
{
    StopWatch stopWatch;
    mImg = cv::imread(fileName, CV_LOAD_IMAGE_COLOR);

    std::cout << "Time to read image: " << stopWatch.getElapsedTime() << std::endl;
    return 0;
}

Choose between template function and auto type deduction

I have a generic question about template functions versus auto type deduction for functions.

For years, we have have been able to write template function :

template <class T> T add(T a,T b){
    return a+b;
}

There is a TS for using auto for function's parameters deduction

auto add(auto a,auto b){
    return a+b;
}

I though with auto, one had no way to get to the actual type and for instance use static members, but this works just fine :

#include <iostream>

struct foo
{
    static void bar(){std::cout<<"bar"<<std::endl;}
    static int i ;
};
int foo::i{0};
void t(auto f){
    decltype(f)::bar();
    std::cout<<    decltype(f)::i<<std::endl;
}
int main(int argc, char *argv[])
{
    t(foo());
    return 0;
}    

So is there any reason to choose one instead of the other ?

Refreshing List Control with F5 key press C++

I have a List Control that shows a list of my database users. I also have a function that refreshes the list control (currently it is mapped to a "Refresh" button).

When the user presses the "F5" key, I want to call my refresh function.

I have found an event LVN_KEYDOWN (Indicates that a key has been pressed). After some research, I have found that the virtual keycode for "F5" is VK_F5. I am having trouble putting the two together, how can I check to see (in my event) that the "F5" key was the one that was pressed? I have tried several things similar to the code below:

void ListOption::OnLvnKeydownList1(NMHDR *pNMHDR, LRESULT *pResult)
{
    LPNMLVKEYDOWN pLVKeyDow = reinterpret_cast<LPNMLVKEYDOWN>(pNMHDR);

    // TODO: Add your control notification handler code here
    if(pLVKeyDow == (LPNMLVKEYDOWN)VK_F5)  
        callRefreshFunction();

    *pResult = 0;
}

How to add data dynamically in structure which is a Pointer to an array of pointers

I have two structure as below:

typdef struct abc
{
   int id;
   char name;
}s_abc,*lpabc;
typdef struct result
{
    int acc_no;
    lpabc *details;
}s_res;

I need to dynamically add the data within the structure result which points out to an array of pointers ie: struct abc The structure abc could be an array of 5 values for eg. How should i add the values ?

the structure defined are explicit: For better understanding i'm attaching the structure below:-

typedef struct _wfs_cdm_physicalcu
{
    LPSTR                 lpPhysicalPositionName;
    CHAR                  cUnitID[5];
    ULONG                 ulInitialCount;
    ULONG                 ulCount;
    ULONG                 ulRejectCount;
    ULONG                 ulMaximum;
    USHORT                usPStatus;
    BOOL                  bHardwareSensor; 
 } WFSCDMPHCU, *LPWFSCDMPHCU;

typedef struct _wfs_cdm_cashunit
{
    USHORT                usNumber;
    USHORT                usType;
    LPSTR                 lpszCashUnitName;
    CHAR                  cUnitID[5];
    CHAR                  cCurrencyID[3];
    BOOL                  bAppLock;
    USHORT                usStatus;
    USHORT                usNumPhysicalCUs;
    LPWFSCDMPHCU         *lppPhysical;

} WFSCDMCASHUNIT, *LPWFSCDMCASHUNIT;
typedef struct _wfs_cdm_cu_info
{
    USHORT                usTellerID;
    USHORT                usCount;
    LPWFSCDMCASHUNIT *lppList;
} WFSCDMCUINFO, *LPWFSCDMCUINFO;

Here i need to access the data of _wfs_cdm_physicalcu 4 times ie : an array.

Why std::random_device entropy is always 0?

Suppose I have this cross-platform program

#include <random>
#include <iostream>

int main()
{
    std::random_device rd;
    std::cout << "rd.entropy = " << rd.entropy() << std::endl;
    std::uniform_int_distribution<int> dist(0, 9);

    for (int i = 0; i < 10; ++i) {
        std::cout << dist(rd) << " ";
    }
    std::cout << std::endl;
}

On Linux Mint 17.1 with g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2 it always produces random numbers:

$ g++ -std=c++11 testrd.cpp -o testrd
$ ./testrd
rd.entropy = 0
9 2 6 0 8 1 0 2 3 8 
$ ./testrd
rd.entropy = 0
3 6 2 4 1 1 8 3 7 5 
$ ./testrd
rd.entropy = 0
3 4 4 6 8 5 4 6 6 3 
$ ./testrd
rd.entropy = 0
2 4 7 7 6 3 0 1 1 9 
$ ./testrd
rd.entropy = 0
7 2 5 0 7 8 6 6 0 6 

But how can I be sure, that on any system std::random_device is random? For example, on Windows with mingw-gcc it is not random (see, for example this question), it will produce same sequence on start. But on MSVC++ (according to S. Lavavej) starting from 2013.4 it is random.

I thought that I can do this:

if (rd.entropy() != 0) {
    // initialize some generator like mt19937 with rd()
}
else {
    // use another seed generator (for example, time in milliseconds)
}

i.e. comparing rd.entropy() with 0. But it turns out to be wrong.

How can I test std::random_device for randomness?

How to use qDebug() with two parameters in qt?

I am trying to use qDebug() with two parameters but it fails everytime.

When I use separately there is no problem, such as;

qDebug() << "img:width = " << img.width();
qDebug() << "img:height = " << img.height();

However when I combine them, it gives error.

qDebug() << "img:width = " << img.width() << "/t img:height = " << img.height() << std::endl;

Error is :

error: no match for 'operator<<' in '((QDebug*)((QDebug*)((QDebug*)qDebug()().QDebug::operator<<(((const char*)"img:width = ")))->QDebug::operator<<(img.QImage::width()))->QDebug::operator<<(((const char*)"/t img:height = ")))->QDebug::operator<<(img.QImage::height()) << std::endl'

Can I use two or more parameters in qDebug?

how does one pass an Armadillo vec/mat as a ref argument to another method?

I apologise as it might be a daft question but: I want to use a function to fill my matrix but am struggling to pass it as an argument. Can anyone help?

calculating vertex normals in opengl with c++

could anyone please help me calculating vertex normals in OpenGL? I am loading an obj file and adding Gouraud shading by calculating vertex normals without using glNormal3f or glLight functions.. I have declared functions like operators, crossproduct, innerproduct,and etc.. I have understood that in order to get vertex normals, I first need to calculate surface normal aka normal vector with crossproduct.. and also since I am loading an obj file.. and I am placing the three points of Faces of the obj file in id1,id2,id3 something like that

I would be grateful if anyone can help me writing codes or give me a guideline how to start the codes. please ... thanks..

its to draw

FACE cur_face = cube.face[i];
        glColor3f(cube.vertex_color[cur_face.id1].x,cube.vertex_color[cur_face.id1].y,cube.vertex_color[cur_face.id1].z);
        glVertex3f(cube.vertex[cur_face.id1].x,cube.vertex[cur_face.id1].y,cube.vertex[cur_face.id1].z);
        glColor3f(cube.vertex_color[cur_face.id2].x,cube.vertex_color[cur_face.id2].y,cube.vertex_color[cur_face.id2].z);
        glVertex3f(cube.vertex[cur_face.id2].x,cube.vertex[cur_face.id2].y,cube.vertex[cur_face.id2].z);
        glColor3f(cube.vertex_color[cur_face.id3].x,cube.vertex_color[cur_face.id3].y,cube.vertex_color[cur_face.id3].z);
        glVertex3f(cube.vertex[cur_face.id3].x,cube.vertex[cur_face.id3].y,cube.vertex[cur_face.id3].z);
    }

This is the equation for color calculation

VECTOR kd;
VECTOR ks;
kd=VECTOR(0.8, 0.8, 0.8);
ks=VECTOR(1.0, 0.0, 0.0);
double inner =  kd.InnerProduct(ks);

int i, j;
for(i=0;i<cube.vertex.size();i++)
{
    VECTOR n = cube.vertex_normal[i];
    VECTOR l = VECTOR(100,100,0) - cube.vertex[i];
    VECTOR v = VECTOR(0,0,1) - cube.vertex[i];
    float xl = n.InnerProduct(l)/n.Magnitude();
    VECTOR x = (n * (1.0/ n.Magnitude())) * xl;
    VECTOR r = x - (l-x);

    VECTOR color = kd * (n.InnerProduct(l)) + ks * pow((v.InnerProduct(r)),10);
    cube.vertex_color[i] = color;

C++: Parsing with strtok and creating char* array

I have a problem today with parsing a string, and, although I have used strtok previously, I came across a problem. My code looks like this>

int main()
{
char *arr[8]; //create a pointer to array of 8 elements
string data;

cout<<"please input string "<<endl;
cin>> data;

ifstream in(data.c_str());
    if (in.is_open()) {
        cout<<"opened"<<endl;
    } else{
        cout<<"can't open the file you asked for"<<endl;
    }

std::string line;

while(getline(in,line)) {
        if(line.find("STR") == 0) { //looking only for lines that start with STR

  char *forParsing = new char[line.size()+1];
  std::copy(line.begin(), line.end(), forParsing);
  forParsing[line.size()]='\0';  //everything looks good up to here

  char * pch;

  pch = strtok (forParsing,","); //separate input string on every comma
  while (pch != NULL)
  {
     arr[x] = pch; x++;  //x previously initialized to zero
     cout<<pch<<endl;
     pch = strtok (NULL, ",");
  }

  delete[] forParsing;
} //end if
} //end while

After some debugging, it seems to me that strtok does it's work on a first line it gets. After that, program takes a next line from a file and then entire thing crashes.

My plan with this is to put all the non-empty tokens in arr, then do some light editing, and collect it all into one string that will later be used.

Does anyone have any idea why is this happening?

Thanks in advance.

NOTE> if its of any importance Process return 255(0xFF) when it crashes.

Import a persistent key in to Windows key storage using CNG storage functions

I'm trying to import a persistent RSA public key into the key storage. I read on the CNG help page that it's possible for private keys and I wonder if I can also apply is to public keys (specifically the BCRYPT_RSAPUBLIC_BLOB). I've tried with the following code, but in the import section, when I call NCryptSetProperty to set the public blob as a property, I get "Error 0x80090029" which is NTE Bad Data. Having trouble debugging why this function is failing.

NCRYPT_PROV_HANDLE providerHandle = NULL;
NCRYPT_KEY_HANDLE keyHandle = NULL;
NTSTATUS status = STATUS_UNSUCCESSFUL;
PBYTE blob = NULL;
DWORD blob_len = 0;

///////////////////Export Test (extract key from storage)///////////////////////////

// Open handle to the Key Storage Provider
if(FAILED(status = NCryptOpenStorageProvider(
    &providerHandle,            //OUT: provider handle
    MS_KEY_STORAGE_PROVIDER,    //IN: Microsoft key storage provider
    0)))                        //IN: dwFlags (unused)
{
    //report fail
}

// Open key in the Key Storage Provider
if (FAILED(status = NCryptOpenKey(
    providerHandle,
    &keyHandle,
    keyName.c_str(),
    0,
    0)))
{
    //report fail
}

// (2 step key extraction process) 1. Get size of key
if (FAILED(status = NCryptExportKey(
    keyHandle,              //IN: Handle of the key to export
    NULL,                   //IN(opt): key used to encrypt exported BLOB data   <-- potentially an safer way for key extraction, encrypt it with a key during extraction (decrypt with NCryptDecrypt)
    BCRYPT_RSAPUBLIC_BLOB,  //IN: BLOB type (http://ift.tt/1EURer6)
    NULL,                   //IN(opt): List of paramters for the key
    NULL,                   //OUT(opt): Output byte buffer
    0,                      //IN:  Size of the output buffer
    &blob_len,              //OUT: Amount of bytes copied to the output buffer
    0)))                    //IN: Flag to modify function behaviour (0 means no flag set)
{
    //report fail
}

// Allocate data blob to store key in
blob = (PBYTE)malloc(blob_len); 
if (NULL == blob) {
    //report fail
}

// (2 step key extraction process) 2. Get key and store in byte array (Extracted key is in form of BCRYPT_RSAKEY_BLOB)
if (FAILED(status = NCryptExportKey(
    keyHandle,
    NULL,
    BCRYPT_RSAPUBLIC_BLOB,
    NULL,
    blob,
    blob_len,
    &blob_len,
    0)))
{
    //report fail
}


///////////////Import Test (Store into storage)//////////////////////////////////////////////

// Create a persisted key
if(FAILED(status = NCryptCreatePersistedKey(
    providerHandle,             //IN: provider handle
    &keyHandle,                 //OUT: Handle to key
    NCRYPT_RSA_ALGORITHM,       //IN: CNG Algorithm Identifiers. NCRYPT_RSA_ALGORITHM creates public key
    keyName.c_str(),            //IN: Key name. If NULL, the key does not persist 
    0,                          //IN: Key type
    NCRYPT_OVERWRITE_KEY_FLAG)))//IN: Behaviour: 0 - apply to current user only, NCRYPT_MACHINE_KEY_FLAG - apply to local comp only, NCRYPT_OVERWRITE_KEY_FLAG - overwrite existing key
{
    //report fail
}

// Set the size of the key
if(FAILED(status = NCryptSetProperty(
    keyHandle,                          //IN: Handle to key
    BCRYPT_RSAPUBLIC_BLOB,              //IN: CNG Algorithm Identifiers. BCRYPT_RSAPUBLIC_BLOB allows me to use set this blob as the new key's blob
    blob,                               //IN: Key name. If NULL, the key does not persist 
    blob_len,                           //IN: Key Length
    0)))                                //IN: Bahaviour: 0 - apply to current user only, NCRYPT_MACHINE_KEY_FLAG - apply to local comp only, NCRYPT_OVERWRITE_KEY_FLAG - overwrite existing key
{
    //report fail <<-------------------------- Fail here
}

// Finalize key generation (Key is now usable, but uneditable) 
if(FAILED(status = NCryptFinalizeKey(keyHandle, 0)))            {
    //report fail
}
////////////////////////////////////////////////////////////////////////

Critical error detected c0000374 when allocating memory C++

When I try to allocate memory below:

float* vert = new float[24];

for ( int index = 0, subIndex = 0 ; index < 5; index++ )
{
    vert[(subIndex++) % 3] = vertexRegAOS[index].m128_f32[(subIndex++) % 3];
    vert[(subIndex++) % 3] = vertexRegAOS[index].m128_f32[(subIndex++) % 3];
    vert[(subIndex++) % 3] = vertexRegAOS[index].m128_f32[(subIndex++) % 3];
    vert[(subIndex++) % 3] = vertexRegAOS[index].m128_f32[(subIndex++) % 3];
}

I get a 'Critical error detected c0000374' and a breakpoint is triggered. VS sends me here in malloc.c :

__forceinline void * __cdecl _heap_alloc (size_t size)
{

    if (_crtheap == 0) {
        _FF_MSGBANNER();    /* write run-time error banner */

        _NMSG_WRITE(_RT_CRT_NOTINIT);  /* write message */
        __crtExitProcess(255);  /* normally _exit(255) */
    }

    return HeapAlloc(_crtheap, 0, size ? size : 1);
}

Any suggestions on this? :)

stxxl save and read vector from disk file

I'm struggling in trying to use the stxxl library in a way, that I cannot only store the data from their vector structure into a file but also recover it from that file in a rerun of my program.

I found out that you can construct a vector from a file ( http://ift.tt/1EUReaK ) but the class "file" only contains these functions ( http://ift.tt/1dSjz8C ) with no way (that I can see) to actually access an existing file with some given path.

Does someone who worked with this library before have an idea how to do that?

Thanks in advance

Capture screen using DirectX

I know how to use GDI to capture screen, however it is very slow (it barely captures 10 fps)

I have read that DirectX offers the best speed. But before I start learning DirectX I wanted to test a sample to see if it is really that fast.

I have found this question that offers a sample code to do that:

void dump_buffer()
{
   IDirect3DSurface9* pRenderTarget=NULL;
   IDirect3DSurface9* pDestTarget=NULL;
     const char file[] = "Pickture.bmp";
   // sanity checks.
   if (Device == NULL)
      return;

   // get the render target surface.
   HRESULT hr = Device->GetRenderTarget(0, &pRenderTarget);
   // get the current adapter display mode.
   //hr = pDirect3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT,&d3ddisplaymode);

   // create a destination surface.
   hr = Device->CreateOffscreenPlainSurface(DisplayMde.Width,
                         DisplayMde.Height,
                         DisplayMde.Format,
                         D3DPOOL_SYSTEMMEM,
                         &pDestTarget,
                         NULL);
   //copy the render target to the destination surface.
   hr = Device->GetRenderTargetData(pRenderTarget, pDestTarget);
   //save its contents to a bitmap file.
   hr = D3DXSaveSurfaceToFile(file,
                              D3DXIFF_BMP,
                              pDestTarget,
                              NULL,
                              NULL);

   // clean up.
   pRenderTarget->Release();
   pDestTarget->Release();
}

I have tried to include the required files. However not all of them can be included (for example #include <D3dx9tex.h>).

Can anyone provide a working example that has all of the required includes or point me to what libraries I should install.

I am using Visual C++ 2010 Express on Windows 7 Ultimate (x64).


Edit:

Also, this code is not complete, for example what is the Device identifier?!

Using Boost.Python to build a shared lib and import it in Blender through Python

What I currently try to achieve is building a python mapping of my C++ classes through Boost.Python. After this I want to use the resulting shared library in a blender add-on to be able to take advantage of already existing functionality coming from the mapped C++ classes.

I can already build my shared library and write sample scripts in python, which are using my library as well.

Everything fine here but the problem is that as soon as I try to use it in an add-on, Blender 2.74 keeps crashing all the time as soon as I add an import statement with this little hint in the crash report:

6   libboost_python.dylib           0x000000010aa7cc3e boost::python::detail::init_module(PyModuleDef&, void (*)()) + 30 (module.cpp:44)

In module.cpp inside of boost line 41-46:

BOOST_PYTHON_DECL PyObject* init_module(PyModuleDef& moduledef,       void(*init_function)())
{
    return init_module_in_scope(
        PyModule_Create(&moduledef),
        init_function);
}

My boost 1_58 is compiled using Python 3.4.2:

otool -L /usr/local/lib/libboost_python.dylib
/usr/local/lib/libboost_python.dylib:
libboost_python.dylib (compatibility version 0.0.0, current version 0.0.0)
/Library/Frameworks/Python.framework/Versions/3.4/Python (compatibility version 3.4.0, current version 3.4.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 120.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1213.0.0)

Running the python3 bin from that directory gives me:

python3
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  5 2014, 20:42:22)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

The Blender Python console gives me:

PYTHON INTERACTIVE CONSOLE 3.4.2 (default, Nov 25 2014, 12:01:44)  [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.54)]

Command History:     Up/Down Arrow
Cursor:              Left/Right Home/End
Remove:              Backspace/Delete
Execute:             Enter
Autocomplete:        Ctrl-Space
Zoom:                Ctrl +/-, Ctrl-Wheel
Builtin Modules:     bpy, bpy.data, bpy.ops, bpy.props, bpy.types, bpy.context, bpy.utils, bgl, blf, mathutils
Convenience Imports: from mathutils import *; from math import *
Convenience Variables: C = bpy.context, D = bpy.data
>>> 

My own project uses this python version as well. Also Blender uses this Python version.

I really don't know what to try next here since in standalone mode EVERYTHING works as expected. Also the fact that the crash even occurs as soon as I run a new script inside Blenders Text Editor having the import statement.

Anybody having experience with Boost.Python and Blender?

Thanks in advance

Why does std::vector require move-constructors for its elements?

C++98 stated that std::vector elements should have copy-constructors. In C++11 that's no longer the case. Instead, the elements must have move-constructors.

Depending on what you do with std::vector, you may or may not really need to call the copy- or move-constructor, yet only one of them is always formally required by the standard. Why?

"constructing" a trivially-copyable object with memcpy

In C++, is this code correct?

#include <cstdlib>
#include <cstring>

struct T   // trivially copyable type
{
    int x, y;
};

int main()
{
    void *buf = std::malloc( sizeof(T) );
    if ( !buf ) return 0;

    T a{};
    std::memcpy(buf, &a, sizeof a);
    T *b = static_cast<T *>(buf);

    b->x = b->y;

    free(buf);
}

In other words, is *b an object whose lifetime has begun? (If so, when did it begin exactly?)

Perform Infinite Loop While Waiting for Input C++

A C++ program that perform such:

 cout<<"Hello please enter in your age: "; 
 int age;
 cin>>age; 

While the system waits for input, I want to display this following loop:

for(;;)
{
 cout << "Waiting.............." << '\r' << flush; Sleep(500);
 cout << ".......Waiting......." << '\r' << flush; Sleep(500);
 cout << "..............Waiting" << '\r' << flush; Sleep(500);
}

The loop should stop when there is any input.

Segmentation Fault each 2.5 hours [on hold]

every 2.5 hours i get the following error

Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7fffcae4c700 (LWP 27177)]
0x0000000001266491 in BaseClientCleanUpEvent::cleanUp(engine::service::DatagramS erviceThread*) ()
(gdb)

any advice?

How to make a template-dependent typedef more convenient?

I have several classes with all the same template arguments. They use OftenUsedType which is also a template. So I typedef it to R to have more convenient notation:

template <class T, int A, int B>
class Obj{
   typedef OftenUsedType<T, A, B> R;
}

Unfortunately, I have to do this in all classes which use OftenUsedType, since it depends on the template parameters.

The only way to make this a bit more convenient is to do the typedef in a class and inherit it to all classes which use it:

template <class T, int A, int B>
class ObjTypedef{
   typedef OftenUsedType<T, A, B> R;
}

template <class T, int A, int B>
class Obj : public ObjTypedef<T, A, B>{
}

But I still have to inherit the typedef class into all classes which use the type...

Is there a more convenient, good-style way to do it?

Untouched shared resources in C++ threading

Imagine the following scenario:

#include <chrono>
#include <iostream>
#include <thread>
#include <vector>

void DoSomething(int* i)
{
    std::cout << *i << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(1));
    *i = 2;
    std::cout << *i << std::endl;
}

int main()
{
    std::vector<int> v = {0, 0, 0};
    v[0] = 1;
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::thread t(&DoSomething, &v[0]);
    t.join();
    std::cout << v[0] << std::endl;
}

Is there any reason that there should be a mutex passed along with the vector element?

P.D. from 08/May/2015

I did not elaborate on the question more when posting, since I didn't want to influence the answer. What you've answered would have been pretty much my understanding till yesterday. However, it has been suggested to me that intuitive behaviour might not be serviceable in threading scenarios as much as one would hope. Particularly, in this case, it has been suggested that, for instance, the assumption that the writing v[0] = 1 happening on the main thread is something that, without a mutex, will be reflected when printing in DoSomething is not guaranteed. As a possible explanation I was offered that the value might go into thread accessible memory, but that it might be swapped out by the state of a different thread before it is written to cross-thread memory, and again, that the only way of guaranteeing the desired propagation would be using a mutex. What is your opinion on that argument?

Downcasting SOAP Response in gSoap

I currently have a web service written in J2EE which has a webservice which looks something like this in the generated gSoap proxy class:

performAction(CommandAction *actionIn, BaseClass &actionOut)

Depending on the actionIn, the actionOut result can be one of several child classes of BaseClass. In order for me to access the results, i need to be able to cast actionOut to the correct derived class and access member variables.

The resulting XML looks something like this:

...

<ns1:performAction xsi:type="ns2:DerivedClass" xmlns:ns2="blah..">
<data>Hello</data>
</ns1:performAction>

....

The data variable is only present in the Derived class.

So far i have tried passing in derived class objects to the method but the derived member variables remain empty or null. Any advice would be appreciated.

Drop sniffed packet on matching content

I have made a packet sniffer in C using rawsockets that sniffs all outgoing UDP traffic on a specified port.

I now want to drop certain outgoing UDP packets that match a certain payload, so that they can be resent with a different payload.

A sniffer will no longer be useful in this situation, because it seems unable to motify the network traffic it detects.

Is there a way to drop packets that match a certain payload and port on a Linux system without modifying kernel code? Is my sniffer useless for the goal I have?

If I use python to write a bitarray to binary file (on linux/unix) can I then directly read that file into a c++ 0x vector_bool? Or do the python vs c++ organize their bits differently?

TIA

Error "undefined reference" to my signals [on hold]

I am getting undefined reference to 'Initializer::draw()' for this code:

I don't know what to do with it. I know that there is no need to implement a signal in cpp. So why is that happening?

header:

class Initializer : public QThread
{
    Q_OBJECT

public:
    Game* game;
    explicit Initializer(QObject* parent = 0);

signals:
    void draw();

protected:
    void run(void);
};

cpp:

void Initializer::run(void)
{
    game->Initialize();
    emit draw();
}
Initializer::Initializer(QObject *parent)
    : QThread(parent)
{
}

Can anyone help?

SSIM between different image resolutions

I need to compare the quality of streaming between Linux desktop server and an Android client. So I have two images one from Linux server and the other one from Android client and they have different resolution.

My question is how to calculate SSIM between these two images (I do not need CODE just a direction to the solution). I already have SSIM code in c++ but it will compare between similar resolutions.

THANKS

Wrong answer in UVa for SWERC "Nochange"

I meet a problem when I do the exercise in UVa Online Judge.

Here is the link to this problem. http://ift.tt/1bD5Sc7

To solve this problem, like 13 3(number of different values) 9 2 1, I need to solve the problem like 9x + 2y + 1z = 13(x >= y >= z), which is equal to the problem 9x + 11y + 12z = 13, is it have non-negative integer roots?

I use the algorithm to calculate all the possibilities of sum 9x + 11y + 12z with the changing the value of x, y, z.

Here is my code,

#include <cstdio>
#include <vector>

using namespace std;

int main(){
    int nb_case;
    int k;
    scanf("%d", &nb_case);
    vector<int> right;

    for (k = 0; k < nb_case; k++){
        int i, j;
        int total = 0;
        int nb_value = 0;
        int cache_coin = 0;
        scanf("%d %d", &total, &nb_value);

        vector<int> coins;
        scanf("%d", &cache_coin);
        coins.push_back(cache_coin);
        for (i = 1; i < nb_value; i++){
            scanf("%d", &cache_coin);
            coins.push_back(cache_coin + coins[i - 1]);
        }

        vector<bool> possible;
        possible.push_back(true);
        for (i = 1; i <= total; i++){
            possible.push_back(false);
        }

        for (i = 0; i < nb_value; i++){
            for (j = coins[i]; j <= total; j++){
                possible[j] = possible[j] | possible[j - coins[i]];
            }
        }

        if (possible[total]){
            right.push_back(1);
        } else{
            right.push_back(0);
        }

    }

    for (k = 0; k < nb_case; k++){
        if (right[k] == 1){
            printf("YES\n\n");
        }
        else{
            printf("NO\n\n");
        }
    }
}

The judge system told me that it is wrong answer.

But I find a similar problem in SPOJ. http://ift.tt/1H61qAF

These two problems just have slight differences which is not related to the core algorithm. I change the code.

#include <cstdio>
#include <vector>

using namespace std;

int main(){
    int nb_case = 1;
    int k;
    vector<int> right;

    for (k = 0; k < nb_case; k++){
        int i, j;
        int total = 0;
        int nb_value = 0;
        int cache_coin = 0;
        scanf("%d %d", &total, &nb_value);

        vector<int> coins;
        scanf("%d", &cache_coin);
        coins.push_back(cache_coin);
        for (i = 1; i < nb_value; i++){
            scanf("%d", &cache_coin);
            coins.push_back(cache_coin + coins[i - 1]);
        }

        vector<bool> possible;
        possible.push_back(true);
        for (i = 1; i <= total; i++){
            possible.push_back(false);
        }

        for (i = 0; i < nb_value; i++){
            for (j = coins[i]; j <= total; j++){
                possible[j] = possible[j] | possible[j - coins[i]];
            }
        }

        if (possible[total]){
            right.push_back(1);
        } else{
            right.push_back(0);
        }

    }

    for (k = 0; k < nb_case; k++){
        if (right[k] == 1){
            printf("YES\n\n");
        }
        else{
            printf("NO\n\n");
        }
    }
}

my code is correct in SPOJ.

I cannot figure out why it is not correct with UVa Online Judge.

I test many example for my algorithm but I cannot find an error.

Thanks in advance.

OpenCV heap corruption on Release mode

I have a simple code written in Visual Studio 2010 with openCV 2.4.10 which extracts some features from some input file.

Mat extractSIFT(Mat img)
{
    cv::Ptr<cv::FeatureDetector> detector;
    cv::Ptr<cv::Feature2D> descriptorExtractor;

    detector = cv::FeatureDetector::create("Dense");
    descriptorExtractor = cv::DescriptorExtractor::create("SIFT");

    detector->set("initXyStep",GRID_SPACING);

    vector<cv::KeyPoint> keypoints;
    detector->detect(img,keypoints);

    Mat o;
    //Mat o(keypoints.size(),128,CV_8U);
    descriptorExtractor->compute(img,keypoints,o);

    return o;
}

Although this code works fine in debug mode(albeit slow), it gives this error:

Windows has triggered a breakpoint in Prototype.exe.

This may be due to a corruption of the heap, which indicates a bug in Prototype.exe or any of the DLLs it has loaded.

This may also be due to the user pressing F12 while Prototype.exe has focus.

The output window may have more diagnostic information.

Upon further investigation, I found that the output variable o cannot be seen in release mode(hover over), but can print values on simple console dump.

In disassembler:

   848:     //Mat o(keypoints.size(),128,CV_8U);
   849:     descriptorExtractor->compute(img,keypoints,o);
   850: 
   851:     return o;
013F6FCF 56                   push        esi  
013F6FD0 8D 55 C0             lea         edx,[keypoints]  
013F6FD3 52                   push        edx  
013F6FD4 8D 45 0C             lea         eax,[img]  
013F6FD7 50                   push        eax  
013F6FD8 8B CF                mov         ecx,edi  
013F6FDA C7 45 F0 01 00 00 00 mov         dword ptr [ebp-10h],1  
013F6FE1 E8 42 35 02 00       call        cv::Feature2D::compute (141A528h)  
013F6FE6 8B 45 C0             mov         eax,dword ptr [keypoints]  
013F6FE9 3B C3                cmp         eax,ebx  
013F6FEB 74 09                je          extractSIFT4+306h (13F6FF6h)  
013F6FED 50                   push        eax  
**013F6FEE E8 EC 5C 02 00       call        operator delete (141CCDFh)**  
013F6FF3 83 C4 04             add         esp,4  

The error occurs in line with asterisks. I tried several project properties (/Md, MT, incremental build,...) recompiled openCV, checked platform version(v100) but no avail.

Snake game doesn't work

this is the part of the code isn't compiling. It will start and then stop when it gets here. I have a Char Map of [11][22] that is my board. What I'm trying to do is get the '*' to random generate, and act as the food for my snake.

srand(time(NULL));
int pellet=rand()%21;

while (GameRunning == true)
{
    for (int pellet = rand(); pellet % Map[11][22]; pellet++)
    {
        cout << '*';
    }
    system("cls");

Is it safe to use the Structure dereference(->) operator on the result of std::atomic::load

Whilst trying to work with std atomic pointer, I ran into the following. Say I do this:

std::atomic<std::string*> myString;
// <do fancy stuff with the string... also on other threads>

//A can I do this?
myString.load()->size()

//B can I do this?
char myFifthChar = *(myString.load()->c_str() + 5);

//C can I do this?
char myCharArray[255];
strcpy(myCharArray, myString.load()->c_str());

I'm pretty sure C is illegal because myString might be deleted in the meantime.

However I'm unsure about A and B. I suppose they are illegal since the pointer might be deferenced whilst performing the read operation.

However if this is the case, how can you ever read from an atomic pointer that might be deleted. Since the load is 1 step, and the reading of the data is 1 step.

How do I setup a systemwide hook to listen for WM_DEVICECHANGE?

I want to setup a System wide hook to listen for WM_DEVICECHANGE in C++. I know that hooks are setup using SetWindowsHookEx(). I have done this before for Keyboard messages (WM_KEYUP, WM_KEYDOWN) but I want to do it for WM_DEVICECHANGE. I am currently using:

void WinHook()
{
HHOOK hook = NULL;
hook = SetWindowsHookEx(WH_GETMESSAGE, HookProc, NULL, GetCurrentThreadId());
}

LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam){
switch (wParam){
case WM_DEVICECHANGE:std::cout << "SUCCESS!!!!!";
    break;
    }
}

Multiple inheritance via templates

Is it good idea to replace virtual multiple inheritance (diamon) with teplates inheritence (linear)? For example I have this class diagram :

       IBase
    /          \
   /            \
IExtendedBase  BaseImpl
  \            /
   ExtendedImpl

I know that I can implement it with virtual inheritance. But can I use templates in order to make this diagram linear?

class IBase
    {
    public:
        virtual std::string name() = 0;
    };

    template<typename T>
    class BaseImpl : public T
    {
    public:
        virtual std::string name() override
        {
            return "BaseCommonImpl";
        }
    };

    template<typename T>
    class IExtendedBase : public T
    {
    public:
        virtual std::string extended_name() = 0;
    };

    template<typename T>
    class ExtendedBaseImpl : public T
    {
    public:
        virtual std::string extended_name() override
        {
            return "ExtendedBaseImpl";
        }
    };

Now with typedef I can specialize ExtendedBase

typedef IExtendedBase<BaseImpl<IBase>> _ExtendedBase;
typedef ExtendedBaseImpl<_ExtendedBase> _ExtendedBaseImpl;

Which method is better? Virtual inheritance or template inheritance?

reading two vectors from file

Problem is described here. I tried to solve it using code that's below, but it's not working.

const char* filename = "test.txt";
ifstream file1(filename);
vector<int> v1;
vector<int> v2;
vector<int> res;

int number;
char c;

while(1){
    while(1){
        v1.push_back(number);
        file1.get(c);
        if (c==';') break;
    }

    while(1){
        v2.push_back(number);
        file1.get(c);
        if (c=='\n') break;
    }

    for (vector<int>::iterator it = v2.begin(); it!=v2.end(); it++)
        cout << *it << ',';
    cout << endl;
    file1.get(c);
    if (c==EOF) break;
    file1.unget();
}

There is a problem with reading end of line. Is c=='\n' right?

Write binary data to file in linux in c++

I'm trying to learn C++ and I would interested in how I could write better code. The code should be independent of the architecture it is running on. What I want to do is writing some binary data to /dev/rfkill so that I can change some settings. The target is an embedded system so the program does run with root privileges and the program is using the Qt framework.

This is the code I currently have and which does what I want:

    rfkill_event event;
    event.type = RFKILL_TYPE_ALL;
    event.op = RFKILL_OP_CHANGE_ALL;
    event.soft = RFKILL_ACTION_UNBLOCK;

    QFile file("/dev/rfkill");
    if (!file.open(QIODevice::WriteOnly))
        quit();

    QDataStream out(&file);
    if (-1 == out.writeRawData((char*)(&(event.idx)), sizeof(event.idx))) {
        file.close();
        quit();
    }
    if (-1 == out.writeRawData((char*)(&(event.type)), sizeof(event.type))) {
        file.close();
        quit();
    }
    if (-1 == out.writeRawData((char*)(&(event.op)), sizeof(event.op))) {
        file.close();
        quit();
    }
    if (-1 == out.writeRawData((char*)(&(event.soft)), sizeof(event.soft))) {
        file.close();
        quit();
    }
    if (-1 == out.writeRawData((char*)(&(event.hard)), sizeof(event.hard))) {
        file.close();
        quit();
    }
    file.close();
    quit();

and the struct looks like this:

struct rfkill_event {
    __u32 idx;
    __u8  type;
    __u8  op;
    __u8  soft, hard;
};

The code is taken and adapted from the rfkill program.

I've removed __attribute__((packed)) from the struct because of the pitfalls mentioned here: Why you shouldn’t use __attribute__((packed))

I'm using the writeRawData function instead of the << operator to write the data. The reason for this is that this code should work on big and little endian machines.

Are my assumptions correct and do you have any suggestions on how I could improve this code (besides not having any error handling)?

Regards Martin